From 52f0f9d54e1f5aa8b3b7412b55f97ae2b71750ae Mon Sep 17 00:00:00 2001 From: Iamasoldier <1272745473@qq.com> Date: Tue, 20 May 2025 14:04:52 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E8=AE=A2=E5=8D=95=E7=AE=A1=E7=90=86)?= =?UTF-8?q?=EF=BC=9A=E8=AE=A2=E5=8D=95=E5=88=9B=E5=BB=BA=E9=87=8D=E5=A4=8D?= =?UTF-8?q?=E4=B8=8B=E5=8D=95=E9=97=AE=E9=A2=98=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- zlt-business/edu-center/README.md | 45 + zlt-business/edu-center/pom.xml | 192 +++++ .../java/com/central/order/EduCenterApp.java | 22 + .../central/order/config/AliyunImsConfig.java | 42 + .../com/central/order/config/AsyncConfig.java | 31 + .../order/config/ProfitSharingProperties.java | 58 ++ .../order/config/TencentPayConfiguration.java | 145 ++++ .../order/config/TencentPayProperties.java | 25 + .../central/order/config/WxMaProperties.java | 9 + .../order/config/WxMpConfiguration.java | 68 ++ .../central/order/config/WxMpProperties.java | 54 ++ .../order/constants/EditTaskStatus.java | 53 ++ .../order/constants/OrderStatusConstants.java | 21 + .../constants/ProfitSharingConstants.java | 16 + .../central/order/constants/WxConstants.java | 35 + .../controller/AutoCutVideoController.java | 266 ++++++ .../order/controller/DashboardController.java | 34 + .../controller/HomeCarouselController.java | 90 ++ .../order/controller/MessageController.java | 47 ++ .../order/controller/OrderController.java | 680 ++++++++++++++++ .../order/controller/OrderFileController.java | 187 +++++ .../controller/OrderStatisticsController.java | 102 +++ .../controller/PaymentRecordController.java | 57 ++ .../controller/ProfitSharingController.java | 62 ++ .../order/controller/QrCodeController.java | 149 ++++ .../order/controller/RefundController.java | 146 ++++ .../order/controller/TourismController.java | 69 ++ .../controller/TourismFileController.java | 78 ++ .../controller/VideoTemplateController.java | 95 +++ .../controller/WxCallbackController.java | 58 ++ .../controller/WxMessageRecordController.java | 54 ++ .../order/controller/WxPayController.java | 467 +++++++++++ .../order/controller/WxTestController.java | 39 + .../order/controller/orderStatusLogic.md | 46 ++ .../com/central/order/enums/CommonStatus.java | 24 + .../com/central/order/enums/FileType.java | 41 + .../central/order/enums/HomeCarouselType.java | 26 + .../order/enums/MessageTemplateEnum.java | 67 ++ .../com/central/order/enums/OrderStatus.java | 86 ++ .../order/enums/OrderStatusChangeEnum.java | 64 ++ .../central/order/enums/PayeeTypeEnum.java | 26 + .../order/enums/ProfitSharingStatusEnum.java | 28 + .../com/central/order/enums/QrcodeStatus.java | 4 + .../com/central/order/enums/RefundState.java | 26 + .../order/event/OrderStatusChangeEvent.java | 23 + .../order/feign/DeviceCenterService.java | 33 + .../order/feign/FileCenterService.java | 50 ++ .../order/feign/UserCenterService.java | 29 + .../DeviceCenterServiceFallbackFactory.java | 36 + .../FileCenterServiceFallbackFactory.java | 66 ++ .../UserCenterServiceFallbackFactory.java | 31 + .../order/handler/WxMessageHandler.java | 134 +++ .../listener/OrderStatusChangeListener.java | 258 ++++++ .../central/order/mapper/DashboardMapper.java | 91 +++ .../central/order/mapper/EditTaskMapper.java | 12 + .../order/mapper/HomeCarouselMapper.java | 29 + .../central/order/mapper/MessageMapper.java | 77 ++ .../central/order/mapper/OrderFileMapper.java | 49 ++ .../com/central/order/mapper/OrderMapper.java | 61 ++ .../order/mapper/OrderStatisticsMapper.java | 66 ++ .../order/mapper/PaymentRecordMapper.java | 33 + .../order/mapper/ProfitSharingMapper.java | 43 + .../central/order/mapper/QrCodeMapper.java | 35 + .../central/order/mapper/RefundMapper.java | 27 + .../order/mapper/TourismFileMapper.java | 32 + .../central/order/mapper/TourismMapper.java | 35 + .../order/mapper/VideoTemplateMapper.java | 9 + .../order/mapper/WxMessageRecordMapper.java | 9 + .../com/central/order/model/EditTask.java | 38 + .../com/central/order/model/HomeCarousel.java | 47 ++ .../java/com/central/order/model/Message.java | 58 ++ .../java/com/central/order/model/Order.java | 58 ++ .../com/central/order/model/OrderFile.java | 49 ++ .../com/central/order/model/OrderRanking.java | 13 + .../central/order/model/OrderStatistics.java | 44 + .../order/model/OrderStatisticsQuery.java | 28 + .../central/order/model/PaymentRecord.java | 43 + .../central/order/model/ProfitSharing.java | 163 ++++ .../order/model/ProfitSharingResult.java | 104 +++ .../java/com/central/order/model/QrCode.java | 96 +++ .../com/central/order/model/QrCodeVO.java | 26 + .../java/com/central/order/model/Refund.java | 51 ++ .../order/model/RequestParamsEntity.java | 38 + .../com/central/order/model/SourceDTO.java | 35 + .../java/com/central/order/model/Tourism.java | 46 ++ .../com/central/order/model/TourismFile.java | 43 + .../central/order/model/VideoTemplate.java | 52 ++ .../central/order/model/WxMessageRecord.java | 32 + .../central/order/model/WxTemplateInfo.java | 44 + .../central/order/model/WxUserSubscribe.java | 20 + .../central/order/model/dto/CallbackDTO.java | 18 + .../order/model/dto/VideoEditRequest.java | 36 + .../order/model/dto/VideoEditStatus.java | 32 + .../model/params/EditTaskQueryParams.java | 18 + .../order/model/vo/ChartStatistics.java | 19 + .../order/model/vo/DashboardStatisticsVO.java | 28 + .../order/model/vo/DeviceStatistics.java | 19 + .../order/model/vo/DistributionDataVO.java | 16 + .../central/order/model/vo/IncomeDataVO.java | 16 + .../order/model/vo/IncomeStatistics.java | 19 + .../order/model/vo/OrderStatistics.java | 22 + .../model/vo/ProfitSharingStatisticsVO.java | 56 ++ .../order/model/vo/TourismRankingVO.java | 19 + .../central/order/model/vo/TrendDataVO.java | 19 + .../order/model/vo/WaylineStatistics.java | 19 + .../order/scheduler/OrderScheduler.java | 31 + .../order/scheduler/VideoEditTaskChecker.java | 55 ++ .../scheduler/WxAccessTokenRefreshTask.java | 29 + .../order/service/IDashboardService.java | 10 + .../order/service/IEditTaskService.java | 76 ++ .../order/service/IHomeCarouselService.java | 32 + .../central/order/service/IMediaService.java | 25 + .../order/service/IMessageService.java | 36 + .../order/service/IOrderFileService.java | 88 ++ .../central/order/service/IOrderService.java | 92 +++ .../service/IOrderStatisticsService.java | 64 ++ .../order/service/IPaymentRecordService.java | 31 + .../order/service/IProfitSharingService.java | 60 ++ .../central/order/service/IQrCodeService.java | 38 + .../central/order/service/IRefundService.java | 38 + .../order/service/ITourismFileService.java | 40 + .../order/service/ITourismService.java | 39 + .../order/service/IVideoEditService.java | 28 + .../order/service/IVideoTemplateService.java | 40 + .../order/service/IWxAccessTokenService.java | 14 + .../service/IWxMessageRecordService.java | 36 + .../service/IWxTemplateMessageService.java | 9 + .../central/order/service/IWxUserService.java | 11 + .../order/service/WxMiniSubscribeService.java | 35 + .../service/impl/DashboardServiceImpl.java | 123 +++ .../service/impl/EditTaskServiceImpl.java | 214 +++++ .../service/impl/HomeCarouselServiceImpl.java | 45 + .../order/service/impl/MediaServiceImpl.java | 279 +++++++ .../service/impl/MessageServiceImpl.java | 98 +++ .../service/impl/OrderFileServiceImpl.java | 106 +++ .../order/service/impl/OrderServiceImpl.java | 327 ++++++++ .../impl/OrderStatisticsServiceImpl.java | 303 +++++++ .../impl/PaymentRecordServiceImpl.java | 96 +++ .../impl/ProfitSharingServiceImpl.java | 768 ++++++++++++++++++ .../order/service/impl/QrCodeServiceImpl.java | 54 ++ .../order/service/impl/RefundServiceImpl.java | 52 ++ .../service/impl/TourismFileServiceImpl.java | 50 ++ .../service/impl/TourismServiceImpl.java | 50 ++ .../service/impl/VideoEditServiceImpl.java | 214 +++++ .../impl/VideoTemplateServiceImpl.java | 82 ++ .../impl/WxAccessTokenServiceImpl.java | 106 +++ .../impl/WxMessageRecordServiceImpl.java | 112 +++ .../impl/WxMiniSubscribeServiceImpl.java | 83 ++ .../impl/WxTemplateMessageServiceImpl.java | 179 ++++ .../order/service/impl/WxUserServiceImpl.java | 72 ++ .../central/order/util/ContentTypeUtil.java | 29 + .../com/central/order/util/DateUtils.java | 77 ++ .../central/order/util/ExceptionUtils.java | 51 ++ .../central/order/util/HttpServletUtils.java | 47 ++ .../java/com/central/order/util/MapUtil.java | 52 ++ .../com/central/order/util/RequestUtils.java | 119 +++ .../com/central/order/util/StringUtils.java | 29 + .../java/com/central/order/util/Utils.java | 47 ++ .../central/order/util/http/HeaderUtils.java | 80 ++ .../central/order/util/http/HttpRequest.java | 39 + .../com/central/order/util/http/Response.java | 13 + .../order/util/http/SimpleHttpRequest.java | 184 +++++ .../order/util/http/SimpleResponse.java | 26 + .../src/main/resources/application.yml | 128 +++ .../src/main/resources/bootstrap.yml | 15 + .../resources/mapper/HomeCarouselMapper.xml | 12 + .../main/resources/mapper/MessageMapper.xml | 125 +++ .../main/resources/mapper/OrderFileMapper.xml | 43 + .../src/main/resources/mapper/OrderMapper.xml | 63 ++ .../main/resources/mapper/PaymentRecord.xml | 20 + .../main/resources/mapper/QrCodeMapper.xml | 20 + .../main/resources/mapper/RefundMapper.xml | 12 + .../resources/mapper/TourismFileMapper.xml | 15 + .../main/resources/mapper/TourismMapper.xml | 20 + .../order/controller/OrderController.java | 6 +- .../order/service/impl/OrderServiceImpl.java | 13 +- zlt-business/pom.xml | 2 + .../db/config/TenantAutoConfigure.java | 3 +- .../src/main/resources/bootstrap.properties | 10 +- .../src/main/frontend/config/proxy.ts | 32 +- 180 files changed, 12354 insertions(+), 34 deletions(-) create mode 100644 zlt-business/edu-center/README.md create mode 100644 zlt-business/edu-center/pom.xml create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/EduCenterApp.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/config/AliyunImsConfig.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/config/AsyncConfig.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/config/ProfitSharingProperties.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/config/TencentPayConfiguration.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/config/TencentPayProperties.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/config/WxMaProperties.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/config/WxMpConfiguration.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/config/WxMpProperties.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/constants/EditTaskStatus.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/constants/OrderStatusConstants.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/constants/ProfitSharingConstants.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/constants/WxConstants.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/controller/AutoCutVideoController.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/controller/DashboardController.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/controller/HomeCarouselController.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/controller/MessageController.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/controller/OrderController.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/controller/OrderFileController.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/controller/OrderStatisticsController.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/controller/PaymentRecordController.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/controller/ProfitSharingController.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/controller/QrCodeController.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/controller/RefundController.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/controller/TourismController.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/controller/TourismFileController.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/controller/VideoTemplateController.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/controller/WxCallbackController.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/controller/WxMessageRecordController.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/controller/WxPayController.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/controller/WxTestController.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/controller/orderStatusLogic.md create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/enums/CommonStatus.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/enums/FileType.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/enums/HomeCarouselType.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/enums/MessageTemplateEnum.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/enums/OrderStatus.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/enums/OrderStatusChangeEnum.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/enums/PayeeTypeEnum.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/enums/ProfitSharingStatusEnum.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/enums/QrcodeStatus.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/enums/RefundState.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/event/OrderStatusChangeEvent.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/feign/DeviceCenterService.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/feign/FileCenterService.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/feign/UserCenterService.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/feign/fallback/DeviceCenterServiceFallbackFactory.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/feign/fallback/FileCenterServiceFallbackFactory.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/feign/fallback/UserCenterServiceFallbackFactory.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/handler/WxMessageHandler.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/listener/OrderStatusChangeListener.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/mapper/DashboardMapper.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/mapper/EditTaskMapper.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/mapper/HomeCarouselMapper.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/mapper/MessageMapper.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/mapper/OrderFileMapper.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/mapper/OrderMapper.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/mapper/OrderStatisticsMapper.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/mapper/PaymentRecordMapper.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/mapper/ProfitSharingMapper.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/mapper/QrCodeMapper.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/mapper/RefundMapper.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/mapper/TourismFileMapper.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/mapper/TourismMapper.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/mapper/VideoTemplateMapper.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/mapper/WxMessageRecordMapper.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/model/EditTask.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/model/HomeCarousel.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/model/Message.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/model/Order.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/model/OrderFile.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/model/OrderRanking.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/model/OrderStatistics.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/model/OrderStatisticsQuery.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/model/PaymentRecord.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/model/ProfitSharing.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/model/ProfitSharingResult.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/model/QrCode.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/model/QrCodeVO.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/model/Refund.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/model/RequestParamsEntity.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/model/SourceDTO.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/model/Tourism.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/model/TourismFile.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/model/VideoTemplate.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/model/WxMessageRecord.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/model/WxTemplateInfo.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/model/WxUserSubscribe.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/model/dto/CallbackDTO.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/model/dto/VideoEditRequest.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/model/dto/VideoEditStatus.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/model/params/EditTaskQueryParams.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/model/vo/ChartStatistics.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/model/vo/DashboardStatisticsVO.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/model/vo/DeviceStatistics.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/model/vo/DistributionDataVO.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/model/vo/IncomeDataVO.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/model/vo/IncomeStatistics.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/model/vo/OrderStatistics.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/model/vo/ProfitSharingStatisticsVO.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/model/vo/TourismRankingVO.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/model/vo/TrendDataVO.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/model/vo/WaylineStatistics.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/scheduler/OrderScheduler.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/scheduler/VideoEditTaskChecker.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/scheduler/WxAccessTokenRefreshTask.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/IDashboardService.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/IEditTaskService.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/IHomeCarouselService.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/IMediaService.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/IMessageService.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/IOrderFileService.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/IOrderService.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/IOrderStatisticsService.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/IPaymentRecordService.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/IProfitSharingService.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/IQrCodeService.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/IRefundService.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/ITourismFileService.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/ITourismService.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/IVideoEditService.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/IVideoTemplateService.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/IWxAccessTokenService.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/IWxMessageRecordService.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/IWxTemplateMessageService.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/IWxUserService.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/WxMiniSubscribeService.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/impl/DashboardServiceImpl.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/impl/EditTaskServiceImpl.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/impl/HomeCarouselServiceImpl.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/impl/MediaServiceImpl.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/impl/MessageServiceImpl.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/impl/OrderFileServiceImpl.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/impl/OrderServiceImpl.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/impl/OrderStatisticsServiceImpl.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/impl/PaymentRecordServiceImpl.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/impl/ProfitSharingServiceImpl.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/impl/QrCodeServiceImpl.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/impl/RefundServiceImpl.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/impl/TourismFileServiceImpl.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/impl/TourismServiceImpl.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/impl/VideoEditServiceImpl.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/impl/VideoTemplateServiceImpl.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/impl/WxAccessTokenServiceImpl.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/impl/WxMessageRecordServiceImpl.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/impl/WxMiniSubscribeServiceImpl.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/impl/WxTemplateMessageServiceImpl.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/service/impl/WxUserServiceImpl.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/util/ContentTypeUtil.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/util/DateUtils.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/util/ExceptionUtils.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/util/HttpServletUtils.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/util/MapUtil.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/util/RequestUtils.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/util/StringUtils.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/util/Utils.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/util/http/HeaderUtils.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/util/http/HttpRequest.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/util/http/Response.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/util/http/SimpleHttpRequest.java create mode 100644 zlt-business/edu-center/src/main/java/com/central/order/util/http/SimpleResponse.java create mode 100644 zlt-business/edu-center/src/main/resources/application.yml create mode 100644 zlt-business/edu-center/src/main/resources/bootstrap.yml create mode 100644 zlt-business/edu-center/src/main/resources/mapper/HomeCarouselMapper.xml create mode 100644 zlt-business/edu-center/src/main/resources/mapper/MessageMapper.xml create mode 100644 zlt-business/edu-center/src/main/resources/mapper/OrderFileMapper.xml create mode 100644 zlt-business/edu-center/src/main/resources/mapper/OrderMapper.xml create mode 100644 zlt-business/edu-center/src/main/resources/mapper/PaymentRecord.xml create mode 100644 zlt-business/edu-center/src/main/resources/mapper/QrCodeMapper.xml create mode 100644 zlt-business/edu-center/src/main/resources/mapper/RefundMapper.xml create mode 100644 zlt-business/edu-center/src/main/resources/mapper/TourismFileMapper.xml create mode 100644 zlt-business/edu-center/src/main/resources/mapper/TourismMapper.xml diff --git a/zlt-business/edu-center/README.md b/zlt-business/edu-center/README.md new file mode 100644 index 00000000..3156812e --- /dev/null +++ b/zlt-business/edu-center/README.md @@ -0,0 +1,45 @@ + +待开发功能: +1. 景区管理 +2. 套餐管理 +3. 素材管理 + + + +-- 订单创建时间 + 状态的联合索引(用于时间范围和状态统计) +CREATE INDEX idx_orders_create_status ON orders(create_time, order_status); + +-- 二维码ID + 创建时间的联合索引(用于按二维码统计) +CREATE INDEX idx_orders_qrcode_time ON orders(code_id, create_time); + +-- 景区ID + 创建时间的联合索引(用于按景区统计) +CREATE INDEX idx_orders_tourism_time ON orders(tourism_id, create_time); + +-- 设备编号 + 创建时间的联合索引(用于按设备统计) +CREATE INDEX idx_orders_device_time ON orders(device_sn, create_time); + +-- 软删除标记 + 创建时间的联合索引(用于过滤已删除订单) +CREATE INDEX idx_orders_del_time ON orders(is_del, create_time); + +服务号推送消息功能 + +1. 登录微信公众平台(mp.weixin.qq.com) + +2. 配置服务器: + - 进入"设置与开发 -> 基本配置" + - 填写服务器配置 + - URL: https://你的域名/wx/message + - Token: 与配置文件中的token一致 + - EncodingAESKey: 点击随机生成,复制到配置文件 + - 消息加解密方式: 选择安全模式 + +3. 配置消息模板: + - 进入"功能 -> 模板消息" + - 添加所需的消息模板 + - 复制模板ID到配置文件 + +4. 配置云托管(如果使用): + - 进入"云托管" + - 创建环境 + - 部署服务 + - 配置域名 diff --git a/zlt-business/edu-center/pom.xml b/zlt-business/edu-center/pom.xml new file mode 100644 index 00000000..e069757c --- /dev/null +++ b/zlt-business/edu-center/pom.xml @@ -0,0 +1,192 @@ + + + 4.0.0 + + com.zlt + zlt-business + 6.0.0 + + + edu-center + 教育中心 + + + 17 + 17 + UTF-8 + + + + + + com.zlt + zlt-config + + + com.zlt + zlt-log-spring-boot-starter + + + com.zlt + zlt-common-spring-boot-starter + + + com.zlt + zlt-db-spring-boot-starter + + + com.zlt + zlt-redis-spring-boot-starter + + + com.zlt + zlt-loadbalancer-spring-boot-starter + + + com.zlt + zlt-sentinel-spring-boot-starter + + + + com.github.xiaoymin + knife4j-openapi3-jakarta-spring-boot-starter + + + com.zlt + search-client + + + + org.springframework.boot + spring-boot-starter-web + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + + + org.springframework.boot + spring-boot-starter-actuator + + + + mysql + mysql-connector-java + + + + io.micrometer + micrometer-registry-prometheus + + + junit + junit + test + + + org.hibernate + hibernate-validator + + + + com.github.wechatpay-apiv3 + wechatpay-java + 0.2.15 + + + + + com.github.binarywang + weixin-java-mp + 4.5.0 + + + + com.squareup.okhttp3 + okhttp + 4.9.1 + + + com.github.binarywang + weixin-java-miniapp + 4.6.0 + + + + com.github.binarywang + weixin-java-common + 4.6.0 + + + javax.servlet + javax.servlet-api + 4.0.1 + compile + + + org.springframework + spring-webflux + + + + com.aliyun + alibabacloud-ice20201109 + 5.0.3 + + + + + org.springframework.retry + spring-retry + + + org.springframework.boot + spring-boot-starter-aop + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + + + + com.spotify + docker-maven-plugin + + ${docker.image.prefix}/${project.artifactId} + + ${project.version} + latest + + true + ${docker.baseImage} + ${docker.volumes} + + ${docker.java.opts} + + ["sh","-c","java $JAVA_OPTS ${docker.java.security.egd} -jar /${project.build.finalName}.jar"] + + + / + ${project.build.directory} + ${project.build.finalName}.jar + + + + + + ${project.artifactId} + + diff --git a/zlt-business/edu-center/src/main/java/com/central/order/EduCenterApp.java b/zlt-business/edu-center/src/main/java/com/central/order/EduCenterApp.java new file mode 100644 index 00000000..ab5ec2b0 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/EduCenterApp.java @@ -0,0 +1,22 @@ +package com.central.order; + +import com.central.common.lb.annotation.EnableFeignInterceptor; +import com.central.search.annotation.EnableSearchClient; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +/** + * @author 作者 lsl E-mail: 1272745473@qq.com + */ +@EnableDiscoveryClient +@EnableSearchClient +@EnableTransactionManagement +@EnableFeignInterceptor +@SpringBootApplication +public class EduCenterApp { + public static void main(String[] args) { + SpringApplication.run(EduCenterApp.class, args); + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/config/AliyunImsConfig.java b/zlt-business/edu-center/src/main/java/com/central/order/config/AliyunImsConfig.java new file mode 100644 index 00000000..b7faf27c --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/config/AliyunImsConfig.java @@ -0,0 +1,42 @@ +package com.central.order.config; + +import com.aliyun.auth.credentials.Credential; +import com.aliyun.auth.credentials.provider.StaticCredentialProvider; +import com.aliyun.sdk.service.ice20201109.AsyncClient; +import darabonba.core.client.ClientOverrideConfiguration; +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Data +@Configuration +@ConfigurationProperties(prefix = "aliyun.ims") +public class AliyunImsConfig { + private String endpoint; // ice.cn-beijing.aliyuncs.com + private String ossEndpoint; // oss-cn-beijing.aliyuncs.com + private String accessKeyId; + private String accessKeySecret; + private String region; // cn-beijing + private String bucket; // goflyapp + private String callbackUrl; + + @Bean + public AsyncClient imsClient() { + // 配置凭证 + StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder() + .accessKeyId(accessKeyId) + .accessKeySecret(accessKeySecret) + .build()); + + // 配置客户端 + return AsyncClient.builder() + .region(region) + .credentialsProvider(provider) + .overrideConfiguration( + ClientOverrideConfiguration.create() + .setEndpointOverride(endpoint) + ) + .build(); + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/config/AsyncConfig.java b/zlt-business/edu-center/src/main/java/com/central/order/config/AsyncConfig.java new file mode 100644 index 00000000..b21b4534 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/config/AsyncConfig.java @@ -0,0 +1,31 @@ +package com.central.order.config; + +import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; +import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.annotation.AsyncConfigurer; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; + +import java.util.concurrent.Executor; + +@Configuration +@EnableAsync +public class AsyncConfig implements AsyncConfigurer { + + @Override + public Executor getAsyncExecutor() { + ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); + executor.setCorePoolSize(5); + executor.setMaxPoolSize(10); + executor.setQueueCapacity(25); + executor.setThreadNamePrefix("message-async-"); + executor.initialize(); + return executor; + } + + @Override + public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { + return new SimpleAsyncUncaughtExceptionHandler(); + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/config/ProfitSharingProperties.java b/zlt-business/edu-center/src/main/java/com/central/order/config/ProfitSharingProperties.java new file mode 100644 index 00000000..7757afdc --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/config/ProfitSharingProperties.java @@ -0,0 +1,58 @@ +package com.central.order.config; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +@ConfigurationProperties(prefix = "wechat.pay.profit-sharing") +@Component +public class ProfitSharingProperties { + /** + * 是否启用分账功能 + */ + @Builder.Default + private boolean enabled = true; + + /** + * 最大重试次数 + */ + @Builder.Default + private int maxRetryTimes = 3; + + /** + * 重试间隔(毫秒) + */ + @Builder.Default + private long retryInterval = 300000; // 5分钟 + + /** + * 平台分账比例(%) + */ + @Builder.Default + private String platformRate = "30"; + + /** + * 分账超时时间(毫秒) + */ + @Builder.Default + private long timeout = 1800000; // 30分钟 + + /** + * 是否启用异步处理 + */ + @Builder.Default + private boolean asyncEnabled = true; + + /** + * 异步处理线程池大小 + */ + @Builder.Default + private int asyncPoolSize = 5; +} \ No newline at end of file diff --git a/zlt-business/edu-center/src/main/java/com/central/order/config/TencentPayConfiguration.java b/zlt-business/edu-center/src/main/java/com/central/order/config/TencentPayConfiguration.java new file mode 100644 index 00000000..fd7c3105 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/config/TencentPayConfiguration.java @@ -0,0 +1,145 @@ +package com.central.order.config; + +import com.wechat.pay.java.core.Config; +import com.wechat.pay.java.core.RSAAutoCertificateConfig; +import com.wechat.pay.java.core.notification.NotificationConfig; +import com.wechat.pay.java.core.notification.NotificationParser; +import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension; +import com.wechat.pay.java.service.payments.jsapi.model.SettleInfo; +import com.wechat.pay.java.service.profitsharing.ProfitsharingService; +import com.wechat.pay.java.service.refund.RefundService; +import lombok.Getter; +import lombok.Setter; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; +import org.springframework.beans.factory.annotation.Qualifier; + +import java.util.concurrent.Executor; +import java.util.concurrent.ThreadPoolExecutor; + +/** + * 支付配置类 + * + * @author lsl + * @date 2025-01-14 + * + */ +@Getter +@Setter +@Configuration +@ConfigurationProperties(prefix = "tencent") +@EnableConfigurationProperties(ProfitSharingProperties.class) +public class TencentPayConfiguration { + + private String merchantId; + + private String merchantSerialNumber; + + private String apiV3Key; + + private String privateKeyPath; + + private String appId; + + private String appSecret; + + private String notifyUrl; + + /** + * jsapi支付方式 支持小程序公众号支付 + * @return + */ + @Bean + public JsapiServiceExtension initialJsapiServiceExtension() { + // 构建service + return new JsapiServiceExtension.Builder().config(getConfig()).build(); + } + + @Bean + public RefundService initialRefundService() { + // 构建service + return new RefundService.Builder().config(getConfig()).build(); + } + + /** + * 微信支付配置获取 + * @return + */ + public Config getConfig() { + return new RSAAutoCertificateConfig.Builder() + .merchantId(merchantId) + .privateKeyFromPath(privateKeyPath) + .merchantSerialNumber(merchantSerialNumber) + .apiV3Key(apiV3Key) + .build(); + } + + + @Bean + public NotificationConfig initialNotificationConfig() { + // . 如果你仍在使用微信支付平台证书,则使用 RSAAutoCertificateConfig + return new RSAAutoCertificateConfig.Builder() + .merchantId(merchantId) + .privateKeyFromPath(privateKeyPath) + .merchantSerialNumber(merchantSerialNumber) + .apiV3Key(apiV3Key) + .build(); + } + + @Bean + public TencentPayProperties initTencentPayProperties() { + TencentPayProperties tencentPayProperties = new TencentPayProperties(); + tencentPayProperties.setApiV3Key(apiV3Key); + tencentPayProperties.setMerchantId(merchantId); + tencentPayProperties.setMerchantSerialNumber(merchantSerialNumber); + tencentPayProperties.setAppId(appId); + tencentPayProperties.setAppSecret(appSecret); + tencentPayProperties.setNotifyUrl(notifyUrl); + return tencentPayProperties; + } + + @Value("${wechat.pay.profit-sharing.enabled:true}") + private boolean profitSharingEnabled; + + @Bean + public SettleInfo defaultSettleInfo() { + SettleInfo settleInfo = new SettleInfo(); + settleInfo.setProfitSharing(profitSharingEnabled); + return settleInfo; + } + + @Bean + public NotificationParser notificationParser(NotificationConfig config) { + return new NotificationParser(config); + } + + @Bean + public ProfitsharingService profitsharingService() { + // 使用已有的配置方法 + Config config = getConfig(); + return new ProfitsharingService.Builder() + .config(config) + .build(); + } + + @Bean + public Executor profitSharingExecutor(@Qualifier("wechat.pay.profit-sharing-com.central.order.config.ProfitSharingProperties") + ProfitSharingProperties properties) { + if (!properties.isAsyncEnabled()) { + return null; + } + + ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); + executor.setCorePoolSize(properties.getAsyncPoolSize()); + executor.setMaxPoolSize(properties.getAsyncPoolSize()); + executor.setQueueCapacity(100); + executor.setThreadNamePrefix("profit-sharing-"); + executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); + executor.initialize(); + return executor; + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/config/TencentPayProperties.java b/zlt-business/edu-center/src/main/java/com/central/order/config/TencentPayProperties.java new file mode 100644 index 00000000..61b449fe --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/config/TencentPayProperties.java @@ -0,0 +1,25 @@ +package com.central.order.config; + + +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class TencentPayProperties { + + private String merchantId; + + private String merchantSerialNumber; + + private String apiV3Key; + + private String privateKeyPath; + + private String appId; + + private String appSecret; + + private String notifyUrl; + +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/config/WxMaProperties.java b/zlt-business/edu-center/src/main/java/com/central/order/config/WxMaProperties.java new file mode 100644 index 00000000..66b79b90 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/config/WxMaProperties.java @@ -0,0 +1,9 @@ +package com.central.order.config; + +import lombok.Data; + +@Data +public class WxMaProperties { + private String appId; + private String secret; +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/config/WxMpConfiguration.java b/zlt-business/edu-center/src/main/java/com/central/order/config/WxMpConfiguration.java new file mode 100644 index 00000000..a5d9d1b4 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/config/WxMpConfiguration.java @@ -0,0 +1,68 @@ +package com.central.order.config; + +import cn.binarywang.wx.miniapp.api.WxMaService; +import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl; +import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl; +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.RequiredArgsConstructor; +import me.chanjar.weixin.mp.api.WxMpService; +import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl; +import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.converter.StringHttpMessageConverter; +import org.springframework.web.client.RestTemplate; + +import java.nio.charset.StandardCharsets; + +@Configuration +@RequiredArgsConstructor +public class WxMpConfiguration { + + @Bean + @ConfigurationProperties(prefix = "wx.mp") + public WxMpProperties wxMpProperties() { + return new WxMpProperties(); + } + + @Bean + public WxMpService wxMpService(WxMpProperties wxMpProperties) { + WxMpService service = new WxMpServiceImpl(); + WxMpDefaultConfigImpl config = new WxMpDefaultConfigImpl(); + + config.setAppId(wxMpProperties.getAppId()); + config.setSecret(wxMpProperties.getSecret()); + + service.setWxMpConfigStorage(config); + return service; + } + + @Bean + public RestTemplate restTemplate() { + RestTemplate restTemplate = new RestTemplate(); + restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8)); + return restTemplate; + } + + @Bean + public ObjectMapper objectMapper() { + return new ObjectMapper(); + } + + @Bean + @ConfigurationProperties(prefix = "wx.mini") + public WxMaProperties wxMaProperties() { + return new WxMaProperties(); + } + + @Bean + public WxMaService wxMaService(WxMaProperties wxMaProperties) { + WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl(); + config.setAppid(wxMaProperties.getAppId()); + config.setSecret(wxMaProperties.getSecret()); + WxMaService service = new WxMaServiceImpl(); + service.setWxMaConfig(config); + return service; + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/config/WxMpProperties.java b/zlt-business/edu-center/src/main/java/com/central/order/config/WxMpProperties.java new file mode 100644 index 00000000..b0b53fb0 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/config/WxMpProperties.java @@ -0,0 +1,54 @@ +package com.central.order.config; + +import lombok.Data; + +@Data +public class WxMpProperties { + /** + * 设置微信公众号的appid + */ + private String appId; + + /** + * 设置微信公众号的app secret + */ + private String secret; + + /** + * 设置云托管环境ID + */ + private String cloudEnv; + + /** + * 设置服务基础URL + */ + private String baseUrl; + + /** + * 模板ID配置 + */ + private TemplateConfig templateId = new TemplateConfig(); + + @Data + public static class TemplateConfig { + /** + * 支付成功通知模板ID + * 模板内容: + * 服务名称:{{thing2.DATA}} + * 出行时间:{{time3.DATA}} + * 订单号:{{character_string1.DATA}} + * 支付金额:{{amount4.DATA}} + */ + private String paymentSuccess; + + /** + * 视频处理完成通知模板ID + */ + private String videoComplete; + + /** + * 视频处理失败通知模板ID + */ + private String videoFail; + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/constants/EditTaskStatus.java b/zlt-business/edu-center/src/main/java/com/central/order/constants/EditTaskStatus.java new file mode 100644 index 00000000..afd51433 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/constants/EditTaskStatus.java @@ -0,0 +1,53 @@ +package com.central.order.constants; + +/** + * 编辑任务状态常量 + */ +public interface EditTaskStatus { + /** + * 待处理 + */ + int PENDING = 0; + + /** + * 处理中 + */ + int PROCESSING = 1; + + /** + * 处理完成 + */ + int COMPLETED = 2; + + /** + * 处理失败 + */ + int FAILED = 3; + + /** + * 判断是否为处理中状态 + */ + static boolean isProcessing(Integer status) { + return PROCESSING == status; + } + + /** + * 判断是否为完成状态 + */ + static boolean isCompleted(Integer status) { + return COMPLETED == status; + } + + /** + * 获取状态描述 + */ + static String getStatusDesc(Integer status) { + switch (status) { + case PENDING: return "待处理"; + case PROCESSING: return "处理中"; + case COMPLETED: return "已完成"; + case FAILED: return "失败"; + default: return "未知状态"; + } + } +} \ No newline at end of file diff --git a/zlt-business/edu-center/src/main/java/com/central/order/constants/OrderStatusConstants.java b/zlt-business/edu-center/src/main/java/com/central/order/constants/OrderStatusConstants.java new file mode 100644 index 00000000..f30536ee --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/constants/OrderStatusConstants.java @@ -0,0 +1,21 @@ +package com.central.order.constants; + +import com.central.order.enums.OrderStatus; + +public class OrderStatusConstants { + + // 已支付状态集合(已支付排队中、正在服务中、设备执行完成、素材上传中、素材上传完成) + public static final String PAID_STATUS = String.format("(%d,%d,%d,%d,%d)", + OrderStatus.PAID.getId(), // 1-已支付排队中 + OrderStatus.DOING.getId(), // 4-正在服务中 + OrderStatus.COMPLETE.getId(), // 3-设备执行完成 + OrderStatus.UPLOADING.getId(), // 5-素材上传中 + OrderStatus.UPLOADED.getId() // 6-素材上传完成 + ); + + // 退款状态集合(退款中、已退款) + public static final String REFUND_STATUS = String.format("(%d,%d)", + OrderStatus.REFUNDING.getId(), // 7-退款中 + OrderStatus.REFUNDED.getId() // 8-已退款 + ); +} \ No newline at end of file diff --git a/zlt-business/edu-center/src/main/java/com/central/order/constants/ProfitSharingConstants.java b/zlt-business/edu-center/src/main/java/com/central/order/constants/ProfitSharingConstants.java new file mode 100644 index 00000000..4eee7ccb --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/constants/ProfitSharingConstants.java @@ -0,0 +1,16 @@ +package com.central.order.constants; + +public interface ProfitSharingConstants { + String PROFIT_SHARING_PREFIX = "PS"; + String PROFIT_SHARING_DESC = "二维码分账"; + + int MAX_RETRY_TIMES = 3; + long RETRY_INTERVAL = 300000; // 5分钟 + + interface Status { + int INIT = 0; + int PROCESSING = 1; + int SUCCESS = 2; + int FAILED = 3; + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/constants/WxConstants.java b/zlt-business/edu-center/src/main/java/com/central/order/constants/WxConstants.java new file mode 100644 index 00000000..a9cd7e76 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/constants/WxConstants.java @@ -0,0 +1,35 @@ +package com.central.order.constants; + + +public class WxConstants { + /** + * Redis key前缀 + */ + public static final String REDIS_KEY_PREFIX = "wx:"; + + /** + * access_token相关 + */ + public static class AccessToken { + public static final String CACHE_KEY = REDIS_KEY_PREFIX + "access_token"; + public static final String LOCK_KEY = REDIS_KEY_PREFIX + "access_token:lock"; + public static final long EXPIRE_TIME = 7000; // 7000秒 + public static final long REFRESH_TIME = 5400000; // 1.5小时 + } + + /** + * 模板消息相关 + */ + public static class Template { + public static final String API_SEND = "https://api.weixin.qq.com/cgi-bin/message/template/send"; + public static final String API_GET_LIST = "https://api.weixin.qq.com/cgi-bin/template/get_all_private_template"; + public static final String API_DELETE = "https://api.weixin.qq.com/cgi-bin/template/del_private_template"; + } + + /** + * 微信接口相关 + */ + public static class Api { + public static final String ACCESS_TOKEN = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s"; + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/controller/AutoCutVideoController.java b/zlt-business/edu-center/src/main/java/com/central/order/controller/AutoCutVideoController.java new file mode 100644 index 00000000..b6ed639d --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/controller/AutoCutVideoController.java @@ -0,0 +1,266 @@ +package com.central.order.controller; + +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.common.model.SysUser; +import com.central.order.constants.EditTaskStatus; +import com.central.order.enums.OrderStatus; +import com.central.order.feign.UserCenterService; +import com.central.order.model.*; +import com.central.order.model.dto.CallbackDTO; +import com.central.order.model.params.EditTaskQueryParams; +import com.central.order.service.*; +import com.central.order.util.DateUtils; +import com.central.order.util.StringUtils; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * 一键成片 + * + */ +@Slf4j +@RestController +@Tag(name = "剪辑管理") +@RequestMapping("/auto/cut") +@RequiredArgsConstructor +public class AutoCutVideoController { + + @Autowired + private IOrderService orderService; + @Autowired + private IEditTaskService editTaskService; + @Autowired + private IOrderFileService orderFileService; + @Autowired + private IVideoEditService videoEditService; + @Autowired + private IQrCodeService qrCodeService; + @Autowired + private WxMiniSubscribeService wxMiniSubscribeService; + + @Autowired + private UserCenterService userCenterService; + + @Autowired + private ITourismService tourismService; + + @Operation(summary = "根据订单号生成视频") + @PostMapping("/generate") + public Result generateVideo(@RequestParam String orderNo) { + try { + // 1. 验证订单状态 + Order order = orderService.getOrderByNumber(orderNo); + if (order == null || !OrderStatus.isValidForEdit(order.getOrderStatus())) { + return Result.failed("订单状态不允许生成视频"); + } + + // 1. 检查是否开启一键成片 + QrCode qrCode = qrCodeService.getByCodeId(order.getCodeId()); + if (!isVideoEditEnabled(qrCode)) { + log.info("未开启一键成片功能: orderNo={}, codeId={}", + order.getOrderNo(), order.getCodeId()); + return Result.failed("未开启一键成片功能"); + } + + // 2. 检查是否存在进行中的任务 + EditTask existingTask = editTaskService.getTaskByOrderSn(orderNo); + if (existingTask != null && EditTaskStatus.isProcessing(existingTask.getStatus())) { + return Result.failed("已存在进行中的编辑任务"); + } + + // 3. 创建新任务 + EditTask task = editTaskService.createTask(orderNo, order.getUserId()); + + // 4. 获取素材文件 + List orderFiles = orderFileService.getOrderFileByOrderNo(orderNo); + + // 5. 提交编辑任务 + String jobId = videoEditService.submitEditTask(orderNo, orderFiles); + + // 6. 更新任务信息 + task.setJobId(jobId); + task.setStatus(EditTaskStatus.PROCESSING); + editTaskService.saveOrUpdateTask(task); + + return Result.succeed(jobId); + + } catch (Exception e) { + log.error("提交视频编辑任务失败: orderNo={}", orderNo, e); + return Result.failed("提交任务失败:" + e.getMessage()); + } + } + + @Operation(summary = "智能剪辑回调接口") + @PostMapping("/callback") + public Result handleCallback(@RequestBody CallbackDTO callback) { + log.info("收到视频编辑回调: {}", callback); + try { + // 1. 验证回调信息 + if (!isValidCallback(callback)) { + return Result.failed("无效的回调信息"); + } + + // 2. 获取任务信息 + EditTask task = editTaskService.getTaskByJobId(callback.getJobId()); + if (task == null) { + return Result.failed("未找到对应的任务"); + } + + // 3. 处理成功回调 + if ("Success".equals(callback.getStatus())) { + // 更新任务状态 + editTaskService.updateTaskStatus( + callback.getJobId(), + EditTaskStatus.COMPLETED, + callback.getResult() + ); + + // 发送通知 + notifyUser(task.getUserId().toString(), task.getOrderSn()); + } + // 4. 处理失败回调 + else { + editTaskService.updateTaskStatus( + callback.getJobId(), + EditTaskStatus.FAILED, + callback.getErrorMessage() + ); + + // 记录错误日志 + log.error("视频编辑失败: jobId={}, error={}", + callback.getJobId(), callback.getErrorMessage()); + } + + return Result.succeed("回调处理成功"); + + } catch (Exception e) { + log.error("处理视频编辑回调失败", e); + return Result.failed("处理回调失败:" + e.getMessage()); + } + } + + @Operation(summary = "获取任务状态") + @GetMapping("/task/status/{orderNo}") + public Result getTaskStatus(@PathVariable String orderNo) { + try { + EditTask task = editTaskService.getTaskByOrderSn(orderNo); + if (task == null) { + return Result.failed("未找到任务记录"); + } + return Result.succeed(task); + } catch (Exception e) { + log.error("获取任务状态失败", e); + return Result.failed("获取任务状态失败:" + e.getMessage()); + } + } + + + private boolean isValidCallback(CallbackDTO callback) { + // Implementation of isValidCallback method + return false; // Placeholder return, actual implementation needed + } + + private void notifyUser(String userId,String orderNo) { + try { + // 1. 获取用户信息 + SysUser user = userCenterService.findUserById(Long.valueOf(userId)); + if (user == null || user.getOpenId() == null) { + log.warn("未找到用户或用户未绑定小程序openId,无法发送成片完成通知: userId={}", userId); + return; + } + + // 2. 获取任务和订单信息 + // 假设 message 里包含订单号或任务名,实际可根据 EditTask 查找 + Order order = orderService.getOrderByNumber(orderNo); + if (order == null) { + log.warn("未找到订单信息,无法发送成片完成通知: orderNo={}", orderNo); + return; + } + + Tourism tourism = tourismService.getTourismById(order.getTourismId()); + String result = "视频已生成请查阅"; + + wxMiniSubscribeService.sendPaySuccessMsg( + user.getOpenId(), + tourism.getTourismName(), + orderNo, + result, + StringUtils.fenToYuan(order.getOrderAmount()), + DateUtils.sdf.format(order.getPayTime()) + ); + log.info("已发送一键成片完成通知: userId={}, openId={}, orderNo={}", userId, user.getOpenId(), orderNo); + } catch (Exception e) { + log.error("发送一键成片完成通知失败: userId={}, message={}", userId, orderNo, e); + } + } + + + @Operation(summary = "获取剪辑任务列表") + @GetMapping("/list") + public Result> getTaskList( + @RequestParam(defaultValue = "1") Integer page, + @RequestParam(defaultValue = "10") Integer limit, + @RequestParam(required = false) String orderSn, + @RequestParam(required = false) String jobId, + @RequestParam(required = false) Integer status) { + try { + EditTaskQueryParams params = EditTaskQueryParams.builder() + .page(page) + .limit(limit) + .orderSn(orderSn) + .jobId(jobId) + .status(status) + .build(); + + PageResult result = editTaskService.getTaskList(params); + return Result.succeed(result); + + } catch (Exception e) { + log.error("查询剪辑任务列表失败", e); + return Result.failed("查询任务列表失败"); + } + } + + @Operation(summary = "保存或更新剪辑任务") + @PostMapping("/save") + public Result saveOrUpdateTask(@RequestBody EditTask task) { + try { + boolean success = editTaskService.saveOrUpdateTask(task); + return Result.succeed(success); + + } catch (Exception e) { + log.error("保存剪辑任务失败: task={}", task, e); + return Result.failed("保存任务失败: " + e.getMessage()); + } + } + + @Operation(summary = "删除剪辑任务") + @DeleteMapping("/delete/{id}") + public Result deleteTask(@PathVariable Integer id) { + try { + boolean success = editTaskService.deleteTask(id); + return Result.succeed(success); + + } catch (Exception e) { + log.error("删除剪辑任务失败: id={}", id, e); + return Result.failed("删除任务失败: " + e.getMessage()); + } + } + + /** + * 检查是否开启一键成片功能 + */ + private boolean isVideoEditEnabled(QrCode qrCode) { + return qrCode != null + && qrCode.getEnableVideoEdit() != null + && qrCode.getEnableVideoEdit() == 1 + && qrCode.getTemplateId() != null; // 确保有模板ID + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/controller/DashboardController.java b/zlt-business/edu-center/src/main/java/com/central/order/controller/DashboardController.java new file mode 100644 index 00000000..600e4a66 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/controller/DashboardController.java @@ -0,0 +1,34 @@ +package com.central.order.controller; + +import com.central.common.model.Result; +import com.central.order.model.vo.DashboardStatisticsVO; +import com.central.order.service.IDashboardService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@Slf4j +@RestController +@RequestMapping("/dashboard") +@Tag(name = "首页统计", description = "首页统计数据接口") +@RequiredArgsConstructor +public class DashboardController { + + private final IDashboardService dashboardService; + + @Operation(summary = "获取首页统计数据") + @GetMapping("/statistics") + public Result getStatistics() { + try { + DashboardStatisticsVO statistics = dashboardService.getDashboardStatistics(); + return Result.succeed(statistics, "获取首页统计数据成功"); + } catch (Exception e) { + log.error("获取首页统计数据失败", e); + return Result.failed("获取统计数据失败:" + e.getMessage()); + } + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/controller/HomeCarouselController.java b/zlt-business/edu-center/src/main/java/com/central/order/controller/HomeCarouselController.java new file mode 100644 index 00000000..34194594 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/controller/HomeCarouselController.java @@ -0,0 +1,90 @@ +package com.central.order.controller; + +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.order.feign.FileCenterService; +import com.central.order.model.HomeCarousel; +import com.central.order.service.IHomeCarouselService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +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; + +/** + * HomeCarousel information + * + * @author lsl + * @date 2025-2-19 17:51:47 + */ +@Slf4j +@RestController +@Tag(name = "HomeCarousel管理") +@RequestMapping("/home/carousel") +@RequiredArgsConstructor +public class HomeCarouselController { + + @Autowired + private IHomeCarouselService homeCarouselService; + + @Autowired + private FileCenterService fileCenterService; + + /** + * 列表 + */ + @Operation(summary = "查询列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping + public PageResult list(@RequestParam Map params) { + PageResult pageResult = homeCarouselService.findList(params); + if (pageResult.getCount()>0){ + for (HomeCarousel homeCarousel: pageResult.getData()){ + homeCarousel.setImageUrl(fileCenterService.getViewUrlByPath(homeCarousel.getImageUrl())); + } + } + return pageResult; + } + + @GetMapping("/app") + public Result> homeList() { + List list = homeCarouselService.list(); + if (!list.isEmpty()){ + for (HomeCarousel homeCarousel: list){ + homeCarousel.setImageUrl(fileCenterService.getViewUrlByPath(homeCarousel.getImageUrl())); + } + } + return Result.succeed(list,"获取成功"); + } + + @PostMapping() + public Result saveOrUpdate(@RequestBody HomeCarousel homeCarousel) { + return homeCarouselService.saveOrUpdateHomeCarousel(homeCarousel); + } + + @Operation(summary = "查询HomeCarousel") + @GetMapping("/{id}") + public Result getHomeCarousel(@PathVariable("id") Long id) { + HomeCarousel homeCarousel = homeCarouselService.getById(id); + if (homeCarousel == null) { + return Result.failed("暂无数据"); + } + return Result.succeed(homeCarousel,"获取成功"); + } + + @DeleteMapping("/{id}") + public Result delete(@PathVariable Long id) { + homeCarouselService.removeById(id); + return Result.succeed("操作成功"); + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/controller/MessageController.java b/zlt-business/edu-center/src/main/java/com/central/order/controller/MessageController.java new file mode 100644 index 00000000..c3baaea8 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/controller/MessageController.java @@ -0,0 +1,47 @@ +package com.central.order.controller; + +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.order.model.Message; +import com.central.order.service.IMessageService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.annotation.*; + +import java.util.Map; + +@Slf4j +@RestController +@RequestMapping("/messages") +@Tag(name = "站内信管理") +@RequiredArgsConstructor +public class MessageController { + + private final IMessageService messageService; + + @Operation(summary = "获取消息列表") + @GetMapping + public PageResult getMessages(@RequestParam Map params) { + return messageService.findMessages(params); + } + + @Operation(summary = "标记消息已读") + @PutMapping("/{id}/read") + public Result markAsRead(@PathVariable Long id) { + return messageService.markAsRead(id); + } + + @Operation(summary = "标记所有消息已读") + @PutMapping("/read/all") + public Result markAllAsRead() { + return messageService.markAllAsRead(); + } + + @Operation(summary = "删除消息") + @DeleteMapping("/{id}") + public Result deleteMessage(@PathVariable Long id) { + return messageService.deleteMessage(id); + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/controller/OrderController.java b/zlt-business/edu-center/src/main/java/com/central/order/controller/OrderController.java new file mode 100644 index 00000000..18795f52 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/controller/OrderController.java @@ -0,0 +1,680 @@ +package com.central.order.controller; + +import com.alibaba.csp.sentinel.util.StringUtil; +import com.central.common.constant.CommonConstant; +import com.central.common.context.LoginUserContextHolder; +import com.central.common.context.TenantContextHolder; +import com.central.common.model.LoginAppUser; +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.common.model.SysUser; +import com.central.log.annotation.AuditLog; +import com.central.order.config.TencentPayProperties; +import com.central.order.enums.CommonStatus; +import com.central.order.enums.OrderStatus; +import com.central.order.feign.DeviceCenterService; +import com.central.order.feign.FileCenterService; +import com.central.order.feign.UserCenterService; +import com.central.order.model.*; +import com.central.order.service.*; +import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension; +import com.wechat.pay.java.service.payments.jsapi.model.*; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.util.Assert; +import org.springframework.web.bind.annotation.*; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Order information + * + * @author lsl + * @date 2024-12-19 17:51:47 + */ +@Slf4j +@RestController +@Tag(name = "订单管理") +@RequiredArgsConstructor +public class OrderController { + + //设备执行任务默认时间长度3分钟 + private static final long DEVICE_EXEC_TIME = 4; + + @Autowired + private IOrderService orderService; + + @Autowired + private IOrderFileService orderFileService; + + @Autowired + private ITourismService tourismService; + + @Autowired + private ITourismFileService tourismFileService; + + @Autowired + private UserCenterService userCenterService; + + @Autowired + private FileCenterService fileCenterService; + + @Autowired + private JsapiServiceExtension service; + + @Autowired + private IQrCodeService qrCodeService; + + @Autowired + private TencentPayProperties tencentPayProperties; + + @Value("${file.oss-url}") + private String cdnOssUrl; + + @Value("${file.cdn-url}") + private String cdnUrl; + + @Value("${file.style}") + private String fileStyle; + // 获取当前日期,格式化为 yyyyMMdd + SimpleDateFormat sdf = new SimpleDateFormat(CommonConstant.DATEMINUTE_FORMAT); + + @Autowired + private DeviceCenterService deviceCenterService; + + @Autowired + private IProfitSharingService profitSharingService; + + /** + * 列表 + */ + @Operation(summary = "查询全部列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping("/list") + public PageResult list(@RequestParam Map params) { + return orderService.findList(params); + } + + /** + * 列表 + */ + @Operation(summary = "查询用户订单列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping + public PageResult listByUser(@RequestParam Map params) { + LoginAppUser user = LoginUserContextHolder.getUser(); + if (user == null) { + return new PageResult<>(); + } + params.put("userId", user.getId()); + return orderService.findListByUser(params); + } + + /** + * 列表 + */ + @Operation(summary = "查询用户订单详情列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping("/user") + public PageResult listInfoByUser(@RequestParam Map params) { + LoginAppUser user = LoginUserContextHolder.getUser(); + params.put("userId", user.getId()); + String fileType = MapUtils.getString(params, "fileType"); + if (StringUtil.isBlank(fileType)) { + fileType = "image/jpeg"; + } + + PageResult result = orderService.findListByUser(params); + if (result.getCount() > 0){ + List page = new ArrayList<>(); + Map fileMap = new HashMap<>(); + fileMap.put("style", fileStyle); + for(Order order : result.getData()){ + Map orderFileMap = new HashMap<>(); + orderFileMap.put("time", sdf.format(order.getCreateTime())); + orderFileMap.put("addr", tourismService.getTourismById(order.getTourismId()).getTourismAddress()); + orderFileMap.put("orderNo", order.getOrderNo()); + + List list = orderFileService.getOrderFileByOrderNoAndFileType(order.getOrderNo(),fileType); + List> resultList = new ArrayList<>(); + if (!list.isEmpty()){ + for (OrderFile orderFile : list){ + Map imgMap = new HashMap<>(); + String url = fileCenterService.getViewUrlByPath(orderFile.getFilePath()); + imgMap.put("url", url.replace(cdnOssUrl,cdnUrl)); + imgMap.put("contentType", orderFile.getFileType()); + fileMap.put("path",orderFile.getFilePath()); + imgMap.put("viewUrl", fileCenterService.getViewUrlByPathStyle(fileMap)); + resultList.add(imgMap); + } + } + orderFileMap.put("imgList", resultList); + page.add(orderFileMap); + } + return PageResult.builder().data(page).resp_code(0).count(result.getCount()).build(); + } + return new PageResult<>(); + } + + + // 创建订单--》 + // 返回前端订单信息--》 + // 前端发起支付(PUT api-order/{id}/pay)--》 + // 等待回调更新订单状态(微信支付回调接口/api-order/pay/notify)--》 + // 同时创建支付记录(/api-order/payment) + // 前端进入排队队列中(/api-order/queue)已支付订单列表 + // 设备执行完成后更新订单状态已完成(根据设备上报状态触发或者设备直接调用接口进行更新任务状态) + @Operation(summary = "创建订单") + @PostMapping + public Result createOrder(@RequestBody Order order) { + + LoginAppUser user = LoginUserContextHolder.getUser(); + + order.setUserId(user.getId()); + order.setTenantId(TenantContextHolder.getTenant()); + + List userOrderList = orderService.getOrderCountByStatusAndUser(user.getId(),OrderStatus.PAID.getId()); + if (!userOrderList.isEmpty()){ + return Result.succeed("已存在订单"); + } + + QrCode qrCode = qrCodeService.getByCodeId(order.getCodeId()); + if (qrCode != null){ + if (qrCode.getStatus().equals(CommonStatus.UNABLE.getId())){ + return Result.failed("该二维码已过期"); + } + //设置订单所属tenantId + TenantContextHolder.setTenant(qrCode.getTenantId()); + order.setTourismId(qrCode.getTourismId()); + order.setDeviceSn(qrCode.getDeviceSn()); + order.setOrderAmount(qrCode.getPrice()); + }else { + Assert.notNull(qrCode,"二维码不存在"); + } + boolean result = orderService.createOrder(order); + if (result) { + return Result.succeed(order,"订单创建成功"); + } else { + return Result.failed("订单创建失败"); + } + } + + + /** + * 公众号小程序支付 + * + * @param orderId 微信公众号对应微信付款用户的唯一标识 + * @return 返回jsapi所需参数 + */ + + @Operation(summary = "生成预支付订单") + @PutMapping("/{orderId}/pay") + public Result payOrder(@PathVariable("orderId") Long orderId) { + try { + // 1. 获取用户和订单信息 + SysUser user = userCenterService.findUserById(LoginUserContextHolder.getUser().getId()); + Order order = orderService.getById(orderId); + if (order == null) { + return Result.failed("订单数据不存在"); + } + + // 检查是否需要开启分账 + QrCode qrCode = qrCodeService.getByCodeId(order.getCodeId()); + if (qrCode == null) { + return Result.failed("二维码不存在"); + } + + // 3. 创建支付请求 + PrepayRequest request = new PrepayRequest(); + + // 设置基本支付信息 + Amount amount = new Amount(); + amount.setTotal(Integer.parseInt(order.getOrderAmount())); + request.setAmount(amount); + request.setAppid(tencentPayProperties.getAppId()); + request.setMchid(tencentPayProperties.getMerchantId()); + request.setDescription(order.getOrderNo()); + request.setNotifyUrl(tencentPayProperties.getNotifyUrl()); + request.setOutTradeNo(order.getOrderNo()); + + // 设置支付者信息 + Payer payer = new Payer(); + payer.setOpenid(user.getOpenId()); + request.setPayer(payer); + + // 设置分账信息 + SettleInfo settleInfo = new SettleInfo(); + if (isEnableProfit(qrCode)) { + settleInfo.setProfitSharing(true); + request.setSettleInfo(settleInfo); + + // 创建分账记录 + ProfitSharing profitSharing = profitSharingService.createProfitSharing(order,qrCode); + } else { + settleInfo.setProfitSharing(false); + request.setSettleInfo(settleInfo); + } + + // 5. 调用支付接口 + PrepayWithRequestPaymentResponse response = service.prepayWithRequestPayment(request); + + // 6. 返回结果 + return Result.succeed(response, order.getOrderNo()); + } catch (Exception e) { + log.error("创建预支付订单失败", e); + return Result.failed("创建预支付订单失败:" + e.getMessage()); + } + } + + /** + * 检查是否开启分润 + */ + private boolean isEnableProfit(QrCode qrCode) { + return qrCode != null && + Integer.valueOf(1).equals(qrCode.getEnableProfit()) && + qrCode.getPayeeStatus() != null && + qrCode.getPayeeStatus() == 1 && // 确保分账账号已验证 + qrCode.getPayeeAccount() != null && // 确保有收款账号 + qrCode.getProfitRate() != null; // 确保有分润比例 + } + + @Operation(summary = "获取排队总览信息") + @GetMapping("/queue/info") + public Result getQueueInfo(@RequestParam String codeId) { + LoginAppUser user = LoginUserContextHolder.getUser(); + QrCode qrCode = qrCodeService.getByCodeId(codeId); + Assert.notNull(qrCode,"二维码CODEID不能为空"); + Order order = orderService.getOrderByStatusAndUser(OrderStatus.PAID.getId(), user.getId(),qrCode.getTourismId()); + Map map = new HashMap<>(); + map.put("price",appendPriceStr(qrCode.getPrice())); + //如果用户存在已支付订单,则查询当前排在第几 + if (order != null){ + Integer count = orderService.getOrderRankingByOrderId(order.getId(),qrCode.getTourismId()); + map.put("count", count == 1 ? -1 : count-1 ); + map.put("time",Math.multiplyExact((count-1),DEVICE_EXEC_TIME)); + }else { + Long count = orderService.getOrderCountByStatus(OrderStatus.PAID.getId(),qrCode.getTourismId()); + map.put("count", count == 0 ? -1 : count); + map.put("time",Math.multiplyExact(count,DEVICE_EXEC_TIME)); + } + return Result.succeed(map,"获取成功"); + } + + @Operation(summary = "获取订单排队总览信息") + @GetMapping("/queue/info/{orderNo}") + public Result getQueueInfoByOrderNo(@PathVariable("orderNo") String orderNo) { + + Order order = orderService.getOrderByNumber(orderNo); + Assert.notNull(order,"订单数据不能为空"); + QrCode qrCode = qrCodeService.getByCodeId(order.getCodeId()); + Map map = new HashMap<>(); + map.put("price",appendPriceStr(qrCode.getPrice())); + Integer count = orderService.getOrderRankingByOrderId(order.getId(),qrCode.getTourismId()); + map.put("count", count == 1 ? -1 : count-1 ); + map.put("time",Math.multiplyExact((count-1),DEVICE_EXEC_TIME)); + return Result.succeed(map,"获取成功"); + } + + @Operation(summary = "获取用户是否存在排队订单") + @GetMapping("/queue/info/user") + public Result getOrderInfoByUser() { + LoginAppUser user = LoginUserContextHolder.getUser(); + Map res = new HashMap(); + List orders = orderService.getOrderCountByStatusAndUser(user.getId(),OrderStatus.PAID.getId(),OrderStatus.DOING.getId()); + if(!orders.isEmpty()){ + for (Order order : orders){ + order.setCreatedTime(sdf.format(order.getCreateTime())); + if(order.getOrderStatus().equals(OrderStatus.PAID.getId())){ + res.put("orderNo",order.getOrderNo()); + Integer count = orderService.getOrderRankingByOrderId(order.getId(),order.getTourismId()); + res.put("orderStatus",order.getOrderStatus()); + res.put("waitCount", count == 1 ? -1 : count-1 ); + res.put("waitTime",Math.multiplyExact((count-1),DEVICE_EXEC_TIME)); + res.put("createdTime",sdf.format(order.getCreateTime())); + } + if (order.getOrderStatus().equals(OrderStatus.DOING.getId())){ + res.put("orderNo",order.getOrderNo()); + res.put("createdTime",sdf.format(order.getCreateTime())); + res.put("orderStatus",order.getOrderStatus()); + } + } + } + return Result.succeed(res,"获取成功"); + + } + + @Operation(summary = "获取排队中的订单列表") + @GetMapping("/queue") + public Result> getOrdersInQueue() { + List orders = orderService.getOrdersInQueue(); + return Result.succeed(orders,"获取成功"); + } + + // 获取排队中的订单列表 + @Operation(summary = "获取排队中的第一个订单") + @GetMapping("/queue/first") + public Result getOrdersInQueueFirstOne(@RequestParam String deviceSn) { + Assert.notNull(deviceSn,"设备SN不能为空"); + if (orderService.getUnCompleteOrderCount(deviceSn)==0){ + List orders = orderService.getOrdersInQueueByDevice(deviceSn); + if (!orders.isEmpty()){ + Order order = orders.get(0); + QrCode qrCode = qrCodeService.getByCodeId(order.getCodeId()); + Assert.notNull(qrCode,"二维码数据不能为空"); + + // 从二维码中获取航线ID + String waylineId = qrCode.getWaylineId(); + // 根据航线ID获取对应的文件路径 + String waylineFilePath = fileCenterService.getFileViewUrl(waylineId); + Assert.notNull(waylineFilePath,"订单航线数据不能为空"); + + order.setFileMd5(deviceCenterService.getLineFileSign(waylineId)); + order.setWaylineLinkUrl(waylineFilePath); + order.setStreamUrls(deviceCenterService.getStreamUrls(order.getDeviceSn())); + return Result.succeed(order,"获取成功"); + } + } + return Result.failed("未存在排队队列"); + } + + // 处理排队中的订单(模拟消费通知等操作) + @Operation(summary = "通知排队中的订单") + @PutMapping("/queue/process") + public Result processOrdersInQueue() { + orderService.processOrdersInQueue(); + return Result.succeed("排队订单处理已启动"); + } + + @Operation(summary = "更新订单正在服务中状态") + @AuditLog(operation = "'下发任务更新订单正在服务中状态:' + #orderNo") + @PostMapping("/status") + public Result updateOrderStatusDoing(@RequestBody String orderNo) { + Order order = orderService.getOrderByNumber(orderNo); + Assert.notNull(order, "订单数据不能为空"); + if (order.getOrderStatus().equals(OrderStatus.PAID.getId())) { + order.setOrderStatus(OrderStatus.DOING.getId()); + if (orderService.updateOrder(order)) { // 这里会触发事件 + return Result.succeed("更新成功"); + } + } + return Result.failed("未查询到订单数据"); + } + + @Operation(summary = "根据设备状态更新订单正在服务中状态") + @AuditLog(operation = "'下发任务更新订单正在服务中状态:' + #orderNo") + @PutMapping("/device/status") + public Result updateOrderStatusDoingFromDevice(@RequestBody Map payload) { + Order order = orderService.getOrderByNumber(payload.get("orderNo").toString()); + Assert.notNull(order,"订单数据不能为空"); + if (order.getOrderStatus().equals(OrderStatus.PAID.getId())){ + order.setOrderStatus(OrderStatus.DOING.getId()); + if (orderService.updateOrder(order)){ + return Result.succeed("更新成功"); + } + } + return Result.failed("未查询到订单数据"); + } + + @Operation(summary = "机库更新订单完成状态") + @AuditLog(operation = "'机库更新订单完成状态:' + #payload") + @PutMapping("/update") + public Result updateOrderStatusCompleted(@RequestBody Map payload) { + Order order = orderService.getOrderByNumber(payload.get("orderNo").toString()); + Assert.notNull(order,"订单数据不能为空"); + if (order.getOrderStatus().equals(OrderStatus.DOING.getId()) + || order.getOrderStatus().equals(OrderStatus.UPLOADED.getId()) + || order.getOrderStatus().equals(OrderStatus.UPLOADING.getId())){ + order.setOrderStatus(OrderStatus.COMPLETE.getId()); + if (orderService.updateOrder(order)){ + return Result.succeed("更新成功"); + } + }else { + return Result.failed("已更新"); + } + return Result.failed("未查询到订单数据"); + } + + @Operation(summary = "取消订单") + @PutMapping("/{id}") + public Result cancelOrder(@PathVariable("id") Long id) { + Order order = orderService.getById(id); + order.setOrderStatus(OrderStatus.CANCELED.getId()); + boolean res = orderService.updateOrder(order); // 这里会触发事件 + if (res) { + return Result.succeed("已取消"); + } + return Result.failed("请重试"); + } + + @Operation(summary = "后台管理更新订单") + @PostMapping("/update/order") + public Result updateOrder(@RequestBody Order order) { + LoginAppUser loginAppUser = LoginUserContextHolder.getUser(); + if (loginAppUser.getId() == 1){ + boolean res = orderService.updateOrder(order); + if (res){ + return Result.succeed("已更新"); + } + } + + return Result.failed("请重试"); + } + + @Operation(summary = "机库查询订单执行情况") + @AuditLog(operation = "'机库查询订单执行情况:' + #orderNo") + @GetMapping("/status/{orderNo}") + public Result getOrderExecStatus(@PathVariable("orderNo") String orderNo) { + + Order order = orderService.getOrderByNumber(orderNo); + Assert.notNull(order,"订单数据为空"); + if (order.getOrderStatus().equals(OrderStatus.COMPLETE.getId())){ + return Result.failed("已执行"); + }else if (order.getOrderStatus().equals(OrderStatus.PAID.getId())){ + return Result.succeed("待执行"); + } + return Result.failed("不满足执行条件"); + } + + @Operation(summary = "获取订单对应的景区素材") + @GetMapping("/resource/tourism/{orderNo}") + public Result> getTourismByOrder(@PathVariable("orderNo") String orderNo) { + Order order = orderService.getOrderByNumber(orderNo); + Assert.notNull(order,"订单数据不存在"); + List tourismFiles = tourismFileService.getByTourismId(order.getTourismId()); + if (!tourismFiles.isEmpty()){ + for (TourismFile tourismFile : tourismFiles){ + tourismFile.setImageUrl(fileCenterService.getViewUrlByPath(tourismFile.getImageUrl())); + } + } + return Result.succeed(tourismFiles,"获取成功"); + } + + @Operation(summary = "获取订单对应的景区Info") + @GetMapping("/info/tourism/{orderNo}") + public Result getTourismInfoByOrder(@PathVariable("orderNo") String orderNo) { + Order order = orderService.getOrderByNumber(orderNo); + Assert.notNull(order,"订单数据不存在"); + Tourism tourism = tourismService.getTourismById(order.getTourismId()); + return Result.succeed(tourism,"获取成功"); + } + + @Operation(summary = "获取订单的设备") + @GetMapping("/device/{orderNo}") + public Result getDeviceByOrder(@PathVariable("orderNo") String orderNo) { + Order order = orderService.getOrderByNumber(orderNo); + Assert.notNull(order,"订单数据不存在"); + return Result.succeed(order.getDeviceSn(),"获取成功"); + } + + @Operation(summary = "获取订单状态") + @GetMapping("/{orderNo}/status") + public String getOrderStatusByOrderNo(@PathVariable("orderNo") String orderNo) { + Order order = orderService.getOrderByNumber(orderNo); + Assert.notNull(order,"订单数据不存在"); + return order.getOrderStatus().toString(); + } + + @Operation(summary = "获取订单详情") + @GetMapping("/detail/{orderNo}") + public Result> getOrderDetail(@PathVariable("orderNo") String orderNo) { + try { + // 获取订单基本信息 + Order order = orderService.getOrderByNumber(orderNo); + if (order == null) { + return Result.failed("订单不存在"); + } + + // 获取景区信息 + Tourism tourism = tourismService.getTourismById(order.getTourismId()); + if (tourism == null) { + return Result.failed("景区信息不存在"); + } + + // 获取订单文件信息 + List orderFiles = orderFileService.getOrderFileByOrderNo(orderNo); + + // 构建返回数据 + Map detailMap = new HashMap<>(); + // 订单基本信息 + detailMap.put("orderNo", order.getOrderNo()); + detailMap.put("orderStatus", order.getOrderStatus()); + detailMap.put("orderAmount", appendPriceStr(order.getOrderAmount())); + detailMap.put("createTime", sdf.format(order.getCreateTime())); + detailMap.put("deviceSn", order.getDeviceSn()); + detailMap.put("mobile", userCenterService.findUserById(order.getUserId()).getMobile()); + + // 景区信息 + Map tourismMap = new HashMap<>(); + tourismMap.put("tourismName", tourism.getTourismName()); + tourismMap.put("tourismAddress", tourism.getTourismAddress()); + tourismMap.put("tourismDesc", tourism.getTourismDesc()); + detailMap.put("tourism", tourismMap); + + // 订单文件信息 + if (!orderFiles.isEmpty()) { + List> fileList = new ArrayList<>(); + Map fileMap = new HashMap<>(); + fileMap.put("style", fileStyle); + + for (OrderFile orderFile : orderFiles) { + Map fileInfo = new HashMap<>(); + String url = fileCenterService.getViewUrlByPath(orderFile.getFilePath()); + fileInfo.put("url", url.replace(cdnOssUrl, cdnUrl)); + fileInfo.put("contentType", orderFile.getFileType()); + fileMap.put("path", orderFile.getFilePath()); + fileInfo.put("viewUrl", fileCenterService.getViewUrlByPathStyle(fileMap)); + fileList.add(fileInfo); + } + detailMap.put("files", fileList); + } + + // 如果是排队中的订单,添加排队信息 + if (OrderStatus.PAID.getId().equals(order.getOrderStatus())) { + Integer ranking = orderService.getOrderRankingByOrderId(order.getId(), order.getTourismId()); + detailMap.put("queueCount", ranking == 1 ? -1 : ranking - 1); + detailMap.put("estimatedTime", Math.multiplyExact((ranking - 1), DEVICE_EXEC_TIME)); + } + + return Result.succeed(detailMap, "获取成功"); + + } catch (Exception e) { + log.error("获取订单详情失败: orderNo={}", orderNo, e); + return Result.failed("获取订单详情失败"); + } + } + + /** + * 将分的价格转换为元的str,方便前端显示 + * @param str + * @return + */ + private String appendPriceStr(String str){ + // 获取字符串长度 + int length = str.length(); + + // 获取除了最后两位字符之外的部分 + String prefix = str.substring(0, length - 2); + + // 获取最后两位字符 + String lastTwo = str.substring(length - 2); + + // 在最后两位字符前添加小数点 + return prefix + "." + lastTwo; + } + + /** + * 列表 + */ + @Operation(summary = "查询用户订单临时演示") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping("/user/temp") + public PageResult listInfoByUserForTemp(@RequestParam Map params) { + params.put("orderNo", "332025051700001"); + String fileType = MapUtils.getString(params, "fileType"); + if (StringUtil.isBlank(fileType)) { + fileType = "image/jpeg"; + } + + PageResult result = orderService.findList(params); + if (result.getCount() > 0){ + List page = new ArrayList<>(); + Map fileMap = new HashMap<>(); + fileMap.put("style", fileStyle); + for(Order order : result.getData()){ + Map orderFileMap = new HashMap<>(); + orderFileMap.put("time", sdf.format(order.getCreateTime())); + orderFileMap.put("addr", tourismService.getTourismById(order.getTourismId()).getTourismAddress()); + orderFileMap.put("orderNo", order.getOrderNo()); + +// List list = orderFileService.getOrderFileByOrderNoAndFileType(order.getOrderNo(),fileType); + List list = fileCenterService.getListFiles("temp/332025051700001/Remote-Control/"); + List> resultList = new ArrayList<>(); + if (!list.isEmpty()){ + list.remove(0); + for (String orderFile : list){ + Map imgMap = new HashMap<>(); + String url = fileCenterService.getViewUrlByPath(orderFile); + imgMap.put("url", url.replace(cdnOssUrl,cdnUrl)); + if (orderFile.endsWith(".jpeg") || orderFile.endsWith(".png")){ + imgMap.put("contentType", "image/jpeg"); + } + if (orderFile.endsWith(".mp4")){ + imgMap.put("contentType", "video/mp4"); + } + fileMap.put("path",orderFile); + imgMap.put("viewUrl", fileCenterService.getViewUrlByPathStyle(fileMap)); + resultList.add(imgMap); + } + } + orderFileMap.put("imgList", resultList); + page.add(orderFileMap); + } + return PageResult.builder().data(page).resp_code(0).count(result.getCount()).build(); + } + return new PageResult<>(); + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/controller/OrderFileController.java b/zlt-business/edu-center/src/main/java/com/central/order/controller/OrderFileController.java new file mode 100644 index 00000000..34abbe78 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/controller/OrderFileController.java @@ -0,0 +1,187 @@ +package com.central.order.controller; + +import com.central.common.context.LoginUserContextHolder; +import com.central.common.model.FileInfo; +import com.central.common.model.LoginAppUser; +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.order.enums.OrderStatus; +import com.central.order.feign.FileCenterService; +import com.central.order.model.Order; +import com.central.order.model.OrderFile; +import com.central.order.service.IOrderFileService; +import com.central.order.service.IOrderService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.util.CollectionUtils; +import org.springframework.web.bind.annotation.*; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Order Files information + * + * @author lsl + * @date 2024-12-19 17:51:47 + */ +@Slf4j +@RestController +@Tag(name = "任务资源管理") +@RequestMapping("/files") +@RequiredArgsConstructor +public class OrderFileController { + + @Autowired + private IOrderFileService orderFileService; + + @Autowired + private FileCenterService fileCenterService; + + @Autowired + private IOrderService orderService; + + @Value("${file.style}") + private String fileStyle; + + /** + * 列表 + */ + @Operation(summary = "查询列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping + public PageResult list(@RequestParam Map params) { + PageResult pageResult = orderFileService.findList(params); + Map fileMap = new HashMap<>(); + fileMap.put("style", fileStyle); + if (pageResult.getResp_code() == 0){ + for (OrderFile orderFile: pageResult.getData()){ + orderFile.setViewUrl(fileCenterService.getViewUrlByPath(orderFile.getFilePath())); + fileMap.put("path", orderFile.getFilePath()); + orderFile.setZipViewUrl(fileCenterService.getViewUrlByPathStyle(fileMap)); + } + } + return pageResult; + } + + /** + * 列表 + */ + @Operation(summary = "查询用户列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping("/user") + public PageResult listByUser(@RequestParam Map params) { + LoginAppUser user = LoginUserContextHolder.getUser(); + params.put("userId", user.getId()); + return orderFileService.findListByUser(params); + } + + @Operation(summary = "创建订单资源") + @PostMapping + public Result createOrderFile(@RequestBody OrderFile orderFile) { + + LoginAppUser user = LoginUserContextHolder.getUser(); + orderFile.setFileType(fileCenterService.getFileContentType(orderFile.getFileId())); + orderFile.setUserId(user.getId()); + boolean result = orderFileService.createOrderFile(orderFile); + if (result) { + return Result.succeed(orderFile,"文件资源创建成功"); + } else { + return Result.failed("文件资源创建失败"); + } + } + + public Result getOrderFile(@PathVariable("fileId") String fileId) { + OrderFile orderFile = orderFileService.getOrderFileByFileId(fileId); + if (orderFile == null) { + return Result.failed("暂无数据"); + } + return Result.succeed(orderFile,"获取成功"); + } + + @Operation(summary = "查询订单资源列表") + @GetMapping("/order/{orderNo}") + public Result> getOrderFiles(@PathVariable("orderNo") String orderNo) { + List orderFiles = orderFileService.getOrderFileByOrderNo(orderNo); + if (!CollectionUtils.isEmpty(orderFiles)) { + for (OrderFile orderFile : orderFiles) { + String viewUrl = fileCenterService.getFileViewUrl(orderFile.getFileId()); + orderFile.setViewUrl(viewUrl); + } + }else { + return Result.failed("暂无数据"); + } + return Result.succeed(orderFiles); + } + + @Operation(summary = "查询用户订单资源列表") + @GetMapping("/user/{userId}") + public Result> getUserOrderFiles(@PathVariable("userId") Long userId) { + List orderFiles = orderFileService.getOrderFileByUserId(userId); + if (!CollectionUtils.isEmpty(orderFiles)) { + for (OrderFile orderFile : orderFiles) { + String viewUrl = fileCenterService.getFileViewUrl(orderFile.getFileId()); + orderFile.setViewUrl(viewUrl); + } + }else { + return Result.failed("暂无数据"); + } + return null; + } + + @Operation(summary = "设备回传照片path记录创建") + @PostMapping("/path") + public Result createOrderFileForPath(@RequestBody OrderFile orderFile) { + + if (orderFile != null && orderFile.getOrderNo() != null) { + Order order = orderService.getOrderByNumber(orderFile.getOrderNo()); + orderFile.setOrderNo(order.getOrderNo()); + orderFile.setUserId(order.getUserId()); + if (orderFile.getFilePath() != null) { + + FileInfo fileInfo = fileCenterService.creatFileInfo(orderFile.getFilePath()); + orderFile.setFileId(fileInfo.getId()); + orderFile.setFilePath(fileInfo.getPath()); + orderFile.setFileType(fileInfo.getContentType()); + orderFile.setTourismId(order.getTourismId()); + } + if (orderFileService.save(orderFile)){ + // 机库上报订单素材,更新订单状态为素材上传中,如果订单为设备执行中则更新,否则说明状态已更新 + if (order.getOrderStatus().equals(OrderStatus.DOING.getId()) + || order.getOrderStatus().equals(OrderStatus.PAID.getId())) { + order.setOrderStatus(OrderStatus.UPLOADING.getId()); + orderService.updateOrder(order); + } + return Result.succeed(order,"更新成功"); + } + } + return Result.failed("素材内容为空"); + + } + + @Operation(summary = "删除文件") + @DeleteMapping( "/{id}") + public Result delete(@PathVariable Long id) { + + if (orderFileService.delete(id) > 0){ + return Result.succeed("删除成功"); + } + return Result.failed("删除失败"); + + } + +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/controller/OrderStatisticsController.java b/zlt-business/edu-center/src/main/java/com/central/order/controller/OrderStatisticsController.java new file mode 100644 index 00000000..2af2eeba --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/controller/OrderStatisticsController.java @@ -0,0 +1,102 @@ +package com.central.order.controller; + +import com.central.common.model.Result; +import com.central.order.service.IOrderStatisticsService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.Map; + +@Slf4j +@RestController +@RequestMapping("/statistics") +@Tag(name = "订单统计", description = "订单多维度统计接口") +@RequiredArgsConstructor +public class OrderStatisticsController { + + private final IOrderStatisticsService orderStatisticsService; + + @Operation(summary = "生成统计数据", description = "根据时间范围生成订单统计数据") + @Parameters({ + @Parameter(name = "startTime", description = "开始时间 (格式:yyyy-MM-dd HH:mm:ss)", required = true), + @Parameter(name = "endTime", description = "结束时间 (格式:yyyy-MM-dd HH:mm:ss)", required = true) + }) + @PostMapping("/generate") + public Result generateStatistics( + @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String startTime, + @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String endTime) { + try { + boolean result = orderStatisticsService.generateStatistics(startTime, endTime); + return result ? Result.succeed("统计数据生成成功") : Result.failed("统计数据生成失败"); + } catch (Exception e) { + log.error("生成统计数据失败", e); + return Result.failed("生成统计数据时发生错误:" + e.getMessage()); + } + } + + @Operation(summary = "按时间维度统计", description = "统计指定二维码在时间范围内的订单数据") + @Parameters({ + @Parameter(name = "qrcodeId", description = "二维码ID", required = true), + @Parameter(name = "startTime", description = "开始时间 (格式:yyyy-MM-dd HH:mm:ss)", required = true), + @Parameter(name = "endTime", description = "结束时间 (格式:yyyy-MM-dd HH:mm:ss)", required = true), + @Parameter(name = "timeType", description = "时间维度类型(hour/day/month)", required = false) + }) + @GetMapping("/time") + public Result>> statisticsByTime( + @RequestParam String qrcodeId, + @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String startTime, + @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String endTime, + @RequestParam(defaultValue = "day") String timeType) { + try { + List> result = orderStatisticsService.statisticsByTime( + qrcodeId, startTime, endTime, timeType); + return Result.succeed(result, "获取时间维度统计数据成功"); + } catch (Exception e) { + log.error("获取时间维度统计数据失败", e); + return Result.failed("获取统计数据时发生错误:" + e.getMessage()); + } + } + + @Operation(summary = "按景区维度统计", description = "统计时间范围内各景区的订单数据") + @Parameters({ + @Parameter(name = "startTime", description = "开始时间 (格式:yyyy-MM-dd HH:mm:ss)", required = true), + @Parameter(name = "endTime", description = "结束时间 (格式:yyyy-MM-dd HH:mm:ss)", required = true) + }) + @GetMapping("/tourism") + public Result>> statisticsByTourism( + @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String startTime, + @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String endTime) { + try { + List> result = orderStatisticsService.statisticsByTourism(startTime, endTime); + return Result.succeed(result, "获取景区维度统计数据成功"); + } catch (Exception e) { + log.error("获取景区维度统计数据失败", e); + return Result.failed("获取统计数据时发生错误:" + e.getMessage()); + } + } + + @Operation(summary = "按设备维度统计", description = "统计时间范围内各设备的订单数据") + @Parameters({ + @Parameter(name = "startTime", description = "开始时间 (格式:yyyy-MM-dd HH:mm:ss)", required = true), + @Parameter(name = "endTime", description = "结束时间 (格式:yyyy-MM-dd HH:mm:ss)", required = true) + }) + @GetMapping("/device") + public Result>> statisticsByDevice( + @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String startTime, + @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String endTime) { + try { + List> result = orderStatisticsService.statisticsByDevice(startTime, endTime); + return Result.succeed(result, "获取设备维度统计数据成功"); + } catch (Exception e) { + log.error("获取设备维度统计数据失败", e); + return Result.failed("获取统计数据时发生错误:" + e.getMessage()); + } + } +} \ No newline at end of file diff --git a/zlt-business/edu-center/src/main/java/com/central/order/controller/PaymentRecordController.java b/zlt-business/edu-center/src/main/java/com/central/order/controller/PaymentRecordController.java new file mode 100644 index 00000000..fa229ab0 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/controller/PaymentRecordController.java @@ -0,0 +1,57 @@ +package com.central.order.controller; + +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.order.service.IPaymentRecordService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.Map; + +/** + * Payment information + * + * @author lsl + * @date 2024-12-19 17:51:47 + */ +@Slf4j +@RestController +@Tag(name = "支付记录管理") +@RequestMapping("/payment") +@RequiredArgsConstructor +public class PaymentRecordController { + + @Autowired + private IPaymentRecordService paymentRecordService; + + /** + * 列表 + */ + @Operation(summary = "查询列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping + public PageResult list(@RequestParam Map params) { + return paymentRecordService.findList(params); + } + + // 接收前端传来的订单编号和支付金额,处理订单支付 + @PostMapping + public Result processPayment(@RequestParam String orderNumber, @RequestParam Double paymentAmount) { + boolean result = paymentRecordService.processPayment(orderNumber, paymentAmount); + if (result) { + return Result.succeed("订单支付成功"); + } else { + return Result.failed("订单支付失败"); + } + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/controller/ProfitSharingController.java b/zlt-business/edu-center/src/main/java/com/central/order/controller/ProfitSharingController.java new file mode 100644 index 00000000..bf810ed2 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/controller/ProfitSharingController.java @@ -0,0 +1,62 @@ +package com.central.order.controller; + +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.order.model.ProfitSharing; +import com.central.order.model.vo.ProfitSharingStatisticsVO; +import com.central.order.service.IProfitSharingService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.Map; + +@Slf4j +@RestController +@RequestMapping("/profitSharing") +@Tag(name = "分账管理") +@RequiredArgsConstructor +public class ProfitSharingController { + + private final IProfitSharingService profitSharingService; + + @Operation(summary = "分页查询分账记录") + @GetMapping("/list") + public PageResult list(@RequestParam Map params) { + return profitSharingService.findList(params); + } + + @Operation(summary = "获取分账记录详情") + @GetMapping("/{orderNo}") + public Result detail(@PathVariable String orderNo) { + ProfitSharing profitSharing = profitSharingService.getByOrderNo(orderNo); + return Result.succeed(profitSharing); + } + + @Operation(summary = "手动触发分账") + @PostMapping("/execute/{orderNo}") + public Result executeProfitSharing(@PathVariable String orderNo) { + try { + profitSharingService.executeProfitSharing(orderNo); + return Result.succeed("分账执行成功"); + } catch (Exception e) { + log.error("手动触发分账失败", e); + return Result.failed("分账执行失败:" + e.getMessage()); + } + } + + @Operation(summary = "获取分账统计数据") + @GetMapping("/statistics") + public Result getStatistics() { + try { + ProfitSharingStatisticsVO statistics = profitSharingService.getStatistics(); + return Result.succeed(statistics); + } catch (Exception e) { + log.error("获取分账统计数据失败", e); + return Result.failed("获取统计数据失败"); + } + } +} \ No newline at end of file diff --git a/zlt-business/edu-center/src/main/java/com/central/order/controller/QrCodeController.java b/zlt-business/edu-center/src/main/java/com/central/order/controller/QrCodeController.java new file mode 100644 index 00000000..877f4e7f --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/controller/QrCodeController.java @@ -0,0 +1,149 @@ +package com.central.order.controller; + +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.order.feign.FileCenterService; +import com.central.order.model.*; +import com.central.order.service.IOrderService; +import com.central.order.service.IQrCodeService; +import com.central.order.service.ITourismFileService; +import com.central.order.service.ITourismService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.util.Assert; +import org.springframework.util.CollectionUtils; +import org.springframework.web.bind.annotation.*; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +/** + * qrcode information + * + * @author lsl + * @date 2024-12-19 17:51:47 + */ +@Slf4j +@RestController +@Tag(name = "二维码管理") +@RequestMapping("/qrcode") +@RequiredArgsConstructor +public class QrCodeController { + + @Autowired + private IQrCodeService qrCodeService; + + @Autowired + private FileCenterService fileCenterService; + + @Autowired + private ITourismService tourismService; + + @Autowired + private ITourismFileService tourismFileService; + + @Autowired + private IOrderService orderService; + /** + * 列表 + */ + @Operation(summary = "查询列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping + public PageResult list(@RequestParam Map params) { + PageResult pageResult = qrCodeService.findList(params); + if (pageResult.getResp_code() == 0){ + for (QrCode qrCode: pageResult.getData()){ + qrCode.setViewUrl(fileCenterService.getViewUrlByPath(qrCode.getFilePath())); + } + } + return pageResult; + } + + @Operation(summary = "生成景区二维码") + @PostMapping + public Result saveOrUpdateQrcode(@RequestBody QrCode qrCode) throws Exception { + + if (qrCode.getId() == null){ + String codeId = UUID.randomUUID().toString(); + Result result = fileCenterService.uploadQrCodeFile(codeId); + if (result.getResp_code() == 0){ + qrCode.setCodeId(codeId); + qrCode.setFilePath(result.getData().get("filePath").toString()); + qrCode.setFileId(result.getData().get("fileId").toString()); + if (qrCodeService.saveOrUpdate(qrCode)) { + return Result.succeed(qrCode,"qrcode创建成功"); + } else { + return Result.failed("qrcode创建失败"); + } + } + }else { + qrCodeService.saveOrUpdate(qrCode); + return Result.succeed(qrCode,"qrcode修改成功"); + } + return Result.failed("创建失败"); + + } + + @Operation(summary = "根据code查询二维码信息") + @GetMapping("/{codeId}") + public Result getQrCode(@PathVariable("codeId") String codeId) { + QrCode qrCode = qrCodeService.getByCodeId(codeId); + if (qrCode == null) { + return Result.failed("暂无数据"); + } + return Result.succeed(qrCode,"获取成功"); + } + + @Operation(summary = "根据code查询二维码信息") + @GetMapping("/info/{codeId}") + public Result getQrCodeInfo(@PathVariable("codeId") String codeId) { + QrCode qrCode = qrCodeService.getByCodeId(codeId); + Assert.notNull(qrCode,"QRCODE不能为空"); + Tourism tourism = tourismService.getTourismById(qrCode.getTourismId()); + Assert.notNull(tourism,"TOURISM数据不能为空"); + List tourismFiles = tourismFileService.getByTourismId(qrCode.getTourismId()); + if (!CollectionUtils.isEmpty(tourismFiles)) { + for (TourismFile tourismFile: tourismFiles) { + tourismFile.setImageUrl(fileCenterService.getViewUrlByPath(tourismFile.getImageUrl())); + } + } + QrCodeVO qrCodeVO = new QrCodeVO(); + qrCodeVO.setCodeId(codeId); + qrCodeVO.setTourism(tourism); + qrCodeVO.setTourismFiles(tourismFiles); + return Result.succeed(qrCodeVO,"获取成功"); + } + + + @DeleteMapping("/{id}") + public Result delete(@PathVariable Long id) { + qrCodeService.removeById(id); + return Result.succeed("操作成功"); + } + + @GetMapping("/wayline/{orderNo}") + public Map getWaylineByOrderNo(@PathVariable("orderNo") String orderNo){ + + Order order = orderService.getOrderByNumber(orderNo); + Assert.notNull(order,"订单No不能为空"); + QrCode qrCode = qrCodeService.getByCodeId(order.getCodeId()); + Assert.notNull(qrCode,"二维码数据不能为空"); + String waylineFilePath = fileCenterService.getFileViewUrl(qrCode.getWaylineId()); + Map map = new HashMap<>(); + map.put("waylineFilePath",waylineFilePath); + map.put("waylineId",qrCode.getWaylineId()); + return map; + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/controller/RefundController.java b/zlt-business/edu-center/src/main/java/com/central/order/controller/RefundController.java new file mode 100644 index 00000000..b2e7998e --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/controller/RefundController.java @@ -0,0 +1,146 @@ +package com.central.order.controller; + +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.order.enums.OrderStatus; +import com.central.order.enums.RefundState; +import com.central.order.model.Order; +import com.central.order.service.IOrderService; +import com.central.order.service.IRefundService; +import com.wechat.pay.java.service.refund.RefundService; +import com.wechat.pay.java.service.refund.model.AmountReq; +import com.wechat.pay.java.service.refund.model.CreateRequest; +import com.wechat.pay.java.service.refund.model.Refund; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.Assert; +import org.springframework.web.bind.annotation.*; + +import java.util.Map; + +@RestController +@RequestMapping("/refund") +public class RefundController { + + @Autowired + private RefundService service; + + @Autowired + private IOrderService orderService; + + @Autowired + private IRefundService refundService; + + @Value("${tencent.refund-notify-url}") + private String refundNotifyUrl; + + /** + * 列表 + */ + @Operation(summary = "查询全部列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in= ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping() + public PageResult list(@RequestParam Map params) { + return refundService.findList(params); + } + + @Operation(summary = "创建退款单") + @PostMapping("/{orderNo}") + public Result createRefundOrder(@PathVariable String orderNo,@RequestBody com.central.order.model.Refund refundBody) { + Order order = orderService.getOrderByNumber(orderNo); + Assert.notNull(order,"ORDER DATA不存在"); + if (order.getOrderStatus().equals(OrderStatus.PAID.getId()) + || order.getOrderStatus().equals(OrderStatus.COMPLETE.getId()) + || order.getOrderStatus().equals(OrderStatus.DOING.getId())) { + // 创建退款订单 + com.central.order.model.Refund refund = new com.central.order.model.Refund(); + refund.setRefundNo("RF" + order.getOrderNo()); + com.central.order.model.Refund existRefund = refundService.getRefundByNo(refund.getRefundNo()); + if (existRefund != null){ + return Result.succeed("已提交"); + } + refund.setOrderNo(order.getOrderNo()); + refund.setUserId(order.getUserId()); + refund.setOrderAmount(order.getOrderAmount()); + refund.setRefundAmount(order.getOrderAmount()); + refund.setStatus(OrderStatus.REFUNDING.getId()); + refund.setState(RefundState.APPROVING.getId()); + refund.setRefundReason(refundBody.getRefundReason()); + refund.setRefundImgs(refundBody.getRefundImgs()); + boolean res = refundService.createRefund(refund); + if (res) { + order.setOrderStatus(OrderStatus.REFUNDING.getId()); + orderService.updateOrder(order); + return Result.succeed("退款成功"); + } + return Result.failed("请重试"); + }else { + return Result.failed("该订单不支持退款操作"); + } + } + + @Operation(summary = "微信支付退款") + @PostMapping("/approve") + @Transactional(rollbackFor = Exception.class) + public Result approveOrder(@RequestBody com.central.order.model.Refund refund) { + + // 检查订单是否存在 + Order order = orderService.getOrderByNumber(refund.getOrderNo()); + Assert.notNull(order, "ORDER DATA不存在"); + if (!order.getOrderStatus().equals(OrderStatus.REFUNDING.getId())){ + return Result.failed("请重试"); + } + if (! refund.getStatus().equals(OrderStatus.REFUNDING.getId())){ + return Result.failed("该状态不支持审核"); + } + if (refund.getState().equals(RefundState.APPROVED.getId())){ + dealRefundRequest(order); + return Result.succeed("已处理退款"); + } + if (refund.getState().equals(RefundState.REFUSED.getId())){ + order.setOrderStatus(OrderStatus.REFUND_FAILED.getId()); + refund.setStatus(OrderStatus.REFUND_FAILED.getId()); + orderService.updateOrder(order); + refundService.updateById(refund); + return Result.succeed("处理成功"); + } + return Result.failed("处理退款失败"); + } + + private void dealRefundRequest(Order order) { + try { + // 创建微信退款请求 + CreateRequest request = new CreateRequest(); + request.setOutTradeNo(order.getOrderNo()); + request.setOutRefundNo("RF" + order.getOrderNo()); + request.setReason("用户申请退款"); + // 从配置文件中获取退款结果回调通知地址 + request.setNotifyUrl(refundNotifyUrl); + + // 设置退款金额 + AmountReq amount = new AmountReq(); + // 订单总金额,单位为分 + amount.setTotal(Long.valueOf(order.getOrderAmount())); + // 退款金额,单位为分 + amount.setRefund(Long.valueOf(order.getOrderAmount())); + amount.setCurrency("CNY"); + request.setAmount(amount); + + // 发起退款请求 + Refund response = service.create(request); + Assert.notNull(response, "退款失败"); + } catch (Exception e) { + // 记录异常信息 + e.printStackTrace(); + } + } + +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/controller/TourismController.java b/zlt-business/edu-center/src/main/java/com/central/order/controller/TourismController.java new file mode 100644 index 00000000..a370d51d --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/controller/TourismController.java @@ -0,0 +1,69 @@ +package com.central.order.controller; + +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.order.model.Tourism; +import com.central.order.service.ITourismService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.Map; + +/** + * Tourism information + * + * @author lsl + * @date 2024-12-19 17:51:47 + */ +@Slf4j +@RestController +@Tag(name = "Tourism管理") +@RequestMapping("/tourism") +@RequiredArgsConstructor +public class TourismController { + + @Autowired + private ITourismService tourismService; + + /** + * 列表 + */ + @Operation(summary = "查询列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping + public PageResult list(@RequestParam Map params) { + return tourismService.findList(params); + } + + @PostMapping() + public Result saveOrUpdate(@RequestBody Tourism tourism) { + return tourismService.saveOrUpdateTourism(tourism); + } + + @Operation(summary = "查询Tourism") + @GetMapping("/{id}") + public Result getTourism(@PathVariable("id") Long id) { + Tourism tourism = tourismService.getTourismById(id); + if (tourism == null) { + return Result.failed("暂无数据"); + } + return Result.succeed(tourism,"获取成功"); + } + + @DeleteMapping() +// @AuditLog(operation = "'新增或更新用户:' + #sysUser.username") + public Result delete(@RequestBody Tourism tourism) { + boolean result = tourismService.removeById(tourism); + return result ? Result.succeed(tourism, "操作成功") : Result.failed("操作失败"); + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/controller/TourismFileController.java b/zlt-business/edu-center/src/main/java/com/central/order/controller/TourismFileController.java new file mode 100644 index 00000000..f3ae755c --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/controller/TourismFileController.java @@ -0,0 +1,78 @@ +package com.central.order.controller; + +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.order.feign.FileCenterService; +import com.central.order.model.TourismFile; +import com.central.order.service.ITourismFileService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.Map; + +/** + * Tourism File information + * + * @author lsl + * @date 2025-2-19 17:51:47 + */ +@Slf4j +@RestController +@Tag(name = "TourismFile管理") +@RequestMapping("/tourism/files") +@RequiredArgsConstructor +public class TourismFileController { + + @Autowired + private ITourismFileService tourismFileService; + + @Autowired + private FileCenterService fileCenterService; + + /** + * 列表 + */ + @Operation(summary = "查询列表") + @Parameters({ + @Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY), + @Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY) + }) + @GetMapping + public PageResult list(@RequestParam Map params) { + PageResult pageResult = tourismFileService.findList(params); + if (pageResult.getCount()>0){ + for (TourismFile tourismFile: pageResult.getData()){ + tourismFile.setImageUrl(fileCenterService.getViewUrlByPath(tourismFile.getImageUrl())); + } + } + return pageResult; + } + + @PostMapping() + public Result saveOrUpdate(@RequestBody TourismFile tourismFile) { + return tourismFileService.saveOrUpdateTourismFile(tourismFile); + } + + @Operation(summary = "查询TourismFile") + @GetMapping("/{id}") + public Result getTourismFile(@PathVariable("id") Long id) { + TourismFile tourismFile = tourismFileService.getById(id); + if (tourismFile == null) { + return Result.failed("暂无数据"); + } + return Result.succeed(tourismFile,"获取成功"); + } + + @DeleteMapping("/{id}") + public Result delete(@PathVariable Long id) { + tourismFileService.removeById(id); + return Result.succeed( "操作成功"); + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/controller/VideoTemplateController.java b/zlt-business/edu-center/src/main/java/com/central/order/controller/VideoTemplateController.java new file mode 100644 index 00000000..70c14cd4 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/controller/VideoTemplateController.java @@ -0,0 +1,95 @@ +package com.central.order.controller; + +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.order.model.VideoTemplate; +import com.central.order.service.IVideoTemplateService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.annotation.*; + +import java.util.Map; + +@Slf4j +@RestController +@RequiredArgsConstructor +@RequestMapping("/video/template") +@Tag(name = "视频模板管理") +public class VideoTemplateController { + + private final IVideoTemplateService videoTemplateService; + + @Operation(summary = "分页查询模板") + @GetMapping("/list") + public Result> list(@RequestParam Map params) { + try { + PageResult result = videoTemplateService.findList(params); + return Result.succeed(result); + } catch (Exception e) { + log.error("查询模板列表失败", e); + return Result.failed("查询失败"); + } + } + + @Operation(summary = "添加模板") + @PostMapping + public Result save(@RequestBody VideoTemplate template) { + try { + boolean result = videoTemplateService.saveTemplate(template); + return Result.succeed(result); + } catch (Exception e) { + log.error("添加模板失败", e); + return Result.failed("添加失败"); + } + } + + @Operation(summary = "更新模板") + @PutMapping + public Result update(@RequestBody VideoTemplate template) { + try { + boolean result = videoTemplateService.updateTemplate(template); + return Result.succeed(result); + } catch (Exception e) { + log.error("更新模板失败", e); + return Result.failed("更新失败"); + } + } + + @Operation(summary = "删除模板") + @DeleteMapping("/{id}") + public Result delete(@PathVariable Long id) { + try { + boolean result = videoTemplateService.deleteTemplate(id); + return Result.succeed(result); + } catch (Exception e) { + log.error("删除模板失败", e); + return Result.failed("删除失败"); + } + } + + @Operation(summary = "更新模板状态") + @PutMapping("/{id}/status/{status}") + public Result updateStatus(@PathVariable Long id, @PathVariable Integer status) { + try { + boolean result = videoTemplateService.updateStatus(id, status); + return Result.succeed(result); + } catch (Exception e) { + log.error("更新模板状态失败", e); + return Result.failed("更新状态失败"); + } + } + + @Operation(summary = "获取可用模板") + @GetMapping("/active") + public Result getActiveTemplate() { + try { + VideoTemplate template = videoTemplateService.getActiveTemplate(); + return Result.succeed(template); + } catch (Exception e) { + log.error("获取可用模板失败", e); + return Result.failed("获取失败"); + } + } +} \ No newline at end of file diff --git a/zlt-business/edu-center/src/main/java/com/central/order/controller/WxCallbackController.java b/zlt-business/edu-center/src/main/java/com/central/order/controller/WxCallbackController.java new file mode 100644 index 00000000..288ff0b5 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/controller/WxCallbackController.java @@ -0,0 +1,58 @@ +package com.central.order.controller; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.security.MessageDigest; +import java.util.Arrays; + +/** + * + * 服务号调用API + * @author lsl + * @date 2025-04-24 + * + */ + +@Slf4j +@RestController +@RequestMapping("/token/callback") +@RequiredArgsConstructor +public class WxCallbackController { + + private static final String TOKEN = "codechangetheworld2025"; //MIUFvX040zDQtUHUGEFjpzDwgNLmPe6gWPVsnQMW3nL + + @GetMapping() + public String verify( + @RequestParam("signature") String signature, + @RequestParam("timestamp") String timestamp, + @RequestParam("nonce") String nonce, + @RequestParam("echostr") String echostr) throws Exception { + + log.info("开始验证微信token请求:{}", signature); + // 1. 字典序排序并拼接 + String[] arr = {TOKEN, timestamp, nonce}; + Arrays.sort(arr); + String rawStr = String.join("", arr); + + // 2. SHA1 加密 + MessageDigest md = MessageDigest.getInstance("SHA-1"); + byte[] digest = md.digest(rawStr.getBytes()); + StringBuilder sb = new StringBuilder(); + for (byte b : digest) { + sb.append(String.format("%02x", b)); + } + String hash = sb.toString(); + + // 3. 校验签名 + if (hash.equals(signature)) { + return echostr; + } else { + return "Invalid signature"; + } + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/controller/WxMessageRecordController.java b/zlt-business/edu-center/src/main/java/com/central/order/controller/WxMessageRecordController.java new file mode 100644 index 00000000..67c7dfe5 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/controller/WxMessageRecordController.java @@ -0,0 +1,54 @@ +package com.central.order.controller; + +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.order.model.WxMessageRecord; +import com.central.order.service.IWxMessageRecordService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.time.LocalDateTime; +import java.util.Map; + +@Slf4j +@RestController +@Tag(name = "微信消息记录管理") +@RequestMapping("/wx/message") +public class WxMessageRecordController { + + @Autowired + private IWxMessageRecordService messageRecordService; + + @Operation(summary = "分页查询消息记录") + @GetMapping("/records") + public PageResult records(@RequestParam Map params) { + return messageRecordService.findRecords(params); + } + + @Operation(summary = "获取消息统计") + @GetMapping("/statistics") + public Result> statistics( + @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime, + @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) { + if (startTime == null) { + startTime = LocalDateTime.now().minusDays(7); + } + if (endTime == null) { + endTime = LocalDateTime.now(); + } + return Result.succeed(messageRecordService.getStatistics(startTime, endTime)); + } + + @Operation(summary = "获取失败消息记录") + @GetMapping("/failed") + public Result getFailedRecords() { + return Result.succeed(messageRecordService.getFailedRecords()); + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/controller/WxPayController.java b/zlt-business/edu-center/src/main/java/com/central/order/controller/WxPayController.java new file mode 100644 index 00000000..4ec10a51 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/controller/WxPayController.java @@ -0,0 +1,467 @@ +package com.central.order.controller; + +import com.central.order.constants.ProfitSharingConstants; +import com.central.order.enums.OrderStatus; +import com.central.order.enums.RefundState; +import com.central.order.model.Order; +import com.central.order.model.ProfitSharing; +import com.central.order.model.QrCode; +import com.central.order.service.IOrderService; +import com.central.order.service.IProfitSharingService; +import com.central.order.service.IQrCodeService; +import com.central.order.service.IRefundService; +import com.wechat.pay.java.core.notification.NotificationConfig; +import com.wechat.pay.java.core.notification.NotificationParser; +import com.wechat.pay.java.core.notification.RequestParam; +import com.wechat.pay.java.service.payments.model.Transaction; +import com.wechat.pay.java.service.refund.model.RefundNotification; +import com.wechat.pay.java.service.refund.model.Status; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.Data; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.util.Assert; +import org.springframework.web.bind.annotation.*; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; + +@Slf4j +@RestController +@Tag(name = "支付管理") +@RequestMapping("/wechat") +public class WxPayController { + + @Autowired + private IOrderService orderService; + @Autowired + private IRefundService refundService; + @Autowired + private IQrCodeService qrCodeService; + @Autowired + private IProfitSharingService profitSharingService; + + @Autowired + private NotificationConfig config; + + @PostMapping("/pay/notify") + public String handleCallback(@RequestHeader("Wechatpay-Signature") String signature, + @RequestHeader("Wechatpay-Timestamp") String timestamp, + @RequestHeader("Wechatpay-Nonce") String nonce, + @RequestHeader("Wechatpay-Serial") String serial, + @RequestBody String body) { + try { + // 构建请求参数 + RequestParam requestParam = new RequestParam + .Builder() + .body(body) + .nonce(nonce) + .signature(signature) + .serialNumber(serial) + .timestamp(timestamp) + .build(); + + + NotificationParser notificationParser = new NotificationParser(config); + // 解析通知 + Transaction transaction = notificationParser.parse(requestParam,Transaction.class); + + // 处理支付结果 + handlePaymentResult(transaction); + + // 返回成功响应 + return "{\"code\":\"SUCCESS\",\"message\":\"成功\"}"; + } catch (Exception e) { + // 处理异常,记录日志等 + e.printStackTrace(); + return "{\"code\":\"FAIL\",\"message\":\"失败\"}"; + } + } + + private void handlePaymentResult(Transaction transaction) { + String outTradeNo = transaction.getOutTradeNo(); + String tradeState = transaction.getTradeState().toString(); + + try { + if ("SUCCESS".equals(tradeState)) { + // 1. 获取订单和二维码信息 + Order order = orderService.getOrderByNumber(outTradeNo); + if (order == null) { + log.error("订单不存在: {}", outTradeNo); + return; + } + + QrCode qrCode = qrCodeService.getByCodeId(order.getCodeId()); + if (qrCode == null) { + log.error("二维码不存在: {}", order.getCodeId()); + return; + } + + // 2. 更新订单状态 + order.setOrderStatus(OrderStatus.PAID.getId()); + order.setPayTime(new Date()); + orderService.updateOrder(order); + + // 3. 处理分账 + if (isEnableProfit(qrCode)) { + try { + // 更新分账记录的微信支付订单号 + profitSharingService.updateTransactionId( + outTradeNo, + transaction.getTransactionId() + ); + + // 发起分账 + profitSharingService.executeProfitSharing(outTradeNo); + } catch (Exception e) { + log.error("处理分账失败: orderNo={}", outTradeNo, e); + // 分账失败不影响支付结果,但需要记录并告警 + sendProfitSharingAlert(order, e.getMessage()); + } + } + } else { + log.info("支付未成功: orderNo={}, state={}", outTradeNo, tradeState); + } + } catch (Exception e) { + log.error("处理支付结果异常: orderNo={}", outTradeNo, e); + throw e; + } + } + + /** + * 检查是否开启分润 + */ + private boolean isEnableProfit(QrCode qrCode) { + return qrCode != null && + Integer.valueOf(1).equals(qrCode.getEnableProfit()) && + qrCode.getPayeeStatus() != null && + qrCode.getPayeeStatus() == 1 && // 确保分账账号已验证 + qrCode.getPayeeAccount() != null && // 确保有收款账号 + qrCode.getProfitRate() != null; // 确保有分润比例 + } + + /** + * 发送分账异常告警 + */ + private void sendProfitSharingAlert(Order order, String errorMessage) { + try { + String alertMessage = String.format( + "分账处理异常告警\n" + + "订单号:%s\n" + + "异常信息:%s\n" + + "时间:%s", + order.getOrderNo(), + errorMessage, + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + ); + + log.error(alertMessage); + // TODO: 实现具体的告警通知逻辑 + } catch (Exception e) { + log.error("发送分账异常告警失败", e); + } + } + + @PostMapping("/refund/notify") + public String refundCallback(@RequestHeader("Wechatpay-Signature") String signature, + @RequestHeader("Wechatpay-Timestamp") String timestamp, + @RequestHeader("Wechatpay-Nonce") String nonce, + @RequestHeader("Wechatpay-Serial") String serial, + @RequestBody String body) { + log.info("------收到微信退款回调通知------"); + try { + // 构建请求参数 + RequestParam requestParam = new RequestParam + .Builder() + .body(body) + .nonce(nonce) + .signature(signature) + .serialNumber(serial) + .timestamp(timestamp) + .build(); + + NotificationParser notificationParser = new NotificationParser(config); + // 解析通知 + RefundNotification notification = notificationParser.parse(requestParam, RefundNotification.class); + + // 处理退款结果 + handleRefundResult(notification); + + // 返回成功响应 + return buildSuccessResponse(); + } catch (Exception e) { + // 处理异常,记录日志等 + e.printStackTrace(); + return buildErrorResponse(); + } + } + + /** + * 构建请求参数 + */ + private RequestParam buildRequestParam(Map headers, String body) { + return new RequestParam.Builder() + .serialNumber(headers.get("Wechatpay-Serial")) + .nonce(headers.get("Wechatpay-Nonce")) + .signature(headers.get("Wechatpay-Signature")) + .timestamp(headers.get("Wechatpay-Timestamp")) + .body(body) + .build(); + } + + /** + * 解析通知数据 + */ + private ProfitSharingNotification parseNotification(RequestParam requestParam) { + try { + NotificationParser parser = new NotificationParser(config); + // 解析为Map后转换为ProfitSharingNotification对象 + Map result = parser.parse(requestParam, Map.class); + + ProfitSharingNotification notification = new ProfitSharingNotification(); + notification.setMchid((String) result.get("mchid")); + notification.setTransactionId((String) result.get("transaction_id")); + notification.setOutOrderNo((String) result.get("out_order_no")); + notification.setState((String) result.get("state")); + notification.setFailReason((String) result.get("fail_reason")); + + // 处理接收方列表 + if (result.containsKey("receivers")) { + List> receiversMap = (List>) result.get("receivers"); + List receivers = new ArrayList<>(); + + for (Map receiverMap : receiversMap) { + ProfitSharingNotification.Receiver receiver = new ProfitSharingNotification.Receiver(); + receiver.setType((String) receiverMap.get("type")); + receiver.setAccount((String) receiverMap.get("account")); + receiver.setAmount(Long.valueOf(receiverMap.get("amount").toString())); + receiver.setDescription((String) receiverMap.get("description")); + receiver.setResult((String) receiverMap.get("result")); + receiver.setFailReason((String) receiverMap.get("fail_reason")); + receiver.setDetailId((String) receiverMap.get("detail_id")); + receivers.add(receiver); + } + notification.setReceivers(receivers); + } + + return notification; + } catch (Exception e) { + log.error("解析分账回调通知失败", e); + throw new RuntimeException("解析分账回调通知失败", e); + } + } + + /** + * 优化后的分账回调处理方法 + */ + @PostMapping("/profitsharing/notify") + public String handleProfitSharingNotify(@RequestHeader Map headers, + @RequestBody String body) { + log.info("收到分账回调通知: headers={}, body={}", headers, body); + + try { + // 1. 验证通知签名 + RequestParam requestParam = buildRequestParam(headers, body); + + // 2. 解析通知数据 + ProfitSharingNotification notification = parseNotification(requestParam); + + // 3. 处理分账结果 + handleProfitSharingNotification(notification); + + // 4. 返回成功响应 + return buildSuccessResponse(); + + } catch (Exception e) { + log.error("处理分账回调失败", e); + return buildErrorResponse(); + } + } + + private void handleProfitSharingNotification(ProfitSharingNotification notification) { + String orderNo = notification.getOutOrderNo(); + String state = notification.getState(); + + try { + // 1. 获取分账记录 + ProfitSharing profitSharing = profitSharingService.getByOrderNo(orderNo); + if (profitSharing == null) { + log.error("分账记录不存在: {}", orderNo); + return; + } + + // 2. 根据状态处理 + switch (state) { + case "FINISHED": + // 分账成功 + handleProfitSharingSuccess(profitSharing, notification); + break; + + case "FAILED": + // 分账失败 + handleProfitSharingFailure(profitSharing, notification); + break; + + default: + log.warn("未知的分账状态: orderNo={}, state={}", orderNo, state); + } + } catch (Exception e) { + log.error("处理分账回调异常: orderNo={}", orderNo, e); + // 确保更新状态 + profitSharingService.updateProfitSharingStatus( + orderNo, + ProfitSharingConstants.Status.FAILED + ); + } + } + + /** + * 处理分账成功 + */ + private void handleProfitSharingSuccess(ProfitSharing profitSharing, + ProfitSharingNotification notification) { + // 1. 更新分账状态 + profitSharing.setStatus(ProfitSharingConstants.Status.SUCCESS); + profitSharing.setFinishTime(new Date()); + + // 2. 如果有接收方信息,更新接收方结果 + if (notification.getReceivers() != null && !notification.getReceivers().isEmpty()) { + ProfitSharingNotification.Receiver receiver = notification.getReceivers().get(0); + profitSharing.setReceiverAmount(receiver.getAmount()); + profitSharing.setProfitSharingId(receiver.getDetailId()); + } + + // 3. 保存更新 + profitSharingService.updateById(profitSharing); + + log.info("分账成功: orderNo={}", profitSharing.getOrderNo()); + } + + /** + * 处理分账失败 + */ + private void handleProfitSharingFailure(ProfitSharing profitSharing, + ProfitSharingNotification notification) { + // 1. 更新分账状态和失败原因 + profitSharing.setStatus(ProfitSharingConstants.Status.FAILED); + profitSharing.setFailReason(notification.getFailReason()); + profitSharing.setUpdateTime(new Date()); + + // 2. 判断是否需要重试 + if (profitSharing.canRetry()) { + log.info("准备重试分账: orderNo={}, retryTimes={}", + profitSharing.getOrderNo(), profitSharing.getRetryTimes()); + + // 更新重试信息 + profitSharing.setRetryTimes(profitSharing.getRetryTimes() + 1); + profitSharing.setLastRetryTime(new Date()); + profitSharingService.updateById(profitSharing); + + // 发起重试 + profitSharingService.retryFailedProfitSharing(profitSharing.getOrderNo()); + } else { + log.warn("分账失败且不再重试: orderNo={}, retryTimes={}", + profitSharing.getOrderNo(), profitSharing.getRetryTimes()); + + // 发送告警 + sendFailureAlert(profitSharing); + + // 保存最终状态 + profitSharingService.updateById(profitSharing); + } + } + + /** + * 发送失败告警 + */ + private void sendFailureAlert(ProfitSharing profitSharing) { + try { + String alertMessage = String.format( + "分账失败告警\n" + + "订单号:%s\n" + + "交易号:%s\n" + + "失败原因:%s\n" + + "重试次数:%d\n" + + "分账金额:%d分\n" + + "失败时间:%s", + profitSharing.getOrderNo(), + profitSharing.getTransactionId(), + profitSharing.getFailReason(), + profitSharing.getRetryTimes(), + profitSharing.getQrCodeAmount(), + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + ); + + log.error(alertMessage); + // TODO: 实现具体的告警通知逻辑,如发送邮件、钉钉消息等 + + } catch (Exception e) { + log.error("发送分账失败告警异常", e); + } + } + + /** + * 退款订单结果处理逻辑 + * @param notification + */ + private void handleRefundResult(RefundNotification notification) { + // 获取退款通知中的关键信息 + String outRefundNo = notification.getOutRefundNo(); + + log.info("回调返回结果"+notification); + // 根据退款状态进行相应处理 + if (Status.SUCCESS.equals(notification.getRefundStatus())) { + // 退款成功,更新订单状态等操作 + com.central.order.model.Refund refund = refundService.getRefundByNo(outRefundNo); + Assert.notNull(refund,"退款订单数据不存在"); + refund.setStatus(OrderStatus.REFUNDED.getId()); + refund.setState(RefundState.APPROVED.getId()); + refund.setRefundTime(new Date()); + refundService.updateById(refund); + + Order order = orderService.getOrderByNumber(refund.getOrderNo()); + Assert.notNull(order,"订单数据不存在"); + order.setOrderStatus(OrderStatus.REFUNDED.getId()); + orderService.updateOrder(order); + } else if ("CLOSED".equals(notification.getRefundStatus())) { + // 退款关闭,处理退款关闭逻辑 + } else { + // 其他退款状态,如退款中、失败等 + } + } + + private String buildSuccessResponse() { + return "{\"code\":\"SUCCESS\",\"message\":\"成功\"}"; + } + + private String buildErrorResponse() { + return "{\"code\":\"FAIL\",\"message\":\"失败\"}"; + } +} + +/** + * 分账通知解析实体类 + */ +@Data +class ProfitSharingNotification { + private String mchid; // 商户号 + private String transactionId; // 微信订单号 + private String outOrderNo; // 商户分账单号 + private String state; // 分账状态 + private String failReason; // 失败原因 + private List receivers; // 分账接收方列表 + + @Data + public static class Receiver { + private String type; // 分账接收方类型 + private String account; // 分账接收方账号 + private Long amount; // 分账金额 + private String description; // 分账描述 + private String result; // 分账结果 + private String failReason; // 分账失败原因 + private String detailId; // 分账明细单号 + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/controller/WxTestController.java b/zlt-business/edu-center/src/main/java/com/central/order/controller/WxTestController.java new file mode 100644 index 00000000..967832bb --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/controller/WxTestController.java @@ -0,0 +1,39 @@ +package com.central.order.controller; + +import com.central.common.model.Result; +import com.central.order.service.IWxTemplateMessageService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@Slf4j +@RestController +@RequestMapping("/wx/test") +@RequiredArgsConstructor +public class WxTestController { + + private final IWxTemplateMessageService templateMessageService; + + @GetMapping("/template/send") + public Result testSendTemplate( + @RequestParam String openId, + @RequestParam String orderNo, + @RequestParam String serviceName, + @RequestParam Integer rank) { + try { + + + // 发送消息 + templateMessageService.sendPaymentSuccessNotice( + openId, orderNo, serviceName, rank); + + return Result.succeed("发送成功"); + } catch (Exception e) { + log.error("发送模板消息失败", e); + return Result.failed("发送失败:" + e.getMessage()); + } + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/controller/orderStatusLogic.md b/zlt-business/edu-center/src/main/java/com/central/order/controller/orderStatusLogic.md new file mode 100644 index 00000000..01a83b59 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/controller/orderStatusLogic.md @@ -0,0 +1,46 @@ +1. 待支付 +说明:用户成功提交订单,但尚未完成支付操作。此状态下,订单处于暂挂状态,可能因为用户还在选择支付方式、支付过程中出现问题等原因导致未支付。 +操作:用户可选择支付、取消订单;商家可设置订单自动取消时间,超时未支付则订单自动取消。 + +2. 已取消 +说明:订单在支付前被用户主动取消,或者因超过规定的支付时间而被系统自动取消。 +操作:一般无后续操作,订单流程结束。 + +3. 支付成功 +说明:用户成功完成支付,订单进入待处理排队(此时的状态也称作排队中)阶段。 +操作:商家开始处理订单,如确认设备状态;系统可发送支付成功通知给用户。 + +4. 设备执行中 +说明:商家正在对订单进行处理调度设备作业,包括但不限于确认订单信息、设备作业状态、设备素材上传等操作。 +操作:商家完成处理后,可将订单状态更新为素材上传完成或素材上传中(对于多素材订单)。 + +5. 素材上传中 +说明:商家已将照片上传。用户可以通过订单号查询订单对应素材。 +操作:商家上传照片中,用户可查询上传进度。 + +6. 素材上传完成 +说明:订单上传素材完成,处于用户下载状态。 +操作:用户可查询素材信息并进行下载操作;若出现上传异常,商家需及时处理。 + +7. 用户已下载完成 +说明:用户确认订单素材并下载完成且可能已完成评价,整个订单流程结束。 +操作:无后续主要操作,可作为历史订单进行存档和统计分析。 + +8. 退款中 +说明:用户发起退款申请,商家或平台正在处理该申请。 +操作:商家需审核退款申请,根据情况决定是否同意退款;若同意,需进行退款操作。 + +9. 退款成功 +说明:商家或平台已同意退款申请,并完成退款操作,款项已返还给用户。 +操作:订单流程结束,可记录退款相关信息。 + +10. 退款失败 +说明:退款申请因各种原因未能成功处理,如支付渠道问题、用户账户异常等。 +操作:商家或平台需与用户沟通,解决问题后重新发起退款操作。 +状态流转图示例 + +注意:(括号中的为订单状态),发起支付、用户支付中等为处理逻辑 +(待支付) ── 发起支付 ── 用户支付中 ── 支付回调成功或者主动查询支付成功状态 ──> (支付成功) ── 排队中 ──> (设备执行中)── 飞机拍照 ── 飞机返航 ──> (素材上传中) ──> (素材上传完成) ── 用户下载 ──> (用户下载完成) + └─ 长时间未支付自动取消 ──> (已取消) + └─ 退款 ──> (退款中) ── 同意 ──> (退款成功) + └─ 拒绝并填写原因 ──> (退款失败) diff --git a/zlt-business/edu-center/src/main/java/com/central/order/enums/CommonStatus.java b/zlt-business/edu-center/src/main/java/com/central/order/enums/CommonStatus.java new file mode 100644 index 00000000..12951cf5 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/enums/CommonStatus.java @@ -0,0 +1,24 @@ +package com.central.order.enums; + +import com.central.common.enums.ZltEnum; +import lombok.Getter; + +/** + * 数据状态枚举类型 + * + * @author lsl create by 2025/1/10 + */ +@Getter +public enum CommonStatus implements ZltEnum { + ENABLE(0,"启用"), + UNABLE(1, "未启用"); + + CommonStatus(Integer id, String content) { + this.id = id; + this.content = content; + } + + private Integer id; + private String content; + +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/enums/FileType.java b/zlt-business/edu-center/src/main/java/com/central/order/enums/FileType.java new file mode 100644 index 00000000..c93dd7fe --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/enums/FileType.java @@ -0,0 +1,41 @@ +package com.central.order.enums; + +public enum FileType { + JPEG("image/jpeg", ".jpeg", ".jpg"), + PNG("image/png", ".png"), + GIF("image/gif", ".gif"), + MP4("video/mp4", ".mp4"); + + private final String contentType; + private final String[] extensions; + + FileType(String contentType, String... extensions) { + this.contentType = contentType; + this.extensions = extensions; + } + + public String getContentType() { + return contentType; + } + + public String[] getExtensions() { + return extensions; + } + + /** + * 根据文件扩展名获取对应的 FileType + * + * @param extension 文件扩展名 + * @return 对应的 FileType,如果不支持则返回 null + */ + public static FileType fromExtension(String extension) { + for (FileType type : values()) { + for (String ext : type.getExtensions()) { + if (ext.equalsIgnoreCase(extension)) { + return type; + } + } + } + return null; + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/enums/HomeCarouselType.java b/zlt-business/edu-center/src/main/java/com/central/order/enums/HomeCarouselType.java new file mode 100644 index 00000000..bc5c2e57 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/enums/HomeCarouselType.java @@ -0,0 +1,26 @@ +package com.central.order.enums; + +import com.central.common.enums.ZltEnum; +import lombok.Getter; + +/** + * 轮播类型枚举类型 + * + * @author lsl create by 2025/2/19 + */ +@Getter +public enum HomeCarouselType implements ZltEnum { + HOME(0,"首页轮播"), + ACTIVITY(1, "活动"), + SHOOTING_ANGLE(2,"拍照角度"), + GUIDANCE(3,"引导"), + BIG_PICTURE(4,"大图"); + + private Integer id; + private String content; + + HomeCarouselType(Integer i, String content) { + this.id = i; + this.content = content; + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/enums/MessageTemplateEnum.java b/zlt-business/edu-center/src/main/java/com/central/order/enums/MessageTemplateEnum.java new file mode 100644 index 00000000..47ab6ce9 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/enums/MessageTemplateEnum.java @@ -0,0 +1,67 @@ +package com.central.order.enums; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public enum MessageTemplateEnum { + // 基础订单状态 + ORDER_CREATED(1, "新订单提醒", "您有一个新的订单 #{orderNo} 已创建"), + ORDER_PAID(2, "支付成功提醒", "订单 #{orderNo} 已支付成功,正在排队中"), + ORDER_CANCELLED(3, "订单取消提醒", "订单 #{orderNo} 已取消"), + + // 服务状态 + SERVICE_START(4, "服务开始提醒", "订单 #{orderNo} 已开始服务"), + SERVICE_COMPLETE(5, "服务完成提醒", "订单 #{orderNo} 服务已完成"), + + // 素材上传状态 + MATERIAL_UPLOADING(6, "素材上传提醒", "订单 #{orderNo} 正在上传素材"), + MATERIAL_UPLOADED(7, "素材上传完成提醒", "订单 #{orderNo} 素材已上传完成"), + + // 退款相关状态 + REFUND_APPLYING(8, "退款申请提醒", "订单 #{orderNo} 正在申请退款"), + REFUND_SUCCESS(9, "退款成功提醒", "订单 #{orderNo} 已退款成功"), + REFUND_FAILED(10, "退款失败提醒", "订单 #{orderNo} 退款失败"), + REFUND_RETRYING(11, "重新退款提醒", "订单 #{orderNo} 正在重新申请退款"); + + private final Integer type; + private final String title; + private final String contentTemplate; + + public static MessageTemplateEnum getByOrderStatus(Integer orderStatus) { + if (orderStatus == null) { + return null; + } + + switch (orderStatus) { + case 0: return ORDER_CREATED; // 待支付 + case 1: return ORDER_PAID; // 已支付排队中 + case 2: return ORDER_CANCELLED; // 已取消 + case 3: return SERVICE_COMPLETE; // 设备执行完成 + case 4: return SERVICE_START; // 正在服务中 + case 5: return MATERIAL_UPLOADING; // 素材上传中 + case 6: return MATERIAL_UPLOADED; // 素材上传完成 + case 7: return REFUND_APPLYING; // 退款中 + case 8: return REFUND_SUCCESS; // 已退款 + case 9: return REFUND_FAILED; // 退款失败 + default: return null; + } + } + + /** + * 根据状态变更获取消息模板 + */ + public static MessageTemplateEnum getByStatusChange(Integer oldStatus, Integer newStatus) { + if (oldStatus == null || newStatus == null) { + return getByOrderStatus(newStatus); + } + + // 特殊状态变更处理 + if (oldStatus == 9 && newStatus == 7) { // 从退款失败到退款中 + return REFUND_RETRYING; + } + + return getByOrderStatus(newStatus); + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/enums/OrderStatus.java b/zlt-business/edu-center/src/main/java/com/central/order/enums/OrderStatus.java new file mode 100644 index 00000000..a34dfedd --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/enums/OrderStatus.java @@ -0,0 +1,86 @@ +package com.central.order.enums; + +import com.central.common.enums.ZltEnum; +import lombok.Getter; +/** + * 订单状态枚举类型 + * + * @author lsl create by 2025/1/10 + */ +@Getter +public enum OrderStatus implements ZltEnum { + UNPAID(0,"待支付"), + PAID(1, "已支付排队中"), + CANCELED(2, "已取消"), + DOING(4,"正在服务中"), + COMPLETE(3,"设备执行完成"), + UPLOADING(5,"素材上传中"), + UPLOADED(6,"素材上传完成(任务完成)"), + REFUNDING(7,"退款中"), + REFUNDED(8,"已退款"), + REFUND_FAILED(9,"退款失败"); + + OrderStatus(Integer id, String content) { + this.id = id; + this.content = content; + } + + private Integer id; + private String content; + + /** + * 判断订单状态是否允许编辑视频 + * 只有设备执行完成的订单才能进行视频编辑 + */ + public static boolean isValidForEdit(Integer status) { + return status != null && status.equals(COMPLETE.getId()); + } + + /** + * 根据ID获取状态枚举 + */ + public static OrderStatus fromId(Integer id) { + if (id == null) { + return null; + } + for (OrderStatus status : values()) { + if (status.getId().equals(id)) { + return status; + } + } + return null; + } + + /** + * 获取状态描述 + */ + public static String getDesc(Integer id) { + OrderStatus status = fromId(id); + return status != null ? status.getContent() : "未知状态"; + } + + /** + * 判断是否为最终状态 + */ + public static boolean isFinalStatus(Integer status) { + return status != null && ( + status.equals(CANCELED.getId()) || + status.equals(UPLOADED.getId()) || + status.equals(REFUNDED.getId()) || + status.equals(REFUND_FAILED.getId()) + ); + } + + /** + * 判断是否可以退款 + */ + public static boolean canRefund(Integer status) { + return status != null && ( + status.equals(PAID.getId()) || + status.equals(DOING.getId()) || + status.equals(COMPLETE.getId()) || + status.equals(UPLOADING.getId()) || + status.equals(UPLOADED.getId()) + ); + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/enums/OrderStatusChangeEnum.java b/zlt-business/edu-center/src/main/java/com/central/order/enums/OrderStatusChangeEnum.java new file mode 100644 index 00000000..66095bca --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/enums/OrderStatusChangeEnum.java @@ -0,0 +1,64 @@ +package com.central.order.enums; + +import lombok.Getter; + +@Getter +public enum OrderStatusChangeEnum { + // 支付相关 + PAID(OrderStatus.UNPAID.getId(), OrderStatus.PAID.getId(), + "订单支付成功通知", "您的订单 #{orderNo} 已支付成功,正在排队中"), + + // 取消相关 + CANCELED(null, OrderStatus.CANCELED.getId(), + "订单取消通知", "您的订单 #{orderNo} 已取消"), + + // 服务状态相关 + SERVICE_START(OrderStatus.PAID.getId(), OrderStatus.DOING.getId(), + "服务开始通知", "您的订单 #{orderNo} 已开始服务"), + SERVICE_COMPLETE(OrderStatus.DOING.getId(), OrderStatus.COMPLETE.getId(), + "服务完成通知", "您的订单 #{orderNo} 服务已完成"), + + // 素材上传相关 + UPLOADING(OrderStatus.DOING.getId(), OrderStatus.UPLOADING.getId(), + "素材上传通知", "您的订单 #{orderNo} 正在上传素材"), + UPLOADED(OrderStatus.UPLOADING.getId(), OrderStatus.COMPLETE.getId(), + "素材上传完成通知", "您的订单 #{orderNo} 素材已上传完成"), + + // 退款相关 + REFUNDING(null, OrderStatus.REFUNDING.getId(), + "退款申请通知", "您的订单 #{orderNo} 正在申请退款"), + REFUND_SUCCESS(OrderStatus.REFUNDING.getId(), OrderStatus.REFUNDED.getId(), + "退款成功通知", "您的订单 #{orderNo} 已退款成功"), + REFUND_FAILED(OrderStatus.REFUNDING.getId(), OrderStatus.REFUND_FAILED.getId(), + "退款失败通知", "您的订单 #{orderNo} 退款失败"), + RETRY_REFUND(OrderStatus.REFUND_FAILED.getId(), OrderStatus.REFUNDING.getId(), + "重新退款通知", "您的订单 #{orderNo} 正在重新申请退款"); + + private final Integer oldStatus; + private final Integer newStatus; + private final String title; + private final String contentTemplate; + + OrderStatusChangeEnum(Integer oldStatus, Integer newStatus, String title, String contentTemplate) { + this.oldStatus = oldStatus; + this.newStatus = newStatus; + this.title = title; + this.contentTemplate = contentTemplate; + } + + public static OrderStatusChangeEnum getByStatusChange(Integer oldStatus, Integer newStatus) { + for (OrderStatusChangeEnum changeEnum : values()) { + // 如果oldStatus为null,则只匹配newStatus + if (changeEnum.oldStatus == null) { + if (changeEnum.newStatus.equals(newStatus)) { + return changeEnum; + } + } + // 否则匹配两个状态 + else if (changeEnum.oldStatus.equals(oldStatus) && changeEnum.newStatus.equals(newStatus)) { + return changeEnum; + } + } + return null; + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/enums/PayeeTypeEnum.java b/zlt-business/edu-center/src/main/java/com/central/order/enums/PayeeTypeEnum.java new file mode 100644 index 00000000..49422bf5 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/enums/PayeeTypeEnum.java @@ -0,0 +1,26 @@ +package com.central.order.enums; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public enum PayeeTypeEnum { + MERCHANT_ID("MERCHANT_ID", "商户ID"), + PERSONAL_OPENID("PERSONAL_OPENID", "个人openid"); + + private final String code; + private final String desc; + + public static String getDesc(String code) { + if (code == null) { + return ""; + } + for (PayeeTypeEnum type : values()) { + if (type.getCode().equals(code)) { + return type.getDesc(); + } + } + return "未知类型"; + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/enums/ProfitSharingStatusEnum.java b/zlt-business/edu-center/src/main/java/com/central/order/enums/ProfitSharingStatusEnum.java new file mode 100644 index 00000000..9236730b --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/enums/ProfitSharingStatusEnum.java @@ -0,0 +1,28 @@ +package com.central.order.enums; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public enum ProfitSharingStatusEnum { + INIT(0, "待分账"), + PROCESSING(1, "分账中"), + SUCCESS(2, "分账成功"), + FAILED(3, "分账失败"); + + private final int code; + private final String desc; + + public static String getDesc(Integer code) { + if (code == null) { + return ""; + } + for (ProfitSharingStatusEnum status : values()) { + if (status.getCode() == code) { + return status.getDesc(); + } + } + return "未知状态"; + } +} \ No newline at end of file diff --git a/zlt-business/edu-center/src/main/java/com/central/order/enums/QrcodeStatus.java b/zlt-business/edu-center/src/main/java/com/central/order/enums/QrcodeStatus.java new file mode 100644 index 00000000..f766d984 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/enums/QrcodeStatus.java @@ -0,0 +1,4 @@ +package com.central.order.enums; + +public enum QrcodeStatus { +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/enums/RefundState.java b/zlt-business/edu-center/src/main/java/com/central/order/enums/RefundState.java new file mode 100644 index 00000000..0fb44523 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/enums/RefundState.java @@ -0,0 +1,26 @@ +package com.central.order.enums; + +import com.central.common.enums.ZltEnum; +import lombok.Getter; + +/** + * 订单状态枚举类型 + * + * @author lsl create by 2025/1/10 + */ +@Getter +public enum RefundState implements ZltEnum { + APPROVING(0,"审核中"), + APPROVED(1, "已通过"), + REFUSED(2,"已拒绝"); + + + RefundState(Integer id, String content) { + this.id = id; + this.content = content; + } + + private Integer id; + private String content; + +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/event/OrderStatusChangeEvent.java b/zlt-business/edu-center/src/main/java/com/central/order/event/OrderStatusChangeEvent.java new file mode 100644 index 00000000..d10280d9 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/event/OrderStatusChangeEvent.java @@ -0,0 +1,23 @@ +package com.central.order.event; + +import lombok.Getter; +import org.springframework.context.ApplicationEvent; + +@Getter +public class OrderStatusChangeEvent extends ApplicationEvent { + private String orderNo; + private Integer oldStatus; + private Integer newStatus; + private Long userId; + private String orderInfo; + + public OrderStatusChangeEvent(Object source, String orderNo, Integer oldStatus, + Integer newStatus, Long userId, String orderInfo) { + super(source); + this.orderNo = orderNo; + this.oldStatus = oldStatus; + this.newStatus = newStatus; + this.userId = userId; + this.orderInfo = orderInfo; + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/feign/DeviceCenterService.java b/zlt-business/edu-center/src/main/java/com/central/order/feign/DeviceCenterService.java new file mode 100644 index 00000000..c70bef6f --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/feign/DeviceCenterService.java @@ -0,0 +1,33 @@ +package com.central.order.feign; + +import com.alibaba.fastjson.JSONObject; +import com.central.common.constant.ServiceNameConstants; +import com.central.order.feign.fallback.DeviceCenterServiceFallbackFactory; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestParam; + +/** + * device-center模块远程调用 + * + * @author lsl + * @version 1.0 + * @description user-center模块远程调用 + * @create 2025/1/13 + **/ +@FeignClient(name = ServiceNameConstants.DEVICE_SERVICE, fallbackFactory = DeviceCenterServiceFallbackFactory.class, dismiss404 = true) +public interface DeviceCenterService { + + /** + * 通过ID查询文件sign + * + * @param id 文件ID + * @return + */ + @GetMapping("/wayline/sign/{id}") + String getLineFileSign(@PathVariable("id") String id); + + @GetMapping("/live/stream-urls") + JSONObject getStreamUrls(@RequestParam("deviceId") String deviceId) ; +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/feign/FileCenterService.java b/zlt-business/edu-center/src/main/java/com/central/order/feign/FileCenterService.java new file mode 100644 index 00000000..8afc0f57 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/feign/FileCenterService.java @@ -0,0 +1,50 @@ +package com.central.order.feign; + +import com.central.common.constant.ServiceNameConstants; +import com.central.common.model.FileInfo; +import com.central.common.model.Result; +import com.central.order.feign.fallback.FileCenterServiceFallbackFactory; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.Map; + +/** + * user-center模块远程调用 + * + * @author lsl + * @version 1.0 + * @description user-center模块远程调用 + * @create 2025/1/13 + **/ +@FeignClient(name = ServiceNameConstants.FILE_SERVICE, fallbackFactory = FileCenterServiceFallbackFactory.class, dismiss404 = true) +public interface FileCenterService { + + /** + * 通过ID查询预览地址 + * + * @param id 文件ID + * @return + */ + @GetMapping("/file/{id}") + String getFileViewUrl(@PathVariable("id") String id); + + @GetMapping("/type/{id}") + String getFileContentType(@PathVariable("id") String id); + + @GetMapping("/qrcode/{codeId}") + Result uploadQrCodeFile(@PathVariable("codeId") String codeId) throws Exception; + + @PostMapping("/path") + FileInfo creatFileInfo(@RequestBody String path); + + @GetMapping("/files/path") + String getViewUrlByPath(@RequestParam("path") String path) ; + + @GetMapping("/files/path/style") + String getViewUrlByPathStyle(@RequestParam("params") Map params) ; + + @GetMapping("/list/files") + List getListFiles(@RequestParam("prefix") String prefix) ; +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/feign/UserCenterService.java b/zlt-business/edu-center/src/main/java/com/central/order/feign/UserCenterService.java new file mode 100644 index 00000000..246ad679 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/feign/UserCenterService.java @@ -0,0 +1,29 @@ +package com.central.order.feign; + +import com.central.common.constant.ServiceNameConstants; +import com.central.common.model.SysUser; +import com.central.order.feign.fallback.UserCenterServiceFallbackFactory; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; + +/** + * user-center模块远程调用 + * + * @author lsl + * @version 1.0 + * @description user-center模块远程调用 + * @create 2025/1/13 + **/ +@FeignClient(name = ServiceNameConstants.USER_SERVICE, fallbackFactory = UserCenterServiceFallbackFactory.class, dismiss404 = true) +public interface UserCenterService { + + /** + * 通过ID查询用户信息 + * + * @param id 用户ID + * @return + */ + @GetMapping("/users/{id}") + SysUser findUserById(@PathVariable("id") Long id); +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/feign/fallback/DeviceCenterServiceFallbackFactory.java b/zlt-business/edu-center/src/main/java/com/central/order/feign/fallback/DeviceCenterServiceFallbackFactory.java new file mode 100644 index 00000000..3f7be7de --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/feign/fallback/DeviceCenterServiceFallbackFactory.java @@ -0,0 +1,36 @@ +package com.central.order.feign.fallback; + +import com.alibaba.fastjson.JSONObject; +import com.central.order.feign.DeviceCenterService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.cloud.openfeign.FallbackFactory; +import org.springframework.stereotype.Component; + +/** + * 文件中心调用失败回调 + * + * @author lsl + * @version 1.0 + * @description 设备中心调用失败回调 + * @create 2025/1/17 11:33 + **/ +@Slf4j +@Component +public class DeviceCenterServiceFallbackFactory implements FallbackFactory { + + @Override + public DeviceCenterService create(Throwable cause) { + return new DeviceCenterService() { + + @Override + public String getLineFileSign(String id) { + return ""; + } + + @Override + public JSONObject getStreamUrls(String deviceId) { + return null; + } + }; + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/feign/fallback/FileCenterServiceFallbackFactory.java b/zlt-business/edu-center/src/main/java/com/central/order/feign/fallback/FileCenterServiceFallbackFactory.java new file mode 100644 index 00000000..03b6253a --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/feign/fallback/FileCenterServiceFallbackFactory.java @@ -0,0 +1,66 @@ +package com.central.order.feign.fallback; + +import com.central.common.model.FileInfo; +import com.central.common.model.Result; +import com.central.order.feign.FileCenterService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.cloud.openfeign.FallbackFactory; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.Map; + +/** + * 文件中心调用失败回调 + * + * @author lsl + * @version 1.0 + * @description 用户中心调用失败回调 + * @create 2025/1/17 11:33 + **/ +@Slf4j +@Component +public class FileCenterServiceFallbackFactory implements FallbackFactory { + + @Override + public FileCenterService create(Throwable cause) { + return new FileCenterService() { + + @Override + public String getFileViewUrl(String id) { + return ""; + } + + @Override + public String getFileContentType(String id) { + return ""; + } + + @Override + public Result uploadQrCodeFile(String codeId) throws Exception { + return null; + } + + @Override + public FileInfo creatFileInfo(String path) { + return null; + } + + @Override + public String getViewUrlByPath(String path) { + return ""; + } + + @Override + public String getViewUrlByPathStyle(Map params) { + return ""; + } + + @Override + public List getListFiles(String prefix) { + return List.of(); + } + + }; + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/feign/fallback/UserCenterServiceFallbackFactory.java b/zlt-business/edu-center/src/main/java/com/central/order/feign/fallback/UserCenterServiceFallbackFactory.java new file mode 100644 index 00000000..ed4a98a1 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/feign/fallback/UserCenterServiceFallbackFactory.java @@ -0,0 +1,31 @@ +package com.central.order.feign.fallback; + +import com.central.common.model.SysUser; +import com.central.order.feign.UserCenterService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.cloud.openfeign.FallbackFactory; +import org.springframework.stereotype.Component; + +/** + * 用户中心调用失败回调 + * + * @author caiji + * @version 1.0 + * @description 用户中心调用失败回调 + * @create 2024/8/6 11:33 + **/ +@Slf4j +@Component +public class UserCenterServiceFallbackFactory implements FallbackFactory { + + @Override + public UserCenterService create(Throwable cause) { + return new UserCenterService() { + + @Override + public SysUser findUserById(Long id) { + return null; + } + }; + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/handler/WxMessageHandler.java b/zlt-business/edu-center/src/main/java/com/central/order/handler/WxMessageHandler.java new file mode 100644 index 00000000..b7199fdb --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/handler/WxMessageHandler.java @@ -0,0 +1,134 @@ +package com.central.order.handler; + +import com.central.order.model.WxMessageRecord; +import com.central.order.model.WxUserSubscribe; +import com.central.order.service.IWxTemplateMessageService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import me.chanjar.weixin.common.api.WxConsts; +import me.chanjar.weixin.mp.api.WxMpService; +import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage; +import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage; +import org.springframework.stereotype.Component; + +import java.time.LocalDateTime; + +@Slf4j +@Component +@RequiredArgsConstructor +public class WxMessageHandler { + + private final WxMpService wxMpService; + private final IWxTemplateMessageService templateMessageService; + + public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage) { + try { + String msgType = wxMessage.getMsgType(); + if (WxConsts.XmlMsgType.EVENT.equals(msgType)) { + return handleEventMessage(wxMessage); + } + return null; + } catch (Exception e) { + log.error("处理微信消息失败", e); + return null; + } + } + + private WxMpXmlOutMessage handleEventMessage(WxMpXmlMessage wxMessage) { + String event = wxMessage.getEvent(); + switch (event) { + case WxConsts.EventType.TEMPLATE_SEND_JOB_FINISH: + return handleTemplateSendJobFinish(wxMessage); + case WxConsts.EventType.SUBSCRIBE: + return handleSubscribeEvent(wxMessage); + case WxConsts.EventType.UNSUBSCRIBE: + return handleUnsubscribeEvent(wxMessage); + default: + log.info("未处理的事件类型:{}", event); + return null; + } + } + + /** + * 处理模板消息发送完成事件 + */ + private WxMpXmlOutMessage handleTemplateSendJobFinish(WxMpXmlMessage wxMessage) { + try { + String openId = wxMessage.getFromUser(); + String msgId = wxMessage.getMsgId().toString(); + String status = wxMessage.getStatus(); + + log.info("模板消息发送结果:openId={}, msgId={}, status={}", + openId, msgId, status); + + // 更新消息发送状态 + updateMessageStatus(openId, msgId, status.equals("SUCCESS")?1:0); + + } catch (Exception e) { + log.error("处理模板消息发送结果事件失败", e); + } + return null; + } + + private WxMpXmlOutMessage handleSubscribeEvent(WxMpXmlMessage wxMessage) { + String openId = wxMessage.getFromUser(); + log.info("用户关注:openId={}", openId); + + // 保存用户关注状态 + saveUserSubscribeStatus(openId, true); + + return WxMpXmlOutMessage.TEXT() + .content("感谢关注!") + .fromUser(wxMessage.getToUser()) + .toUser(openId) + .build(); + } + + private WxMpXmlOutMessage handleUnsubscribeEvent(WxMpXmlMessage wxMessage) { + String openId = wxMessage.getFromUser(); + log.info("用户取消关注:openId={}", openId); + + // 更新用户关注状态 + saveUserSubscribeStatus(openId, false); + + return null; + } + + /** + * 更新消息发送状态 + */ + private void updateMessageStatus(String openId, String msgId, Integer status) { + try { + WxMessageRecord record = WxMessageRecord.builder() + .openId(openId) + .msgId(msgId) + .status(status) + .build(); + + // TODO: 调用消息记录服务更新状态 + // messageRecordService.updateStatus(record); + + } catch (Exception e) { + log.error("更新消息状态失败:openId={}, msgId={}", openId, msgId, e); + } + } + + /** + * 保存用户关注状态 + */ + private void saveUserSubscribeStatus(String openId, boolean isSubscribe) { + try { + WxUserSubscribe userSubscribe = WxUserSubscribe.builder() + .openId(openId) + .subscribed(isSubscribe) + .updateTime(LocalDateTime.now()) + .build(); + + // TODO: 调用用户服务更新关注状态 + // userSubscribeService.updateStatus(userSubscribe); + + } catch (Exception e) { + log.error("更新用户关注状态失败:openId={}", openId, e); + } + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/listener/OrderStatusChangeListener.java b/zlt-business/edu-center/src/main/java/com/central/order/listener/OrderStatusChangeListener.java new file mode 100644 index 00000000..939b326c --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/listener/OrderStatusChangeListener.java @@ -0,0 +1,258 @@ +package com.central.order.listener; + +import com.alibaba.fastjson.JSON; +import com.central.common.model.SysUser; +import com.central.order.constants.EditTaskStatus; +import com.central.order.enums.MessageTemplateEnum; +import com.central.order.enums.OrderStatus; +import com.central.order.enums.OrderStatusChangeEnum; +import com.central.order.event.OrderStatusChangeEvent; +import com.central.order.feign.UserCenterService; +import com.central.order.model.*; +import com.central.order.service.*; +import com.central.order.util.DateUtils; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.event.EventListener; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Slf4j +@Component +@RequiredArgsConstructor +public class OrderStatusChangeListener { + + @Autowired + private IMessageService messageService; + @Autowired + private ITourismService tourismService; + @Autowired + private IOrderService orderService; + @Autowired + private IQrCodeService qrCodeService; + @Autowired + private IVideoEditService videoEditService; + @Autowired + private IOrderFileService orderFileService; + @Autowired + private IWxTemplateMessageService wxTemplateMessageService; + @Autowired + private UserCenterService userCenterService; + @Autowired + private IEditTaskService editTaskService; + @Autowired + private WxMiniSubscribeService wxMiniSubscribeService; + + @EventListener + @Async + @Transactional(propagation = Propagation.REQUIRES_NEW) + public void handleOrderStatusChange(OrderStatusChangeEvent event) { + try { + log.info("开始处理订单状态变更事件: orderId={}, oldStatus={}, newStatus={}", + event.getOrderNo(), event.getOldStatus(), event.getNewStatus()); + + // 参数校验 + if (event.getOrderNo() == null) { + log.error("订单号为空,无法处理状态变更事件"); + return; + } + + // 获取状态变更类型 + OrderStatusChangeEnum changeEnum = OrderStatusChangeEnum + .getByStatusChange(event.getOldStatus(), event.getNewStatus()); + + if (changeEnum == null) { + log.warn("未找到对应的状态变更类型: oldStatus={}, newStatus={}", + event.getOldStatus(), event.getNewStatus()); + return; + } + + // 获取订单信息 + Order order = orderService.getOrderByNumber(event.getOrderNo()); + if (order == null) { + log.error("未找到订单信息: orderId={}", event.getOrderNo()); + return; + } + + // 获取景区信息 + Tourism tourism = tourismService.getTourismById(order.getTourismId()); + if (tourism == null) { + log.error("未找到景区信息: tourismId={}", order.getTourismId()); + return; + } + + // 处理支付成功状态 + if (isPaymentSuccess(event.getOldStatus(), event.getNewStatus())) { + handlePaymentSuccess(order, tourism); + } + + // 构建消息内容 + String content = changeEnum.getContentTemplate() + .replace("#{orderNo}", event.getOrderNo()) + + "\n景区名称:" + tourism.getTourismName() + + "\n" + event.getOrderInfo(); + + // 获取消息模板 + MessageTemplateEnum template = MessageTemplateEnum.getByStatusChange(event.getOldStatus(), event.getNewStatus()); + if (template == null) { + log.warn("未找到对应的消息模板: oldStatus={}, newStatus={}", + event.getOldStatus(), event.getNewStatus()); + return; + } + + // 创建站内信 + Message message = new Message(); + message.setTitle(changeEnum.getTitle()); + message.setContent(content); + message.setType(template.getType()); // 使用模板中的类型 + message.setUserId(event.getUserId()); + message.setRelatedId(event.getOrderNo()); + + // 设置额外信息 + Map extra = new HashMap<>(); + extra.put("oldStatus", event.getOldStatus()); + extra.put("newStatus", event.getNewStatus()); + extra.put("tourismId", order.getTourismId()); + extra.put("tourismName", tourism.getTourismName()); + + message.setExtra(JSON.toJSONString(extra)); // Fastjson不会抛出受检异常 + + log.info("准备保存站内信: title={}, userId={}, content={}", + message.getTitle(), message.getUserId(), message.getContent()); + + // 保存消息 + messageService.createMessage(message); + + log.info("站内信创建成功: userId={}", message.getUserId()); + + // 订单完成时,检查是否需要触发一键成片 + if (OrderStatus.COMPLETE.getId().equals(event.getNewStatus())) { + handleOrderComplete(order); + } + + } catch (Exception e) { + log.error("处理订单状态变更事件失败", e); + throw new RuntimeException("处理订单状态变更事件失败", e); + } + } + + /** + * 判断是否为支付成功状态变更 + */ + private boolean isPaymentSuccess(Integer oldStatus, Integer newStatus) { + return OrderStatus.UNPAID.getId() + .equals(oldStatus) && OrderStatus.PAID.getId().equals(newStatus); + } + + /** + * 处理支付成功逻辑 + */ + + private void handlePaymentSuccess(Order order, Tourism tourism) { + try { + // 1. 发送微信通知 + + SysUser sysUser = userCenterService.findUserById(order.getUserId()); + // 2. 查询订单排队信息 + Integer queue = orderService.getOrderRankingByOrderId(order.getId(),tourism.getId()); + + // 发送小程序订阅消息 + if (sysUser.getOpenId() != null) { + String tip = "支付成功,当前排第"+queue+"位"; + String orderName = tourism.getTourismName(); + String pageUrl = "pages/task/task"; + wxMiniSubscribeService.sendServiceProcessMsg( + sysUser.getOpenId(), + orderName, + tip, + order.getOrderNo(), + DateUtils.sdf.format(order.getPayTime()), + "", + pageUrl + ); + } + + // 2. 记录支付成功日志 + log.info("订单支付成功: orderNo={}, amount={}, tourismName={}", + order.getOrderNo(), order.getOrderAmount(), tourism.getTourismName()); + + } catch (Exception e) { + // 通知失败不影响主流程 + log.error("处理支付成功通知失败: orderNo={}", order.getOrderNo(), e); + } + } + + /** + * 处理订单完成逻辑 + */ + private void handleOrderComplete(Order order) { + try { + // 1. 检查是否开启一键成片 + QrCode qrCode = qrCodeService.getByCodeId(order.getCodeId()); + if (!isVideoEditEnabled(qrCode)) { + log.info("未开启一键成片功能: orderNo={}, codeId={}", + order.getOrderNo(), order.getCodeId()); + return; + } + + // 3. 创建新任务 + EditTask task = editTaskService.createTask(order.getOrderNo(), order.getUserId()); + + // 4. 获取素材文件 + List orderFiles = orderFileService.getOrderFileByOrderNo(order.getOrderNo()); + + // 5. 提交编辑任务 + String jobId = videoEditService.submitEditTask(order.getOrderNo(), orderFiles); + log.info("提交一键成片任务成功: orderNo={}, jobId={}, totalMediaFiles={}", + order.getOrderNo(), jobId, orderFiles.size()); + + // 6. 更新任务信息 + task.setJobId(jobId); + task.setStatus(EditTaskStatus.PROCESSING); + editTaskService.saveOrUpdateTask(task); + + // 新增:查找下一个排队用户 + Order nextOrder = orderService.getNextQueueOrder(order.getTourismId(), order.getId()); + if (nextOrder != null) { + SysUser nextUser = userCenterService.findUserById(nextOrder.getUserId()); + Tourism tourism = tourismService.getTourismById(nextOrder.getTourismId()); + if (nextUser != null && nextUser.getOpenId() != null && tourism != null) { + String activityName = tourism.getTourismName(); // 活动名称 + String remark = "即将为您进行拍摄服务"; + String activityNo = nextOrder.getOrderNo(); // 活动编号 + String pageUrl = "pages/task/task"; + wxMiniSubscribeService.sendServiceProcessMsg( + nextUser.getOpenId(), + activityName, + remark, + activityNo, + DateUtils.sdf.format(nextOrder.getPayTime()), + "", + pageUrl + ); + log.info("已通知下一个排队用户: userId={}, openId={}, orderNo={}", nextUser.getId(), nextUser.getOpenId(), activityNo); + } + } + + } catch (Exception e) { + log.error("触发一键成片或排队通知失败: orderNo={}", order.getOrderNo(), e); + } + } + + /** + * 检查是否开启一键成片功能 + */ + private boolean isVideoEditEnabled(QrCode qrCode) { + return qrCode != null + && qrCode.getEnableVideoEdit() != null + && qrCode.getEnableVideoEdit() == 1 + && qrCode.getTemplateId() != null; // 确保有模板ID + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/mapper/DashboardMapper.java b/zlt-business/edu-center/src/main/java/com/central/order/mapper/DashboardMapper.java new file mode 100644 index 00000000..ccee4a92 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/mapper/DashboardMapper.java @@ -0,0 +1,91 @@ +package com.central.order.mapper; + +import com.central.order.model.vo.IncomeDataVO; +import com.central.order.model.vo.TourismRankingVO; +import com.central.order.model.vo.TrendDataVO; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Select; + +import java.util.List; + +@Mapper +public interface DashboardMapper { + + @Select("SELECT COUNT(*) FROM orders WHERE is_del = 0") + Long getTotalOrders(); + + @Select("SELECT COUNT(*) FROM orders WHERE is_del = 0 AND DATE(create_time) = CURDATE()") + Long getTodayOrders(); + + @Select("SELECT COUNT(*) FROM orders WHERE is_del = 0 AND DATE(create_time) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)") + Long getYesterdayOrders(); + + @Select("SELECT COUNT(*) FROM orders WHERE is_del = 0 AND order_status = #{completeStatus}") + Long getCompletedOrders(); + + @Select({ + "" + }) + Long getTotalIncome(); + + @Select({ + "" + }) + Long getTodayIncome(); + + + + @Select({ + "SELECT", + " DATE_FORMAT(create_time, '%Y-%m-%d') as date,", + " 'orders' as type,", + " COUNT(*) as value", + "FROM orders", + "WHERE is_del = 0", + " AND create_time >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)", + "GROUP BY DATE_FORMAT(create_time, '%Y-%m-%d')" + }) + List getOrderTrend(); + + @Select({ + "SELECT", + " 'platform' as type,", + " SUM(platform_amount) as value", + "FROM order_statistics", + "WHERE DATE(create_time) = CURDATE()", + "UNION ALL", + "SELECT", + " 'tourism' as type,", + " SUM(tourism_amount) as value", + "FROM order_statistics", + "WHERE DATE(create_time) = CURDATE()" + }) + List getIncomeData(); + + @Select({ + "SELECT", + " t.id,", + " t.tourism_name as name,", + " COUNT(o.id) as value", + "FROM tourisms t", + "LEFT JOIN orders o ON t.id = o.tourism_id", + "WHERE t.is_del = 0", + " AND o.is_del = 0", + " AND o.create_time >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)", + "GROUP BY t.id, t.tourism_name", + "ORDER BY value DESC", + "LIMIT 10" + }) + List getTourismRanking(); +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/mapper/EditTaskMapper.java b/zlt-business/edu-center/src/main/java/com/central/order/mapper/EditTaskMapper.java new file mode 100644 index 00000000..e4bf409c --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/mapper/EditTaskMapper.java @@ -0,0 +1,12 @@ +package com.central.order.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.central.order.model.EditTask; +import org.apache.ibatis.annotations.Mapper; + +/** + * 视频编辑任务Mapper接口 + */ +@Mapper +public interface EditTaskMapper extends BaseMapper { +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/mapper/HomeCarouselMapper.java b/zlt-business/edu-center/src/main/java/com/central/order/mapper/HomeCarouselMapper.java new file mode 100644 index 00000000..82af46dd --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/mapper/HomeCarouselMapper.java @@ -0,0 +1,29 @@ +package com.central.order.mapper; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.db.mapper.SuperMapper; +import com.central.order.model.HomeCarousel; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +/** + * HomeCarousel information + * + * @author lsl + * @date 2025-2-19 17:52:54 + */ +@Mapper +public interface HomeCarouselMapper extends SuperMapper { + /** + * 分页查询用户列表 + * + * @param page + * @param params + * @return + */ + List findList(Page page, @Param("p") Map params); + +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/mapper/MessageMapper.java b/zlt-business/edu-center/src/main/java/com/central/order/mapper/MessageMapper.java new file mode 100644 index 00000000..9553ab6f --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/mapper/MessageMapper.java @@ -0,0 +1,77 @@ +package com.central.order.mapper; + + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.db.mapper.SuperMapper; +import com.central.order.model.Message; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Update; + +import java.util.Date; +import java.util.List; +import java.util.Map; + +@Mapper +public interface MessageMapper extends SuperMapper { + + List findList(Page page, + @Param("tenantId") String tenantId); + + @Update("UPDATE sys_message SET status = 1, read_time = #{readTime} " + + "WHERE id = #{id}") + int markAsRead(@Param("id") Long id, + @Param("readTime") Date readTime); + + @Update("UPDATE sys_message SET status = 1, read_time = #{readTime} " + + "WHERE status = 0") + int markAllAsRead( @Param("readTime") Date readTime); + + /** + * 查询消息列表 + * 使用@Param注解明确指定参数名 + */ + List findList(Page page, + @Param("userId") Long userId, + @Param("tenantId") String tenantId, + @Param("params") Map params); + + /** + * 批量插入消息 + */ + int batchInsert(@Param("list") List messages); + + /** + * 批量更新消息状态 + */ + int batchUpdateStatus(@Param("ids") List ids, + @Param("status") Integer status, + @Param("readTime") Date readTime, + @Param("userId") Long userId); + + /** + * 获取未读消息数量 + */ + int getUnreadCount(@Param("userId") Long userId, + @Param("tenantId") String tenantId); + + /** + * 按类型获取未读消息数量 + */ + List> getUnreadCountByType(@Param("userId") Long userId, + @Param("tenantId") String tenantId); + + /** + * 删除指定时间之前的已读消息 + */ + int deleteReadMessages(@Param("beforeTime") Date beforeTime, + @Param("userId") Long userId, + @Param("tenantId") String tenantId); + + /** + * 根据关联ID查询消息 + */ + List findByRelatedId(@Param("relatedId") String relatedId, + @Param("userId") Long userId, + @Param("tenantId") String tenantId); +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/mapper/OrderFileMapper.java b/zlt-business/edu-center/src/main/java/com/central/order/mapper/OrderFileMapper.java new file mode 100644 index 00000000..715a2844 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/mapper/OrderFileMapper.java @@ -0,0 +1,49 @@ +package com.central.order.mapper; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.db.mapper.SuperMapper; +import com.central.order.model.OrderFile; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +import java.util.List; +import java.util.Map; + +/** + * Order File information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +@Mapper +public interface OrderFileMapper extends SuperMapper { + /** + * 分页查询用户列表 + * + * @param page + * @param params + * @return + */ + List findList(Page page, @Param("params") Map params); + + + // 新增订单资源 + int insertOrderFile(OrderFile orderFile); + // 根据订单编号查询文件资源信息 + List getOrderFileByOrderNo(@Param("orderNo") String orderNo); + + List getOrderFileByOrderNoAndFileType(@Param("orderNo") String orderNo, @Param("fileType") String contentType); + // 文件ID查询文件 + OrderFile getFileByFileId(@Param("fileId") String fileId); + // 查询所有处于排队状态的订单,用于后续按顺序处理(可根据业务需求添加排序等逻辑) + List getOrderFilesByUserId(@Param("userId") Long userId); + + List findListByUser(Page page, @Param("p") Map params); + + /** + * 获取订单的视频文件 + */ + @Select("SELECT * FROM order_files WHERE order_no = #{orderNo} AND file_type = 'video/mp4' ORDER BY create_time ASC") + List getOrderVideoFiles(@Param("orderNo") String orderNo); +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/mapper/OrderMapper.java b/zlt-business/edu-center/src/main/java/com/central/order/mapper/OrderMapper.java new file mode 100644 index 00000000..20602ef2 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/mapper/OrderMapper.java @@ -0,0 +1,61 @@ +package com.central.order.mapper; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.db.mapper.SuperMapper; +import com.central.order.model.Order; +import com.central.order.model.OrderRanking; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +import java.util.Date; +import java.util.List; +import java.util.Map; + +/** + * Order information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +@Mapper +public interface OrderMapper extends SuperMapper { + /** + * 分页查询用户列表 + * @param page + * @param params + * @return + */ + List findList(Page page, @Param("p") Map params); + + // 根据订单状态查询订单列表 + List getOrdersByStatus(@Param("status") Integer status); + // 新增订单 + int insertOrder(Order order); + // 根据订单编号查询订单信息 + Order getOrderById(@Param("orderId") Long orderId); + // 更新订单状态 + int updateOrderStatus(@Param("orderId") Long orderId, @Param("newStatus") Integer newStatus); + // 查询所有处于排队状态的订单,用于后续按顺序处理(可根据业务需求添加排序等逻辑) + List getOrdersInQueue(); + + // 根据店铺编号和创建时间(当天)查询订单数量 + List findByShopIdAndCreateTimeGreaterThanEqualAndCreateTimeLessThanEqual(@Param("tourismId") Long tourismId, @Param("startDate") Date startDate, @Param("endDate") Date endDate); + + // 根据订单编号查询订单信息 + Order getOrderByNumber(@Param("orderNumber") String orderNumber); + + List findListByUser(Page page, @Param("p") Map params); + + @Select("SELECT \n" + + " id,\n" + + " @rank := @rank + 1 as ranking\n" + + "FROM \n" + + " orders,\n" + + " (SELECT @rank := 0) r\n" + + "WHERE \n" + + " order_status in(1,4,5,6) and tourism_id = #{tourismId} \n" + + "ORDER BY \n" + + " pay_time;") + List getOrderRanking1(@Param("tourismId") Long tourismId); +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/mapper/OrderStatisticsMapper.java b/zlt-business/edu-center/src/main/java/com/central/order/mapper/OrderStatisticsMapper.java new file mode 100644 index 00000000..1ca87532 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/mapper/OrderStatisticsMapper.java @@ -0,0 +1,66 @@ +package com.central.order.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.central.order.model.OrderStatistics; +import com.central.order.model.OrderStatisticsQuery; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Select; + +import java.util.List; +import java.util.Map; + +@Mapper +public interface OrderStatisticsMapper extends BaseMapper { + + @Select({ + "" + }) + List> getOrderStatistics(OrderStatisticsQuery query); + + @Select({ + "" + }) + List> getOrderStatisticsByGroup(OrderStatisticsQuery query); +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/mapper/PaymentRecordMapper.java b/zlt-business/edu-center/src/main/java/com/central/order/mapper/PaymentRecordMapper.java new file mode 100644 index 00000000..ec9df4da --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/mapper/PaymentRecordMapper.java @@ -0,0 +1,33 @@ +package com.central.order.mapper; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.db.mapper.SuperMapper; +import com.central.order.model.PaymentRecord; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +/** + * Order information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +@Mapper +public interface PaymentRecordMapper extends SuperMapper { + /** + * 分页查询用户列表 + * @param page + * @param params + * @return + */ + List findList(Page page, @Param("p") Map params); + + // 插入支付记录 + int insertPaymentRecord(PaymentRecord paymentRecord); + // 根据支付流水号查询支付记录(用于幂等性判断) + PaymentRecord getPaymentRecordByNumber(@Param("paymentNumber") String paymentNumber); + +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/mapper/ProfitSharingMapper.java b/zlt-business/edu-center/src/main/java/com/central/order/mapper/ProfitSharingMapper.java new file mode 100644 index 00000000..1380b9b3 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/mapper/ProfitSharingMapper.java @@ -0,0 +1,43 @@ +package com.central.order.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.central.order.model.ProfitSharing; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Select; +import org.apache.ibatis.annotations.Param; + +import java.util.Date; +import java.util.List; +import java.util.Map; + +@Mapper +public interface ProfitSharingMapper extends BaseMapper { + // 获取总体统计 + @Select("SELECT " + + "COUNT(*) as total_count, " + + "SUM(CASE WHEN status = 2 THEN 1 ELSE 0 END) as success_count, " + + "SUM(CASE WHEN status = 3 THEN 1 ELSE 0 END) as fail_count, " + + "SUM(qrcode_amount) as total_amount " + + "FROM profit_sharing") + Map getTotalStatistics(); + + // 获取每日金额趋势 + @Select("SELECT " + + "DATE_FORMAT(create_time, '%Y-%m-%d') as date, " + + "'DAY' as type, " + + "SUM(qrcode_amount) as amount " + + "FROM profit_sharing " + + "WHERE create_time >= #{startTime} " + + "GROUP BY DATE_FORMAT(create_time, '%Y-%m-%d')") + List> getDailyAmountTrend(@Param("startTime") Date startTime); + + // 获取每日成功率 + @Select("SELECT " + + "DATE_FORMAT(create_time, '%Y-%m-%d') as date, " + + "'DAY' as type, " + + "ROUND(SUM(CASE WHEN status = 2 THEN 1 ELSE 0 END) * 100.0 / COUNT(*), 2) as value " + + "FROM profit_sharing " + + "WHERE create_time >= #{startTime} " + + "GROUP BY DATE_FORMAT(create_time, '%Y-%m-%d')") + List> getDailySuccessRate(@Param("startTime") Date startTime); +} \ No newline at end of file diff --git a/zlt-business/edu-center/src/main/java/com/central/order/mapper/QrCodeMapper.java b/zlt-business/edu-center/src/main/java/com/central/order/mapper/QrCodeMapper.java new file mode 100644 index 00000000..5c09cb96 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/mapper/QrCodeMapper.java @@ -0,0 +1,35 @@ +package com.central.order.mapper; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.db.mapper.SuperMapper; +import com.central.order.model.QrCode; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +/** + * Qrcode information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +@Mapper +public interface QrCodeMapper extends SuperMapper { + /** + * 分页查询用户列表 + * + * @param page + * @param params + * @return + */ + List findList(Page page, @Param("p") Map params); + + + // 新增二维码资源 + int insertQrCode(QrCode qrCode); + // ID查询 + QrCode getByCodeId(@Param("codeId") String codeId); + +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/mapper/RefundMapper.java b/zlt-business/edu-center/src/main/java/com/central/order/mapper/RefundMapper.java new file mode 100644 index 00000000..e2abf4bb --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/mapper/RefundMapper.java @@ -0,0 +1,27 @@ +package com.central.order.mapper; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.db.mapper.SuperMapper; +import com.central.order.model.Refund; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +/** + * Order information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +@Mapper +public interface RefundMapper extends SuperMapper { + /** + * 分页查询用户列表 + * @param page + * @param params + * @return + */ + List findList(Page page, @Param("p") Map params); +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/mapper/TourismFileMapper.java b/zlt-business/edu-center/src/main/java/com/central/order/mapper/TourismFileMapper.java new file mode 100644 index 00000000..ebf01fec --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/mapper/TourismFileMapper.java @@ -0,0 +1,32 @@ +package com.central.order.mapper; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.db.mapper.SuperMapper; +import com.central.order.model.TourismFile; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +/** + * Tourism File information + * + * @author lsl + * @date 2025-2-17 17:52:54 + */ +@Mapper +public interface TourismFileMapper extends SuperMapper { + /** + * 分页查询用户列表 + * + * @param page + * @param params + * @return + */ + List findList(Page page, @Param("p") Map params); + + // ID查询 + List getByTourismId(@Param("tourismId") Long tourismId); + +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/mapper/TourismMapper.java b/zlt-business/edu-center/src/main/java/com/central/order/mapper/TourismMapper.java new file mode 100644 index 00000000..a49b5690 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/mapper/TourismMapper.java @@ -0,0 +1,35 @@ +package com.central.order.mapper; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.db.mapper.SuperMapper; +import com.central.order.model.Tourism; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +/** + * Tourism information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +@Mapper +public interface TourismMapper extends SuperMapper { + /** + * 分页查询用户列表 + * + * @param page + * @param params + * @return + */ + List findList(Page page, @Param("p") Map params); + + + // 新增订单资源 + int insertTourism(Tourism tourism); + // ID查询 + Tourism getTourismById(@Param("id") Long id); + +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/mapper/VideoTemplateMapper.java b/zlt-business/edu-center/src/main/java/com/central/order/mapper/VideoTemplateMapper.java new file mode 100644 index 00000000..b42a34ca --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/mapper/VideoTemplateMapper.java @@ -0,0 +1,9 @@ +package com.central.order.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.central.order.model.VideoTemplate; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface VideoTemplateMapper extends BaseMapper { +} \ No newline at end of file diff --git a/zlt-business/edu-center/src/main/java/com/central/order/mapper/WxMessageRecordMapper.java b/zlt-business/edu-center/src/main/java/com/central/order/mapper/WxMessageRecordMapper.java new file mode 100644 index 00000000..68f3138f --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/mapper/WxMessageRecordMapper.java @@ -0,0 +1,9 @@ +package com.central.order.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.central.order.model.WxMessageRecord; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface WxMessageRecordMapper extends BaseMapper { +} \ No newline at end of file diff --git a/zlt-business/edu-center/src/main/java/com/central/order/model/EditTask.java b/zlt-business/edu-center/src/main/java/com/central/order/model/EditTask.java new file mode 100644 index 00000000..cf415fee --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/model/EditTask.java @@ -0,0 +1,38 @@ +package com.central.order.model; + +import com.baomidou.mybatisplus.annotation.*; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.Date; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +@TableName("edit_task") +public class EditTask { + @TableId(type = IdType.AUTO) + private Integer id; + + private Long userId; + private String orderSn; + private String jobId; + private String result; + + @Schema(description = "状态:0-待处理 1-处理中 2-处理完成 3-处理失败") + private Integer status; + + @TableField(fill = FieldFill.INSERT) + private Date createTime; + + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; + //租户ID + private Long tenantId; + + private String remark; +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/model/HomeCarousel.java b/zlt-business/edu-center/src/main/java/com/central/order/model/HomeCarousel.java new file mode 100644 index 00000000..4770e6fb --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/model/HomeCarousel.java @@ -0,0 +1,47 @@ +package com.central.order.model; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.central.common.model.SuperEntity; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; + +import java.util.Date; + +/** + * HomeCarousel File information + * + * @author lsl + * @date 2025-2-17 17:51:47 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +@TableName("home_carousel") +public class HomeCarousel extends SuperEntity { + + private static final long serialVersionUID=1L; + + private String imageUrl; + private String redirectUrl; + private int type; + private Integer status; + + private String title; + private String description; + private int sortOrder; + private Date startTime; + private Date endTime; + + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; + + //租户ID + private String tenantId; + private String company; + private Integer isDel; +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/model/Message.java b/zlt-business/edu-center/src/main/java/com/central/order/model/Message.java new file mode 100644 index 00000000..89fb85fc --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/model/Message.java @@ -0,0 +1,58 @@ +package com.central.order.model; + +import com.baomidou.mybatisplus.annotation.TableName; +import com.central.common.model.SuperEntity; +import lombok.Data; + +import java.util.Date; + +@Data +@TableName("sys_message") +public class Message extends SuperEntity { + private static final long serialVersionUID = 1L; + + /** + * 消息标题 + */ + private String title; + + /** + * 消息内容 + */ + private String content; + + /** + * 消息类型:1-退款订单 2-新增订单 + */ + private Integer type; + + /** + * 消息状态:0-未读 1-已读 + */ + private Integer status; + + /** + * 阅读时间 + */ + private Date readTime; + + /** + * 关联ID + */ + private String relatedId; + + /** + * 额外信息(JSON格式) + */ + private String extra; + + /** + * 接收用户ID + */ + private Long userId; + + /** + * 租户ID + */ + private String tenantId; +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/model/Order.java b/zlt-business/edu-center/src/main/java/com/central/order/model/Order.java new file mode 100644 index 00000000..5630f14a --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/model/Order.java @@ -0,0 +1,58 @@ +package com.central.order.model; + +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.central.common.model.SuperEntity; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; + +import java.util.Date; + +/** + * Device information + * + * @author lsl + * @date 2024-12-19 17:51:47 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +@TableName("orders") +public class Order extends SuperEntity { + private static final long serialVersionUID=1L; + + private String orderNo; + private String deviceSn; + + private Long userId; + private Long tourismId; + private transient String tourismName; + private String workspaceId; + + private String orderAmount; + private Integer orderStatus; + + private Date payTime; + + private transient String createdTime; + private transient String fileMd5; + private transient String mobile; + + private String codeId; + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; + + private String tenantId; + private String company; + private Integer isDel; + + private transient String waylineLinkUrl; + private transient JSONObject streamUrls; + + +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/model/OrderFile.java b/zlt-business/edu-center/src/main/java/com/central/order/model/OrderFile.java new file mode 100644 index 00000000..9df9b83f --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/model/OrderFile.java @@ -0,0 +1,49 @@ +package com.central.order.model; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.central.common.model.SuperEntity; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; + +import java.util.Date; + +/** + * order files information + * + * @author lsl + * @date 2024-12-19 17:51:47 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +@TableName("order_files") +public class OrderFile extends SuperEntity { + private static final long serialVersionUID=1L; + + private String orderNo; + private String fileId; + + private Long userId; + + private transient String viewUrl; + + //文件缩略图 + private transient String zipViewUrl; + // 景区ID + private Long tourismId; + + private String fileType; + //该Path不包含bucketName + private String filePath; + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; + //租户ID + private String tenantId; + private Integer isDel; + +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/model/OrderRanking.java b/zlt-business/edu-center/src/main/java/com/central/order/model/OrderRanking.java new file mode 100644 index 00000000..087ccd6f --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/model/OrderRanking.java @@ -0,0 +1,13 @@ +package com.central.order.model; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class OrderRanking { + + private Integer ranking; + private Long id; + +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/model/OrderStatistics.java b/zlt-business/edu-center/src/main/java/com/central/order/model/OrderStatistics.java new file mode 100644 index 00000000..bcc9bfc0 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/model/OrderStatistics.java @@ -0,0 +1,44 @@ +package com.central.order.model; + +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.math.BigDecimal; +import java.util.Date; + +@Data +@TableName("order_statistics") +public class OrderStatistics { + private Long id; + + // 统计维度 + private String qrcodeId; // 二维码ID + private Long tourismId; // 景区ID + private String tourismName; // 景区名称 + private String deviceSn; // 设备编号 + private String tenantId; // 租户ID + + // 订单统计 + private Integer totalOrders; // 总订单数 + private Integer paidOrders; // 已支付订单数 + private Integer completedOrders;// 已完成订单数 + private Integer canceledOrders; // 已取消订单数 + + // 金额统计(单位:分) + private Long totalAmount; // 总金额 + private Long paidAmount; // 已支付金额 + private Long refundAmount; // 退款金额 + + // 分账金额 + private BigDecimal platformRate = BigDecimal.ZERO; + private BigDecimal tourismRate = BigDecimal.ZERO; + private Long platformAmount = 0L; + private Long tourismAmount = 0L; + + // 时间维度 + private Date startTime; // 统计开始时间 + private Date endTime; // 统计结束时间 + private String statisticsDate; // 统计日期(yyyy-MM-dd) + private Integer statisticsHour; // 统计小时(0-23) + private Date createTime; // 创建时间 +} \ No newline at end of file diff --git a/zlt-business/edu-center/src/main/java/com/central/order/model/OrderStatisticsQuery.java b/zlt-business/edu-center/src/main/java/com/central/order/model/OrderStatisticsQuery.java new file mode 100644 index 00000000..d2efde49 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/model/OrderStatisticsQuery.java @@ -0,0 +1,28 @@ +package com.central.order.model; + +import com.central.order.constants.OrderStatusConstants; +import com.central.order.enums.OrderStatus; +import lombok.Builder; +import lombok.Data; + +@Data +@Builder +public class OrderStatisticsQuery { + private String startTime; + private String endTime; + private String qrcodeId; + private Long tourismId; + private String deviceSn; + private String groupField; // 分组字段 + + @Builder.Default + private Integer completeStatus = OrderStatus.COMPLETE.getId(); + @Builder.Default + private Integer cancelStatus = OrderStatus.CANCELED.getId(); + + // 添加状态集合字符串 + @Builder.Default + private String paidStatus = OrderStatusConstants.PAID_STATUS; + @Builder.Default + private String refundStatus = OrderStatusConstants.REFUND_STATUS; +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/model/PaymentRecord.java b/zlt-business/edu-center/src/main/java/com/central/order/model/PaymentRecord.java new file mode 100644 index 00000000..41933f83 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/model/PaymentRecord.java @@ -0,0 +1,43 @@ +package com.central.order.model; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; + +import java.util.Date; + +/** + * PaymentRecord information + * + * @author lsl + * @date 2024-12-19 17:51:47 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +@TableName("payment_records") +public class PaymentRecord { + private static final long serialVersionUID = 1L; + + @TableId + private Long id; + private Long orderId; + private String orderNo; + private String paymentNumber; + private Double paymentAmount; + private Date paymentTime; + + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; + + private Long createId; + private String company; + private Integer isDel; + +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/model/ProfitSharing.java b/zlt-business/edu-center/src/main/java/com/central/order/model/ProfitSharing.java new file mode 100644 index 00000000..d2681dd7 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/model/ProfitSharing.java @@ -0,0 +1,163 @@ +package com.central.order.model; + +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.baomidou.mybatisplus.annotation.TableField; +import com.central.order.enums.PayeeTypeEnum; +import com.central.order.enums.ProfitSharingStatusEnum; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.AllArgsConstructor; +import org.hibernate.validator.constraints.Length; + +import javax.validation.constraints.Min; +import javax.validation.constraints.NotNull; +import java.util.Date; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +@TableName("profit_sharing") +@Schema(description = "分账记录") +public class ProfitSharing { + @TableId + @Schema(description = "主键ID") + private Long id; + + @NotNull(message = "订单ID不能为空") + @Length(max = 64, message = "订单ID长度不能超过64") + @Schema(description = "订单ID") + private String orderId; + + @NotNull(message = "订单编号不能为空") + @Length(max = 64, message = "订单编号长度不能超过64") + @Schema(description = "订单编号") + private String orderNo; + + @Length(max = 64, message = "微信支付订单号长度不能超过64") + @Schema(description = "微信支付订单号") + private String transactionId; + + @Length(max = 64, message = "微信分账单号长度不能超过64") + @Schema(description = "微信分账单号") + @TableField("profit_sharing_id") + private String profitSharingId; + + @NotNull(message = "订单总金额不能为空") + @Min(value = 1, message = "订单总金额必须大于0") + @Schema(description = "订单总金额(分)") + private Long totalAmount; + + @NotNull(message = "平台分账金额不能为空") + @Min(value = 0, message = "平台分账金额不能小于0") + @Schema(description = "平台分账金额(分)") + private Long platformAmount; + + @NotNull(message = "二维码分账金额不能为空") + @Min(value = 1, message = "二维码分账金额必须大于0") + @Schema(description = "二维码分账金额(分)") + @TableField("qrcode_amount") + private Long qrCodeAmount; + + @Schema(description = "分账状态:0-待分账 1-分账中 2-分账成功 3-分账失败") + private Integer status; + + @NotNull(message = "二维码ID不能为空") + @Schema(description = "二维码ID") + private String codeId; + + @NotNull(message = "分账接收账号不能为空") + @Schema(description = "分账接收账号") + @TableField("payee_account") + private String payeeAccount; + + @NotNull(message = "分账账号类型不能为空") + @Schema(description = "分账账号类型:MERCHANT_ID-商户ID,PERSONAL_OPENID-个人openid") + @TableField("payee_type") + private String payeeType; + + @Length(max = 256, message = "分账描述长度不能超过256") + @Schema(description = "分账描述") + @TableField("description") + private String description; + + @Length(max = 256, message = "分账失败原因长度不能超过256") + @Schema(description = "分账失败原因") + @TableField("fail_reason") + private String failReason; + + @Schema(description = "实际分账金额(分)") + @TableField("receiver_amount") + private Long receiverAmount; + + @Schema(description = "分账完成时间") + @TableField("finish_time") + private Date finishTime; + + @Length(max = 64, message = "分账请求号长度不能超过64") + @Schema(description = "分账请求号") + @TableField("out_order_no") + private String outOrderNo; + + @Schema(description = "重试次数") + @TableField("retry_times") + private Integer retryTimes; + + @Schema(description = "最后重试时间") + @TableField("last_retry_time") + private Date lastRetryTime; + + @Schema(description = "创建时间") + private Date createTime; + + @Schema(description = "更新时间") + private Date updateTime; + + /** + * 获取状态描述 + */ + public String getStatusDesc() { + return ProfitSharingStatusEnum.getDesc(status); + } + + /** + * 获取分账账号类型描述 + */ + public String getPayeeTypeDesc() { + return PayeeTypeEnum.getDesc(payeeType); + } + + /** + * 判断是否可以重试 + * 条件: + * 1. 状态为失败 + * 2. 重试次数小于3次 + * 3. 距离上次重试时间超过5分钟 + */ + public boolean canRetry() { + return status == ProfitSharingStatusEnum.FAILED.getCode() + && (retryTimes == null || retryTimes < 3) + && (lastRetryTime == null || System.currentTimeMillis() - lastRetryTime.getTime() > 300000); + } + + /** + * 更新重试信息 + */ + public void updateRetryInfo() { + this.retryTimes = (this.retryTimes == null ? 0 : this.retryTimes) + 1; + this.lastRetryTime = new Date(); + } + + /** + * 检查金额是否合法 + */ + public boolean isAmountValid() { + return totalAmount != null && totalAmount > 0 + && platformAmount != null && platformAmount >= 0 + && qrCodeAmount != null && qrCodeAmount > 0 + && (platformAmount + qrCodeAmount == totalAmount); + } +} \ No newline at end of file diff --git a/zlt-business/edu-center/src/main/java/com/central/order/model/ProfitSharingResult.java b/zlt-business/edu-center/src/main/java/com/central/order/model/ProfitSharingResult.java new file mode 100644 index 00000000..d6b8dd0d --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/model/ProfitSharingResult.java @@ -0,0 +1,104 @@ +package com.central.order.model; + +import com.central.order.enums.ProfitSharingStatusEnum; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.Date; +import java.util.List; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Schema(description = "分账结果") +public class ProfitSharingResult { + + @Schema(description = "订单号") + private String orderNo; + + @Schema(description = "微信支付订单号") + private String transactionId; + + @Schema(description = "分账单号") + private String profitSharingId; + + @Schema(description = "分账状态") + private Integer status; + + @Schema(description = "分账状态描述") + private String statusDesc; + + @Schema(description = "分账总金额(分)") + private Long totalAmount; + + @Schema(description = "实际分账金额(分)") + private Long receiverAmount; + + @Schema(description = "分账完成时间") + private Date finishTime; + + @Schema(description = "失败原因") + private String failReason; + + @Schema(description = "分账接收方列表") + private List receivers; + + @Data + @Builder + @NoArgsConstructor + @AllArgsConstructor + public static class ReceiverResult { + @Schema(description = "接收方类型") + private String type; + + @Schema(description = "接收方账号") + private String account; + + @Schema(description = "分账金额(分)") + private Long amount; + + @Schema(description = "分账描述") + private String description; + + @Schema(description = "分账结果") + private String result; + + @Schema(description = "失败原因") + private String failReason; + + @Schema(description = "分账明细单号") + private String detailId; + } + + /** + * 获取状态描述 + */ + public String getStatusDesc() { + return ProfitSharingStatusEnum.getDesc(status); + } + + /** + * 判断分账是否成功 + */ + public boolean isSuccess() { + return ProfitSharingStatusEnum.SUCCESS.getCode() == status; + } + + /** + * 判断分账是否失败 + */ + public boolean isFailed() { + return ProfitSharingStatusEnum.FAILED.getCode() == status; + } + + /** + * 判断分账是否处理中 + */ + public boolean isProcessing() { + return ProfitSharingStatusEnum.PROCESSING.getCode() == status; + } +} \ No newline at end of file diff --git a/zlt-business/edu-center/src/main/java/com/central/order/model/QrCode.java b/zlt-business/edu-center/src/main/java/com/central/order/model/QrCode.java new file mode 100644 index 00000000..1ee42371 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/model/QrCode.java @@ -0,0 +1,96 @@ +package com.central.order.model; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.central.common.model.SuperEntity; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.*; + +import java.math.BigDecimal; +import java.util.Date; + +/** + * qrcodes information + * + * @author lsl + * @date 2024-12-19 17:51:47 + */ +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +@EqualsAndHashCode(callSuper = false) +@TableName("qrcodes") +public class QrCode extends SuperEntity { + + private static final long serialVersionUID=1L; + + private String codeId; + private Long tourismId; + + // 新增二维码名称字段 + private String name; + + private String templateId; + private String filePath; + + private transient String viewUrl; + + private String fileId; + private Integer status; + + private String waylineId; + private String price; + + private String deviceSn; + + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; + //租户ID + private String tenantId; + private String company; + private Integer isDel; + + /** + * 分账接收账号 + */ + + private String payeeAccount; + + /** + * 分账比例(百分比,例如:30.00 表示 30%) + */ + + private BigDecimal profitRate; + + /** + * 分账账号类型(MERCHANT_ID:商户ID,PERSONAL_OPENID:个人openid) + */ + + private String payeeType; + + /** + * 分账账号状态(0:未验证,1:已验证,2:验证失败) + */ + + private Integer payeeStatus; + + @Schema(description = "分账失败原因") + private String payeeFailReason; + + /** + * 是否开启分润(0:否,1:是) + */ + @Schema(description = "是否开启分润") + private Integer enableProfit; + + /** + * 是否开启一键成片(0:否,1:是) + */ + @Schema(description = "是否开启一键成片") + private Integer enableVideoEdit; + +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/model/QrCodeVO.java b/zlt-business/edu-center/src/main/java/com/central/order/model/QrCodeVO.java new file mode 100644 index 00000000..198b81df --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/model/QrCodeVO.java @@ -0,0 +1,26 @@ +package com.central.order.model; + +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; + +import java.util.List; + +/** + * qrcodes information + * + * @author lsl + * @date 2024-12-19 17:51:47 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +public class QrCodeVO { + + private static final long serialVersionUID=1L; + + private String codeId; + private Tourism tourism; + private List tourismFiles; + +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/model/Refund.java b/zlt-business/edu-center/src/main/java/com/central/order/model/Refund.java new file mode 100644 index 00000000..c7ca9120 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/model/Refund.java @@ -0,0 +1,51 @@ +package com.central.order.model; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.central.common.model.SuperEntity; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; + +import java.util.Date; + +/** + * Refund information + * + * @author lsl + * @date 2025-2-19 17:51:47 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +@TableName("orders_refund") +public class Refund extends SuperEntity { + private static final long serialVersionUID=1L; + + private String orderNo; + private String refundNo; + + private Long userId; + private String orderAmount; + private String refundAmount; + private String refundReason; + private String refundImgs; + private Integer status; + + private Integer state; + private String approveReason; + + private Date refundTime; + + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; + + private String tenantId; + private String company; + private Integer isDel; + + +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/model/RequestParamsEntity.java b/zlt-business/edu-center/src/main/java/com/central/order/model/RequestParamsEntity.java new file mode 100644 index 00000000..716a1ada --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/model/RequestParamsEntity.java @@ -0,0 +1,38 @@ +package com.central.order.model; + +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotBlank; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.validation.constraints.NotNull; + +/** + * 一键成片请求参数实体类 + * @author lsl + * + */ +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class RequestParamsEntity { + + @Schema(description = "应用ID") + @NotBlank(message = "应用ID不能为空") + private String appId; + + @Schema(description = "任务ID") + @NotBlank(message = "任务ID不能为空") + private String taskId; + + @Schema(description = "回调地址") + @NotBlank(message = "回调地址不能为空") + private String callbackUrl; + + @Schema(description = "素材来源") + @NotNull(message = "素材来源不能为空") + private SourceDTO source; +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/model/SourceDTO.java b/zlt-business/edu-center/src/main/java/com/central/order/model/SourceDTO.java new file mode 100644 index 00000000..ef033105 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/model/SourceDTO.java @@ -0,0 +1,35 @@ +package com.central.order.model; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; +import lombok.Data; +import lombok.Builder; +import lombok.NoArgsConstructor; +import io.swagger.v3.oas.annotations.media.Schema; + +import java.util.List; + +/** + * 定义请求参数中的sourceDTO类 + * @author lsl + * + */ + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class SourceDTO { + @Schema(description = "文本列表") + private List textList; + + @Schema(description = "视频列表") + private List videoList; + + @Schema(description = "音频列表") + private List audioList; + + @Schema(description = "图片列表") + private List imageList; +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/model/Tourism.java b/zlt-business/edu-center/src/main/java/com/central/order/model/Tourism.java new file mode 100644 index 00000000..d0d78196 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/model/Tourism.java @@ -0,0 +1,46 @@ +package com.central.order.model; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.central.common.model.SuperEntity; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; + +import java.util.Date; + +/** + * Device information + * + * @author lsl + * @date 2024-12-19 17:51:47 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +@TableName("tourisms") +public class Tourism extends SuperEntity { + + private static final long serialVersionUID=1L; + + private String tourismName; + private String tourismDesc; + private Integer type; + private Integer status; + + private String tourismNo; + private String tourismAddress; + private String tourismPhone; + private String tourismEmail; + + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; + + //租户ID + private String tenantId; + private String company; + private Integer isDel; +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/model/TourismFile.java b/zlt-business/edu-center/src/main/java/com/central/order/model/TourismFile.java new file mode 100644 index 00000000..3492caa8 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/model/TourismFile.java @@ -0,0 +1,43 @@ +package com.central.order.model; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.central.common.model.SuperEntity; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; + +import java.util.Date; + +/** + * Tourism File information + * + * @author lsl + * @date 2025-2-17 17:51:47 + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +@TableName("tourisms_files") +public class TourismFile extends SuperEntity { + + private static final long serialVersionUID=1L; + + private Long tourismId; + private String imageUrl; + private int type; + private Integer status; + + private String linkUrl; + private String description; + + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; + //租户ID + private String tenantId; + private String company; + private Integer isDel; +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/model/VideoTemplate.java b/zlt-business/edu-center/src/main/java/com/central/order/model/VideoTemplate.java new file mode 100644 index 00000000..acb336ba --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/model/VideoTemplate.java @@ -0,0 +1,52 @@ +package com.central.order.model; + +import com.baomidou.mybatisplus.annotation.*; +import com.central.common.model.SuperEntity; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.util.Date; + +@Data +@EqualsAndHashCode(callSuper = false) +@TableName("video_template") +@Schema(description = "视频模板") +public class VideoTemplate extends SuperEntity { + + @TableId(type = IdType.AUTO) + @Schema(description = "主键ID") + private Long id; + + @Schema(description = "模板ID") + private String templateId; + + @Schema(description = "模板名称") + private String templateName; + + @Schema(description = "模板描述") + private String description; + + @Schema(description = "状态:0-禁用 1-启用") + private Integer status; + + @Schema(description = "模板配置JSON") + private String config; + + @Schema(description = "创建时间") + @TableField(fill = FieldFill.INSERT) + private Date createTime; + + @Schema(description = "更新时间") + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; + + @Schema(description = "租户ID") + private Long tenantId; + + @Schema(description = "所属公司") + private String company; + + @Schema(description = "是否删除:0-否 1-是") + private Integer isDel; +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/model/WxMessageRecord.java b/zlt-business/edu-center/src/main/java/com/central/order/model/WxMessageRecord.java new file mode 100644 index 00000000..29c765d0 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/model/WxMessageRecord.java @@ -0,0 +1,32 @@ +package com.central.order.model; + +import com.baomidou.mybatisplus.annotation.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.Date; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +@TableName("wx_message_record") +public class WxMessageRecord { + @TableId(type = IdType.AUTO) + private Long id; + private String openId; + private String templateId; + private String msgId; + private String content; + private Integer status; + private String errorMsg; + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; + + //租户ID + private Long tenantId; +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/model/WxTemplateInfo.java b/zlt-business/edu-center/src/main/java/com/central/order/model/WxTemplateInfo.java new file mode 100644 index 00000000..bb417033 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/model/WxTemplateInfo.java @@ -0,0 +1,44 @@ +package com.central.order.model; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.Date; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class WxTemplateInfo { + /** + * 模板ID + */ + private String priTmplId; + + /** + * 模板标题 + */ + private String title; + + /** + * 模板内容 + */ + private String content; + + /** + * 模板示例 + */ + private String example; + + /** + * 类型 + */ + private Integer type; + + /** + * 创建时间 + */ + private Date createTime; +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/model/WxUserSubscribe.java b/zlt-business/edu-center/src/main/java/com/central/order/model/WxUserSubscribe.java new file mode 100644 index 00000000..37838285 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/model/WxUserSubscribe.java @@ -0,0 +1,20 @@ +package com.central.order.model; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.LocalDateTime; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class WxUserSubscribe { + private Long id; + private String openId; + private Boolean subscribed; + private LocalDateTime createTime; + private LocalDateTime updateTime; +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/model/dto/CallbackDTO.java b/zlt-business/edu-center/src/main/java/com/central/order/model/dto/CallbackDTO.java new file mode 100644 index 00000000..c1bb33d0 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/model/dto/CallbackDTO.java @@ -0,0 +1,18 @@ +package com.central.order.model.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class CallbackDTO { + private String jobId; + private String status; // SUCCESS, FAILED + private String result; // 处理结果,可能包含视频URL或错误信息 + private String errorCode; + private String errorMessage; +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/model/dto/VideoEditRequest.java b/zlt-business/edu-center/src/main/java/com/central/order/model/dto/VideoEditRequest.java new file mode 100644 index 00000000..4b48a6c3 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/model/dto/VideoEditRequest.java @@ -0,0 +1,36 @@ +package com.central.order.model.dto; + +import lombok.Builder; +import lombok.Data; + +import java.util.List; + +@Data +@Builder +public class VideoEditRequest { + private List sources; + private OutputInfo output; + private String templateId; + private String projectName; + private String pipelineName; + private String callbackUrl; + + @Data + @Builder + public static class MediaInfo { + private String mediaUrl; + private String mediaType; // VIDEO, IMAGE, AUDIO + private Integer duration; // 持续时间(毫秒) + private String text; // 文本内容 + } + + @Data + @Builder + public static class OutputInfo { + private String outputName; + private String outputType; // MP4, MOV等 + private Integer width; + private Integer height; + private String quality; // HD, SD等 + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/model/dto/VideoEditStatus.java b/zlt-business/edu-center/src/main/java/com/central/order/model/dto/VideoEditStatus.java new file mode 100644 index 00000000..b9a6f955 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/model/dto/VideoEditStatus.java @@ -0,0 +1,32 @@ +package com.central.order.model.dto; + +import lombok.Getter; + +/** + * 视频编辑状态枚举 + */ +@Getter +public enum VideoEditStatus { + QUEUED("Queued", "排队中"), + RUNNING("Running", "处理中"), + SUCCESS("Success", "处理成功"), + FAIL("Fail", "处理失败"), + UNKNOWN("Unknown", "未知状态"); + + private final String code; + private final String desc; + + VideoEditStatus(String code, String desc) { + this.code = code; + this.desc = desc; + } + + public static VideoEditStatus fromCode(String code) { + for (VideoEditStatus status : values()) { + if (status.getCode().equals(code)) { + return status; + } + } + return UNKNOWN; + } +} \ No newline at end of file diff --git a/zlt-business/edu-center/src/main/java/com/central/order/model/params/EditTaskQueryParams.java b/zlt-business/edu-center/src/main/java/com/central/order/model/params/EditTaskQueryParams.java new file mode 100644 index 00000000..12cdd010 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/model/params/EditTaskQueryParams.java @@ -0,0 +1,18 @@ +package com.central.order.model.params; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class EditTaskQueryParams { + private Integer page = 1; + private Integer limit = 10; + private String orderSn; + private String jobId; + private Integer status; +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/model/vo/ChartStatistics.java b/zlt-business/edu-center/src/main/java/com/central/order/model/vo/ChartStatistics.java new file mode 100644 index 00000000..ea106819 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/model/vo/ChartStatistics.java @@ -0,0 +1,19 @@ +package com.central.order.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.util.List; + +@Data +@Schema(description = "图表统计数据") +public class ChartStatistics { + @Schema(description = "订单趋势") + private List orderTrend; + + @Schema(description = "设备分布") + private List deviceDistribution; + + @Schema(description = "收入构成") + private List incomeData; +} \ No newline at end of file diff --git a/zlt-business/edu-center/src/main/java/com/central/order/model/vo/DashboardStatisticsVO.java b/zlt-business/edu-center/src/main/java/com/central/order/model/vo/DashboardStatisticsVO.java new file mode 100644 index 00000000..71196488 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/model/vo/DashboardStatisticsVO.java @@ -0,0 +1,28 @@ +package com.central.order.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.util.List; + +@Data +@Schema(description = "首页统计数据VO") +public class DashboardStatisticsVO { + @Schema(description = "订单统计") + private OrderStatistics orderStats; + + @Schema(description = "收入统计") + private IncomeStatistics incomeStats; + + @Schema(description = "航线统计") + private WaylineStatistics waylineStats; + + @Schema(description = "设备统计") + private DeviceStatistics deviceStats; + + @Schema(description = "图表统计") + private ChartStatistics chartStats; + + @Schema(description = "景区排行") + private List tourismRanking; +} \ No newline at end of file diff --git a/zlt-business/edu-center/src/main/java/com/central/order/model/vo/DeviceStatistics.java b/zlt-business/edu-center/src/main/java/com/central/order/model/vo/DeviceStatistics.java new file mode 100644 index 00000000..672589e3 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/model/vo/DeviceStatistics.java @@ -0,0 +1,19 @@ +package com.central.order.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.math.BigDecimal; + +@Data +@Schema(description = "设备统计数据") +public class DeviceStatistics { + @Schema(description = "设备总数") + private Long totalDevices; + + @Schema(description = "在线设备数") + private Long onlineDevices; + + @Schema(description = "设备在线率") + private BigDecimal deviceOnlineRate; +} \ No newline at end of file diff --git a/zlt-business/edu-center/src/main/java/com/central/order/model/vo/DistributionDataVO.java b/zlt-business/edu-center/src/main/java/com/central/order/model/vo/DistributionDataVO.java new file mode 100644 index 00000000..0a287a0c --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/model/vo/DistributionDataVO.java @@ -0,0 +1,16 @@ +package com.central.order.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.math.BigDecimal; + +@Data +@Schema(description = "分布数据") +public class DistributionDataVO { + @Schema(description = "类型") + private String type; + + @Schema(description = "数值") + private BigDecimal value; +} \ No newline at end of file diff --git a/zlt-business/edu-center/src/main/java/com/central/order/model/vo/IncomeDataVO.java b/zlt-business/edu-center/src/main/java/com/central/order/model/vo/IncomeDataVO.java new file mode 100644 index 00000000..568842b0 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/model/vo/IncomeDataVO.java @@ -0,0 +1,16 @@ +package com.central.order.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.math.BigDecimal; + +@Data +@Schema(description = "收入数据") +public class IncomeDataVO { + @Schema(description = "类型") + private String type; + + @Schema(description = "数值") + private BigDecimal value; +} \ No newline at end of file diff --git a/zlt-business/edu-center/src/main/java/com/central/order/model/vo/IncomeStatistics.java b/zlt-business/edu-center/src/main/java/com/central/order/model/vo/IncomeStatistics.java new file mode 100644 index 00000000..07dbfb4a --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/model/vo/IncomeStatistics.java @@ -0,0 +1,19 @@ +package com.central.order.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.math.BigDecimal; + +@Data +@Schema(description = "收入统计数据") +public class IncomeStatistics { + @Schema(description = "总收入(分)") + private Long totalAmount; + + @Schema(description = "今日收入(分)") + private Long todayAmount; + + @Schema(description = "目标完成率") + private BigDecimal targetCompletion; +} \ No newline at end of file diff --git a/zlt-business/edu-center/src/main/java/com/central/order/model/vo/OrderStatistics.java b/zlt-business/edu-center/src/main/java/com/central/order/model/vo/OrderStatistics.java new file mode 100644 index 00000000..a91a0098 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/model/vo/OrderStatistics.java @@ -0,0 +1,22 @@ +package com.central.order.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.math.BigDecimal; + +@Data +@Schema(description = "订单统计数据") +public class OrderStatistics { + @Schema(description = "订单总数") + private Long totalOrders; + + @Schema(description = "今日订单数") + private Long todayOrders; + + @Schema(description = "订单增长率") + private BigDecimal orderGrowth; + + @Schema(description = "订单完成率") + private BigDecimal completionRate; +} \ No newline at end of file diff --git a/zlt-business/edu-center/src/main/java/com/central/order/model/vo/ProfitSharingStatisticsVO.java b/zlt-business/edu-center/src/main/java/com/central/order/model/vo/ProfitSharingStatisticsVO.java new file mode 100644 index 00000000..077c906b --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/model/vo/ProfitSharingStatisticsVO.java @@ -0,0 +1,56 @@ +package com.central.order.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; +import lombok.Builder; + +import java.util.List; + +@Data +@Builder +@Schema(description = "分账统计数据") +public class ProfitSharingStatisticsVO { + @Schema(description = "总分账笔数") + private Long totalCount; + + @Schema(description = "成功笔数") + private Long successCount; + + @Schema(description = "失败笔数") + private Long failCount; + + @Schema(description = "总分账金额(分)") + private Long totalAmount; + + @Schema(description = "金额趋势数据") + private List amountTrend; + + @Schema(description = "成功率数据") + private List successRate; + + @Data + @Builder + public static class TrendData { + @Schema(description = "日期") + private String date; + + @Schema(description = "类型(DAY-日,WEEK-周,MONTH-月)") + private String type; + + @Schema(description = "金额(分)") + private Long amount; + } + + @Data + @Builder + public static class RateData { + @Schema(description = "日期") + private String date; + + @Schema(description = "类型(DAY-日,WEEK-周,MONTH-月)") + private String type; + + @Schema(description = "成功率(0-100)") + private Double value; + } +} \ No newline at end of file diff --git a/zlt-business/edu-center/src/main/java/com/central/order/model/vo/TourismRankingVO.java b/zlt-business/edu-center/src/main/java/com/central/order/model/vo/TourismRankingVO.java new file mode 100644 index 00000000..7e30a636 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/model/vo/TourismRankingVO.java @@ -0,0 +1,19 @@ +package com.central.order.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.math.BigDecimal; + +@Data +@Schema(description = "景区排行数据") +public class TourismRankingVO { + @Schema(description = "景区ID") + private String id; + + @Schema(description = "景区名称") + private String name; + + @Schema(description = "数值") + private BigDecimal value; +} \ No newline at end of file diff --git a/zlt-business/edu-center/src/main/java/com/central/order/model/vo/TrendDataVO.java b/zlt-business/edu-center/src/main/java/com/central/order/model/vo/TrendDataVO.java new file mode 100644 index 00000000..a903059c --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/model/vo/TrendDataVO.java @@ -0,0 +1,19 @@ +package com.central.order.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.math.BigDecimal; + +@Data +@Schema(description = "趋势数据") +public class TrendDataVO { + @Schema(description = "日期") + private String date; + + @Schema(description = "类型") + private String type; + + @Schema(description = "数值") + private BigDecimal value; +} \ No newline at end of file diff --git a/zlt-business/edu-center/src/main/java/com/central/order/model/vo/WaylineStatistics.java b/zlt-business/edu-center/src/main/java/com/central/order/model/vo/WaylineStatistics.java new file mode 100644 index 00000000..54f89bbe --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/model/vo/WaylineStatistics.java @@ -0,0 +1,19 @@ +package com.central.order.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.math.BigDecimal; + +@Data +@Schema(description = "航线统计数据") +public class WaylineStatistics { + @Schema(description = "航线总数") + private Long totalWaylines; + + @Schema(description = "活跃航线数") + private Long activeWaylines; + + @Schema(description = "航线使用率") + private BigDecimal waylineUsage; +} \ No newline at end of file diff --git a/zlt-business/edu-center/src/main/java/com/central/order/scheduler/OrderScheduler.java b/zlt-business/edu-center/src/main/java/com/central/order/scheduler/OrderScheduler.java new file mode 100644 index 00000000..2ee589e3 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/scheduler/OrderScheduler.java @@ -0,0 +1,31 @@ +package com.central.order.scheduler; + +import com.central.order.service.IOrderService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +@Component +@Configuration +@EnableScheduling +public class OrderScheduler { + + @Autowired + private IOrderService orderService; + + // 每隔一定时间(这里设置为每分钟检查一次,可根据实际情况调整)检查订单超时情况 + @Scheduled(fixedRate = 60 * 1000) + public void checkOrderTimeout() { + orderService.checkAndHandleOrderTimeout(); + } + + // 每隔一定时间(这里设置为每分钟检查一次,可根据实际情况调整)检查是否存在未服务完成的订单 +// @Scheduled(fixedRate = 60 * 1000) + public void processOrdersInQueue() { + orderService.processOrdersInQueue(); + } + @Scheduled(fixedRate = 2 * 60 * 1000) + public void processOrdersCompleted() {} +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/scheduler/VideoEditTaskChecker.java b/zlt-business/edu-center/src/main/java/com/central/order/scheduler/VideoEditTaskChecker.java new file mode 100644 index 00000000..bb320b10 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/scheduler/VideoEditTaskChecker.java @@ -0,0 +1,55 @@ +package com.central.order.scheduler; + +import com.central.order.constants.EditTaskStatus; +import com.central.order.model.EditTask; +import com.central.order.service.IEditTaskService; +import com.central.order.service.IVideoEditService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import java.util.List; + +@Slf4j +@Component +public class VideoEditTaskChecker { + + @Autowired + private IEditTaskService editTaskService; + @Autowired + private IVideoEditService videoEditService; + + // 每30秒检查一次任务状态 + @Scheduled(fixedRate = 30000) + public void checkEditTasks() { + try { + // 获取所有处理中的任务 + List processingTasks = editTaskService.getProcessingTasks(); + + for (EditTask task : processingTasks) { + try { + // 检查任务是否超时 + if (isTaskTimeout(task)) { + editTaskService.updateTaskStatus(task.getJobId(), + EditTaskStatus.FAILED, "任务超时"); + continue; + } + + videoEditService.handleEditStatus(task.getJobId()); + + } catch (Exception e) { + log.error("检查任务状态失败: taskId={}", task.getJobId(), e); + } + } + } catch (Exception e) { + log.error("执行任务状态检查失败", e); + } + } + + private boolean isTaskTimeout(EditTask task) { + // 假设2小时超时 + return System.currentTimeMillis() - task.getCreateTime().getTime() > 7200000; + } + +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/scheduler/WxAccessTokenRefreshTask.java b/zlt-business/edu-center/src/main/java/com/central/order/scheduler/WxAccessTokenRefreshTask.java new file mode 100644 index 00000000..f21f4945 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/scheduler/WxAccessTokenRefreshTask.java @@ -0,0 +1,29 @@ +package com.central.order.scheduler; + +import com.central.order.service.IWxAccessTokenService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +@RequiredArgsConstructor +public class WxAccessTokenRefreshTask { + + @Autowired + private IWxAccessTokenService wxAccessTokenService; + + /** + * 每100分钟刷新一次access_token + */ +// @Scheduled(initialDelay = 60000, fixedRate = 6000000) + public void refreshAccessToken() { + try { + log.info("开始执行定时刷新access_token任务"); + wxAccessTokenService.refreshAccessToken(); + } catch (Exception e) { + log.error("定时刷新access_token失败", e); + } + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/IDashboardService.java b/zlt-business/edu-center/src/main/java/com/central/order/service/IDashboardService.java new file mode 100644 index 00000000..e67974aa --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/IDashboardService.java @@ -0,0 +1,10 @@ +package com.central.order.service; + +import com.central.order.model.vo.DashboardStatisticsVO; + +public interface IDashboardService { + /** + * 获取首页统计数据 + */ + DashboardStatisticsVO getDashboardStatistics(); +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/IEditTaskService.java b/zlt-business/edu-center/src/main/java/com/central/order/service/IEditTaskService.java new file mode 100644 index 00000000..6cb96b3f --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/IEditTaskService.java @@ -0,0 +1,76 @@ +package com.central.order.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.central.common.model.PageResult; +import com.central.order.model.EditTask; +import com.central.order.model.params.EditTaskQueryParams; + +import java.util.List; + +/** + * 视频编辑任务服务接口 + */ +public interface IEditTaskService extends IService { + /** + * 创建编辑任务 + * + * @param orderSn 订单编号 + * @param userId 用户ID + * @return 任务实体 + */ + EditTask createTask(String orderSn, Long userId); + + /** + * 更新任务状态 + * + * @param jobId 任务ID + * @param status 状态 + * @param result 结果信息 + * @return 是否更新成功 + */ + boolean updateTaskStatus(String jobId, Integer status, String result); + + /** + * 根据任务ID获取任务 + * + * @param jobId 任务ID + * @return 任务实体 + */ + EditTask getTaskByJobId(String jobId); + + /** + * 根据订单号获取最新任务 + * + * @param orderSn 订单编号 + * @return 任务实体 + */ + EditTask getTaskByOrderSn(String orderSn); + + /** + * 分页查询剪辑任务 + */ + PageResult getTaskList(EditTaskQueryParams params); + + /** + * 保存或更新剪辑任务 + */ + boolean saveOrUpdateTask(EditTask task); + + /** + * 删除剪辑任务 + */ + boolean deleteTask(Integer id); + + /** + * 获取处理中的任务列表 + * @return 处理中的任务列表 + */ + List getProcessingTasks(); + + /** + * 根据jobId获取编辑任务 + * @param jobId 任务ID + * @return 编辑任务信息 + */ + EditTask getByJobId(String jobId); +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/IHomeCarouselService.java b/zlt-business/edu-center/src/main/java/com/central/order/service/IHomeCarouselService.java new file mode 100644 index 00000000..d19bc980 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/IHomeCarouselService.java @@ -0,0 +1,32 @@ +package com.central.order.service; + +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.common.service.ISuperService; +import com.central.order.model.HomeCarousel; + +import java.util.Map; + +/** + * HomeCarousel file information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +public interface IHomeCarouselService extends ISuperService { + /** + * 列表 + * @param params + * @return + */ + PageResult findList(Map params); + + /** + * 创建 + * + * @param tourism + * @return + */ + Result saveOrUpdateHomeCarousel(HomeCarousel tourism) ; +} + diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/IMediaService.java b/zlt-business/edu-center/src/main/java/com/central/order/service/IMediaService.java new file mode 100644 index 00000000..394dccbb --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/IMediaService.java @@ -0,0 +1,25 @@ +package com.central.order.service; + +import com.central.order.model.OrderFile; +import com.central.order.model.TourismFile; +import java.util.List; + +public interface IMediaService { + /** + * 提交编辑任务 + * @param orderNo 订单号 + * @param orderFiles 订单文件列表 + * @return 任务ID + */ + String submitEditTask(String orderNo, List orderFiles); + + /** + * 查询任务状态 + */ + String getTaskStatus(String jobId); + + /** + * 获取任务结果 + */ + String getTaskResult(String jobId); +} \ No newline at end of file diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/IMessageService.java b/zlt-business/edu-center/src/main/java/com/central/order/service/IMessageService.java new file mode 100644 index 00000000..58dcb0f1 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/IMessageService.java @@ -0,0 +1,36 @@ +package com.central.order.service; + +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.common.service.ISuperService; +import com.central.order.model.Message; + +import java.util.Map; + +public interface IMessageService extends ISuperService { + + /** + * 获取消息列表 + */ + PageResult findMessages(Map params); + + /** + * 标记消息已读 + */ + Result markAsRead(Long id); + + /** + * 标记所有消息已读 + */ + Result markAllAsRead(); + + /** + * 删除消息 + */ + Result deleteMessage(Long id); + + /** + * 创建消息 + */ + void createMessage(Message message); +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/IOrderFileService.java b/zlt-business/edu-center/src/main/java/com/central/order/service/IOrderFileService.java new file mode 100644 index 00000000..2dedf00d --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/IOrderFileService.java @@ -0,0 +1,88 @@ +package com.central.order.service; + +import com.central.common.model.PageResult; +import com.central.common.service.ISuperService; +import com.central.order.model.OrderFile; + +import java.util.List; +import java.util.Map; + +/** + * Firmware file information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +public interface IOrderFileService extends ISuperService { + /** + * 列表 + * @param params + * @return + */ + PageResult findList(Map params); + + /** + * 列表 + * @param params + * @return + */ + PageResult findListByUser(Map params); + + /** + * 创建订单文件资源 + * + * @param orderFile + * @return + */ + boolean createOrderFile(OrderFile orderFile) ; + + + /** + * 订单编号查询订单文件资源 + * @param orderNo + * @return + */ + List getOrderFileByOrderNo(String orderNo); + + /** + * 订单编号查询订单文件资源 + * @param orderNo + * @return + */ + List getOrderFileByOrderNoAndFileType(String orderNo,String contentType); + + /** + * 用户ID查询订单文件资源 + * @param userId + * @return + */ + List getOrderFileByUserId(Long userId); + + /** + * 文件ID查询订单文件资源 + * @param fileId + * @return + */ + OrderFile getOrderFileByFileId(String fileId); + + /** + * 删除文件 + * + * @param id + * @return + */ + int delete(Long id); + + /** + * 获取订单的视频文件列表 + * @param orderNo 订单号 + * @return 视频文件列表 + */ + List getOrderVideoFiles(String orderNo); + + /** + * 获取订单图片文件 + */ + List getOrderImageFiles(String orderNo); +} + diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/IOrderService.java b/zlt-business/edu-center/src/main/java/com/central/order/service/IOrderService.java new file mode 100644 index 00000000..08c8685c --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/IOrderService.java @@ -0,0 +1,92 @@ +package com.central.order.service; + +import com.central.common.model.PageResult; +import com.central.common.service.ISuperService; +import com.central.order.model.Order; + +import java.util.List; +import java.util.Map; + +/** + * Firmware file information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +public interface IOrderService extends ISuperService { + /** + * 列表 + * @param params + * @return + */ + PageResult findList(Map params); + + /** + * 创建订单 + * + * @param order + * @return + */ + boolean createOrder(Order order) ; + + /** + * 超时订单自动检查 + */ + void checkAndHandleOrderTimeout() ; + + /** + * 排队订单 + * @return + */ + List getOrdersInQueue(); + + /** + * 排队订单 + * @return + */ + List getOrdersInQueueByDevice(String deviceSn); + /** + * 排队逻辑处理 + */ + void processOrdersInQueue(); + + /** + * 订单编号查询订单 + * @param orderNumber + * @return + */ + Order getOrderByNumber(String orderNumber); + + /** + * 订单信息更新 + * @param order + * @return + */ + boolean updateOrder(Order order); + + List getOrderCountByStatusAndUser(Long userId, Integer... status); + + Long getOrderCountByStatus(Integer status,Long tourismId); + + Order getOrderByStatusAndUser(Integer status, Long userId, Long tourismId); + + /** + * 获取user订单记录 + * @param params + * @return + */ + PageResult findListByUser(Map params); + + + Integer getOrderRankingByOrderId(Long orderId,Long tourismId); + + /** + * 自动更新订单完成状态 + */ + void autoUpdateOrderStatusToComplete(); + + Long getUnCompleteOrderCount(String deviceSn); + + Order getNextQueueOrder(Long tourismId, Long currentOrderId); +} + diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/IOrderStatisticsService.java b/zlt-business/edu-center/src/main/java/com/central/order/service/IOrderStatisticsService.java new file mode 100644 index 00000000..16327d2b --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/IOrderStatisticsService.java @@ -0,0 +1,64 @@ +package com.central.order.service; + +import com.central.common.model.PageResult; +import com.central.common.service.ISuperService; +import com.central.order.model.OrderStatistics; + +import java.util.List; +import java.util.Map; + +public interface IOrderStatisticsService extends ISuperService { + // 基础统计 + PageResult findList(Map params); + + /** + * 生成统计数据 + * @param startTime 开始时间 + * @param endTime 结束时间 + * @return 是否生成成功 + */ + boolean generateStatistics(String startTime, String endTime); + + /** + * 按时间维度统计 + * @param qrcodeId 二维码ID + * @param startTime 开始时间 + * @param endTime 结束时间 + * @param timeType 时间类型(hour/day/month) + * @return 统计数据列表,包含: + * - timeGroup: 时间分组 + * - formatTime: 格式化后的时间 + * - totalOrders: 订单总数 + * - totalAmount: 总金额(分) + * - totalAmountYuan: 总金额(元) + */ + List> statisticsByTime(String qrcodeId, String startTime, String endTime, String timeType); + + /** + * 按景区维度统计 + * @param startTime 开始时间 + * @param endTime 结束时间 + * @return 统计数据列表,包含: + * - tourismId: 景区ID + * - tourismName: 景区名称 + * - totalOrders: 订单总数 + * - completedOrders: 已完成订单数 + * - completionRate: 完成率 + * - totalAmountYuan: 总金额(元) + * - paidAmountYuan: 已支付金额(元) + * - refundAmountYuan: 退款金额(元) + */ + List> statisticsByTourism(String startTime, String endTime); + + /** + * 按设备维度统计 + * @param startTime 开始时间 + * @param endTime 结束时间 + * @return 统计数据列表,包含: + * - deviceSn: 设备编号 + * - totalOrders: 订单总数 + * - totalAmountYuan: 总金额(元) + * - usageRate: 设备使用率 + */ + List> statisticsByDevice(String startTime, String endTime); +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/IPaymentRecordService.java b/zlt-business/edu-center/src/main/java/com/central/order/service/IPaymentRecordService.java new file mode 100644 index 00000000..11f1a8b4 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/IPaymentRecordService.java @@ -0,0 +1,31 @@ +package com.central.order.service; + +import com.central.common.model.PageResult; +import com.central.common.service.ISuperService; +import com.central.order.model.PaymentRecord; + +import java.util.Map; + +/** + * PaymentRecord information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +public interface IPaymentRecordService extends ISuperService { + /** + * 列表 + * @param params + * @return + */ + PageResult findList(Map params); + + /** + * 支付记录 + * @param orderNumber + * @param paymentAmount + * @return + */ + boolean processPayment(String orderNumber, Double paymentAmount); +} + diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/IProfitSharingService.java b/zlt-business/edu-center/src/main/java/com/central/order/service/IProfitSharingService.java new file mode 100644 index 00000000..62458a18 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/IProfitSharingService.java @@ -0,0 +1,60 @@ +package com.central.order.service; + +import com.central.common.model.PageResult; +import com.central.common.service.ISuperService; +import com.central.order.model.Order; +import com.central.order.model.ProfitSharing; +import com.central.order.model.ProfitSharingResult; +import com.central.order.model.QrCode; +import com.central.order.model.vo.ProfitSharingStatisticsVO; + +import java.util.Map; + +public interface IProfitSharingService extends ISuperService { + /** + * 创建分账记录 + */ + ProfitSharing createProfitSharing(Order order, QrCode qrCode); + + /** + * 更新微信支付订单号 + */ + void updateTransactionId(String orderNo, String transactionId); + + /** + * 执行分账 + */ + void executeProfitSharing(String orderNo); + + /** + * 获取分账记录 + */ + ProfitSharing getByOrderNo(String orderNo); + + /** + * 更新分账状态 + */ + void updateProfitSharingStatus(String orderNo, Integer status); + + /** + * 分页查询分账记录 + */ + PageResult findList(Map params); + + /** + * 重试失败的分账 + */ + void retryFailedProfitSharing(String orderNo); + + /** + * 验证并添加接收者 + */ + boolean validateAndAddReceiver(QrCode qrCode); + + /** + * 查询分账状态 + */ + ProfitSharingResult queryProfitSharingStatus(String orderNo); + + ProfitSharingStatisticsVO getStatistics(); +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/IQrCodeService.java b/zlt-business/edu-center/src/main/java/com/central/order/service/IQrCodeService.java new file mode 100644 index 00000000..fa0ef263 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/IQrCodeService.java @@ -0,0 +1,38 @@ +package com.central.order.service; + +import com.central.common.model.PageResult; +import com.central.common.service.ISuperService; +import com.central.order.model.QrCode; + +import java.util.Map; + +/** + * Qrcode file information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +public interface IQrCodeService extends ISuperService { + /** + * 列表 + * @param params + * @return + */ + PageResult findList(Map params); + + /** + * 创建 + * + * @param qrCode + * @return + */ + boolean createQrCode(QrCode qrCode) ; + + /** + * id查询 + * @param codeId + * @return + */ + QrCode getByCodeId(String codeId); +} + diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/IRefundService.java b/zlt-business/edu-center/src/main/java/com/central/order/service/IRefundService.java new file mode 100644 index 00000000..342af85e --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/IRefundService.java @@ -0,0 +1,38 @@ +package com.central.order.service; + +import com.central.common.model.PageResult; +import com.central.common.service.ISuperService; +import com.central.order.model.Refund; + +import java.util.Map; + +/** + * Firmware file information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +public interface IRefundService extends ISuperService { + /** + * 列表 + * @param params + * @return + */ + PageResult findList(Map params); + + /** + * 创建订单 + * + * @param refund + * @return + */ + boolean createRefund(Refund refund) ; + + /** + * + * @param refundNo + */ + Refund getRefundByNo(String refundNo) ; + +} + diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/ITourismFileService.java b/zlt-business/edu-center/src/main/java/com/central/order/service/ITourismFileService.java new file mode 100644 index 00000000..8f784653 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/ITourismFileService.java @@ -0,0 +1,40 @@ +package com.central.order.service; + +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.common.service.ISuperService; +import com.central.order.model.TourismFile; + +import java.util.List; +import java.util.Map; + +/** + * Firmware file information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +public interface ITourismFileService extends ISuperService { + /** + * 列表 + * @param params + * @return + */ + PageResult findList(Map params); + + /** + * 创建 + * + * @param tourismFile + * @return + */ + Result saveOrUpdateTourismFile(TourismFile tourismFile) ; + + /** + * id查询 + * @param id + * @return + */ + List getByTourismId(Long id); +} + diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/ITourismService.java b/zlt-business/edu-center/src/main/java/com/central/order/service/ITourismService.java new file mode 100644 index 00000000..d63fc9d3 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/ITourismService.java @@ -0,0 +1,39 @@ +package com.central.order.service; + +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.common.service.ISuperService; +import com.central.order.model.Tourism; + +import java.util.Map; + +/** + * Firmware file information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +public interface ITourismService extends ISuperService { + /** + * 列表 + * @param params + * @return + */ + PageResult findList(Map params); + + /** + * 创建 + * + * @param tourism + * @return + */ + Result saveOrUpdateTourism(Tourism tourism) ; + + /** + * id查询 + * @param id + * @return + */ + Tourism getTourismById(Long id); +} + diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/IVideoEditService.java b/zlt-business/edu-center/src/main/java/com/central/order/service/IVideoEditService.java new file mode 100644 index 00000000..b90dbacc --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/IVideoEditService.java @@ -0,0 +1,28 @@ +package com.central.order.service; + +import com.central.order.model.OrderFile; +import com.central.order.model.dto.VideoEditStatus; + +import java.util.List; + +/** + * 视频编辑服务接口 + */ +public interface IVideoEditService { + /** + * 提交编辑任务 + * + * @param orderNo 订单号 + * @param orderFiles 订单相关文件 + * @return 任务ID + */ + String submitEditTask(String orderNo, List orderFiles); + + /** + * 查询编辑任务状态 + * + * @param jobId 任务ID + * @return 任务状态 + */ + VideoEditStatus handleEditStatus(String jobId); +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/IVideoTemplateService.java b/zlt-business/edu-center/src/main/java/com/central/order/service/IVideoTemplateService.java new file mode 100644 index 00000000..b634db3c --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/IVideoTemplateService.java @@ -0,0 +1,40 @@ +package com.central.order.service; + +import com.central.common.model.PageResult; +import com.central.common.service.ISuperService; +import com.central.order.model.VideoTemplate; + +import java.util.Map; + +public interface IVideoTemplateService extends ISuperService { + + /** + * 分页查询模板 + */ + PageResult findList(Map params); + + /** + * 添加模板 + */ + boolean saveTemplate(VideoTemplate template); + + /** + * 更新模板 + */ + boolean updateTemplate(VideoTemplate template); + + /** + * 删除模板 + */ + boolean deleteTemplate(Long id); + + /** + * 更新模板状态 + */ + boolean updateStatus(Long id, Integer status); + + /** + * 获取可用模板 + */ + VideoTemplate getActiveTemplate(); +} \ No newline at end of file diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/IWxAccessTokenService.java b/zlt-business/edu-center/src/main/java/com/central/order/service/IWxAccessTokenService.java new file mode 100644 index 00000000..2b81ae59 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/IWxAccessTokenService.java @@ -0,0 +1,14 @@ +package com.central.order.service; + +public interface IWxAccessTokenService { + /** + * 获取access_token + * @return access_token + */ + String getAccessToken(); + + /** + * 刷新access_token + */ + String refreshAccessToken(); +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/IWxMessageRecordService.java b/zlt-business/edu-center/src/main/java/com/central/order/service/IWxMessageRecordService.java new file mode 100644 index 00000000..3ac730e5 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/IWxMessageRecordService.java @@ -0,0 +1,36 @@ +package com.central.order.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.central.common.model.PageResult; +import com.central.order.model.WxMessageRecord; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.Map; + +public interface IWxMessageRecordService extends IService { + /** + * 分页查询消息记录 + */ + PageResult findRecords(Map params); + + /** + * 保存消息记录 + */ + void saveRecord(String openId, String templateId, String content, String msgId, Integer status); + + /** + * 更新消息状态 + */ + void updateStatus(String msgId, Integer status, String errorMsg); + + /** + * 获取时间范围内的发送统计 + */ + Map getStatistics(LocalDateTime startTime, LocalDateTime endTime); + + /** + * 获取失败的消息记录 + */ + List getFailedRecords(); +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/IWxTemplateMessageService.java b/zlt-business/edu-center/src/main/java/com/central/order/service/IWxTemplateMessageService.java new file mode 100644 index 00000000..c753f597 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/IWxTemplateMessageService.java @@ -0,0 +1,9 @@ +package com.central.order.service; + +public interface IWxTemplateMessageService { + /** + * 发送支付成功通知 + */ + void sendPaymentSuccessNotice(String openId, String orderNo, String tourismName, + Integer rank); +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/IWxUserService.java b/zlt-business/edu-center/src/main/java/com/central/order/service/IWxUserService.java new file mode 100644 index 00000000..65744901 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/IWxUserService.java @@ -0,0 +1,11 @@ +package com.central.order.service; + +public interface IWxUserService { + /** + * 通过 unionId 获取服务号的 openId + * + * @param targetUnionId 目标用户的 unionId + * @return 服务号的 openId,如果未找到则返回 null + */ + String getMpOpenIdByUnionId(String targetUnionId); +} \ No newline at end of file diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/WxMiniSubscribeService.java b/zlt-business/edu-center/src/main/java/com/central/order/service/WxMiniSubscribeService.java new file mode 100644 index 00000000..7ca438da --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/WxMiniSubscribeService.java @@ -0,0 +1,35 @@ +package com.central.order.service; + +public interface WxMiniSubscribeService { + /** + * 支付成功后发送小程序订阅消息 + * @param openId 用户openid + * @param orderName 订单名称 + * @param orderNo 订单编号 + * @param tip 温馨提示 + * @param amount 已付金额 + * @param orderTime 下单时间 + */ + void sendPaySuccessMsg(String openId, String orderName, String orderNo, String tip, String amount, String orderTime); + + /** + * 活动即将开始提醒 + */ + void sendActivityStartMsg(String openId, String place, String activityName, String remark, String activityNo); + + /** + * 一键成片制作完成通知 + */ + void sendVideoEditCompleteMsg(String openId, String taskName, String orderNo, String result); + + /** + * 服务进度提醒订阅消息 + * @param openId + * @param taskName + * @param processDesc + * @param orderNo + * @param orderTime + * @param result + */ + void sendServiceProcessMsg(String openId, String taskName,String processDesc, String orderNo,String orderTime, String result, String pageUrl); +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/impl/DashboardServiceImpl.java b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/DashboardServiceImpl.java new file mode 100644 index 00000000..b54102ea --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/DashboardServiceImpl.java @@ -0,0 +1,123 @@ +package com.central.order.service.impl; + +import com.central.order.mapper.DashboardMapper; +import com.central.order.model.vo.*; +import com.central.order.service.IDashboardService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.List; + +@Slf4j +@Service +@RequiredArgsConstructor +public class DashboardServiceImpl implements IDashboardService { + + private final DashboardMapper dashboardMapper; + + @Override + public DashboardStatisticsVO getDashboardStatistics() { + DashboardStatisticsVO statistics = new DashboardStatisticsVO(); + + try { + // 1. 获取订单统计 + statistics.setOrderStats(getOrderStatistics()); + + // 2. 获取收入统计 + statistics.setIncomeStats(getIncomeStatistics()); + + // 5. 获取图表统计 + statistics.setChartStats(getChartStatistics()); + + // 6. 获取景区排行 + statistics.setTourismRanking(getTourismRanking()); + + } catch (Exception e) { + log.error("获取仪表盘统计数据失败", e); + } + + return statistics; + } + + /** + * 获取订单统计 + */ + private OrderStatistics getOrderStatistics() { + OrderStatistics stats = new OrderStatistics(); + + // 获取订单总数 + stats.setTotalOrders(dashboardMapper.getTotalOrders()); + + // 获取今日订单数 + stats.setTodayOrders(dashboardMapper.getTodayOrders()); + + // 计算订单增长率 + Long yesterdayOrders = dashboardMapper.getYesterdayOrders(); + if (yesterdayOrders > 0) { + BigDecimal growth = new BigDecimal(stats.getTodayOrders() - yesterdayOrders) + .divide(new BigDecimal(yesterdayOrders), 4, RoundingMode.HALF_UP) + .multiply(new BigDecimal(100)); + stats.setOrderGrowth(growth); + } + + // 计算完成率 + Long completedOrders = dashboardMapper.getCompletedOrders(); + if (stats.getTotalOrders() > 0) { + BigDecimal completionRate = new BigDecimal(completedOrders) + .divide(new BigDecimal(stats.getTotalOrders()), 4, RoundingMode.HALF_UP) + .multiply(new BigDecimal(100)); + stats.setCompletionRate(completionRate); + } + + return stats; + } + + /** + * 获取收入统计 + */ + private IncomeStatistics getIncomeStatistics() { + IncomeStatistics stats = new IncomeStatistics(); + + // 获取总收入 + stats.setTotalAmount(dashboardMapper.getTotalIncome()); + + // 获取今日收入 + stats.setTodayAmount(dashboardMapper.getTodayIncome()); + + // 计算目标完成率(假设每日目标10000元) + BigDecimal targetAmount = new BigDecimal(1000000); // 100元 * 100(分) + if (stats.getTodayAmount() > 0) { + BigDecimal completion = new BigDecimal(stats.getTodayAmount()) + .divide(targetAmount, 4, RoundingMode.HALF_UP) + .multiply(new BigDecimal(100)); + stats.setTargetCompletion(completion); + } + + return stats; + } + + /** + * 获取图表统计 + */ + private ChartStatistics getChartStatistics() { + ChartStatistics stats = new ChartStatistics(); + + // 获取订单趋势(最近7天) + stats.setOrderTrend(dashboardMapper.getOrderTrend()); + + // 获取收入构成 + stats.setIncomeData(dashboardMapper.getIncomeData()); + + return stats; + } + + /** + * 获取景区排行 + */ + private List getTourismRanking() { + return dashboardMapper.getTourismRanking(); + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/impl/EditTaskServiceImpl.java b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/EditTaskServiceImpl.java new file mode 100644 index 00000000..a69f2089 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/EditTaskServiceImpl.java @@ -0,0 +1,214 @@ +package com.central.order.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.central.common.exception.BusinessException; +import com.central.common.model.PageResult; +import com.central.order.constants.EditTaskStatus; +import com.central.order.mapper.EditTaskMapper; +import com.central.order.model.EditTask; +import com.central.order.model.params.EditTaskQueryParams; +import com.central.order.service.IEditTaskService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.util.Date; +import java.util.List; + +/** + * 视频编辑任务服务实现类 + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class EditTaskServiceImpl extends ServiceImpl implements IEditTaskService { + + private final EditTaskMapper editTaskMapper; + + @Override + @Transactional(rollbackFor = Exception.class) + public EditTask createTask(String orderSn, Long userId) { + try { + EditTask task = EditTask.builder() + .orderSn(orderSn) + .userId(userId) + .status(0) // 初始状态:待处理 + .createTime(new Date()) + .build(); + + // 保存任务 + if (!save(task)) { + throw new BusinessException("创建任务失败"); + } + + return task; + } catch (Exception e) { + log.error("创建编辑任务失败: orderSn={}, userId={}", orderSn, userId, e); + throw new BusinessException("创建任务失败: " + e.getMessage()); + } + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean updateTaskStatus(String jobId, Integer status, String result) { + try { + return update(new LambdaUpdateWrapper() + .eq(EditTask::getJobId, jobId) + .set(EditTask::getStatus, status) + .set(EditTask::getResult, result) + .set(EditTask::getRemark, "状态更新时间:" + new Date())); + } catch (Exception e) { + log.error("更新任务状态失败: jobId={}, status={}", jobId, status, e); + throw new BusinessException("更新任务状态失败: " + e.getMessage()); + } + } + + @Override + public EditTask getTaskByJobId(String jobId) { + try { + return getOne(new LambdaQueryWrapper() + .eq(EditTask::getJobId, jobId)); + } catch (Exception e) { + log.error("查询任务失败: jobId={}", jobId, e); + throw new BusinessException("查询任务失败: " + e.getMessage()); + } + } + + @Override + public EditTask getTaskByOrderSn(String orderSn) { + try { + return getOne(new LambdaQueryWrapper() + .eq(EditTask::getOrderSn, orderSn) + .orderByDesc(EditTask::getId) + .last("LIMIT 1")); + } catch (Exception e) { + log.error("查询订单任务失败: orderSn={}", orderSn, e); + throw new BusinessException("查询订单任务失败: " + e.getMessage()); + } + } + + @Override + public PageResult getTaskList(EditTaskQueryParams params) { + try { + // 构建查询条件 + LambdaQueryWrapper wrapper = new LambdaQueryWrapper() + .eq(StringUtils.hasText(params.getOrderSn()), EditTask::getOrderSn, params.getOrderSn()) + .eq(StringUtils.hasText(params.getJobId()), EditTask::getJobId, params.getJobId()) + .eq(params.getStatus() != null, EditTask::getStatus, params.getStatus()) + .orderByDesc(EditTask::getId); + + // 执行分页查询 + Page page = new Page<>(params.getPage(), params.getLimit()); + Page resultPage = page(page, wrapper); + + // 转换为PageResult + return PageResult.builder() + .data(resultPage.getRecords()) + .resp_code(0) + .count(resultPage.getTotal()) + .build(); + + } catch (Exception e) { + log.error("查询剪辑任务列表失败", e); + throw new BusinessException("查询任务列表失败: " + e.getMessage()); + } + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean saveOrUpdateTask(EditTask task) { + try { + // 参数验证 + validateTask(task); + + // 如果是新增任务 + if (task.getId() == null) { + task.setCreateTime(new Date()); + task.setStatus(EditTaskStatus.PENDING); + } + + // 更新任务 + task.setUpdateTime(new Date()); + return saveOrUpdate(task); + + } catch (Exception e) { + log.error("保存剪辑任务失败: task={}", task, e); + throw new BusinessException("保存任务失败: " + e.getMessage()); + } + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean deleteTask(Integer id) { + try { + // 查询任务 + EditTask task = getById(id); + if (task == null) { + throw new BusinessException("任务不存在"); + } + + // 检查任务状态 + if (EditTaskStatus.isProcessing(task.getStatus())) { + throw new BusinessException("任务处理中,不能删除"); + } + + return removeById(id); + + } catch (Exception e) { + log.error("删除剪辑任务失败: id={}", id, e); + throw new BusinessException("删除任务失败: " + e.getMessage()); + } + } + + @Override + public List getProcessingTasks() { + try { + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(EditTask::getStatus, EditTaskStatus.PROCESSING) + .orderByAsc(EditTask::getCreateTime); + return editTaskMapper.selectList(wrapper); + } catch (Exception e) { + log.error("获取处理中的任务列表失败", e); + throw new BusinessException("获取处理中的任务列表失败: " + e.getMessage()); + } + } + + @Override + public EditTask getByJobId(String jobId) { + try { + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(EditTask::getJobId, jobId) + .last("LIMIT 1"); // 确保只返回一条记录 + + EditTask task = editTaskMapper.selectOne(wrapper); + if (task == null) { + log.warn("未找到编辑任务: jobId={}", jobId); + } + return task; + + } catch (Exception e) { + log.error("查询编辑任务失败: jobId={}", jobId, e); + throw new BusinessException("查询编辑任务失败: " + e.getMessage()); + } + } + + /** + * 验证任务参数 + */ + private void validateTask(EditTask task) { + if (task == null) { + throw new BusinessException("任务参数不能为空"); + } + if (!StringUtils.hasText(task.getOrderSn())) { + throw new BusinessException("订单编号不能为空"); + } + if (task.getUserId() == null) { + throw new BusinessException("用户ID不能为空"); + } + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/impl/HomeCarouselServiceImpl.java b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/HomeCarouselServiceImpl.java new file mode 100644 index 00000000..2e01b6eb --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/HomeCarouselServiceImpl.java @@ -0,0 +1,45 @@ +package com.central.order.service.impl; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.order.mapper.HomeCarouselMapper; +import com.central.order.model.HomeCarousel; +import com.central.order.service.IHomeCarouselService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; + +/** + * Order information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +@Slf4j +@Service +public class HomeCarouselServiceImpl extends SuperServiceImpl implements IHomeCarouselService { + + /** + * 列表 + * @param params + * @return + */ + @Override + public PageResult findList(Map params){ + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findList(page, params); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } + + @Override + public Result saveOrUpdateHomeCarousel(HomeCarousel homeCarousel) { + boolean result = saveOrUpdate(homeCarousel); + return result ? Result.succeed(homeCarousel, "操作成功") : Result.failed("操作失败"); + } + +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/impl/MediaServiceImpl.java b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/MediaServiceImpl.java new file mode 100644 index 00000000..2f73e27f --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/MediaServiceImpl.java @@ -0,0 +1,279 @@ +package com.central.order.service.impl; + +import com.alibaba.fastjson.JSON; +import com.aliyun.sdk.service.ice20201109.AsyncClient; +import com.aliyun.sdk.service.ice20201109.models.GetMediaProducingJobRequest; +import com.aliyun.sdk.service.ice20201109.models.GetMediaProducingJobResponse; +import com.aliyun.sdk.service.ice20201109.models.SubmitMediaProducingJobRequest; +import com.aliyun.sdk.service.ice20201109.models.SubmitMediaProducingJobResponse; +import com.central.common.exception.BusinessException; +import com.central.order.config.AliyunImsConfig; +import com.central.order.feign.FileCenterService; +import com.central.order.model.Order; +import com.central.order.model.OrderFile; +import com.central.order.model.QrCode; +import com.central.order.service.IMediaService; +import com.central.order.service.IOrderFileService; +import com.central.order.service.IOrderService; +import com.central.order.service.IQrCodeService; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +@Slf4j +@Service +@RequiredArgsConstructor +public class MediaServiceImpl implements IMediaService { + + private static final int TASK_SUBMIT_TIMEOUT = 30; + private static final int TASK_QUERY_TIMEOUT = 10; + private static final String OUTPUT_PATH_FORMAT = "output/%s_%s.mp4"; + + @Autowired + private AsyncClient imsClient; + @Autowired + private AliyunImsConfig imsConfig; + @Autowired + private IQrCodeService qrCodeService; + @Autowired + private IOrderService orderService; + @Autowired + private IOrderFileService orderFileService; + @Autowired + private FileCenterService fileCenterService; + + @Override + public String submitEditTask(String orderNo, List orderFiles) { + try { + // 1. 验证并获取必要数据 + TaskSubmitData taskData = validateAndGetTaskData(orderNo, orderFiles); + + // 2. 构建请求参数 + SubmitMediaProducingJobRequest request = buildSubmitRequest(taskData); + + // 3. 提交任务 + return submitTask(request, taskData); + + } catch (BusinessException e) { + log.error("提交编辑任务失败: orderNo={}, error={}", orderNo, e.getMessage()); + throw e; + } catch (Exception e) { + log.error("提交编辑任务异常: orderNo={}", orderNo, e); + throw new BusinessException("提交任务失败: " + e.getMessage()); + } + } + + @Override + public String getTaskStatus(String jobId) { + try { + GetMediaProducingJobRequest request = GetMediaProducingJobRequest.builder() + .jobId(jobId) + .build(); + + CompletableFuture future = imsClient.getMediaProducingJob(request); + GetMediaProducingJobResponse response = future.get(TASK_QUERY_TIMEOUT, TimeUnit.SECONDS); + + return extractTaskStatus(response); + + } catch (Exception e) { + log.error("查询任务状态失败: jobId={}", jobId, e); + throw new BusinessException("查询任务状态失败: " + e.getMessage()); + } + } + + @Override + public String getTaskResult(String jobId) { + try { + GetMediaProducingJobRequest request = GetMediaProducingJobRequest.builder() + .jobId(jobId) + .build(); + + CompletableFuture future = imsClient.getMediaProducingJob(request); + GetMediaProducingJobResponse response = future.get(TASK_QUERY_TIMEOUT, TimeUnit.SECONDS); + log.info("查询剪辑任务RESPONSE: {}", response.toString()); + if (response != null && response.getBody() != null + && response.getBody().getMediaProducingJob() != null) { + // 返回输出URL + return response.getBody().getMediaProducingJob().getMediaURL(); + } + throw new BusinessException("获取任务结果失败: 响应为空"); + } catch (Exception e) { + log.error("获取任务结果失败: jobId={}", jobId, e); + throw new BusinessException("获取任务结果失败: " + e.getMessage()); + } + } + + /** + * 验证并获取任务数据 + */ + private TaskSubmitData validateAndGetTaskData(String orderNo, List orderFiles) { + // 1. 获取订单信息 + Order order = orderService.getOrderByNumber(orderNo); + if (order == null) { + throw new BusinessException("订单不存在"); + } + + // 2. 获取二维码信息 + QrCode qrCode = qrCodeService.getByCodeId(order.getCodeId()); + if (qrCode == null || qrCode.getTemplateId() == null) { + throw new BusinessException("未配置视频模板ID"); + } + + // 3. 获取视频文件 +// List videoFiles = orderFileService.getOrderVideoFiles(orderNo); + if (orderFiles == null || orderFiles.size() < 7) { + throw new BusinessException("订单视频文件数量不足,至少需要2个视频文件"); + } + + return new TaskSubmitData(order, qrCode, orderFiles); + } + + /** + * 构建提交请求 + */ + private SubmitMediaProducingJobRequest buildSubmitRequest(TaskSubmitData taskData) { + String clipsParam = buildClipsParam(taskData); + String outputConfig = buildOutputConfig(taskData.getOrder().getOrderNo()); + String userData = buildUserData(taskData); + + // 打印请求参数 + logRequestParams(taskData, clipsParam, outputConfig, userData); + + return SubmitMediaProducingJobRequest.builder() + .templateId(taskData.getQrCode().getTemplateId()) + .clipsParam(clipsParam) + .outputMediaConfig(outputConfig) + .userData(userData) + .build(); + } + + /** + * 提交任务 + */ + private String submitTask(SubmitMediaProducingJobRequest request, TaskSubmitData taskData) { + try { + CompletableFuture future = imsClient.submitMediaProducingJob(request); + SubmitMediaProducingJobResponse response = future.get(TASK_SUBMIT_TIMEOUT, TimeUnit.SECONDS); + + if (response != null && response.getBody() != null) { + String jobId = response.getBody().getJobId(); + log.info("提交智能一键成片任务成功: orderNo={}, jobId={}, templateId={}", + taskData.getOrder().getOrderNo(), jobId, taskData.getQrCode().getTemplateId()); + return jobId; + } + throw new BusinessException("提交任务失败: 响应为空"); + } catch (TimeoutException e) { + throw new BusinessException("提交任务超时"); + } catch (Exception e) { + throw new BusinessException("提交任务失败: " + e.getMessage()); + } + } + + /** + * 构建剪辑参数 + */ + private String buildClipsParam(TaskSubmitData taskData) { + try { + Map clips = new HashMap<>(); + List videoFiles = taskData.getVideoFiles(); + //@TODO 后期需要通过模板参数进行动态设置clips参数 + clips.put("1", fileCenterService.getViewUrlByPath(videoFiles.get(4).getFilePath())); + clips.put("2", fileCenterService.getViewUrlByPath(videoFiles.get(5).getFilePath())); + clips.put("3", fileCenterService.getViewUrlByPath(videoFiles.get(6).getFilePath())); + clips.put("4", fileCenterService.getViewUrlByPath(videoFiles.get(0).getFilePath())); + clips.put("5", fileCenterService.getViewUrlByPath(videoFiles.get(1).getFilePath())); + clips.put("6", fileCenterService.getViewUrlByPath(videoFiles.get(2).getFilePath())); + clips.put("7", fileCenterService.getViewUrlByPath(videoFiles.get(3).getFilePath())); + + return JSON.toJSONString(clips); + } catch (Exception e) { + throw new BusinessException("构建剪辑参数失败: " + e.getMessage()); + } + } + + /** + * 构建输出配置 + */ + private String buildOutputConfig(String orderNo) { + try { + Map config = new HashMap<>(); + String outputUrl = String.format("https://%s.%s/" + OUTPUT_PATH_FORMAT, + imsConfig.getBucket(), + imsConfig.getOssEndpoint(), + orderNo, + System.currentTimeMillis() + ); + config.put("MediaURL", outputUrl); + return JSON.toJSONString(config); + } catch (Exception e) { + throw new BusinessException("构建输出配置失败: " + e.getMessage()); + } + } + + /** + * 构建用户数据 + */ + private String buildUserData(TaskSubmitData taskData) { + try { + Map userData = new HashMap<>(); + Order order = taskData.getOrder(); + QrCode qrCode = taskData.getQrCode(); + + userData.put("orderNo", order.getOrderNo()); + userData.put("orderId", order.getId()); + userData.put("codeId", order.getCodeId()); + userData.put("templateId", qrCode.getTemplateId()); + userData.put("timestamp", System.currentTimeMillis()); + userData.put("source", "order_center"); + + return JSON.toJSONString(userData); + } catch (Exception e) { + throw new BusinessException("构建用户数据失败: " + e.getMessage()); + } + } + + /** + * 提取任务状态 + */ + private String extractTaskStatus(GetMediaProducingJobResponse response) { + if (response != null && response.getBody() != null + && response.getBody().getMediaProducingJob() != null) { + return response.getBody().getMediaProducingJob().getStatus(); + } + return "UNKNOWN"; + } + + /** + * 记录请求参数 + */ + private void logRequestParams(TaskSubmitData taskData, String clipsParam, + String outputConfig, String userData) { + log.info("提交任务参数: orderNo={}, templateId={}", + taskData.getOrder().getOrderNo(), taskData.getQrCode().getTemplateId()); + log.info("clips参数: {}", clipsParam); + log.info("输出配置: {}", outputConfig); + log.info("用户数据: {}", userData); + } + + + /** + * 任务提交数据封装类 + */ + @Data + @AllArgsConstructor + private static class TaskSubmitData { + private Order order; + private QrCode qrCode; + private List videoFiles; + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/impl/MessageServiceImpl.java b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/MessageServiceImpl.java new file mode 100644 index 00000000..d0036f95 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/MessageServiceImpl.java @@ -0,0 +1,98 @@ +package com.central.order.service.impl; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.context.LoginUserContextHolder; +import com.central.common.context.TenantContextHolder; +import com.central.common.model.LoginAppUser; +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.order.mapper.MessageMapper; +import com.central.order.model.Message; +import com.central.order.service.IMessageService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Date; +import java.util.List; +import java.util.Map; + +@Slf4j +@Service +@RequiredArgsConstructor +public class MessageServiceImpl extends SuperServiceImpl implements IMessageService { + + @Override + public PageResult findMessages(Map params) { + LoginAppUser user = LoginUserContextHolder.getUser(); + + Page page = new Page<>(MapUtils.getInteger(params, "page", 1), + MapUtils.getInteger(params, "limit", 10)); + + List list = baseMapper.findList( + page, + user.getId(), + TenantContextHolder.getTenant(), + params // 作为查询条件传入 + ); + + return PageResult.builder() + .data(list) + .resp_code(0) + .count(page.getTotal()) + .build(); + } + + @Override + public Result markAsRead(Long id) { + try { + int count = baseMapper.markAsRead(id, new Date()); + return count > 0 ? Result.succeed("标记成功") : Result.failed("标记失败"); + } catch (Exception e) { + log.error("标记消息已读失败", e); + return Result.failed("标记失败"); + } + } + + @Override + public Result markAllAsRead() { + try { + int count = baseMapper.markAllAsRead(new Date()); + return count > 0 ? Result.succeed("标记成功") : Result.failed("标记失败"); + } catch (Exception e) { + log.error("标记所有消息已读失败", e); + return Result.failed("标记失败"); + } + } + + @Override + public Result deleteMessage(Long id) { + try { + boolean success = removeById(id); + return success ? Result.succeed("删除成功") : Result.failed("删除失败"); + } catch (Exception e) { + log.error("删除消息失败", e); + return Result.failed("删除失败"); + } + } + + @Transactional(propagation = Propagation.REQUIRES_NEW) + @Override + public void createMessage(Message message) { + try { + log.info("开始保存站内信"); + message.setStatus(0); + message.setCreateTime(new Date()); + message.setTenantId(TenantContextHolder.getTenant()); + baseMapper.insert(message); + log.info("站内信保存成功: id={}", message.getId()); + } catch (Exception e) { + log.error("站内信保存失败", e); + throw e; + } + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/impl/OrderFileServiceImpl.java b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/OrderFileServiceImpl.java new file mode 100644 index 00000000..127ee83f --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/OrderFileServiceImpl.java @@ -0,0 +1,106 @@ +package com.central.order.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.model.PageResult; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.order.mapper.OrderFileMapper; +import com.central.order.model.OrderFile; +import com.central.order.service.IOrderFileService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * Order information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +@Slf4j +@Service +public class OrderFileServiceImpl extends SuperServiceImpl implements IOrderFileService { + + /** + * 列表 + * @param params + * @return + */ + @Override + public PageResult findList(Map params){ + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findList(page, params); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } + + @Override + public PageResult findListByUser(Map params) { + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findListByUser(page, params); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } + + @Override + public boolean createOrderFile(OrderFile orderFile) { + int result = baseMapper.insert(orderFile); + if(result > 0){ + return true; + } + return false; + } + + @Override + public List getOrderFileByOrderNo(String orderNo) { + return baseMapper.getOrderFileByOrderNo(orderNo); + } + + @Override + public List getOrderFileByOrderNoAndFileType(String orderNo, String fileType) { + return baseMapper.getOrderFileByOrderNoAndFileType(orderNo, fileType); + } + + + @Override + public List getOrderFileByUserId(Long userId) { + return baseMapper.getOrderFilesByUserId(userId); + } + + @Override + public OrderFile getOrderFileByFileId(String fileId) { + return baseMapper.getFileByFileId(fileId); + } + + @Override + public int delete(Long id) { + OrderFile orderFile = baseMapper.selectById(id); + if (orderFile != null) { + return baseMapper.deleteById(orderFile.getId()); + } + return 0; + } + + @Override + public List getOrderVideoFiles(String orderNo) { + try { + log.debug("查询订单视频文件: orderNo={}", orderNo); + return baseMapper.getOrderVideoFiles(orderNo); + } catch (Exception e) { + log.error("查询订单视频文件失败: orderNo={}", orderNo, e); + return new ArrayList<>(); + } + } + + @Override + public List getOrderImageFiles(String orderNo) { + return baseMapper.selectList( + new QueryWrapper() + .eq("order_no", orderNo) + .eq("file_type", "image/jpeg") // 假设图片类型为 "image" + .orderByAsc("create_time")); + } + +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/impl/OrderServiceImpl.java b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/OrderServiceImpl.java new file mode 100644 index 00000000..8a2ffbf8 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/OrderServiceImpl.java @@ -0,0 +1,327 @@ +package com.central.order.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.lock.DistributedLock; +import com.central.common.model.PageResult; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.order.enums.OrderStatus; +import com.central.order.event.OrderStatusChangeEvent; +import com.central.order.feign.UserCenterService; +import com.central.order.mapper.OrderFileMapper; +import com.central.order.mapper.OrderMapper; +import com.central.order.mapper.TourismMapper; +import com.central.order.model.Order; +import com.central.order.model.OrderFile; +import com.central.order.model.OrderRanking; +import com.central.order.service.IOrderService; +import com.central.order.util.DateUtils; +import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.context.annotation.Primary; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +/** + * Order information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +@Slf4j +@Service +@Primary +public class OrderServiceImpl extends SuperServiceImpl implements IOrderService { + + private final static String ORDER_LOCK = "order_lock_"; + + @Autowired + private DistributedLock lock; + + private final ExecutorService executorService = Executors.newFixedThreadPool(10); // 线程池,可根据实际并发量调整大小 + + @Autowired + private JsapiServiceExtension service; + + private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); + @Autowired + private OrderMapper orderMapper; + + @Autowired + private TourismMapper tourismMapper; + @Autowired + private OrderFileMapper orderFileMapper; + + @Autowired + private ApplicationEventPublisher eventPublisher; + + @Autowired + private UserCenterService userCenterService; + + /** + * 列表 + * @param params + * @return + */ + @Override + public PageResult findList(Map params){ + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findList(page, params); + for (Order order : list){ + order.setMobile(userCenterService.findUserById(order.getUserId()).getMobile()); + } + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } + + // 创建订单,初始状态为"待支付" + @Override + public boolean createOrder(Order order) { + order.setOrderStatus(OrderStatus.UNPAID.getId()); + String orderNo = generateOrderNumber(order.getTourismId()); + order.setOrderNo(orderNo); + + // 幂等性校验:同一用户、同一二维码、未完成订单只能有一条 + String lockKey = "order:create:" + order.getUserId() + ":" + order.getCodeId(); + try { + return super.saveIdempotency(order, lock, + lockKey, + new QueryWrapper() + .eq("user_id", order.getUserId()) + .eq("code_id", order.getCodeId()) + .ne("order_status", OrderStatus.UNPAID.getId()), // 未支付订单 + "已存在未完成订单"); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + // 异步检查支付超时任务 + @Async + public void checkPayTimeoutAsync(Long orderId) { + // Thread.sleep(5 * 60 * 1000); // 等待5分钟(模拟支付超时时间) + Order order = baseMapper.getOrderById(orderId); + if (order!= null && OrderStatus.PAID.getId().equals(order.getOrderStatus())) { + baseMapper.updateOrderStatus(orderId, OrderStatus.PAID.getId()); + } + } + + // 检查并处理订单超时逻辑,5分钟超时后自动取消 + @Override + public void checkAndHandleOrderTimeout() { + List orders = baseMapper.getOrdersByStatus(OrderStatus.UNPAID.getId()); + long currentTime = new Date().getTime(); + for (Order order : orders) { + long elapsedTime = currentTime - order.getCreateTime().getTime(); + if (TimeUnit.MILLISECONDS.toMinutes(elapsedTime) >= 5) { + baseMapper.updateOrderStatus(order.getId(), OrderStatus.CANCELED.getId()); + } + } + } + + // 获取所有处于排队状态的订单,用于后续按顺序处理 + @Override + public List getOrdersInQueue() { + return baseMapper.getOrdersInQueue(); + } + + @Override + public List getOrdersInQueueByDevice(String deviceSn) { + + return baseMapper.selectList(new QueryWrapper() + .eq("device_sn", deviceSn) + .eq("order_status", OrderStatus.PAID.getId()) + .orderByAsc("id")); + } + + // 处理排队中的订单,当排在前面的用户消费完成后通知下一位用户进行消费操作(此处简化逻辑,实际需结合业务深入实现) + @Override + public void processOrdersInQueue() { + List queueOrders = getOrdersInQueue(); + for (Order order : queueOrders) { + executorService.submit(() -> { + try { + order.setOrderStatus(OrderStatus.DOING.getId()); + updateOrder(order); // 这里会触发事件发布 + } catch (Exception e) { + log.error("处理队列订单失败", e); + } + }); + } + } + + @Override + public Order getOrderByNumber(String orderNumber) { + return baseMapper.getOrderByNumber(orderNumber); + } + + @Override + public boolean updateOrder(Order order) { + try { + // 获取原订单信息 + Order oldOrder = getById(order.getId()); + boolean result = super.saveOrUpdateIdempotency(order, lock, + ORDER_LOCK + order.getOrderNo(), + new QueryWrapper().eq("order_no", order.getOrderNo()), + "订单已存在"); + + // 如果更新成功且状态发生变化,发布事件 + if (result && !order.getOrderStatus().equals(oldOrder.getOrderStatus())) { + // 发布事件前添加日志 + log.info("准备发布订单状态变更事件: orderNo={}, oldStatus={}, newStatus={}", + order.getOrderNo(), oldOrder.getOrderStatus(), order.getOrderStatus()); + + OrderStatusChangeEvent event = new OrderStatusChangeEvent( + this, + oldOrder.getOrderNo(), + oldOrder.getOrderStatus(), + order.getOrderStatus(), + oldOrder.getUserId(), + String.format("订单金额:%.2f分", + order.getOrderAmount() != null && !order.getOrderAmount().isEmpty() + ? Double.parseDouble(order.getOrderAmount().trim()) + : 0.0) + ); + + eventPublisher.publishEvent(event); + log.info("订单状态变更事件发布成功"); + } + return result; + } catch (Exception e) { + log.error("更新订单失败", e); + throw new RuntimeException(e); + } + } + + @Override + public List getOrderCountByStatusAndUser(Long userId, Integer... status) { + return baseMapper.selectList(new QueryWrapper() + .in("order_status", status) + .eq("user_id", userId)); + + } + + @Override + public Long getOrderCountByStatus(Integer status, Long tourismId) { + return baseMapper.selectCount(new QueryWrapper() + .eq("order_status", status).eq("tourism_id", tourismId)); + } + + @Override + public Order getOrderByStatusAndUser(Integer status, Long userId, Long tourismId) { + return baseMapper.selectOne(new QueryWrapper() + .eq("order_status", status) + .eq("user_id", userId) + .eq("tourism_id", tourismId)); + } + + @Override + public PageResult findListByUser(Map params) { + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findListByUser(page, params); + if (list != null && !list.isEmpty()) { + for (Order order : list) { + order.setTourismName(tourismMapper.getTourismById(order.getTourismId()).getTourismName()); + order.setCreatedTime(sdf.format(order.getCreateTime())); + } + } + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } + + @Override + public Integer getOrderRankingByOrderId(Long orderId,Long tourismId) { + + List result = orderMapper.getOrderRanking1(tourismId); + if (!result.isEmpty()) { + for (OrderRanking order : result) { + if (order.getId().equals(orderId)) { + return order.getRanking(); + } + } + } + return 0; + } + + @Override + public void autoUpdateOrderStatusToComplete() { + List orders = baseMapper.getOrdersByStatus(OrderStatus.DOING.getId()); + if (!orders.isEmpty()){ + for (Order order : orders) { + List orderFiles = orderFileMapper.getOrderFileByOrderNo(order.getOrderNo()); + if (!orderFiles.isEmpty()) { + order.setOrderStatus(OrderStatus.COMPLETE.getId()); + orderMapper.updateById(order); + continue; + } + if (DateUtils.isWithinFiveMinutesByNow(order.getUpdateTime())) { + order.setOrderStatus(OrderStatus.COMPLETE.getId()); + orderMapper.updateById(order); + } + } + } + } + + @Override + public Long getUnCompleteOrderCount(String deviceSn) { + return baseMapper.selectCount(new QueryWrapper() + .eq("device_sn", deviceSn) + .in("order_status", OrderStatus.UPLOADING.getId(),OrderStatus.DOING.getId())); + } + + // 生成订单编号 + public String generateOrderNumber(Long tourismId) { + // 获取当前日期,格式化为 yyyyMMdd + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); + Date date = new Date(); + String currentDate = sdf.format(date); + + // 获取当天的起始时间和结束时间,用于查询当天订单数量 + Date startDate = DateUtils.getStartOfDay(date); + Date endDate = DateUtils.getEndOfDay(date); + + // 查询当天已有的订单数量 + List existingOrders = baseMapper.findByShopIdAndCreateTimeGreaterThanEqualAndCreateTimeLessThanEqual(tourismId, startDate, endDate); + int orderCount = existingOrders.size(); + + // 生成当天订单序号,从1开始自增 + int orderSequence = orderCount + 1; + + // 格式化订单序号,确保序号长度固定(例如不足3位前面补0) + String formattedSequence = String.format("%05d", orderSequence); + + // 拼接店铺编号、日期、订单序号形成订单编号 + return tourismId + currentDate + formattedSequence; + } + + @Override + public Order getNextQueueOrder(Long tourismId, Long currentOrderId) { + // 1. 查询当前订单 + Order currentOrder = baseMapper.selectById(currentOrderId); + if (currentOrder == null) { + return null; + } + + // 2. 查询下一个排队订单 + // 假设排队顺序按 createTime 升序,且 orderStatus=1(排队中) + // 你可以根据实际业务调整 orderStatus 的值 + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.eq("tourism_id", tourismId) + .eq("order_status", OrderStatus.PAID.getId()) // 1=排队中,具体值请根据你的枚举定义 + .gt("pay_time", currentOrder.getPayTime()) + .orderByAsc("pay_time") + .last("limit 1"); + + return baseMapper.selectOne(wrapper); + } + +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/impl/OrderStatisticsServiceImpl.java b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/OrderStatisticsServiceImpl.java new file mode 100644 index 00000000..f52e409d --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/OrderStatisticsServiceImpl.java @@ -0,0 +1,303 @@ +package com.central.order.service.impl; + +import com.central.common.model.PageResult; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.order.mapper.OrderStatisticsMapper; +import com.central.order.model.OrderStatistics; +import com.central.order.model.OrderStatisticsQuery; +import com.central.order.service.IOrderStatisticsService; +import com.central.order.service.IQrCodeService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.List; +import java.util.Map; + +@Slf4j +@Service +public class OrderStatisticsServiceImpl extends SuperServiceImpl implements IOrderStatisticsService { + + @Autowired + private OrderStatisticsMapper orderStatisticsMapper; + + @Autowired + private IQrCodeService qrCodeService; + + @Override + public PageResult findList(Map params) { + return null; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean generateStatistics(String startTime, String endTime) { + try { + // 使用新的查询方法 + OrderStatisticsQuery query = OrderStatisticsQuery.builder() + .startTime(startTime) + .endTime(endTime) + .build(); + + List> statisticsList = orderStatisticsMapper.getOrderStatistics(query); + + for (Map statistics : statisticsList) { + OrderStatistics orderStatistics = new OrderStatistics(); + + // 设置基础信息 + orderStatistics.setQrcodeId(String.valueOf(statistics.get("qrcodeId"))); + orderStatistics.setTourismId(getLongValue(statistics.get("tourismId"))); + orderStatistics.setTourismName(String.valueOf(statistics.get("tourismName"))); + orderStatistics.setDeviceSn(String.valueOf(statistics.get("deviceSn"))); + + // 设置订单统计 + orderStatistics.setTotalOrders(getIntegerValue(statistics.get("totalOrders"))); + orderStatistics.setPaidOrders(getIntegerValue(statistics.get("paidOrders"))); + orderStatistics.setCompletedOrders(getIntegerValue(statistics.get("completedOrders"))); + orderStatistics.setCanceledOrders(getIntegerValue(statistics.get("canceledOrders"))); + + // 设置金额统计 + orderStatistics.setTotalAmount(getLongValue(statistics.get("totalAmount"))); + orderStatistics.setPaidAmount(getLongValue(statistics.get("paidAmount"))); + orderStatistics.setRefundAmount(getLongValue(statistics.get("refundAmount"))); + + // 设置默认分账比例和金额 + BigDecimal platformRate = new BigDecimal("0.30"); + BigDecimal tourismRate = new BigDecimal("0.70"); + + orderStatistics.setPlatformRate(platformRate); + orderStatistics.setTourismRate(tourismRate); + + // 计算分账金额 + Long paidAmount = orderStatistics.getPaidAmount(); + if (paidAmount == null) { + paidAmount = 0L; + } + + // 计算平台分成金额 + Long platformAmount = platformRate + .multiply(new BigDecimal(paidAmount)) + .divide(new BigDecimal("100"), 0, RoundingMode.HALF_UP) + .longValue(); + orderStatistics.setPlatformAmount(platformAmount); + + // 计算景区分成金额 + Long tourismAmount = tourismRate + .multiply(new BigDecimal(paidAmount)) + .divide(new BigDecimal("100"), 0, RoundingMode.HALF_UP) + .longValue(); + orderStatistics.setTourismAmount(tourismAmount); + + // 设置时间 + orderStatistics.setStartTime(parseDateTime(startTime)); + orderStatistics.setEndTime(parseDateTime(endTime)); + orderStatistics.setCreateTime(new Date()); + + // 设置统计日期 + SimpleDateFormat dateSdf = new SimpleDateFormat("yyyy-MM-dd"); + orderStatistics.setStatisticsDate(dateSdf.format(new Date())); + + // 设置统计小时 + Calendar cal = Calendar.getInstance(); + orderStatistics.setStatisticsHour(cal.get(Calendar.HOUR_OF_DAY)); + + // 保存统计数据 + orderStatisticsMapper.insert(orderStatistics); + } + + return true; + } catch (Exception e) { + log.error("生成统计数据失败", e); + throw new RuntimeException("生成统计数据失败", e); + } + } + + // 安全的Integer转换方法 + private Integer getIntegerValue(Object value) { + if (value == null) { + return 0; + } + if (value instanceof Integer) { + return (Integer) value; + } + if (value instanceof Long) { + return ((Long) value).intValue(); + } + try { + return Integer.parseInt(value.toString()); + } catch (NumberFormatException e) { + return 0; + } + } + + // 安全的Long转换方法 + private Long getLongValue(Object value) { + if (value == null) { + return 0L; + } + if (value instanceof Long) { + return (Long) value; + } + if (value instanceof Integer) { + return ((Integer) value).longValue(); + } + try { + return Long.parseLong(value.toString()); + } catch (NumberFormatException e) { + return 0L; + } + } + + // 日期转换方法 + private Date parseDateTime(String dateTimeStr) { + try { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + return sdf.parse(dateTimeStr); + } catch (ParseException e) { + log.error("日期解析失败: {}", dateTimeStr, e); + return new Date(); + } + } + + @Override + // 在Service层添加缓存注解 +// @Cacheable(value = "orderStatistics", key = "#startTime + #endTime + #timeType") + public List> statisticsByTime(String qrcodeId, String startTime, String endTime, String timeType) { + try { + String groupField; + switch (timeType) { + case "hour": + groupField = "DATE_FORMAT(o.create_time, '%Y-%m-%d %H:00:00')"; + break; + case "day": + groupField = "DATE_FORMAT(o.create_time, '%Y-%m-%d')"; + break; + case "month": + groupField = "DATE_FORMAT(o.create_time, '%Y-%m')"; + break; + default: + groupField = "DATE_FORMAT(o.create_time, '%Y-%m-%d')"; + } + + OrderStatisticsQuery query = OrderStatisticsQuery.builder() + .startTime(startTime) + .endTime(endTime) + .qrcodeId(qrcodeId) + .groupField(groupField) + .build(); + + List> statistics = baseMapper.getOrderStatisticsByGroup(query); + return processStatisticsResult(statistics); + } catch (Exception e) { + log.error("按时间维度统计失败", e); + return List.of(); + } + } + + @Override + public List> statisticsByTourism(String startTime, String endTime) { + try { + OrderStatisticsQuery query = OrderStatisticsQuery.builder() + .startTime(startTime) + .endTime(endTime) + .groupField("o.tourism_id") + .build(); + + List> statistics = baseMapper.getOrderStatisticsByGroup(query); + return processStatisticsResult(statistics); + } catch (Exception e) { + log.error("按景区维度统计失败", e); + return List.of(); + } + } + + @Override + public List> statisticsByDevice(String startTime, String endTime) { + try { + OrderStatisticsQuery query = OrderStatisticsQuery.builder() + .startTime(startTime) + .endTime(endTime) + .groupField("o.device_sn") + .build(); + + List> statistics = baseMapper.getOrderStatisticsByGroup(query); + return processStatisticsResult(statistics); + } catch (Exception e) { + log.error("按设备维度统计失败", e); + return List.of(); + } + } + + /** + * 处理统计结果 + */ + private List> processStatisticsResult(List> statistics) { + for (Map stat : statistics) { + // 添加金额格式化(转换为元) + Long totalAmount = getLongValue(stat.get("totalAmount")); + Long paidAmount = getLongValue(stat.get("paidAmount")); + Long refundAmount = getLongValue(stat.get("refundAmount")); + + stat.put("totalAmountYuan", formatAmount(totalAmount)); + stat.put("paidAmountYuan", formatAmount(paidAmount)); + stat.put("refundAmountYuan", formatAmount(refundAmount)); + + // 计算完成率 + Integer totalOrders = getIntegerValue(stat.get("totalOrders")); + Integer completedOrders = getIntegerValue(stat.get("completedOrders")); + if (totalOrders > 0) { + double completionRate = (completedOrders * 100.0) / totalOrders; + stat.put("completionRate", String.format("%.2f%%", completionRate)); + } else { + stat.put("completionRate", "0.00%"); + } + } + return statistics; + } + + // 格式化金额 + private String formatAmount(Long amount) { + if (amount == null) { + return "0.00"; + } + return String.format("%.2f", amount / 100.0); + } + + // 格式化时间组 + private String formatTimeGroup(String timeGroup, String timeType) { + if (timeGroup == null) { + return ""; + } + try { + SimpleDateFormat inputFormat; + SimpleDateFormat outputFormat; + switch (timeType) { + case "hour": + inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:00:00"); + outputFormat = new SimpleDateFormat("MM-dd HH:00"); + break; + case "day": + inputFormat = new SimpleDateFormat("yyyy-MM-dd"); + outputFormat = new SimpleDateFormat("MM-dd"); + break; + case "month": + inputFormat = new SimpleDateFormat("yyyy-MM"); + outputFormat = new SimpleDateFormat("yyyy-MM"); + break; + default: + return timeGroup; + } + Date date = inputFormat.parse(timeGroup); + return outputFormat.format(date); + } catch (ParseException e) { + return timeGroup; + } + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/impl/PaymentRecordServiceImpl.java b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/PaymentRecordServiceImpl.java new file mode 100644 index 00000000..df891c15 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/PaymentRecordServiceImpl.java @@ -0,0 +1,96 @@ +package com.central.order.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.lock.DistributedLock; +import com.central.common.model.PageResult; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.order.enums.OrderStatus; +import com.central.order.mapper.PaymentRecordMapper; +import com.central.order.model.Order; +import com.central.order.model.PaymentRecord; +import com.central.order.service.IOrderService; +import com.central.order.service.IPaymentRecordService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; +import java.util.Map; +import java.util.UUID; + +/** + * Order information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +@Slf4j +@Service +public class PaymentRecordServiceImpl extends SuperServiceImpl implements IPaymentRecordService { + + // 定义分布式锁的键,确保唯一性,这里以固定字符串加上当前时间戳来构造 + private final static String PAYMENT_RECORD_LOCK = "payment_records_lock_"; + + private final static String ORDER_LOCK = "order_lock_"; + + @Autowired + private DistributedLock lock; + + @Autowired + private IOrderService orderService; + + /** + * 列表 + * + * @param params + * @return + */ + @Override + public PageResult findList(Map params) { + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findList(page, params); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } + + // 处理订单支付逻辑,处理并发冲突和重复支付等问题 + @Transactional + public boolean processPayment(String orderNumber, Double paymentAmount) { + // 生成唯一支付流水号,用于幂等性判断 + String paymentNumber = UUID.randomUUID().toString(); + + // 幂等性判断,查询是否已存在相同支付流水号的支付记录 + PaymentRecord existingRecord = baseMapper.getPaymentRecordByNumber(paymentNumber); + if (existingRecord != null) { + return true; // 已存在记录,说明支付已处理过,直接返回成功 + } + + // 根据订单编号查询订单信息 + Order order = orderService.getOrderByNumber(orderNumber); + if (order == null || !OrderStatus.UNPAID.getId().equals(order.getOrderStatus())) { + return false; // 订单不存在或状态不符合支付条件,返回失败 + } + PaymentRecord paymentRecord = new PaymentRecord(); + paymentRecord.setOrderNo(orderNumber); + paymentRecord.setPaymentAmount(paymentAmount); + paymentRecord.setOrderId(order.getId()); + paymentRecord.setPaymentNumber(paymentNumber); + paymentRecord.setPaymentAmount(paymentAmount); + try { + order.setOrderStatus(OrderStatus.PAID.getId()); + // 执行支付操作,更新订单状态为已支付,插入支付记录(在事务中保证原子性) + boolean res = orderService.saveOrUpdateIdempotency(order, lock + , ORDER_LOCK + orderNumber, new QueryWrapper().eq("order_no", orderNumber), "状态已更新"); + if (res) { + return super.saveIdempotency(paymentRecord, lock + , PAYMENT_RECORD_LOCK + paymentNumber, new QueryWrapper().eq("payment_no", paymentNumber), "订单已存在"); + + } + return false; + } catch (Exception e) { + throw new RuntimeException(e); + } + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/impl/ProfitSharingServiceImpl.java b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/ProfitSharingServiceImpl.java new file mode 100644 index 00000000..00dd9a88 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/ProfitSharingServiceImpl.java @@ -0,0 +1,768 @@ +package com.central.order.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.exception.BusinessException; +import com.central.common.model.PageResult; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.order.config.ProfitSharingProperties; +import com.central.order.config.TencentPayProperties; +import com.central.order.constants.ProfitSharingConstants; +import com.central.order.enums.ProfitSharingStatusEnum; +import com.central.order.mapper.ProfitSharingMapper; +import com.central.order.model.Order; +import com.central.order.model.ProfitSharing; +import com.central.order.model.ProfitSharingResult; +import com.central.order.model.QrCode; +import com.central.order.model.vo.ProfitSharingStatisticsVO; +import com.central.order.service.IProfitSharingService; +import com.central.order.service.IQrCodeService; +import com.wechat.pay.java.service.profitsharing.ProfitsharingService; +import com.wechat.pay.java.service.profitsharing.model.*; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.apache.commons.lang3.RandomStringUtils; +import org.apache.commons.lang3.time.DateUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Executor; +import java.util.stream.Collectors; + +@Slf4j +@Service +public class ProfitSharingServiceImpl extends SuperServiceImpl implements IProfitSharingService { + + @Autowired + private TencentPayProperties tencentPayProperties; + + @Autowired + private ProfitsharingService profitsharingService; + + @Autowired + private IQrCodeService qrCodeService; + + @Autowired + private ProfitSharingProperties profitSharingProperties; + + @Autowired(required = false) + private Executor profitSharingExecutor; + + @Value("${wechat.pay.platform-rate:0.30}") + private String platformRate; + + @Autowired + private ProfitSharingMapper profitSharingMapper; + + @Override + @Transactional(rollbackFor = Exception.class) + public ProfitSharing createProfitSharing(Order order, QrCode qrCode) { + try { + // 1. 参数校验 + if (order == null || order.getCodeId() == null) { + throw new IllegalArgumentException("订单或二维码ID不能为空"); + } + + // 3. 验证分账账号 + validatePayeeAccount(qrCode); + + // 4. 计算分账金额 + long totalAmount = Long.parseLong(order.getOrderAmount()); + if (totalAmount <= 0) { + throw new IllegalArgumentException("订单金额必须大于0"); + } + + // 使用二维码的分账比例计算 + long qrCodeAmount = calculateQrCodeAmount(totalAmount, qrCode.getProfitRate()); + long platformAmount = totalAmount - qrCodeAmount; + + // 5. 创建分账记录 + ProfitSharing profitSharing = ProfitSharing.builder() + .orderId(order.getId().toString()) + .orderNo(order.getOrderNo()) + .totalAmount(totalAmount) + .platformAmount(platformAmount) + .qrCodeAmount(qrCodeAmount) + .payeeAccount(qrCode.getPayeeAccount()) + .payeeType(qrCode.getPayeeType()) + .codeId(qrCode.getCodeId()) + .status(0) + .createTime(new Date()) + .updateTime(new Date()) + .build(); + + // 6. 保存记录 + save(profitSharing); + log.info("创建分账记录成功: {}", profitSharing); + + return profitSharing; + } catch (Exception e) { + log.error("创建分账记录失败: orderId={}, codeId={}", order.getId(), order.getCodeId(), e); + throw new RuntimeException("创建分账记录失败", e); + } + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void updateTransactionId(String orderNo, String transactionId) { + ProfitSharing profitSharing = getByOrderNo(orderNo); + if (profitSharing != null) { + profitSharing.setTransactionId(transactionId); + profitSharing.setUpdateTime(new Date()); + updateById(profitSharing); + } + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void executeProfitSharing(String orderNo) { + try { + // 1. 获取并验证分账记录 + ProfitSharing profitSharing = validateProfitSharingRecord(orderNo); + + // 2. 检查状态和重试次数 + if (!canExecuteProfitSharing(profitSharing)) { + return; + } + + // 3. 更新状态为处理中 + updateProfitSharingStatus(orderNo, ProfitSharingConstants.Status.PROCESSING); + + // 4. 构建并执行分账请求 + OrdersEntity response = executeProfitSharingRequest(profitSharing); + + // 5. 处理响应 + handleProfitSharingResponse(orderNo, response); + + } catch (Exception e) { + handleProfitSharingError(orderNo, e); + } + } + + private ProfitSharing validateProfitSharingRecord(String orderNo) { + ProfitSharing profitSharing = getByOrderNo(orderNo); + if (profitSharing == null) { + throw new BusinessException("分账记录不存在"); + } + if (StringUtils.isEmpty(profitSharing.getTransactionId())) { + throw new BusinessException("支付交易号不存在"); + } + return profitSharing; + } + + private boolean canExecuteProfitSharing(ProfitSharing profitSharing) { + if (profitSharing.getStatus() == ProfitSharingConstants.Status.SUCCESS) { + log.info("分账已成功完成: {}", profitSharing.getOrderNo()); + return false; + } + + if (profitSharing.getRetryTimes() >= profitSharingProperties.getMaxRetryTimes()) { + log.warn("分账重试次数超限: {}", profitSharing.getOrderNo()); + return false; + } + + return true; + } + + private OrdersEntity executeProfitSharingRequest(ProfitSharing profitSharing) { + CreateOrderRequest request = buildProfitSharingRequest(profitSharing); + try { + return profitsharingService.createOrder(request); + } catch (Exception e) { + log.error("调用微信分账接口失败", e); + throw new BusinessException("分账请求失败"); + } + } + + @Async + public void retryFailedProfitSharing(String orderNo) { + ProfitSharing profitSharing = getByOrderNo(orderNo); + if (profitSharing == null || !canRetry(profitSharing)) { + return; + } + + try { + // 更新重试信息 + updateRetryInfo(profitSharing); + + // 执行分账 + executeProfitSharing(orderNo); + + } catch (Exception e) { + log.error("重试分账失败: orderNo={}", orderNo, e); + } + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean validateAndAddReceiver(QrCode qrCode) { + try { + // 1. 参数校验 + if (qrCode == null) { + log.error("二维码信息为空"); + return false; + } + + if (StringUtils.isEmpty(qrCode.getPayeeAccount())) { + log.error("分账接收方账号为空: codeId={}", qrCode.getCodeId()); + return false; + } + + if (StringUtils.isEmpty(qrCode.getPayeeType())) { + log.error("分账接收方类型为空: codeId={}", qrCode.getCodeId()); + return false; + } + + // 2. 构建添加接收方请求 + AddReceiverRequest request = new AddReceiverRequest(); + request.setAppid(tencentPayProperties.getAppId()); + + // 设置接收方类型 + try { + request.setType(ReceiverType.valueOf(qrCode.getPayeeType())); + } catch (IllegalArgumentException e) { + log.error("无效的接收方类型: type={}", qrCode.getPayeeType()); + updateReceiverStatus(qrCode, 2, "无效的接收方类型"); + return false; + } + + // 设置接收方账号和名称 + request.setAccount(qrCode.getPayeeAccount()); + request.setName(qrCode.getName()); + request.setRelationType(ReceiverRelationType.CUSTOM); + + // 3. 调用微信接口添加接收方 + try { + AddReceiverResponse response = profitsharingService.addReceiver(request); + + // 4. 处理响应结果 + if (response != null && response.getAccount() != null) { + // 更新接收方状态为验证成功 + updateReceiverStatus(qrCode, 1, null); + log.info("添加分账接收方成功: account={}", qrCode.getPayeeAccount()); + return true; + } else { + log.error("添加分账接收方失败: response={}", response); + updateReceiverStatus(qrCode, 2, "接口返回为空"); + return false; + } + + } catch (Exception e) { + String errorMsg = getErrorMessage(e); + log.error("添加分账接收方异常: account={}, error={}", qrCode.getPayeeAccount(), errorMsg); + updateReceiverStatus(qrCode, 2, errorMsg); + return false; + } + + } catch (Exception e) { + log.error("验证并添加分账接收方失败", e); + updateReceiverStatus(qrCode, 2, "系统异常"); + return false; + } + } + + /** + * 更新接收方状态 + */ + private void updateReceiverStatus(QrCode qrCode, Integer status, String failReason) { + try { + qrCode.setPayeeStatus(status); + if (failReason != null) { + // 假设QrCode类中有payeeFailReason字段 + qrCode.setPayeeFailReason(failReason); + } + qrCode.setUpdateTime(new Date()); + qrCodeService.updateById(qrCode); + } catch (Exception e) { + log.error("更新接收方状态失败: codeId={}, status={}", qrCode.getCodeId(), status, e); + } + } + + /** + * 验证接收方类型是否合法 + */ + private boolean isValidReceiverType(String type) { + try { + ReceiverType.valueOf(type); + return true; + } catch (IllegalArgumentException e) { + return false; + } + } + + /** + * 获取格式化的错误信息 + */ + private String getErrorMessage(Exception e) { + String message = e.getMessage(); + if (message == null) { + return "未知错误"; + } + // 移除敏感信息 + message = message.replaceAll("\\{\"password\":\"[^\"]*\"\\}", "{\"password\":\"***\"}"); + // 限制长度 + return message.length() > 200 ? message.substring(0, 200) : message; + } + + private boolean canRetry(ProfitSharing profitSharing) { + return profitSharing.getStatus() == ProfitSharingStatusEnum.FAILED.getCode() + && (profitSharing.getRetryTimes() == null + || profitSharing.getRetryTimes() < profitSharingProperties.getMaxRetryTimes()) + && (profitSharing.getLastRetryTime() == null + || System.currentTimeMillis() - profitSharing.getLastRetryTime().getTime() + > profitSharingProperties.getRetryInterval()); + } + + private void updateRetryInfo(ProfitSharing profitSharing) { + profitSharing.setRetryTimes( + (profitSharing.getRetryTimes() == null ? 0 : profitSharing.getRetryTimes()) + 1 + ); + profitSharing.setLastRetryTime(new Date()); + updateById(profitSharing); + } + + /** + * 处理分账响应 + * @param orderNo 订单号 + * @param response 分账响应 + */ + private void handleProfitSharingResponse(String orderNo, OrdersEntity response) { + try { + if (response == null) { + log.error("分账响应为空: orderNo={}", orderNo); + updateProfitSharingStatus(orderNo, 3); + throw new RuntimeException("分账响应为空"); + } + + OrderStatus state = response.getState(); + ProfitSharing profitSharing = getByOrderNo(orderNo); + + if (state == null) { + log.error("分账状态为空: orderNo={}", orderNo); + updateProfitSharingStatus(orderNo, 3); + throw new RuntimeException("分账状态为空"); + } + + switch (state) { + case PROCESSING: + // 处理中,更新状态并记录 + log.info("分账处理中: orderNo={}", orderNo); + updateProfitSharingStatus(orderNo, 1); + // 可以考虑添加异步任务进行后续查询 + break; + + case FINISHED: + // 分账完成,更新状态和其他相关信息 + log.info("分账成功: orderNo={}, response={}", orderNo, response); + profitSharing.setStatus(2); + profitSharing.setFinishTime(new Date()); + profitSharing.setOrderId(response.getOrderId()); + profitSharing.setUpdateTime(new Date()); + updateById(profitSharing); + + // 记录分账结果详情 + recordProfitSharingResult(orderNo, response); + break; + + default: + // 未知状态 + log.error("未知的分账状态: orderNo={}, state={}", orderNo, state); + updateProfitSharingStatus(orderNo, 3); + throw new RuntimeException("未知的分账状态:" + state); + } + + } catch (Exception e) { + log.error("处理分账响应失败: orderNo={}, response={}", orderNo, response, e); + updateProfitSharingStatus(orderNo, 3); + throw new RuntimeException("处理分账响应失败: " + e.getMessage(), e); + } + } + + /** + * 记录分账结果详情 + */ + private void recordProfitSharingResult(String orderNo, OrdersEntity response) { + try { + ProfitSharing profitSharing = getByOrderNo(orderNo); + if (profitSharing != null) { + // 更新分账接收方信息 + List receivers = response.getReceivers(); + if (receivers != null && !receivers.isEmpty()) { + OrderReceiverDetail receiver = receivers.get(0); + profitSharing.setReceiverAmount(receiver.getAmount()); + profitSharing.setFinishTime(new Date()); + profitSharing.setUpdateTime(new Date()); + updateById(profitSharing); + } + } + } catch (Exception e) { + log.error("记录分账结果详情失败: orderNo={}", orderNo, e); + // 这里只记录日志,不抛出异常,避免影响主流程 + } + } + + @Override + public ProfitSharing getByOrderNo(String orderNo) { + return getOne(new LambdaQueryWrapper() + .eq(ProfitSharing::getOrderNo, orderNo)); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void updateProfitSharingStatus(String orderNo, Integer status) { + ProfitSharing profitSharing = getByOrderNo(orderNo); + if (profitSharing != null) { + profitSharing.setStatus(status); + profitSharing.setUpdateTime(new Date()); + updateById(profitSharing); + } + } + + @Override + public PageResult findList(Map params) { + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.orderByDesc(ProfitSharing::getCreateTime); + + Page result = baseMapper.selectPage(page, wrapper); + return PageResult.builder().data(result.getRecords()).count(result.getTotal()).build(); + } + + private String generateProfitSharingNo() { + return "PS" + System.currentTimeMillis() + RandomStringUtils.randomNumeric(4); + } + + private void validatePayeeAccount(QrCode qrCode) { + if (qrCode.getPayeeAccount() == null) { + throw new IllegalArgumentException("分账账号不能为空"); + } + if (qrCode.getPayeeStatus() != 1) { + throw new IllegalArgumentException("分账账号未验证或验证失败"); + } + } + + private long calculateQrCodeAmount(long totalAmount, BigDecimal profitRate) { + try { + return profitRate.multiply(new BigDecimal(totalAmount)) + .divide(new BigDecimal("100"), 0, RoundingMode.HALF_UP) + .longValue(); + } catch (Exception e) { + log.error("计算分账金额失败: totalAmount={}, profitRate={}", totalAmount, profitRate, e); + throw new RuntimeException("计算分账金额失败", e); + } + } + + // 查询分账结果 + public OrdersEntity queryProfitSharingResult(String outOrderNo, String transactionId) { + try { + QueryOrderRequest request = new QueryOrderRequest(); + request.setOutOrderNo(outOrderNo); + request.setTransactionId(transactionId); + return profitsharingService.queryOrder(request); + } catch (Exception e) { + log.error("查询分账结果失败: outOrderNo={}, transactionId={}", outOrderNo, transactionId, e); + throw new RuntimeException("查询分账结果失败", e); + } + } + + @Override + public ProfitSharingResult queryProfitSharingStatus(String orderNo) { + try { + // 1. 获取分账记录 + ProfitSharing profitSharing = getByOrderNo(orderNo); + if (profitSharing == null) { + throw new IllegalArgumentException("分账记录不存在: " + orderNo); + } + + // 2. 如果分账已完成,直接返回结果 + if (profitSharing.getStatus() == ProfitSharingStatusEnum.SUCCESS.getCode()) { + return buildProfitSharingResult(profitSharing, null); + } + + // 3. 查询微信分账结果 + OrdersEntity response = null; + if (profitSharing.getTransactionId() != null && profitSharing.getOutOrderNo() != null) { + QueryOrderRequest request = new QueryOrderRequest(); + request.setOutOrderNo(profitSharing.getOutOrderNo()); + request.setTransactionId(profitSharing.getTransactionId()); + response = profitsharingService.queryOrder(request); + } + + // 4. 构建返回结果 + return buildProfitSharingResult(profitSharing, response); + + } catch (Exception e) { + log.error("查询分账状态失败: orderNo={}", orderNo, e); + throw new RuntimeException("查询分账状态失败", e); + } + } + + private ProfitSharingResult buildProfitSharingResult(ProfitSharing profitSharing, OrdersEntity response) { + ProfitSharingResult result = ProfitSharingResult.builder() + .orderNo(profitSharing.getOrderNo()) + .transactionId(profitSharing.getTransactionId()) + .profitSharingId(profitSharing.getProfitSharingId()) + .status(profitSharing.getStatus()) + .totalAmount(profitSharing.getTotalAmount()) + .receiverAmount(profitSharing.getReceiverAmount()) + .finishTime(profitSharing.getFinishTime()) + .failReason(profitSharing.getFailReason()) + .build(); + + // 如果有微信返回的分账结果,添加接收方详情 + if (response != null && response.getReceivers() != null) { + List receivers = response.getReceivers().stream() + .map(this::convertToReceiverResult) + .collect(Collectors.toList()); + result.setReceivers(receivers); + } + + return result; + } + + private ProfitSharingResult.ReceiverResult convertToReceiverResult(OrderReceiverDetail detail) { + return ProfitSharingResult.ReceiverResult.builder() + .type(String.valueOf(detail.getType())) + .account(detail.getAccount()) + .amount(detail.getAmount()) + .description(detail.getDescription()) + .result(detail.getResult().toString()) + .failReason(detail.getFailReason().toString()) + .detailId(detail.getDetailId()) + .build(); + } + + private void handleProfitSharingError(String orderNo, Exception e) { + try { + log.error("分账执行失败: orderNo={}", orderNo, e); + + // 1. 获取分账记录 + ProfitSharing profitSharing = getByOrderNo(orderNo); + if (profitSharing == null) { + return; + } + + // 2. 更新分账状态为失败 + profitSharing.setStatus(ProfitSharingStatusEnum.FAILED.getCode()); + profitSharing.setFailReason(getErrorMessage(e)); + profitSharing.setUpdateTime(new Date()); + + // 3. 保存更新 + updateById(profitSharing); + + // 4. 如果开启了自动重试且满足重试条件,则添加重试任务 + if (shouldRetry(profitSharing)) { + scheduleRetry(orderNo); + } + + // 5. 发送告警通知(如果需要) + sendAlertNotification(profitSharing, e); + + } catch (Exception ex) { + log.error("处理分账错误时发生异常", ex); + } + } + + private boolean shouldRetry(ProfitSharing profitSharing) { + return profitSharingProperties.isEnabled() + && profitSharing.canRetry() + && !isSystemError(profitSharing.getFailReason()); + } + + private boolean isSystemError(String failReason) { + // 系统级错误不进行重试,例如:参数错误、签名错误等 + if (failReason == null) { + return false; + } + return failReason.contains("PARAM_ERROR") + || failReason.contains("SIGN_ERROR") + || failReason.contains("INVALID_REQUEST"); + } + + @Async + protected void scheduleRetry(String orderNo) { + try { + // 延迟指定时间后执行重试 + Thread.sleep(profitSharingProperties.getRetryInterval()); + retryFailedProfitSharing(orderNo); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + log.error("重试任务被中断: orderNo={}", orderNo); + } + } + + private void sendAlertNotification(ProfitSharing profitSharing, Exception e) { + try { + // 这里实现告警通知逻辑,例如: + // 1. 发送邮件 + // 2. 发送钉钉消息 + // 3. 发送微信消息 + // 4. 写入告警日志 + + String alertMessage = String.format( + "分账失败告警\n订单号:%s\n失败原因:%s\n重试次数:%d\n异常信息:%s", + profitSharing.getOrderNo(), + profitSharing.getFailReason(), + profitSharing.getRetryTimes(), + e.getMessage() + ); + + log.warn(alertMessage); + + // TODO: 实现具体的告警通知逻辑 + + } catch (Exception ex) { + log.error("发送告警通知失败", ex); + } + } + + /** + * 构建分账请求 + */ + private CreateOrderRequest buildProfitSharingRequest(ProfitSharing profitSharing) { + try { + // 1. 创建分账请求对象 + CreateOrderRequest request = new CreateOrderRequest(); + + // 2. 设置基本信息 + request.setAppid(tencentPayProperties.getAppId()); + request.setTransactionId(profitSharing.getTransactionId()); + request.setOutOrderNo(generateProfitSharingNo()); + + // 3. 设置分账接收方列表 + List receivers = new ArrayList<>(); + CreateOrderReceiver receiver = new CreateOrderReceiver(); + + // 4. 设置接收方信息 + receiver.setType(profitSharing.getPayeeType()); + receiver.setAccount(profitSharing.getPayeeAccount()); + receiver.setAmount(profitSharing.getQrCodeAmount()); + receiver.setDescription("二维码分账"); + + receivers.add(receiver); + request.setReceivers(receivers); + + // 5. 保存分账请求号 + profitSharing.setOutOrderNo(request.getOutOrderNo()); + profitSharing.setUpdateTime(new Date()); + updateById(profitSharing); + + log.info("构建分账请求: orderNo={}, request={}", profitSharing.getOrderNo(), request); + return request; + + } catch (Exception e) { + log.error("构建分账请求失败: profitSharing={}", profitSharing, e); + throw new BusinessException("构建分账请求失败: " + e.getMessage()); + } + } + + /** + * 验证分账请求参数 + */ + private void validateProfitSharingRequest(ProfitSharing profitSharing) { + if (StringUtils.isEmpty(profitSharing.getTransactionId())) { + throw new BusinessException("支付交易号不能为空"); + } + + if (StringUtils.isEmpty(profitSharing.getPayeeAccount())) { + throw new BusinessException("分账接收方账号不能为空"); + } + + if (StringUtils.isEmpty(profitSharing.getPayeeType())) { + throw new BusinessException("分账接收方类型不能为空"); + } + + if (profitSharing.getQrCodeAmount() == null || profitSharing.getQrCodeAmount() <= 0) { + throw new BusinessException("分账金额必须大于0"); + } + + // 验证金额不超过订单总额 + if (profitSharing.getQrCodeAmount() > profitSharing.getTotalAmount()) { + throw new BusinessException("分账金额不能超过订单总额"); + } + } + + @Override + public ProfitSharingStatisticsVO getStatistics() { + try { + // 1. 获取总体统计 + Map totalStats = profitSharingMapper.getTotalStatistics(); + + // 2. 获取最近30天的数据 + Date startTime = DateUtils.addDays(new Date(), -30); + + // 3. 获取趋势数据 + List> dailyTrend = profitSharingMapper.getDailyAmountTrend(startTime); + List amountTrend = convertToTrendData(dailyTrend); + + // 4. 获取成功率数据 + List> dailyRate = profitSharingMapper.getDailySuccessRate(startTime); + List successRate = convertToRateData(dailyRate); + + // 5. 构建返回数据 + return ProfitSharingStatisticsVO.builder() + .totalCount(getLongValue(totalStats, "total_count")) + .successCount(getLongValue(totalStats, "success_count")) + .failCount(getLongValue(totalStats, "fail_count")) + .totalAmount(getLongValue(totalStats, "total_amount")) + .amountTrend(amountTrend) + .successRate(successRate) + .build(); + + } catch (Exception e) { + log.error("获取分账统计数据失败", e); + throw new BusinessException("获取统计数据失败"); + } + } + + private List convertToTrendData(List> dailyTrend) { + return dailyTrend.stream() + .map(map -> ProfitSharingStatisticsVO.TrendData.builder() + .date(String.valueOf(map.get("date"))) + .type(String.valueOf(map.get("type"))) + .amount(getLongValue(map, "amount")) + .build()) + .collect(Collectors.toList()); + } + + private List convertToRateData(List> dailyRate) { + return dailyRate.stream() + .map(map -> ProfitSharingStatisticsVO.RateData.builder() + .date(String.valueOf(map.get("date"))) + .type(String.valueOf(map.get("type"))) + .value(getDoubleValue(map, "value")) + .build()) + .collect(Collectors.toList()); + } + + private Long getLongValue(Map map, String key) { + Object value = map.get(key); + return value == null ? 0L : Long.valueOf(String.valueOf(value)); + } + + private Double getDoubleValue(Map map, String key) { + Object value = map.get(key); + return value == null ? 0.0 : Double.valueOf(String.valueOf(value)); + } + + /** + * 检查是否开启分润 + */ + private boolean isEnableProfit(QrCode qrCode) { + return qrCode != null && + Integer.valueOf(1).equals(qrCode.getEnableProfit()) && + qrCode.getPayeeStatus() != null && + qrCode.getPayeeStatus() == 1; + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/impl/QrCodeServiceImpl.java b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/QrCodeServiceImpl.java new file mode 100644 index 00000000..d6a84862 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/QrCodeServiceImpl.java @@ -0,0 +1,54 @@ +package com.central.order.service.impl; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.model.PageResult; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.order.mapper.QrCodeMapper; +import com.central.order.model.QrCode; +import com.central.order.service.IQrCodeService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; + +/** + * Order information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +@Slf4j +@Service +public class QrCodeServiceImpl extends SuperServiceImpl implements IQrCodeService { + + /** + * 列表 + * @param params + * @return + */ + @Override + public PageResult findList(Map params){ + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findList(page, params); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } + + @Override + public boolean createQrCode(QrCode qrCode) { + int result = baseMapper.insert(qrCode); + if(result > 0){ + return true; + } + return false; + } + + @Override + public QrCode getByCodeId(String codeId) { + return baseMapper.getByCodeId(codeId); + } + + + +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/impl/RefundServiceImpl.java b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/RefundServiceImpl.java new file mode 100644 index 00000000..5265940f --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/RefundServiceImpl.java @@ -0,0 +1,52 @@ +package com.central.order.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.model.PageResult; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.order.mapper.RefundMapper; +import com.central.order.model.Refund; +import com.central.order.service.IRefundService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.context.annotation.Primary; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; + +/** + * Order information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +@Slf4j +@Service +@Primary +public class RefundServiceImpl extends SuperServiceImpl implements IRefundService { + + /** + * 列表 + * @param params + * @return + */ + @Override + public PageResult findList(Map params){ + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findList(page, params); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } + + @Override + public boolean createRefund(Refund refund) { + + return baseMapper.insert(refund) > 0 ? true : false; + } + + @Override + public Refund getRefundByNo(String refundNo) { + return baseMapper.selectOne(new QueryWrapper().eq("refund_no",refundNo)); + } + +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/impl/TourismFileServiceImpl.java b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/TourismFileServiceImpl.java new file mode 100644 index 00000000..8a53b5b9 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/TourismFileServiceImpl.java @@ -0,0 +1,50 @@ +package com.central.order.service.impl; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.order.mapper.TourismFileMapper; +import com.central.order.model.TourismFile; +import com.central.order.service.ITourismFileService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; + +/** + * Order information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +@Slf4j +@Service +public class TourismFileServiceImpl extends SuperServiceImpl implements ITourismFileService { + + /** + * 列表 + * @param params + * @return + */ + @Override + public PageResult findList(Map params){ + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findList(page, params); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } + + @Override + public Result saveOrUpdateTourismFile(TourismFile tourismFile) { + boolean result = saveOrUpdate(tourismFile); + return result ? Result.succeed(tourismFile, "操作成功") : Result.failed("操作失败"); + } + + @Override + public List getByTourismId(Long id) { + return baseMapper.getByTourismId(id); + } + +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/impl/TourismServiceImpl.java b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/TourismServiceImpl.java new file mode 100644 index 00000000..982ebcaf --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/TourismServiceImpl.java @@ -0,0 +1,50 @@ +package com.central.order.service.impl; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.model.PageResult; +import com.central.common.model.Result; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.order.mapper.TourismMapper; +import com.central.order.model.Tourism; +import com.central.order.service.ITourismService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; + +/** + * Order information + * + * @author lsl + * @date 2024-12-19 17:52:54 + */ +@Slf4j +@Service +public class TourismServiceImpl extends SuperServiceImpl implements ITourismService { + + /** + * 列表 + * @param params + * @return + */ + @Override + public PageResult findList(Map params){ + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + List list = baseMapper.findList(page, params); + return PageResult.builder().data(list).resp_code(0).count(page.getTotal()).build(); + } + + @Override + public Result saveOrUpdateTourism(Tourism tourism) { + boolean result = saveOrUpdate(tourism); + return result ? Result.succeed(tourism, "操作成功") : Result.failed("操作失败"); + } + + @Override + public Tourism getTourismById(Long id) { + return baseMapper.getTourismById(id); + } + +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/impl/VideoEditServiceImpl.java b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/VideoEditServiceImpl.java new file mode 100644 index 00000000..445798f5 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/VideoEditServiceImpl.java @@ -0,0 +1,214 @@ +package com.central.order.service.impl; + +import com.central.common.exception.BusinessException; +import com.central.common.model.FileInfo; +import com.central.common.model.SysUser; +import com.central.order.constants.EditTaskStatus; +import com.central.order.feign.FileCenterService; +import com.central.order.feign.UserCenterService; +import com.central.order.model.EditTask; +import com.central.order.model.Order; +import com.central.order.model.OrderFile; +import com.central.order.model.Tourism; +import com.central.order.model.dto.VideoEditStatus; +import com.central.order.service.*; +import com.central.order.util.DateUtils; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Arrays; +import java.util.List; + +/** + * 视频编辑服务实现类 + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class VideoEditServiceImpl implements IVideoEditService { + @Autowired + private IMediaService mediaService; + @Autowired + private IEditTaskService editTaskService; + @Autowired + private IOrderFileService orderFileService; + @Autowired + private FileCenterService fileCenterService; + @Autowired + private IOrderService orderService; + @Autowired + private UserCenterService userCenterService; + @Autowired + private ITourismService tourismService; + @Autowired + private WxMiniSubscribeService wxMiniSubscribeService; + + @Override + @Transactional(rollbackFor = Exception.class) + public String submitEditTask(String orderNo, List orderFiles) { + try { + // 提交智能一键成片任务 + String jobId = mediaService.submitEditTask(orderNo, orderFiles); + + // 更新任务状态 + editTaskService.updateTaskStatus(jobId, EditTaskStatus.PROCESSING, null); + + return jobId; + } catch (Exception e) { + log.error("提交视频编辑任务失败: orderNo={}", orderNo, e); + throw new BusinessException("提交编辑任务失败: " + e.getMessage()); + } + } + + @Override + @Transactional(rollbackFor = Exception.class) + public VideoEditStatus handleEditStatus(String jobId) { + try { + // 1. 获取任务信息 + EditTask task = editTaskService.getByJobId(jobId); + if (task == null) { + throw new BusinessException("任务不存在"); + } + + // 2. 获取任务状态 + String status = mediaService.getTaskStatus(jobId); + VideoEditStatus editStatus = VideoEditStatus.fromCode(status); + + // 3. 处理不同状态 + switch (editStatus) { + case SUCCESS: + handleTaskSuccess(jobId, task); + break; + case FAIL: + handleTaskFailed(jobId, task); + break; + case RUNNING: + // 继续处理中,不需要更新 + break; + default: + log.warn("未知的任务状态: jobId={}, status={}", jobId, status); + } + + return editStatus; + } catch (Exception e) { + log.error("查询任务状态失败: jobId={}", jobId, e); + throw new BusinessException("查询任务状态失败: " + e.getMessage()); + } + } + + /** + * 处理任务成功 + */ + private void handleTaskSuccess(String jobId, EditTask task) { + try { + // 1. 获取输出URL + String outputUrl = mediaService.getTaskResult(jobId); + if (outputUrl == null || outputUrl.isEmpty()) { + throw new BusinessException("获取输出URL失败"); + } + + // 2. 保存视频文件记录 + saveOutputVideo(task.getOrderSn(), outputUrl); + + // 3. 更新任务状态 + editTaskService.updateTaskStatus(jobId, EditTaskStatus.COMPLETED, null); + + log.info("视频编辑任务处理完成: jobId={}, orderNo={}, outputUrl={}", + jobId, task.getOrderSn(), outputUrl); + + // 发送小程序通知 + notifyUser(task.getUserId(),task.getOrderSn()); + + } catch (Exception e) { + log.error("处理任务成功状态失败: jobId={}", jobId, e); + throw new BusinessException("处理任务成功状态失败: " + e.getMessage()); + } + } + + /** + * 处理任务失败 + */ + private void handleTaskFailed(String jobId, EditTask task) { + try { + editTaskService.updateTaskStatus(jobId, EditTaskStatus.FAILED, "任务处理失败"); + log.warn("视频编辑任务失败: jobId={}, orderNo={}", jobId, task.getOrderSn()); + } catch (Exception e) { + log.error("处理任务失败状态失败: jobId={}", jobId, e); + throw new BusinessException("处理任务失败状态失败: " + e.getMessage()); + } + } + + /** + * 保存输出视频信息 + */ + private void saveOutputVideo(String orderNo, String outputUrl) { + try { + FileInfo fileInfo = fileCenterService.creatFileInfo(outputUrl); + Order order = orderService.getOrderByNumber(orderNo); + + OrderFile orderFile = new OrderFile(); + orderFile.setFileId(fileInfo.getId()); + orderFile.setOrderNo(orderNo); + orderFile.setFileType("video/mp4"); + orderFile.setFilePath(extractFilePath(outputUrl)); + orderFile.setUserId(order.getUserId()); + orderFile.setTourismId(order.getTourismId()); + orderFileService.save(orderFile); + } catch (Exception e) { + log.error("保存输出视频信息失败: orderNo={}, outputUrl={}", orderNo, outputUrl, e); + throw new BusinessException("保存视频信息失败: " + e.getMessage()); + } + } + + /** + * 从URL提取文件路径 + */ + private String extractFilePath(String outputUrl) { + try { + // 假设URL格式为: https://bucket.endpoint/output/xxx.mp4 + String[] parts = outputUrl.split("/"); + return String.join("/", Arrays.copyOfRange(parts, 3, parts.length)); + } catch (Exception e) { + log.error("提取文件路径失败: outputUrl={}", outputUrl, e); + throw new BusinessException("提取文件路径失败: " + e.getMessage()); + } + } + + private void notifyUser(Long userId,String orderNo) { + try { + // 1. 获取用户信息 + SysUser user = userCenterService.findUserById(userId); + if (user == null || user.getOpenId() == null) { + log.warn("未找到用户或用户未绑定小程序openId,无法发送成片完成通知: userId={}", userId); + return; + } + + // 2. 获取任务和订单信息 + // 假设 message 里包含订单号或任务名,实际可根据 EditTask 查找 + Order order = orderService.getOrderByNumber(orderNo); + if (order == null) { + log.warn("未找到订单信息,无法发送成片完成通知: orderNo={}", orderNo); + return; + } + + Tourism tourism = tourismService.getTourismById(order.getTourismId()); + String result = "视频已生成请查阅"; + String pageUrl = "pages/album/album"; + wxMiniSubscribeService.sendServiceProcessMsg( + user.getOpenId(), + tourism.getTourismName(), + result, + orderNo, + DateUtils.sdf.format(order.getPayTime()), + "", + pageUrl + ); + log.info("已发送一键成片完成通知: userId={}, openId={}, orderNo={}", userId, user.getOpenId(), orderNo); + } catch (Exception e) { + log.error("发送一键成片完成通知失败: userId={}, message={}", userId, orderNo, e); + } + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/impl/VideoTemplateServiceImpl.java b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/VideoTemplateServiceImpl.java new file mode 100644 index 00000000..f6c7b1aa --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/VideoTemplateServiceImpl.java @@ -0,0 +1,82 @@ +package com.central.order.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.central.common.model.PageResult; +import com.central.common.service.impl.SuperServiceImpl; +import com.central.order.mapper.VideoTemplateMapper; +import com.central.order.model.VideoTemplate; +import com.central.order.service.IVideoTemplateService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Date; +import java.util.Map; + +@Slf4j +@Service +public class VideoTemplateServiceImpl extends SuperServiceImpl implements IVideoTemplateService { + + @Override + public PageResult findList(Map params) { + Page page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); + + LambdaQueryWrapper wrapper = new LambdaQueryWrapper() + .eq(VideoTemplate::getIsDel, 0) + .orderByDesc(VideoTemplate::getCreateTime); + + Page result = baseMapper.selectPage(page, wrapper); + return PageResult.builder().data(result.getRecords()).count(result.getTotal()).build(); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean saveTemplate(VideoTemplate template) { + template.setCreateTime(new Date()); + template.setUpdateTime(new Date()); + template.setIsDel(0); + return save(template); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean updateTemplate(VideoTemplate template) { + template.setUpdateTime(new Date()); + return updateById(template); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean deleteTemplate(Long id) { + VideoTemplate template = getById(id); + if (template != null) { + template.setIsDel(1); + template.setUpdateTime(new Date()); + return updateById(template); + } + return false; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean updateStatus(Long id, Integer status) { + VideoTemplate template = getById(id); + if (template != null) { + template.setStatus(status); + template.setUpdateTime(new Date()); + return updateById(template); + } + return false; + } + + @Override + public VideoTemplate getActiveTemplate() { + return getOne(new LambdaQueryWrapper() + .eq(VideoTemplate::getStatus, 1) + .eq(VideoTemplate::getIsDel, 0) + .orderByDesc(VideoTemplate::getCreateTime) + .last("LIMIT 1")); + } +} \ No newline at end of file diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/impl/WxAccessTokenServiceImpl.java b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/WxAccessTokenServiceImpl.java new file mode 100644 index 00000000..e4b10f44 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/WxAccessTokenServiceImpl.java @@ -0,0 +1,106 @@ +package com.central.order.service.impl; + +import com.central.common.exception.BusinessException; +import com.central.order.service.IWxAccessTokenService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import me.chanjar.weixin.common.error.WxErrorException; +import me.chanjar.weixin.mp.api.WxMpService; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.retry.annotation.Backoff; +import org.springframework.retry.annotation.Recover; +import org.springframework.retry.annotation.Retryable; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestClientException; + +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +@Slf4j +@Service +@RequiredArgsConstructor +public class WxAccessTokenServiceImpl implements IWxAccessTokenService { + + @Autowired + private WxMpService wxMpService; + @Autowired + private StringRedisTemplate redisTemplate; + private static final String ACCESS_TOKEN_KEY = "wx:access_token"; + private static final String ACCESS_TOKEN_LOCK_KEY = "wx:access_token:lock"; + + @Override + public String getAccessToken() { + // 先从Redis获取 + String accessToken = redisTemplate.opsForValue().get(ACCESS_TOKEN_KEY); + if (StringUtils.isNotBlank(accessToken)) { + return accessToken; + } + + // 获取分布式锁 + String lockValue = UUID.randomUUID().toString(); + boolean locked = redisTemplate.opsForValue() + .setIfAbsent(ACCESS_TOKEN_LOCK_KEY, lockValue, 30, TimeUnit.SECONDS); + + if (!locked) { + // 如果没有获取到锁,等待100ms后重试 + try { + Thread.sleep(100); + return getAccessToken(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new BusinessException("获取access_token被中断"); + } + } + + try { + // 双重检查 + accessToken = redisTemplate.opsForValue().get(ACCESS_TOKEN_KEY); + if (StringUtils.isNotBlank(accessToken)) { + return accessToken; + } + + // 刷新token + return refreshAccessToken(); + } finally { + // 释放锁 + if (lockValue.equals(redisTemplate.opsForValue().get(ACCESS_TOKEN_LOCK_KEY))) { + redisTemplate.delete(ACCESS_TOKEN_LOCK_KEY); + } + } + } + + @Retryable( + value = {WxErrorException.class, RestClientException.class}, + maxAttempts = 3, + backoff = @Backoff(delay = 2000, multiplier = 2) + ) + public String refreshAccessToken() { + try { + log.info("开始刷新access_token"); + String newToken = wxMpService.getAccessToken(); + + // 设置到Redis,有效期设置为110分钟(微信token有效期120分钟) + redisTemplate.opsForValue().set(ACCESS_TOKEN_KEY, newToken, 110, TimeUnit.MINUTES); + + log.info("刷新access_token成功"); + return newToken; + } catch (Exception e) { + log.error("刷新access_token失败", e); + throw new BusinessException("刷新access_token失败:" + e.getMessage()); + } + } + + @Recover + public String recover(Exception e) { + log.error("刷新access_token重试耗尽", e); + // 发送告警通知 + sendAlertNotification("刷新access_token失败,请检查网络和配置"); + throw new BusinessException("刷新access_token失败,请稍后重试"); + } + + private void sendAlertNotification(String message) { + // TODO: 实现告警通知逻辑 + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/impl/WxMessageRecordServiceImpl.java b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/WxMessageRecordServiceImpl.java new file mode 100644 index 00000000..2d1e833c --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/WxMessageRecordServiceImpl.java @@ -0,0 +1,112 @@ +package com.central.order.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.central.common.model.PageResult; +import com.central.order.enums.CommonStatus; +import com.central.order.mapper.WxMessageRecordMapper; +import com.central.order.model.WxMessageRecord; +import com.central.order.service.IWxMessageRecordService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.MapUtils; +import org.springframework.stereotype.Service; + +import java.time.LocalDateTime; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Slf4j +@Service +public class WxMessageRecordServiceImpl extends ServiceImpl implements IWxMessageRecordService { + + @Override + public PageResult findRecords(Map params) { + Page page = new Page<>(MapUtils.getInteger(params, "page", 1), + MapUtils.getInteger(params, "limit", 10)); + + QueryWrapper wrapper = new QueryWrapper<>(); + + // 添加查询条件 + String openId = MapUtils.getString(params, "openId"); + if (openId != null) { + wrapper.eq("open_id", openId); + } + + Integer status = MapUtils.getInteger(params, "status"); + if (status != null) { + wrapper.eq("status", status); + } + + String startTime = MapUtils.getString(params, "startTime"); + if (startTime != null) { + wrapper.ge("create_time", startTime); + } + + String endTime = MapUtils.getString(params, "endTime"); + if (endTime != null) { + wrapper.le("create_time", endTime); + } + + wrapper.orderByDesc("create_time"); + + Page recordPage = this.page(page, wrapper); + return PageResult.builder() + .data(recordPage.getRecords()) + .count(recordPage.getTotal()) + .build(); + } + + @Override + public void saveRecord(String openId, String templateId, String content, String msgId, Integer status) { + WxMessageRecord record = WxMessageRecord.builder() + .openId(openId) + .templateId(templateId) + .content(content) + .msgId(msgId) + .status(status) + .build(); + this.save(record); + } + + @Override + public void updateStatus(String msgId, Integer status, String errorMsg) { + WxMessageRecord record = new WxMessageRecord(); + record.setStatus(status); + record.setErrorMsg(errorMsg); + + this.update(record, new QueryWrapper() + .eq("msg_id", msgId)); + } + + @Override + public Map getStatistics(LocalDateTime startTime, LocalDateTime endTime) { + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.between("create_time", startTime, endTime); + + Map statistics = new HashMap<>(); + + // 总发送量 + long total = this.count(wrapper); + statistics.put("total", total); + + // 发送成功量 + long success = this.count(wrapper.clone().eq("status", CommonStatus.ENABLE.getId())); + statistics.put("success", success); + + // 发送失败量 + long failed = this.count(wrapper.clone().eq("status", CommonStatus.UNABLE.getId())); + statistics.put("failed", failed); + + return statistics; + } + + @Override + public List getFailedRecords() { + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.eq("status", CommonStatus.UNABLE.getId()) + .orderByDesc("create_time"); + return this.list(wrapper); + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/impl/WxMiniSubscribeServiceImpl.java b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/WxMiniSubscribeServiceImpl.java new file mode 100644 index 00000000..f014dc0b --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/WxMiniSubscribeServiceImpl.java @@ -0,0 +1,83 @@ +package com.central.order.service.impl; + +import cn.binarywang.wx.miniapp.api.WxMaService; +import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage; +import com.central.order.service.WxMiniSubscribeService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; + + +@Slf4j +@Service +public class WxMiniSubscribeServiceImpl implements WxMiniSubscribeService { + + @Value("${wx.mini.template.pay-success}") + private String templateId; + + @Value("${wx.mini.template.service-process}") + private String serviceProcessTemplateId; + + @Autowired + private WxMaService wxMaService; + + @Override + public void sendPaySuccessMsg(String openId, String orderName, String orderNo, String tip, String amount, String orderTime) { + try { + WxMaSubscribeMessage msg = new WxMaSubscribeMessage(); + msg.setToUser(openId); + msg.setTemplateId(templateId); + msg.setPage("pages/task/task"); // 可选跳转页面 + + List dataList = new ArrayList<>(); + dataList.add(new WxMaSubscribeMessage.MsgData("thing1", orderName)); // 订单名称 + dataList.add(new WxMaSubscribeMessage.MsgData("character_string2", orderNo)); // 订单编号 + dataList.add(new WxMaSubscribeMessage.MsgData("thing4", tip)); // 温馨提示 + dataList.add(new WxMaSubscribeMessage.MsgData("amount9", amount)); // 已付金额 + dataList.add(new WxMaSubscribeMessage.MsgData("time10", orderTime)); // 下单时间 + msg.setData(dataList); + + wxMaService.getSubscribeService().sendSubscribeMsg(msg); + log.info("小程序支付成功订阅消息发送成功: openId={}, orderNo={}", openId, orderNo); + } catch (Exception e) { + log.error("小程序支付成功订阅消息发送失败: openId={}, orderNo={}, error={}", openId, orderNo, e.getMessage(), e); + } + } + + @Override + public void sendActivityStartMsg(String openId, String place, String activityName, String remark, String activityNo) { + + } + + @Override + public void sendVideoEditCompleteMsg(String openId, String taskName, String orderNo, String result) { + + } + + @Override + public void sendServiceProcessMsg(String openId, String taskName, String processDesc, String orderNo, String orderTime, String result, String pageUrl) { + try { + WxMaSubscribeMessage msg = new WxMaSubscribeMessage(); + msg.setToUser(openId); + msg.setTemplateId(serviceProcessTemplateId); + msg.setPage(pageUrl); // 可选跳转页面 "pages/task/task" + + List dataList = new ArrayList<>(); + dataList.add(new WxMaSubscribeMessage.MsgData("thing1", taskName)); // 服务名称 + dataList.add(new WxMaSubscribeMessage.MsgData("thing4", processDesc)); // 服务阶段 + dataList.add(new WxMaSubscribeMessage.MsgData("character_string7", orderNo)); // 订单编号 + dataList.add(new WxMaSubscribeMessage.MsgData("time8", orderTime)); // 已付金额 + dataList.add(new WxMaSubscribeMessage.MsgData("thing6", processDesc)); // 备注 + msg.setData(dataList); + + wxMaService.getSubscribeService().sendSubscribeMsg(msg); + log.info("小程序服务进度订阅消息发送成功: openId={}, orderNo={}", openId, orderNo); + } catch (Exception e) { + log.error("小程序服务进度订阅消息发送失败: openId={}, orderNo={}, error={}", openId, orderNo, e.getMessage(), e); + } + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/impl/WxTemplateMessageServiceImpl.java b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/WxTemplateMessageServiceImpl.java new file mode 100644 index 00000000..9bcb1d46 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/WxTemplateMessageServiceImpl.java @@ -0,0 +1,179 @@ +package com.central.order.service.impl; + +import com.central.common.exception.BusinessException; +import com.central.order.config.TencentPayProperties; +import com.central.order.config.WxMpProperties; +import com.central.order.enums.CommonStatus; +import com.central.order.model.WxMessageRecord; +import com.central.order.service.IWxMessageRecordService; +import com.central.order.service.IWxTemplateMessageService; +import com.central.order.service.IWxUserService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import me.chanjar.weixin.common.error.WxErrorException; +import me.chanjar.weixin.mp.api.WxMpService; +import me.chanjar.weixin.mp.bean.template.WxMpTemplateData; +import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.retry.annotation.Backoff; +import org.springframework.retry.annotation.Recover; +import org.springframework.retry.annotation.Retryable; +import org.springframework.stereotype.Service; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Arrays; + +@Slf4j +@Service +@RequiredArgsConstructor +public class WxTemplateMessageServiceImpl implements IWxTemplateMessageService { + + @Autowired + private WxMpService wxMpService; + @Autowired + private WxMpProperties wxMpProperties; + + @Autowired + private IWxUserService wxUserService; + + @Autowired + private TencentPayProperties tencentPayProperties; + @Autowired + private IWxMessageRecordService wxMessageRecordService; + + @Override + @Retryable(value = WxErrorException.class, maxAttempts = 3, backoff = @Backoff(delay = 1000, multiplier = 2)) + public void sendPaymentSuccessNotice(String unionId, String orderNo, String tourismName, + Integer rank) { + log.info("准备发送支付成功通知: openId={}, orderNo={}, serviceName={}, amount={}, tourTime={}", + unionId, orderNo, tourismName, rank); + + // 参数验证 + if (StringUtils.isAnyBlank(unionId, orderNo, tourismName)) { + throw new BusinessException("参数不能为空"); + } + + try { + String openId = wxUserService.getMpOpenIdByUnionId(unionId); + log.info("获取到服务号openId={}", openId); + // 构建模板消息 + WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder() + .toUser(openId) + .templateId(wxMpProperties.getTemplateId().getPaymentSuccess()) + .data(Arrays.asList( + new WxMpTemplateData("thing2", tourismName+"提示: 您当前排在第"+rank+"位!"), + new WxMpTemplateData("time3", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))), + new WxMpTemplateData("character_string1", orderNo) +// new WxMpTemplateData("amount4", "19.90") + )) + .miniProgram(new WxMpTemplateMessage.MiniProgram( + tencentPayProperties.getAppId(), + "pages/index/index", + true)) + .build(); + + // 发送消息并获取消息ID + String msgId = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage); + + // 记录发送结果 + log.info("模板消息发送成功: openId={}, orderNo={}, msgId={}", openId, orderNo, msgId); + + // 保存发送记录 + saveMessageRecord(openId, msgId, templateMessage,CommonStatus.ENABLE.getId()); + + } catch (WxErrorException e) { + log.error("发送模板消息失败: unionId={}, orderNo={}, errorCode={}, errorMsg={}", + unionId, orderNo, e.getError().getErrorCode(), e.getError().getErrorMsg()); + // 保存发送记录 @TODO +// saveMessageRecord(openId, msgId, templateMessage,CommonStatus.ENABLE.getId()); + throw new BusinessException("发送失败:" + e.getError().getErrorMsg()); + } + } + + private String formatDateTime(LocalDateTime dateTime) { + if (dateTime == null) { + return ""; + } + return dateTime.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm")); + } + + private String formatAmount(BigDecimal amount) { + if (amount == null) { + return "0.00"; + } + return amount.setScale(2, RoundingMode.HALF_UP).toString() + "元"; + } + + private void saveMessageRecord(String openId, String msgId, WxMpTemplateMessage templateMessage,Integer status) { + try { + // 1. 提取模板消息内容 + String content = extractMessageContent(templateMessage); + + // 2. 构建消息记录 + WxMessageRecord record = WxMessageRecord.builder() + .openId(openId) + .templateId(templateMessage.getTemplateId()) + .msgId(msgId) + .content(content) + .status(status) + .build(); + + // 3. 保存记录 + log.info("准备保存微信消息记录: openId={}, msgId={}, templateId={}", + openId, msgId, templateMessage.getTemplateId()); + wxMessageRecordService.save(record); + log.info("微信消息记录保存成功: msgId={}", msgId); + + } catch (Exception e) { + log.error("保存微信消息记录失败: openId={}, msgId={}, error={}", + openId, msgId, e.getMessage(), e); + // 这里选择不抛出异常,因为消息已经发送成功,记录保存失败不应影响主流程 + } + } + + /** + * 提取模板消息内容 + */ + private String extractMessageContent(WxMpTemplateMessage templateMessage) { + StringBuilder content = new StringBuilder(); + + // 提取小程序信息 + if (templateMessage.getMiniProgram() != null) { + content.append("小程序信息:") + .append("appid=").append(templateMessage.getMiniProgram().getAppid()) + .append(", path=").append(templateMessage.getMiniProgram().getPagePath()) + .append("\n"); + } + + // 提取模板数据 + if (templateMessage.getData() != null) { + content.append("模板数据:\n"); + templateMessage.getData().forEach(data -> + content.append(data.getName()) + .append("=") + .append(data.getValue()) + .append("\n") + ); + } + + // 如果内容过长,进行截断 + String result = content.toString(); + if (result.length() > 500) { // 假设数据库字段长度限制为500 + result = result.substring(0, 497) + "..."; + } + + return result; + } + + @Recover + public void recover(WxErrorException e, String openId, String orderNo, + String serviceName, BigDecimal amount, LocalDateTime tourTime) { + log.error("发送模板消息重试耗尽: openId={}, orderNo={}, error={}", + openId, orderNo, e.getMessage()); + // TODO: 实现失败处理逻辑 + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/service/impl/WxUserServiceImpl.java b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/WxUserServiceImpl.java new file mode 100644 index 00000000..0c3da5cf --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/service/impl/WxUserServiceImpl.java @@ -0,0 +1,72 @@ +package com.central.order.service.impl; + +import com.central.order.service.IWxUserService; +import lombok.extern.slf4j.Slf4j; +import me.chanjar.weixin.common.error.WxErrorException; +import me.chanjar.weixin.mp.api.WxMpService; +import me.chanjar.weixin.mp.api.WxMpUserService; +import me.chanjar.weixin.mp.bean.result.WxMpUser; +import me.chanjar.weixin.mp.bean.result.WxMpUserList; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.retry.annotation.Backoff; +import org.springframework.retry.annotation.Recover; +import org.springframework.retry.annotation.Retryable; +import org.springframework.stereotype.Service; + +@Slf4j +@Service +public class WxUserServiceImpl implements IWxUserService { + + @Autowired + private WxMpService wxMpService; + + @Override + @Retryable(value = WxErrorException.class, maxAttempts = 3, backoff = @Backoff(delay = 2000, multiplier = 2)) + public String getMpOpenIdByUnionId(String targetUnionId) { + try { + log.info("开始查找 unionId: {} 对应的 openId", targetUnionId); + + WxMpUserService userService = wxMpService.getUserService(); + String nextOpenId = null; + + do { + // 获取关注者列表 + WxMpUserList userList = userService.userList(nextOpenId); + if (userList == null || userList.getCount() == 0) { + log.warn("未找到关注用户"); + break; + } + + // 批量获取用户信息 + for (String openId : userList.getOpenids()) { + try { + WxMpUser userInfo = userService.userInfo(openId); + if (targetUnionId.equals(userInfo.getUnionId())) { + log.info("找到匹配的 openId: {} 对应的 unionId: {}", openId, targetUnionId); + return openId; + } + } catch (WxErrorException e) { + log.warn("获取用户 {} 信息失败: {}", openId, e.getMessage()); + continue; // 单个用户获取失败继续处理下一个 + } + } + + nextOpenId = userList.getNextOpenid(); + } while (nextOpenId != null && !nextOpenId.isEmpty()); + + log.warn("未找到 unionId: {} 对应的 openId", targetUnionId); + return null; + + } catch (WxErrorException e) { + log.error("获取 MP openId 失败,unionId: {},错误: {}", targetUnionId, e.getMessage(), e); + throw new RuntimeException("获取 MP openId 失败", e); + } + } + + @Recover + public String recover(Exception e, String targetUnionId) { + log.error("获取 MP openId 重试耗尽,unionId: {},最终错误: {}", targetUnionId, e.getMessage()); + // 可以在这里添加告警通知 + return null; + } +} \ No newline at end of file diff --git a/zlt-business/edu-center/src/main/java/com/central/order/util/ContentTypeUtil.java b/zlt-business/edu-center/src/main/java/com/central/order/util/ContentTypeUtil.java new file mode 100644 index 00000000..4f298455 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/util/ContentTypeUtil.java @@ -0,0 +1,29 @@ +package com.central.order.util; + +import com.central.order.enums.FileType; + +public class ContentTypeUtil { + + /** + * 根据 URL 的文件扩展名获取对应的 contentType + * + * @param url 文件的 URL + * @return 包含 contentType 的 Map,如果 URL 为空或不包含支持的扩展名,返回空的 Map + */ + public static String getContentTypeFromUrl(String url) { + + if (url != null && !url.isEmpty()) { + // 获取文件扩展名 + int lastDotIndex = url.lastIndexOf('.'); + if (lastDotIndex != -1) { + String extension = url.substring(lastDotIndex); + FileType fileType = FileType.fromExtension(extension); + if (fileType != null) { + return fileType.getContentType(); + } + } + } + + return FileType.JPEG.getContentType(); + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/util/DateUtils.java b/zlt-business/edu-center/src/main/java/com/central/order/util/DateUtils.java new file mode 100644 index 00000000..6e18733e --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/util/DateUtils.java @@ -0,0 +1,77 @@ +package com.central.order.util; + +import java.text.SimpleDateFormat; +import java.util.Date; + +/** + * + * 时间工具类 + * @author lsl + * @date 2025-03-10 + */ +public class DateUtils { + + public final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + + public final static int INTERNAL = 10; + + public static boolean isWithinFiveMinutes(Date start, Date end) { + // 计算时间差(秒) + long secondsDifference = java.time.Duration.between(start.toInstant(), end.toInstant()).getSeconds(); + // 将时间差转换为分钟 + long minutesDifference = secondsDifference / 60; + // 判断时间差是否不超过 5 分钟 + return minutesDifference <= INTERNAL; + } + + public static boolean isWithinMinutes(Date start, Date end, int minutes) { + // 计算时间差(秒) + long secondsDifference = java.time.Duration.between(start.toInstant(), end.toInstant()).getSeconds(); + // 将时间差转换为分钟 + long minutesDifference = secondsDifference / 60; + // 判断时间差是否不超过 5 分钟 + return minutesDifference <= minutes; + } + + public static boolean isWithinMinutesByNow(Date start, int minutes) { + // 计算时间差(秒) + long secondsDifference = java.time.Duration.between(start.toInstant(), new Date().toInstant()).getSeconds(); + // 将时间差转换为分钟 + long minutesDifference = secondsDifference / 60; + // 判断时间差是否不超过 5 分钟 + return minutesDifference <= minutes; + } + + public static boolean isWithinFiveMinutesByNow(Date start) { + // 计算时间差(秒) + long secondsDifference = java.time.Duration.between(start.toInstant(), new Date().toInstant()).getSeconds(); + // 将时间差转换为分钟 + long minutesDifference = secondsDifference / 60; + // 判断时间差是否不超过 5 分钟 + return minutesDifference <= INTERNAL; + } + + // 获取当天的起始时间(0点0分0秒) + public static Date getStartOfDay(Date date) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + try { + date = sdf.parse(sdf.format(date)); + } catch (Exception e) { + e.printStackTrace(); + } + return date; + } + + // 获取当天的结束时间(23点59分59秒) + public static Date getEndOfDay(Date date) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + try { + date = sdf.parse(sdf.format(date)); + date.setTime(date.getTime() + 24 * 60 * 60 * 1000 - 1); + } catch (Exception e) { + e.printStackTrace(); + } + return date; + } + +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/util/ExceptionUtils.java b/zlt-business/edu-center/src/main/java/com/central/order/util/ExceptionUtils.java new file mode 100644 index 00000000..5811aa03 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/util/ExceptionUtils.java @@ -0,0 +1,51 @@ +package com.central.order.util; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.util.StringUtils; + +@Slf4j +public class ExceptionUtils { + + /** + * 获取异常的根本原因 + */ + public static String getRootCauseMessage(Throwable throwable) { + Throwable rootCause = getRootCause(throwable); + return rootCause.getMessage(); + } + + /** + * 获取异常的根本原因对象 + */ + public static Throwable getRootCause(Throwable throwable) { + Throwable cause = throwable; + while (cause.getCause() != null) { + cause = cause.getCause(); + } + return cause; + } + + /** + * 格式化异常信息 + */ + public static String formatErrorMessage(String message) { + if (!StringUtils.hasText(message)) { + return "未知错误"; + } + // 移除敏感信息 + message = message.replaceAll("\\{\"password\":\"[^\"]*\"\\}", "{\"password\":\"***\"}"); + // 限制长度 + return message.length() > 200 ? message.substring(0, 200) : message; + } + + /** + * 判断是否为业务异常 + */ + public static boolean isBusinessException(Throwable throwable) { + String message = getRootCauseMessage(throwable); + // 根据错误信息判断是否为业务异常 + return message.contains("PARAM_ERROR") + || message.contains("SIGN_ERROR") + || message.contains("INVALID_REQUEST"); + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/util/HttpServletUtils.java b/zlt-business/edu-center/src/main/java/com/central/order/util/HttpServletUtils.java new file mode 100644 index 00000000..3bc732b4 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/util/HttpServletUtils.java @@ -0,0 +1,47 @@ +package com.central.order.util; + +import javax.servlet.ServletInputStream; +import javax.servlet.http.HttpServletRequest; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; + +/** + *

+ * HttpServletRequest 获取请求体 + *

+ * + * @author songfayuan + * @date 2024/9/30 19:11 + */ +public class HttpServletUtils { + + /** + * 获取请求体 + * + * @param request + * @return + * @throws IOException + */ + public static String getRequestBody(HttpServletRequest request) throws IOException { + ServletInputStream stream = null; + BufferedReader reader = null; + StringBuffer sb = new StringBuffer(); + try { + stream = request.getInputStream(); + // 获取响应 + reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8)); + String line; + while ((line = reader.readLine()) != null) { + sb.append(line); + } + } catch (IOException e) { + throw new IOException("读取返回支付接口数据流出现异常!"); + } finally { + reader.close(); + } + return sb.toString(); + } + +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/util/MapUtil.java b/zlt-business/edu-center/src/main/java/com/central/order/util/MapUtil.java new file mode 100644 index 00000000..9ceb1c92 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/util/MapUtil.java @@ -0,0 +1,52 @@ +package com.central.order.util; + +import java.util.Map; + +/** + * 获取map各类型值工具类 + * @author lishilin + * @date 2020/03/12 + */ +public class MapUtil { + public static String getStrValue(Map param, String id) { + Object val = getValue(param, id); + if (null == val) { + return null; + } + return val.toString(); + } + + public static Integer getIntValue(Map param, String id) { + Object val = getValue(param, id); + if (null == val) { + return null; + } + try { + return Integer.parseInt(param.get(id).toString()); + } catch (NumberFormatException exp) { + return null; + } + } + + public static Long getLongValue(Map param, String id) { + Object val = getValue(param, id); + if (null == val) { + return null; + } + try { + return Long.parseLong(param.get(id).toString()); + } catch (NumberFormatException exp) { + return null; + } + } + + public static Object getValue(Map param, String id) { + if (null == param && null == id) { + return null; + } + if (param.containsKey(id)) { + return param.get(id); + } + return null; + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/util/RequestUtils.java b/zlt-business/edu-center/src/main/java/com/central/order/util/RequestUtils.java new file mode 100644 index 00000000..374e92e4 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/util/RequestUtils.java @@ -0,0 +1,119 @@ +package com.central.order.util; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.central.order.util.http.HeaderUtils; +import com.central.order.util.http.HttpRequest; +import com.central.order.util.http.Response; +import com.central.order.util.http.SimpleHttpRequest; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.io.IOException; +import java.util.Map; + +/** + * @author LSL + */ +@Slf4j +@Component +public class RequestUtils { + + @Autowired + private HeaderUtils headerUtils; + + /** + * 获取post请求result + * @param url 请求url + * @param jsonObject 请求参数 + * @return + * @throws IOException + */ + public Map getPostRequestResultMap(String url, JSONObject jsonObject) throws IOException { + System.out.println(url); + HttpRequest request = new SimpleHttpRequest(url); + request.headers(headerUtils.createHeadersOfJsonString(jsonObject.toJSONString())); + request.requestBody(jsonObject.toJSONString()); + Response response = request.post(); + Map result = Utils.queryStringToMap(new String(response.asBytes(), "utf8"), "utf8"); + return result; + } + + /** + * 获取post请求result + * @param url 请求url + * @param param 请求参数 + * @return + * @throws IOException + */ + public Map getPostRequestResultMap(String url, Map param) throws IOException { + System.out.println(url); + HttpRequest request = new SimpleHttpRequest(url); + request.headers(headerUtils.createHeadersOfJsonString(JSON.toJSONString(param))); + request.requestBody(JSON.toJSONString(param)); + Response response = request.post(); + Map result = Utils.queryStringToMap(new String(response.asBytes(), "utf8"), "utf8"); + return result; + } + + /** + * 获取post请求result + * @param url 请求url + * @param body 请求参数 + * @return + * @throws IOException + */ + public Map getPostRequestResultMap(String url, String body) throws IOException { + System.out.println(url); + HttpRequest request = new SimpleHttpRequest(url); + request.headers(headerUtils.createHeadersOfJsonString(body)); + request.requestBody(body); + Response response = request.post(); + Map result = Utils.queryStringToMap(new String(response.asBytes(), "utf8"), "utf8"); + System.out.println(result); + return result; + } + + /** + * @param url 请求url + * @param map 请求参数map + * @return + * @throws IOException + */ + public Map getGetRequestResultMap(String url,Map map) throws IOException { + HttpRequest request = new SimpleHttpRequest(url); + request.headers(headerUtils.createHeadersOfParams(map)); + + Response response = request.get(); + Map result = Utils.queryStringToMap(new String(response.asBytes(), "utf8"), "utf8"); + return result; + } + + /** + * 获取post请求result + * @param url 请求url + * @param param 请求参数 + * @return + * @throws IOException + */ + public Map getThirdPartyPostRequestResultMap(String url, Map param) { + log.info("url:{} , {}",url,param); + HttpRequest request = new SimpleHttpRequest(url); + request.headers(headerUtils.createHeadersOfJsonString(JSON.toJSONString(param))); + request.requestBody(JSON.toJSONString(param)); + Response response; + Map result = null; + try { + response = request.post(); + result = Utils.queryStringToMap(new String(response.asBytes(), "utf8"), "utf8"); + } catch (IOException e) { + log.info("查询异常:{}",e.getMessage()); + e.printStackTrace(); + } +// log.info("获取post请求result结果:{}" ,JSON.toJSONString(result)); + return result; + } + + +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/util/StringUtils.java b/zlt-business/edu-center/src/main/java/com/central/order/util/StringUtils.java new file mode 100644 index 00000000..e30b7a57 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/util/StringUtils.java @@ -0,0 +1,29 @@ +package com.central.order.util; + +/** + * 字符串处理 + * @date + * @author lsl + */ +public class StringUtils { + + public static String fenToYuan(String orderAmountStr) { + if (orderAmountStr != null && !orderAmountStr.isEmpty()) { + StringBuilder result = new StringBuilder(); + int length = orderAmountStr.length(); + if (length >= 3) { + // 字符串长度大于等于 3,正常插入小数点 + result.append(orderAmountStr, 0, length - 2).append(".").append(orderAmountStr.substring(length - 2)); + } else if (length == 2) { + // 字符串长度为 2,前面补 0 + result.append("0.").append(orderAmountStr); + } else { + // 字符串长度为 1,前面补 0 + result.append("0.0").append(orderAmountStr); + } + return result.toString() + "元"; + } else { + return "0.00元"; + } + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/util/Utils.java b/zlt-business/edu-center/src/main/java/com/central/order/util/Utils.java new file mode 100644 index 00000000..72528f12 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/util/Utils.java @@ -0,0 +1,47 @@ +package com.central.order.util; + +import java.io.*; +import java.net.URLDecoder; +import java.util.HashMap; +import java.util.Map; + +/** + * @author lishilin + * @see + * @since 2.0 + */ +public class Utils { + public static Map queryStringToMap(String queryString, String charset){ + try { + Map map = new HashMap<>(); + + String[] decode = URLDecoder.decode(queryString,charset).split("&"); + for (String keyValue : decode) { + String[] kv = keyValue.split("[=]",2); + map.put(kv.length>1?kv[1]:"",kv[0]); + } + return map; + } catch (UnsupportedEncodingException e) { + throw new UnsupportedOperationException(e); + } + } + + /** + * 读文件 + * + * @param file 文件 + * @return + * @throws IOException + * @throws IOException + */ + public static String readTxt(File file) throws IOException { + String s = ""; + InputStreamReader in = new InputStreamReader(new FileInputStream(file), "UTF-8"); + BufferedReader br = new BufferedReader(in); + StringBuffer content = new StringBuffer(); + while ((s = br.readLine()) != null) { + content = content.append(s); + } + return content.toString(); + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/util/http/HeaderUtils.java b/zlt-business/edu-center/src/main/java/com/central/order/util/http/HeaderUtils.java new file mode 100644 index 00000000..45a58b6e --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/util/http/HeaderUtils.java @@ -0,0 +1,80 @@ +package com.central.order.util.http; + +import org.apache.commons.codec.binary.Hex; +import org.apache.commons.codec.digest.DigestUtils; +import org.springframework.stereotype.Component; + +import java.security.MessageDigest; +import java.util.HashMap; +import java.util.Map; +import java.util.TreeMap; +import java.util.stream.Collectors; + +/** + * @author lishilin + * @see + * @since 1.0 + */ +@Component +public class HeaderUtils { + +// @Value("${jetlinks.clientId}") + private String xClientId = "WFMfEGS8iHrEPRBH" ; + +// @Value("${jetlinks.secureKey}") + private String secureKey = "ihat3zHC6T7xPZYFAEnG3tExQiFANd2n" ; + public Map createHeadersOfParams(Map params) { + //时间戳 + String xTimestamp = String.valueOf(System.currentTimeMillis()); + //openApi客户端id +// String xClientId = "rN7cpmQb884W4hcH"; + //密钥 +// String secureKey = "hBYtiNxQrA8FZbtetGhCZJPi"; + //将参数按ASCII排序后拼接为k1=v1&k2=v2的格式 + String paramString = new TreeMap<>(params).entrySet() + .stream() + .map(e -> e.getKey().concat("=").concat(String.valueOf(e.getValue()))) + .collect(Collectors.joining("&")); + + System.out.println(paramString); + + //param+X-Timestamp+SecureKey通过MD5加密 + MessageDigest digest = DigestUtils.getMd5Digest(); + System.out.println(paramString + xTimestamp + secureKey); + digest.update(paramString.getBytes()); + digest.update(xTimestamp.getBytes()); + digest.update(secureKey.getBytes()); + + Map headers = new HashMap<>(); + headers.put("X-Sign", Hex.encodeHexString(digest.digest())); + headers.put("X-Client-Id", xClientId); + headers.put("X-Timestamp", xTimestamp); + + return headers; + } + + + public Map createHeadersOfJsonString(String jsonString) { + //时间戳 + String xTimestamp = String.valueOf(System.currentTimeMillis()); + //openApi客户端id +// String xClientId = "rN7cpmQb884W4hcH"; + //密钥 +// String secureKey = "hBYtiNxQrA8FZbtetGhCZJPi"; + + + //param+X-Timestamp+SecureKey通过MD5加密 + MessageDigest digest = DigestUtils.getMd5Digest(); + System.out.println(jsonString + xTimestamp + secureKey); + digest.update(jsonString.getBytes()); + digest.update(xTimestamp.getBytes()); + digest.update(secureKey.getBytes()); + + Map headers = new HashMap<>(5); + headers.put("X-Sign", Hex.encodeHexString(digest.digest())); + headers.put("X-Client-Id", xClientId); + headers.put("X-Timestamp", xTimestamp); + + return headers; + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/util/http/HttpRequest.java b/zlt-business/edu-center/src/main/java/com/central/order/util/http/HttpRequest.java new file mode 100644 index 00000000..3a8a37f3 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/util/http/HttpRequest.java @@ -0,0 +1,39 @@ +package com.central.order.util.http; + +import java.io.Closeable; +import java.io.IOException; +import java.util.Map; + +/** + * @author wang + * @see + * @since 1.0 + */ +public interface HttpRequest extends Closeable { + + Response get() throws IOException; + + Response post() throws IOException; + + Response put() throws IOException; + + Response delete() throws IOException; + + Response patch() throws IOException; + + HttpRequest encode(String encode); + + HttpRequest contentType(String type); + + HttpRequest param(String name, String value); + + HttpRequest params(Map params); + + HttpRequest header(String name, String value); + + HttpRequest headers(Map headers); + + HttpRequest requestBody(String body); + + HttpRequest resultAsJsonString(); +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/util/http/Response.java b/zlt-business/edu-center/src/main/java/com/central/order/util/http/Response.java new file mode 100644 index 00000000..1ea5d317 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/util/http/Response.java @@ -0,0 +1,13 @@ +package com.central.order.util.http; + +import java.io.IOException; + +/** + * @author wang + * @see + * @since 1.0 + */ +public interface Response { + + byte[] asBytes() throws IOException; +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/util/http/SimpleHttpRequest.java b/zlt-business/edu-center/src/main/java/com/central/order/util/http/SimpleHttpRequest.java new file mode 100644 index 00000000..2844ed61 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/util/http/SimpleHttpRequest.java @@ -0,0 +1,184 @@ +package com.central.order.util.http; + +import org.apache.http.HttpResponse; +import org.apache.http.NameValuePair; +import org.apache.http.client.HttpClient; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.*; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.util.EntityUtils; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * @author wang + * @see + * @since 1.0 + */ +public class SimpleHttpRequest implements HttpRequest { + + private Map params = new LinkedHashMap<>(); + private Map headers = new LinkedHashMap<>(); + private String url; + private String requestBody; + private String contentType; + private String encode = "utf-8"; + protected HttpClient httpClient; + + public SimpleHttpRequest(String url) { + this.url = url; + createHttpClient(); + } + + public SimpleHttpRequest(String url, HttpClient client) { + this.url = url; + this.httpClient = client; + } + + protected void createHttpClient() { + if (httpClient == null) { + HttpClientBuilder builder = HttpClientBuilder.create(); + httpClient = builder.build(); + + } + } + + @Override + public Response get() throws IOException { + String param = EntityUtils.toString(createUrlEncodedFormEntity()); + String tmpUrl = url + (url.contains("?") ? "&" : "?") + param; + HttpGet get = new HttpGet(tmpUrl); + HttpResponse response = execute(get); + return getResultValue(response); + } + + + @Override + public Response post() throws IOException { + HttpPost post = new HttpPost(url); + if (requestBody != null) + post.setEntity(new StringEntity(requestBody, ContentType.create(contentType,encode))); + else { + post.setEntity(createUrlEncodedFormEntity()); + } + HttpResponse response = execute(post); + return getResultValue(response); + } + + @Override + public Response put() throws IOException { + HttpPut put = new HttpPut(url); + if (requestBody != null) + put.setEntity(new StringEntity(requestBody, ContentType.create(contentType, encode))); + else { + + put.setEntity(createUrlEncodedFormEntity()); + } + HttpResponse response = execute(put); + return getResultValue(response); + } + + protected UrlEncodedFormEntity createUrlEncodedFormEntity() throws UnsupportedEncodingException { + List nameValuePair = params.entrySet() + .stream().map(stringStringEntry -> + new BasicNameValuePair(stringStringEntry.getKey(), String.valueOf(stringStringEntry.getValue()))) + .collect(Collectors.toList()); + return new UrlEncodedFormEntity(nameValuePair, encode); + } + + @Override + public Response delete() throws IOException { + HttpDelete delete = new HttpDelete(url); + HttpResponse response = execute(delete); + return getResultValue(response); + } + + @Override + public Response patch() throws IOException { + HttpPatch delete = new HttpPatch(url); + if (requestBody != null) + delete.setEntity(new StringEntity(requestBody, ContentType.create(contentType))); + else { + delete.setEntity(createUrlEncodedFormEntity()); + } + return getResultValue(execute(delete)); + } + + @Override + public void close() throws IOException { + if (httpClient != null && httpClient instanceof CloseableHttpClient) { + ((CloseableHttpClient) httpClient).close(); + } + } + + @Override + public HttpRequest resultAsJsonString() { + header("Accept", "application/json"); + return this; + } + + @Override + public HttpRequest requestBody(String body) { + contentType("application/json"); + this.requestBody = body; + return this; + } + + @Override + public HttpRequest encode(String encode) { + this.encode = encode; + return this; + } + + @Override + public HttpRequest contentType(String type) { + this.contentType = type; + return this; + } + + @Override + public HttpRequest param(String name, String value) { + this.params.put(name, value); + return this; + } + + @Override + public HttpRequest params(Map params) { + this.params.putAll(params); + return this; + } + + @Override + public HttpRequest header(String name, String value) { + this.headers.put(name, value); + return this; + } + + @Override + public HttpRequest headers(Map header) { + this.headers.putAll(header); + return this; + } + + private Response getResultValue(HttpResponse res) throws IOException { + return new SimpleResponse(res); + } + + private HttpResponse execute(HttpRequestBase request) throws IOException { + putHeader(request); + return httpClient.execute(request); + } + + private void putHeader(HttpUriRequest request) { + headers.forEach(request::setHeader); + } +} diff --git a/zlt-business/edu-center/src/main/java/com/central/order/util/http/SimpleResponse.java b/zlt-business/edu-center/src/main/java/com/central/order/util/http/SimpleResponse.java new file mode 100644 index 00000000..d66e16d3 --- /dev/null +++ b/zlt-business/edu-center/src/main/java/com/central/order/util/http/SimpleResponse.java @@ -0,0 +1,26 @@ +package com.central.order.util.http; + +import org.apache.http.HttpResponse; +import org.apache.http.util.EntityUtils; + +import java.io.IOException; + +/** + * @author wang + * @see + * @since 1.0 + */ +public class SimpleResponse implements Response { + + HttpResponse response; + + public SimpleResponse(HttpResponse response) { + this.response = response; + } + + + @Override + public byte[] asBytes() throws IOException { + return EntityUtils.toByteArray(response.getEntity()); + } +} diff --git a/zlt-business/edu-center/src/main/resources/application.yml b/zlt-business/edu-center/src/main/resources/application.yml new file mode 100644 index 00000000..d3c0e8cf --- /dev/null +++ b/zlt-business/edu-center/src/main/resources/application.yml @@ -0,0 +1,128 @@ +spring: + datasource: +# url: jdbc:mysql://${zlt.datasource.ip}:3306/device-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai + url: jdbc:mysql://${zlt.datasource.ip}/edu-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai&allowMultiQueries=true + username: ${zlt.datasource.username} + password: ${zlt.datasource.password} + driver-class-name: com.mysql.cj.jdbc.Driver + +mybatis-plus: + mapper-locations: classpath:/mapper/*Mapper.xml + #实体扫描,多个package用逗号或者分号分隔 + typeAliasesPackage: com.central.device.model +# configuration: +# log-impl: org.apache.ibatis.logging.stdout.StdOutImpl + global-config: + db-config: + id-type: auto + +springdoc: + group-configs: + - group: 'default' + paths-to-match: '/**' + packages-to-scan: com.central.order.controller + +knife4j: + enable: true + setting: + swagger-model-name: 教育中心接口文档 +zlt: + #多租户配置 + tenant: + enable: false + ignoreTables: + - edit_task + - home_carousel + - sys_message + - wx_message_record + - wx_subscribe_status + - video_template + - profit_sharing + - order_statistics + ignoreSqls: + # 查询全部列表 +# - com.central.order.mapper.OrderMapper.findList + # 获取某个订单 +# - com.central.order.mapper.OrderMapper.getOrderByNumber + noIgnoreSqls: + - com.central.order.mapper.OrderMapper.findList + - com.central.order.mapper.TourismMapper.findList + - com.central.order.mapper.OrderFileMapper.findList + - com.central.order.mapper.QrCodeMapper.findList + - com.central.order.mapper.QrCodeMapper.save + # 微信支付商户号 +tencent: + merchantId: ${zlt.wxpay.merchantId} +# 微信支付商户密钥 + merchantSerialNumber: ${zlt.wxpay.merchantSerialNumber} +# 微信支付申请的应用ID + appId: ${zlt.wxpay.appId} +# 微信支付异步通知地址(需外网可访问且与微信支付平台配置一致) + notifyUrl: ${zlt.wxpay.notifyUrl} +# 微信支付API证书路径(如果需要证书的情况下,这里填写证书相关文件的路径) + privateKeyPath: ${zlt.wxpay.privateKeyPath} + apiV3Key: ${zlt.wxpay.apiV3Key} + appSecret: ${zlt.security.tencent.app-secret} + accessTokenUrl: ${zlt.security.tencent.accessTokenUrl} + getwxacodeUrl: https://api.weixin.qq.com/wxa/getwxacode?access_token= +# 微信退款通知地址 + refund-notify-url: ${zlt.wxrefund.notifyUrl} + notification: + app-id: + app-secret: + token: + encoding-aes-key: + pay: + profit-sharing: + enabled: true + max-retry-times: 3 + retry-interval: 300000 + platform-rate: 30 + timeout: 1800000 + async-enabled: true + async-pool-size: 5 + api: + profit-sharing-url: https://api.mch.weixin.qq.com/v3/profitsharing/orders + + +file: + oss-url: goflyapp.oss-cn-beijing.aliyuncs.com + cdn-url: cdn.goflytec.com + style: image/resize,m_mfit,w_300,h_250 + #审计日志 +# audit-log: +# enabled: true +# log-type: db +# datasource: +# driver-class-name: com.mysql.cj.jdbc.Driver +# jdbc-url: jdbc:mysql://${zlt.datasource.ip}:3306/logger-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai +# username: ${zlt.datasource.username} +# password: ${zlt.datasource.password} + +aliyun: + ims: + oss-endpoint: oss-cn-beijing.aliyuncs.com + access-key-id: LTAI5tSNV1RvexXpMMCZhxSe + access-key-secret: XocJRWU8emwjjvYLTrc04l91VZMkQK + endpoint: ice.cn-beijing.aliyuncs.com + region: cn-beijing + bucket: goflyapp # 使用实际存在的bucket名称 + +wx: + mp: + app-id: wx0ea85b13966d88e1 # 服务号应用id + secret: a90637566b2b73f41f8b1dabd64dc32b # 服务号应用密钥 + template-id: + payment-success: uscmjgLdw0cKBRq8vFyCOPbYj7p-fHuEOIhFwwIAe4A # 支付成功通知模板ID + video-complete: TEMPLATE_ID_2 # 视频完成通知模板ID + video-failure: TEMPLATE_ID_3 # 视频失败通知模板ID + + mini: + app-id: ${zlt.wxpay.appId} + secret: ${zlt.security.tencent.app-secret} + template: + pay-success: nSy7NGq1443YCfhgR81fgkeOVv9cSM5Ysp3nMoQYVpc + service-process: rgQCI3fMKPpgO-9nO3TzP-omohraGxX2suVioq7hQhk + activity-start: lgwkRnbdDc3mEwk3RMob43LpLHnLfglZtTkbFRPsPCA + order-complete: ZeIlAA6ImQLxBiLmo-53lM7wkL4KnuKKTGKWBZwYAdM + video-edit-complete: IXpL-Voztm3GM-zFj3sxA39qy8oRtAcxTiT7_Qsyz9Q diff --git a/zlt-business/edu-center/src/main/resources/bootstrap.yml b/zlt-business/edu-center/src/main/resources/bootstrap.yml new file mode 100644 index 00000000..fb30f4e5 --- /dev/null +++ b/zlt-business/edu-center/src/main/resources/bootstrap.yml @@ -0,0 +1,15 @@ +server: + port: 7003 + +spring: + application: + name: edu-center +# cloud: +# nacos: +# discovery: +# ip: 81.70.164.178 +# cloud: +# nacos: +# discovery: +# metadata: +# version: zlt diff --git a/zlt-business/edu-center/src/main/resources/mapper/HomeCarouselMapper.xml b/zlt-business/edu-center/src/main/resources/mapper/HomeCarouselMapper.xml new file mode 100644 index 00000000..953391f8 --- /dev/null +++ b/zlt-business/edu-center/src/main/resources/mapper/HomeCarouselMapper.xml @@ -0,0 +1,12 @@ + + + + + + + + + + diff --git a/zlt-business/edu-center/src/main/resources/mapper/MessageMapper.xml b/zlt-business/edu-center/src/main/resources/mapper/MessageMapper.xml new file mode 100644 index 00000000..88aae0f7 --- /dev/null +++ b/zlt-business/edu-center/src/main/resources/mapper/MessageMapper.xml @@ -0,0 +1,125 @@ + + + + + + id, title, content, type, status, create_time, read_time, + related_id, extra, user_id, tenant_id + + + + + + + + INSERT INTO sys_message ( + title, content, type, status, create_time, + related_id, extra, user_id, tenant_id + ) + VALUES + + ( + #{item.title}, + #{item.content}, + #{item.type}, + #{item.status}, + #{item.createTime}, + #{item.relatedId}, + #{item.extra}, + #{item.userId}, + #{item.tenantId} + ) + + + + + + UPDATE sys_message + SET status = #{status}, + read_time = #{readTime} + WHERE id IN + + #{id} + + AND user_id = #{userId} + + + + + + + + + + + DELETE FROM sys_message + WHERE status = 1 + AND read_time < #{beforeTime} + + AND user_id = #{userId} + + + AND tenant_id = #{tenantId} + + + + + + diff --git a/zlt-business/edu-center/src/main/resources/mapper/OrderFileMapper.xml b/zlt-business/edu-center/src/main/resources/mapper/OrderFileMapper.xml new file mode 100644 index 00000000..3c8e6b11 --- /dev/null +++ b/zlt-business/edu-center/src/main/resources/mapper/OrderFileMapper.xml @@ -0,0 +1,43 @@ + + + + + + + + + + + INSERT INTO order_files (user_id, order_no, file_id,tourism_id,file_path) + VALUES (#{userId}, #{order_no}, #{file_id}, #{tourism_id}, #{file_path}) + + + + + + + + + + diff --git a/zlt-business/edu-center/src/main/resources/mapper/OrderMapper.xml b/zlt-business/edu-center/src/main/resources/mapper/OrderMapper.xml new file mode 100644 index 00000000..ef813741 --- /dev/null +++ b/zlt-business/edu-center/src/main/resources/mapper/OrderMapper.xml @@ -0,0 +1,63 @@ + + + + + + + + + + + + + + + INSERT INTO orders (user_id, order_amount, order_status) + VALUES (#{userId}, #{orderAmount}, #{orderStatus}) + + + + + + + + UPDATE orders + SET order_status = #{newStatus} + WHERE id = #{orderId} + + + + + + + + + + + diff --git a/zlt-business/edu-center/src/main/resources/mapper/PaymentRecord.xml b/zlt-business/edu-center/src/main/resources/mapper/PaymentRecord.xml new file mode 100644 index 00000000..63097516 --- /dev/null +++ b/zlt-business/edu-center/src/main/resources/mapper/PaymentRecord.xml @@ -0,0 +1,20 @@ + + + + + + + + + INSERT INTO payment_records (order_id, payment_number, payment_amount, payment_time) + VALUES (#{orderId}, #{paymentNumber}, #{paymentAmount}, #{paymentTime}) + + + + + + diff --git a/zlt-business/edu-center/src/main/resources/mapper/QrCodeMapper.xml b/zlt-business/edu-center/src/main/resources/mapper/QrCodeMapper.xml new file mode 100644 index 00000000..da4c745b --- /dev/null +++ b/zlt-business/edu-center/src/main/resources/mapper/QrCodeMapper.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + INSERT INTO qrcodes (code_id, tourism_id, device_sn) + VALUES (#{codeId}, #{tourismId}, #{deviceSn}) + + diff --git a/zlt-business/edu-center/src/main/resources/mapper/RefundMapper.xml b/zlt-business/edu-center/src/main/resources/mapper/RefundMapper.xml new file mode 100644 index 00000000..452ac2ab --- /dev/null +++ b/zlt-business/edu-center/src/main/resources/mapper/RefundMapper.xml @@ -0,0 +1,12 @@ + + + + + + + + + + diff --git a/zlt-business/edu-center/src/main/resources/mapper/TourismFileMapper.xml b/zlt-business/edu-center/src/main/resources/mapper/TourismFileMapper.xml new file mode 100644 index 00000000..3ad7728f --- /dev/null +++ b/zlt-business/edu-center/src/main/resources/mapper/TourismFileMapper.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + diff --git a/zlt-business/edu-center/src/main/resources/mapper/TourismMapper.xml b/zlt-business/edu-center/src/main/resources/mapper/TourismMapper.xml new file mode 100644 index 00000000..43ee01eb --- /dev/null +++ b/zlt-business/edu-center/src/main/resources/mapper/TourismMapper.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + INSERT INTO tourisms (tourism_no, tourism_name, tourism_address,tourism_phone) + VALUES (#{tourismNo}, #{tourismName}, #{tourismAddress},#{tourismPhone}) + + diff --git a/zlt-business/order-center/src/main/java/com/central/order/controller/OrderController.java b/zlt-business/order-center/src/main/java/com/central/order/controller/OrderController.java index 18795f52..a861c98b 100644 --- a/zlt-business/order-center/src/main/java/com/central/order/controller/OrderController.java +++ b/zlt-business/order-center/src/main/java/com/central/order/controller/OrderController.java @@ -194,9 +194,9 @@ public class OrderController { order.setUserId(user.getId()); order.setTenantId(TenantContextHolder.getTenant()); - List userOrderList = orderService.getOrderCountByStatusAndUser(user.getId(),OrderStatus.PAID.getId()); + List userOrderList = orderService.getOrderCountByStatusAndUser(user.getId(),OrderStatus.PAID.getId(),OrderStatus.UNPAID.getId()); if (!userOrderList.isEmpty()){ - return Result.succeed("已存在订单"); + return Result.succeed("已存在订单,请前往订单页确认,请勿重复下单"); } QrCode qrCode = qrCodeService.getByCodeId(order.getCodeId()); @@ -216,7 +216,7 @@ public class OrderController { if (result) { return Result.succeed(order,"订单创建成功"); } else { - return Result.failed("订单创建失败"); + return Result.succeed("订单已创建"); } } diff --git a/zlt-business/order-center/src/main/java/com/central/order/service/impl/OrderServiceImpl.java b/zlt-business/order-center/src/main/java/com/central/order/service/impl/OrderServiceImpl.java index 8a2ffbf8..2b7d1b86 100644 --- a/zlt-business/order-center/src/main/java/com/central/order/service/impl/OrderServiceImpl.java +++ b/zlt-business/order-center/src/main/java/com/central/order/service/impl/OrderServiceImpl.java @@ -91,16 +91,11 @@ public class OrderServiceImpl extends SuperServiceImpl imple String orderNo = generateOrderNumber(order.getTourismId()); order.setOrderNo(orderNo); - // 幂等性校验:同一用户、同一二维码、未完成订单只能有一条 - String lockKey = "order:create:" + order.getUserId() + ":" + order.getCodeId(); + // 幂等性校验:同一用户、同一二维码、未完成订单只能有一条 @TODO +// String lockKey = "order:create:" + order.getUserId() + ":" + order.getCodeId(); try { - return super.saveIdempotency(order, lock, - lockKey, - new QueryWrapper() - .eq("user_id", order.getUserId()) - .eq("code_id", order.getCodeId()) - .ne("order_status", OrderStatus.UNPAID.getId()), // 未支付订单 - "已存在未完成订单"); + return super.saveIdempotency(order, lock + , ORDER_LOCK+orderNo, new QueryWrapper().eq("order_no", orderNo), "订单已存在"); } catch (Exception e) { throw new RuntimeException(e); } diff --git a/zlt-business/pom.xml b/zlt-business/pom.xml index 4ee19a6e..3bee452a 100644 --- a/zlt-business/pom.xml +++ b/zlt-business/pom.xml @@ -22,5 +22,7 @@ device-center order-center + + edu-center diff --git a/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/config/TenantAutoConfigure.java b/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/config/TenantAutoConfigure.java index 720d0e6f..77d91237 100644 --- a/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/config/TenantAutoConfigure.java +++ b/zlt-commons/zlt-db-spring-boot-starter/src/main/java/com/central/db/config/TenantAutoConfigure.java @@ -61,6 +61,7 @@ public class TenantAutoConfigure { // 你可以通过ThreadLocal、SecurityContext、LoginUserContextHolder等获取当前用户角色 // 例如: LoginAppUser user = LoginUserContextHolder.getUser(); - return user != null && user.getUsername().equals("admin"); + //@TODO 暂定admin和mgnt为系统管理员 + return user != null && (user.getUsername().equals("admin") || user.getUsername().equals("mgnt")); } } diff --git a/zlt-config/src/main/resources/bootstrap.properties b/zlt-config/src/main/resources/bootstrap.properties index 2168d2fe..19e3c72f 100644 --- a/zlt-config/src/main/resources/bootstrap.properties +++ b/zlt-config/src/main/resources/bootstrap.properties @@ -1,13 +1,13 @@ ########################## bootstrap级别通用配置 ########################## # 默认开发环境 -spring.profiles.active=dev +spring.profiles.active=prod ##### nacos(注册中心和配置中心)地址 -#spring.cloud.nacos.server-addr=81.70.164.178:8848 -spring.cloud.nacos.server-addr=127.0.0.1:8848 +spring.cloud.nacos.server-addr=81.70.164.178:8848 +#spring.cloud.nacos.server-addr=127.0.0.1:8848 spring.cloud.nacos.username=nacos -spring.cloud.nacos.password=nacos -#spring.cloud.nacos.password=nacosGFLY +#spring.cloud.nacos.password=nacos +spring.cloud.nacos.password=nacosGFLY spring.cloud.nacos.config.file-extension=yml spring.cloud.nacos.config.shared-configs[0].data-id=common.yml spring.cloud.nacos.config.shared-configs[0].refresh=true diff --git a/zlt-web/react-web/src/main/frontend/config/proxy.ts b/zlt-web/react-web/src/main/frontend/config/proxy.ts index aa9dedbb..2927d78b 100644 --- a/zlt-web/react-web/src/main/frontend/config/proxy.ts +++ b/zlt-web/react-web/src/main/frontend/config/proxy.ts @@ -9,43 +9,43 @@ export default { dev: { '/api-uaa/': { - target: 'http://119.45.169.13:9900', - // target: 'http://127.0.0.1:9900', + // target: 'http://119.45.169.13:9900', + target: 'http://127.0.0.1:9900', changeOrigin: true, }, '/api-user/': { - target: 'http://119.45.169.13:9900', - // target: 'http://127.0.0.1:9900', + // target: 'http://119.45.169.13:9900', + target: 'http://127.0.0.1:9900', changeOrigin: true, }, '/api-log/': { - target: 'http://119.45.169.13:9900', - // target: 'http://127.0.0.1:9900', + // target: 'http://119.45.169.13:9900', + target: 'http://127.0.0.1:9900', changeOrigin: true, }, '/api-search/': { - target: 'http://119.45.169.13:9900', - // target: 'http://127.0.0.1:9900', + // target: 'http://119.45.169.13:9900', + target: 'http://127.0.0.1:9900', changeOrigin: true, }, '/api-generator/': { - target: 'http://119.45.169.13:9900', - // target: 'http://127.0.0.1:9900', + // target: 'http://119.45.169.13:9900', + target: 'http://127.0.0.1:9900', changeOrigin: true, }, '/api-file/': { - target: 'http://119.45.169.13:9900', - // target: 'http://127.0.0.1:9900', + // target: 'http://119.45.169.13:9900', + target: 'http://127.0.0.1:9900', changeOrigin: true, }, '/api-order/': { - target: 'http://119.45.169.13:9900', - // target: 'http://127.0.0.1:9900', + // target: 'http://119.45.169.13:9900', + target: 'http://127.0.0.1:9900', changeOrigin: true, }, '/api-device/': { - target: 'http://119.45.169.13:9900', - // target: 'http://127.0.0.1:9900', + // target: 'http://119.45.169.13:9900', + target: 'http://127.0.0.1:9900', changeOrigin: true, }, },