From 37979386163c3e601920e326efc7f03574e5c325 Mon Sep 17 00:00:00 2001 From: xiaowang Date: Mon, 18 May 2026 09:46:11 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8A=9F=E8=83=BD=EF=BC=9A=E5=AE=8C=E5=96=84?= =?UTF-8?q?=E9=97=A8=E5=BA=97=E8=83=BD=E5=8A=9B=E4=B8=8E=E7=94=A8=E6=88=B7?= =?UTF-8?q?=E5=AE=89=E5=85=A8=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .idea/compiler.xml | 13 + .idea/dataSources.xml | 23 + .idea/encodings.xml | 2 + .idea/misc.xml | 2 + .idea/sqldialects.xml | 4 +- WeChatProgram/api/auth.js | 11 + WeChatProgram/api/cart.js | 4 + WeChatProgram/api/comment.js | 4 + WeChatProgram/api/coupon.js | 4 + WeChatProgram/api/file.js | 4 + WeChatProgram/api/order.js | 4 + WeChatProgram/api/product-like.js | 4 + WeChatProgram/api/product.js | 4 + WeChatProgram/api/shop.js | 4 + WeChatProgram/api/tag.js | 4 + WeChatProgram/api/user.js | 84 + WeChatProgram/api/wishlist.js | 4 + WeChatProgram/app.json | 2 + .../navigation-bar/navigation-bar.js | 8 +- .../components/product-card/product-card.wxml | 1 + .../components/product-card/product-card.wxss | 10 + WeChatProgram/pages/auth/index.js | 420 ++++- WeChatProgram/pages/auth/index.wxml | 43 +- WeChatProgram/pages/auth/index.wxss | 104 ++ WeChatProgram/pages/cart/index.js | 149 +- WeChatProgram/pages/coupons/index.js | 36 + WeChatProgram/pages/home/index.js | 140 ++ WeChatProgram/pages/home/index.wxml | 6 + WeChatProgram/pages/home/index.wxss | 20 + WeChatProgram/pages/index/index.js | 16 + WeChatProgram/pages/notifications/index.js | 117 ++ WeChatProgram/pages/notifications/index.json | 6 + WeChatProgram/pages/notifications/index.wxml | 50 + WeChatProgram/pages/notifications/index.wxss | 152 ++ WeChatProgram/pages/orders/index.js | 29 + WeChatProgram/pages/orders/index.wxml | 1 + WeChatProgram/pages/orders/index.wxss | 7 + WeChatProgram/pages/product-detail/index.js | 80 + WeChatProgram/pages/products/index.js | 108 ++ WeChatProgram/pages/profile/index.js | 134 +- WeChatProgram/pages/profile/index.wxml | 9 + WeChatProgram/pages/profile/index.wxss | 17 + WeChatProgram/pages/settings/index.js | 219 ++- WeChatProgram/pages/shop-detail/index.js | 113 +- WeChatProgram/pages/shop-detail/index.wxml | 6 + WeChatProgram/pages/shop-detail/index.wxss | 18 + WeChatProgram/pages/vip-center/index.js | 114 ++ WeChatProgram/pages/vip-center/index.json | 5 + WeChatProgram/pages/vip-center/index.wxml | 61 + WeChatProgram/pages/vip-center/index.wxss | 162 ++ WeChatProgram/pages/wishlist/index.js | 52 + WeChatProgram/utils/product.js | 3 +- WeChatProgram/utils/request.js | 1 + .../yuminailcore/config/AuthInterceptor.java | 21 +- .../config/LoginLockProperties.java | 17 + .../config/RateLimitProperties.java | 6 + .../config/SecurityHeadersFilter.java | 26 + .../config/UploadSecurityProperties.java | 23 + .../yuminailcore/config/WebMvcConfig.java | 4 + .../controller/AdminAuthController.java | 62 +- .../controller/AdminCommentController.java | 18 +- .../controller/AdminCouponController.java | 10 +- .../AdminLegalAgreementController.java | 73 + .../controller/AdminNailArtistController.java | 31 +- .../controller/AdminOrderController.java | 12 +- .../controller/AdminPermissionController.java | 78 +- .../controller/AdminProductController.java | 39 +- .../controller/AdminShopController.java | 57 +- .../controller/AdminShopRoleController.java | 182 ++ .../controller/AdminTagController.java | 7 +- .../controller/AdminUserController.java | 199 ++- .../controller/AnnouncementController.java | 119 ++ .../BalanceChangeDetailController.java | 4 +- .../controller/BalanceController.java | 4 +- .../controller/CartController.java | 44 + .../controller/CommentController.java | 4 +- .../controller/ContactInfoController.java | 66 + .../controller/CouponController.java | 10 +- .../controller/DashboardController.java | 72 +- .../controller/EffectDiagramController.java | 4 +- .../controller/FrontendFileController.java | 10 +- .../controller/HealthController.java | 33 +- .../controller/LegalAgreementController.java | 95 ++ .../controller/LoginIdentityController.java | 4 +- .../MessageHubPushConfigController.java | 110 ++ .../ObjectStorageFileController.java | 57 +- .../controller/OrderController.java | 120 +- .../controller/PermissionController.java | 20 +- .../controller/ProductController.java | 56 +- .../controller/ProductLikeController.java | 4 +- .../controller/ShopController.java | 72 +- .../controller/SystemMessageController.java | 181 ++ .../SystemParameterConfigController.java | 52 + .../controller/TagController.java | 7 +- .../controller/UserController.java | 320 +++- .../controller/VipBenefitController.java | 4 +- .../controller/VipInfoController.java | 4 +- .../controller/VipRechargePlanController.java | 99 ++ .../controller/WishlistController.java | 4 + .../dto/AdminUserBalanceChangeDTO.java | 19 + .../dto/AdminUserVipOverrideDTO.java | 10 + .../dto/AgreementAwareRequest.java | 12 + .../dto/AnnouncementCreateDTO.java | 50 + .../dto/BalanceChangeDetailDTO.java | 24 + .../xiaowang/yuminailcore/dto/BalanceDTO.java | 6 + .../dto/ChunkUploadCompleteRequestDTO.java | 3 + .../dto/ChunkUploadInitRequestDTO.java | 15 + .../xiaowang/yuminailcore/dto/CouponDTO.java | 9 + .../yuminailcore/dto/InviteCodeDTO.java | 41 + .../yuminailcore/dto/LegalAgreementDTO.java | 24 + .../yuminailcore/dto/LoginRequestDTO.java | 9 +- .../dto/MessageHubPushConfigDTO.java | 85 + .../dto/MessageHubPushTestDTO.java | 21 + .../yuminailcore/dto/NailArtistInfoDTO.java | 26 + .../xiaowang/yuminailcore/dto/OrderDTO.java | 3 + .../dto/PhoneLoginRequestDTO.java | 20 +- .../yuminailcore/dto/RegisterRequestDTO.java | 32 +- .../dto/SendVerificationCodeRequestDTO.java | 18 +- .../xiaowang/yuminailcore/dto/ShopDTO.java | 14 + .../yuminailcore/dto/ShopRoleDTO.java | 45 + .../dto/SwitchShopRequestDTO.java | 7 + .../dto/SystemMessageCreateDTO.java | 51 + .../dto/SystemParameterConfigDTO.java | 30 + .../dto/UserRelationUpdateDTO.java | 27 + .../yuminailcore/dto/VipBenefitDTO.java | 9 + .../xiaowang/yuminailcore/dto/VipInfoDTO.java | 6 + .../yuminailcore/dto/VipRechargePlanDTO.java | 66 + .../dto/WechatMiniAutoLoginRequestDTO.java | 6 + .../dto/WechatMiniConfirmLoginRequestDTO.java | 15 +- .../dto/WechatMiniPhoneLoginRequestDTO.java | 18 +- .../yuminailcore/entity/AnnouncementDO.java | 86 + .../entity/BalanceChangeDetailDO.java | 27 + .../yuminailcore/entity/BalanceDO.java | 6 + .../xiaowang/yuminailcore/entity/CartDO.java | 22 + .../yuminailcore/entity/CouponDO.java | 9 + .../yuminailcore/entity/LegalAgreementDO.java | 37 + .../entity/MessageHubPushConfigDO.java | 92 + .../yuminailcore/entity/NailArtistInfoDO.java | 19 + .../xiaowang/yuminailcore/entity/OrderDO.java | 40 + .../yuminailcore/entity/OrderItemDO.java | 31 + .../entity/SecurityAuditLogDO.java | 38 + .../xiaowang/yuminailcore/entity/ShopDO.java | 18 + .../yuminailcore/entity/ShopRoleDO.java | 60 + .../entity/ShopRolePermissionDO.java | 36 + .../yuminailcore/entity/SystemMessageDO.java | 92 + .../entity/SystemMessageUserStateDO.java | 62 + .../entity/SystemParameterConfigDO.java | 35 + .../entity/UserAgreementConsentDO.java | 38 + .../yuminailcore/entity/UserInviteCodeDO.java | 62 + .../yuminailcore/entity/UserRelationDO.java | 60 + .../entity/UserShopBindingDO.java | 12 + .../yuminailcore/entity/UserShopRoleDO.java | 48 + .../yuminailcore/entity/VipBenefitDO.java | 9 + .../yuminailcore/entity/VipInfoDO.java | 6 + .../entity/VipRechargePlanDO.java | 74 + .../entity/WechatMiniBindingDO.java | 18 + .../yuminailcore/entity/WishlistDO.java | 13 + .../mapper/AnnouncementMapper.java | 11 + .../yuminailcore/mapper/CartMapper.java | 4 + .../mapper/LegalAgreementMapper.java | 9 + .../mapper/MessageHubPushConfigMapper.java | 11 + .../yuminailcore/mapper/OrderItemMapper.java | 17 + .../yuminailcore/mapper/OrderMapper.java | 4 + .../mapper/SecurityAuditLogMapper.java | 9 + .../yuminailcore/mapper/ShopRoleMapper.java | 11 + .../mapper/ShopRolePermissionMapper.java | 11 + .../mapper/SystemMessageMapper.java | 13 + .../mapper/SystemMessageUserStateMapper.java | 13 + .../mapper/SystemParameterConfigMapper.java | 9 + .../mapper/UserAgreementConsentMapper.java | 9 + .../mapper/UserInviteCodeMapper.java | 11 + .../mapper/UserRelationMapper.java | 11 + .../mapper/UserShopBindingMapper.java | 4 + .../mapper/UserShopRoleMapper.java | 11 + .../mapper/VipRechargePlanMapper.java | 11 + .../yuminailcore/mapper/WishlistMapper.java | 4 + .../service/AnnouncementService.java | 61 + .../yuminailcore/service/CartService.java | 40 +- .../service/ChunkUploadService.java | 92 +- .../yuminailcore/service/CommentService.java | 38 + .../service/ContactInfoService.java | 41 + .../service/LegalAgreementService.java | 33 + .../yuminailcore/service/MapService.java | 11 + .../service/MessageHubClientService.java | 17 +- .../service/MessageHubPushConfigService.java | 70 + .../yuminailcore/service/MinioService.java | 56 +- .../yuminailcore/service/OrderService.java | 81 +- .../yuminailcore/service/ProductService.java | 9 + .../service/SecurityAuditLogService.java | 8 + .../yuminailcore/service/ShopRoleService.java | 119 ++ .../yuminailcore/service/ShopService.java | 10 + .../service/SystemMessageService.java | 110 ++ .../service/SystemParameterConfigService.java | 16 + .../service/UserAssetService.java | 40 +- .../yuminailcore/service/UserService.java | 300 +++- .../service/VerificationCodeService.java | 33 +- .../service/VipRechargePlanService.java | 56 + .../service/WechatMiniAuthService.java | 23 + .../service/WechatMiniClientService.java | 25 + .../yuminailcore/service/WishlistService.java | 30 +- .../service/impl/AnnouncementServiceImpl.java | 483 ++++++ .../impl/BalanceChangeDetailServiceImpl.java | 46 +- .../service/impl/BalanceServiceImpl.java | 52 +- .../service/impl/CartServiceImpl.java | 86 +- .../service/impl/ChunkUploadServiceImpl.java | 476 +++++- .../service/impl/CommentServiceImpl.java | 220 ++- .../service/impl/ContactInfoServiceImpl.java | 205 +++ .../service/impl/CouponServiceImpl.java | 336 +++- .../impl/EffectDiagramServiceImpl.java | 52 +- .../impl/LegalAgreementServiceImpl.java | 252 +++ .../impl/LoginIdentityServiceImpl.java | 52 +- .../service/impl/MapServiceImpl.java | 45 + .../impl/MessageHubClientServiceImpl.java | 115 +- .../impl/MessageHubPushConfigServiceImpl.java | 328 ++++ .../service/impl/MinioServiceImpl.java | 68 +- .../impl/NailArtistInfoServiceImpl.java | 294 ++-- .../impl/ObjectStorageFileServiceImpl.java | 76 +- .../service/impl/OrderServiceImpl.java | 957 ++++++++++- .../service/impl/PermissionServiceImpl.java | 244 ++- .../service/impl/ProductLikeServiceImpl.java | 31 + .../service/impl/ProductServiceImpl.java | 374 ++++- .../impl/SecurityAuditLogServiceImpl.java | 56 + .../service/impl/ShopRoleServiceImpl.java | 547 ++++++ .../service/impl/ShopServiceImpl.java | 200 ++- .../impl/SystemMessageServiceImpl.java | 850 ++++++++++ .../SystemParameterConfigServiceImpl.java | 104 ++ .../service/impl/TagServiceImpl.java | 180 +- .../service/impl/UserAssetServiceImpl.java | 242 ++- .../service/impl/UserServiceImpl.java | 1477 ++++++++++++++++- .../impl/VerificationCodeServiceImpl.java | 52 +- .../service/impl/VipBenefitServiceImpl.java | 46 +- .../service/impl/VipInfoServiceImpl.java | 46 +- .../impl/VipRechargePlanServiceImpl.java | 325 ++++ .../impl/WechatMiniAuthServiceImpl.java | 248 ++- .../impl/WechatMiniClientServiceImpl.java | 181 +- .../service/impl/WishlistServiceImpl.java | 52 + .../support/BookableArtistSupport.java | 27 +- .../support/PermissionPolicy.java | 11 +- .../support/UserShopBindingSupport.java | 22 +- .../security/RequestThrottleService.java | 70 +- .../security/UploadSecurityValidator.java | 65 + .../yuminailcore/vo/AnnouncementVO.java | 66 + .../vo/ArtistCalendarAppointmentVO.java | 90 + .../vo/BalanceChangeDetailVO.java | 24 + .../xiaowang/yuminailcore/vo/BalanceVO.java | 6 + .../yuminailcore/vo/CartArtistVO.java | 25 + .../com/xiaowang/yuminailcore/vo/CartVO.java | 49 + .../yuminailcore/vo/ChunkUploadSessionVO.java | 12 + .../yuminailcore/vo/ContactInfoVO.java | 39 + .../xiaowang/yuminailcore/vo/CouponVO.java | 9 + .../yuminailcore/vo/DashboardStatsVO.java | 22 + .../yuminailcore/vo/HotProductVO.java | 19 + .../yuminailcore/vo/InviteCodeVO.java | 58 + .../yuminailcore/vo/LegalAgreementVO.java | 31 + .../yuminailcore/vo/LoginResponseVO.java | 50 + .../yuminailcore/vo/LoginShopSelectionVO.java | 9 + .../vo/MessageHubPushConfigVO.java | 69 + .../vo/MessageTargetOptionsVO.java | 61 + .../yuminailcore/vo/MessageUnreadCountVO.java | 17 + .../xiaowang/yuminailcore/vo/OrderItemVO.java | 37 + .../com/xiaowang/yuminailcore/vo/OrderVO.java | 61 + .../yuminailcore/vo/PageResultVO.java | 16 + .../yuminailcore/vo/RecentActivityVO.java | 22 + .../xiaowang/yuminailcore/vo/ShopRoleVO.java | 75 + .../yuminailcore/vo/ShopSimpleVO.java | 10 + .../com/xiaowang/yuminailcore/vo/ShopVO.java | 25 + .../yuminailcore/vo/SystemMessageVO.java | 90 + .../vo/SystemParameterConfigVO.java | 19 + .../vo/UserAgreementConsentVO.java | 15 + .../xiaowang/yuminailcore/vo/UserAssetVO.java | 40 + .../yuminailcore/vo/UserCouponVO.java | 9 + .../yuminailcore/vo/UserRelationVO.java | 52 + .../yuminailcore/vo/UserStatisticsVO.java | 53 + .../com/xiaowang/yuminailcore/vo/UserVO.java | 38 + .../yuminailcore/vo/VipBenefitVO.java | 9 + .../xiaowang/yuminailcore/vo/VipInfoVO.java | 6 + .../yuminailcore/vo/VipRechargePlanVO.java | 62 + .../vo/WechatMiniLoginResultVO.java | 27 + ...6-03-20_init_admin_permission_template.sql | 228 --- ...user_asset_vip_coupon_permission_patch.sql | 329 ---- ...ser_shop_binding_and_shop_status_patch.sql | 165 -- ...order_process_default_permission_patch.sql | 29 - ...026-03-30_snowflake_id_alignment_patch.sql | 74 - .../2026-04-02_wechat_mini_binding_patch.sql | 55 - .../main/resources/files/YumiNail-back.sql | 661 -------- .../src/main/resources/files/YumiNail.sql | 699 +++++++- .../.vscode/extensions.json | 0 YumiNail-Frontend/src/App.vue | 187 ++- YumiNail-Frontend/src/api/admin.ts | 739 ++++++++- YumiNail-Frontend/src/api/auth.ts | 93 ++ YumiNail-Frontend/src/api/cart.ts | 36 + YumiNail-Frontend/src/api/comment.ts | 23 + YumiNail-Frontend/src/api/coupon.ts | 45 + YumiNail-Frontend/src/api/file.ts | 34 + YumiNail-Frontend/src/api/index.ts | 17 + YumiNail-Frontend/src/api/order.ts | 77 + YumiNail-Frontend/src/api/permission.ts | 44 + YumiNail-Frontend/src/api/product.ts | 8 + YumiNail-Frontend/src/api/productLike.ts | 23 + YumiNail-Frontend/src/api/shop.ts | 17 + YumiNail-Frontend/src/api/tag.ts | 33 + YumiNail-Frontend/src/api/user.ts | 224 ++- YumiNail-Frontend/src/api/wishlist.ts | 8 + .../src/components/BottomNav.vue | 8 + .../src/components/DraftActions.vue | 5 + .../src/components/TableEllipsisText.vue | 6 + .../components/admin/AdminMobileCardList.vue | 5 + .../src/components/admin/AdminMobileFab.vue | 4 + .../components/admin/AdminResponsiveModal.vue | 10 + YumiNail-Frontend/src/router/index.ts | 48 + .../src/utils/admin-auth-bootstrap.ts | 6 + YumiNail-Frontend/src/utils/admin-session.ts | 2 + .../src/views/AccountSettingsView.vue | 52 +- .../src/views/ArtistCalendarView.vue | 264 +++ .../src/views/ArtistOrderView.vue | 153 +- YumiNail-Frontend/src/views/AuthView.vue | 156 +- YumiNail-Frontend/src/views/CartView.vue | 176 +- YumiNail-Frontend/src/views/CouponView.vue | 10 + YumiNail-Frontend/src/views/HomeView.vue | 84 +- YumiNail-Frontend/src/views/NotFoundView.vue | 6 + .../src/views/NotificationsView.vue | 179 ++ YumiNail-Frontend/src/views/OrderView.vue | 87 +- .../src/views/PasswordSettingsView.vue | 21 +- .../src/views/ProductDetailView.vue | 27 + .../src/views/ProductListView.vue | 36 + YumiNail-Frontend/src/views/ProfileView.vue | 105 +- YumiNail-Frontend/src/views/SettingsView.vue | 7 + .../src/views/ShopDetailView.vue | 120 +- YumiNail-Frontend/src/views/VipCenterView.vue | 171 ++ YumiNail-Frontend/src/views/WishlistView.vue | 15 + .../src/views/admin/AdminLayout.vue | 49 + .../src/views/admin/AdminLoginView.vue | 23 + .../src/views/admin/AnnouncementsView.vue | 156 ++ .../src/views/admin/CommentsView.vue | 8 + .../src/views/admin/CouponsView.vue | 46 +- .../src/views/admin/DashboardView.vue | 12 + .../src/views/admin/HomeView.vue | 28 + .../src/views/admin/LegalAgreementsView.vue | 153 ++ .../src/views/admin/ManageView.vue | 10 + .../views/admin/MessageHubPushConfigsView.vue | 292 ++++ .../src/views/admin/NailArtistsView.vue | 97 ++ .../src/views/admin/OrdersView.vue | 15 + .../src/views/admin/PermissionsView.vue | 37 + .../src/views/admin/ProductsView.vue | 67 +- .../src/views/admin/ProfileView.vue | 17 + .../src/views/admin/ShopsView.vue | 181 +- .../src/views/admin/SystemMessagesView.vue | 350 ++++ .../src/views/admin/TagsView.vue | 30 + .../src/views/admin/UsersView.vue | 74 + .../src/views/admin/VipRechargePlansView.vue | 149 ++ .../filter/AuthGlobalFilter.java | 2 + .../src/main/resources/application.yaml | 2 + ...cement-vip-recharge-contact-test-report.md | 31 + ...6-system-message-and-mysql-mcp-followup.md | 49 + ...026-05-16-店长参与制作与VIP中心测试报告.md | 49 + .../changes/2026-05-17-newcomer-call-guide.md | 73 + 356 files changed, 24983 insertions(+), 1858 deletions(-) create mode 100644 WeChatProgram/pages/notifications/index.js create mode 100644 WeChatProgram/pages/notifications/index.json create mode 100644 WeChatProgram/pages/notifications/index.wxml create mode 100644 WeChatProgram/pages/notifications/index.wxss create mode 100644 WeChatProgram/pages/vip-center/index.js create mode 100644 WeChatProgram/pages/vip-center/index.json create mode 100644 WeChatProgram/pages/vip-center/index.wxml create mode 100644 WeChatProgram/pages/vip-center/index.wxss create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/LoginLockProperties.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/SecurityHeadersFilter.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/UploadSecurityProperties.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminLegalAgreementController.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminShopRoleController.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AnnouncementController.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/ContactInfoController.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/LegalAgreementController.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/MessageHubPushConfigController.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/SystemMessageController.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/SystemParameterConfigController.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/VipRechargePlanController.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/AgreementAwareRequest.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/AnnouncementCreateDTO.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/InviteCodeDTO.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/LegalAgreementDTO.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/MessageHubPushConfigDTO.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/MessageHubPushTestDTO.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/ShopRoleDTO.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/SystemMessageCreateDTO.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/SystemParameterConfigDTO.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/UserRelationUpdateDTO.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/VipRechargePlanDTO.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/AnnouncementDO.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/LegalAgreementDO.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/MessageHubPushConfigDO.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/SecurityAuditLogDO.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/ShopRoleDO.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/ShopRolePermissionDO.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/SystemMessageDO.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/SystemMessageUserStateDO.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/SystemParameterConfigDO.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/UserAgreementConsentDO.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/UserInviteCodeDO.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/UserRelationDO.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/UserShopRoleDO.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/VipRechargePlanDO.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/AnnouncementMapper.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/LegalAgreementMapper.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/MessageHubPushConfigMapper.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/SecurityAuditLogMapper.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/ShopRoleMapper.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/ShopRolePermissionMapper.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/SystemMessageMapper.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/SystemMessageUserStateMapper.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/SystemParameterConfigMapper.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/UserAgreementConsentMapper.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/UserInviteCodeMapper.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/UserRelationMapper.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/UserShopRoleMapper.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/VipRechargePlanMapper.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/AnnouncementService.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/ContactInfoService.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/LegalAgreementService.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/MapService.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/MessageHubPushConfigService.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/SecurityAuditLogService.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/ShopRoleService.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/SystemMessageService.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/SystemParameterConfigService.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/VipRechargePlanService.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/AnnouncementServiceImpl.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/ContactInfoServiceImpl.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/LegalAgreementServiceImpl.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/MapServiceImpl.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/MessageHubPushConfigServiceImpl.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/SecurityAuditLogServiceImpl.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/ShopRoleServiceImpl.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/SystemMessageServiceImpl.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/SystemParameterConfigServiceImpl.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/VipRechargePlanServiceImpl.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/security/UploadSecurityValidator.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/AnnouncementVO.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/ArtistCalendarAppointmentVO.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/ContactInfoVO.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/InviteCodeVO.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/LegalAgreementVO.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/MessageHubPushConfigVO.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/MessageTargetOptionsVO.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/MessageUnreadCountVO.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/ShopRoleVO.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/SystemMessageVO.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/SystemParameterConfigVO.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/UserAgreementConsentVO.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/UserRelationVO.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/UserStatisticsVO.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/VipRechargePlanVO.java delete mode 100644 YumiNail-Core/src/main/resources/files/2026-03-20_init_admin_permission_template.sql delete mode 100644 YumiNail-Core/src/main/resources/files/2026-03-20_user_asset_vip_coupon_permission_patch.sql delete mode 100644 YumiNail-Core/src/main/resources/files/2026-03-25_user_shop_binding_and_shop_status_patch.sql delete mode 100644 YumiNail-Core/src/main/resources/files/2026-03-27_artist_order_process_default_permission_patch.sql delete mode 100644 YumiNail-Core/src/main/resources/files/2026-03-30_snowflake_id_alignment_patch.sql delete mode 100644 YumiNail-Core/src/main/resources/files/2026-04-02_wechat_mini_binding_patch.sql delete mode 100644 YumiNail-Core/src/main/resources/files/YumiNail-back.sql rename {Frontend => YumiNail-Frontend}/.vscode/extensions.json (100%) create mode 100644 YumiNail-Frontend/src/views/ArtistCalendarView.vue create mode 100644 YumiNail-Frontend/src/views/NotificationsView.vue create mode 100644 YumiNail-Frontend/src/views/VipCenterView.vue create mode 100644 YumiNail-Frontend/src/views/admin/AnnouncementsView.vue create mode 100644 YumiNail-Frontend/src/views/admin/LegalAgreementsView.vue create mode 100644 YumiNail-Frontend/src/views/admin/MessageHubPushConfigsView.vue create mode 100644 YumiNail-Frontend/src/views/admin/SystemMessagesView.vue create mode 100644 YumiNail-Frontend/src/views/admin/VipRechargePlansView.vue create mode 100644 docs/changes/2026-05-16-announcement-vip-recharge-contact-test-report.md create mode 100644 docs/changes/2026-05-16-system-message-and-mysql-mcp-followup.md create mode 100644 docs/changes/2026-05-16-店长参与制作与VIP中心测试报告.md create mode 100644 docs/changes/2026-05-17-newcomer-call-guide.md diff --git a/.idea/compiler.xml b/.idea/compiler.xml index 71a33da9..aa3a0cde 100644 --- a/.idea/compiler.xml +++ b/.idea/compiler.xml @@ -16,14 +16,27 @@ + + + + + + + + + + + diff --git a/.idea/dataSources.xml b/.idea/dataSources.xml index 11c25fa4..97acf354 100644 --- a/.idea/dataSources.xml +++ b/.idea/dataSources.xml @@ -14,5 +14,28 @@ $ProjectFileDir$ + + mysql.8 + true + true + $PROJECT_DIR$/YumiNail-Core/src/main/resources/application.yaml + com.mysql.cj.jdbc.Driver + jdbc:mysql://localhost:3306/yumi_nail?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai + + + + + + $ProjectFileDir$ + + + mysql.8 + true + true + $PROJECT_DIR$/YumiNail-Calendar-Core/src/main/resources/application.yaml + com.mysql.cj.jdbc.Driver + jdbc:mysql://localhost:3306/yumi_nail_calendar?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai + $ProjectFileDir$ + \ No newline at end of file diff --git a/.idea/encodings.xml b/.idea/encodings.xml index 316eb68d..20483061 100644 --- a/.idea/encodings.xml +++ b/.idea/encodings.xml @@ -2,6 +2,8 @@ + + diff --git a/.idea/misc.xml b/.idea/misc.xml index 29cb5ef8..51e991c1 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -7,6 +7,8 @@ diff --git a/.idea/sqldialects.xml b/.idea/sqldialects.xml index f6badb19..6509128a 100644 --- a/.idea/sqldialects.xml +++ b/.idea/sqldialects.xml @@ -1,7 +1,9 @@ + + + - \ No newline at end of file diff --git a/WeChatProgram/api/auth.js b/WeChatProgram/api/auth.js index 6426784b..f304e537 100644 --- a/WeChatProgram/api/auth.js +++ b/WeChatProgram/api/auth.js @@ -1,3 +1,7 @@ +/** + * Mini program API wrapper for this module. + * Call guide: require this module in a page, then invoke the matching method from page event handlers or lifecycle hooks. + */ const request = require('../utils/request') module.exports = { @@ -78,5 +82,12 @@ module.exports = { method: 'POST', data }) + }, + + getCurrentAgreements() { + return request({ + url: '/legal-agreement/current', + method: 'GET' + }) } } diff --git a/WeChatProgram/api/cart.js b/WeChatProgram/api/cart.js index 4e781b55..cd6469a7 100644 --- a/WeChatProgram/api/cart.js +++ b/WeChatProgram/api/cart.js @@ -1,3 +1,7 @@ +/** + * Mini program API wrapper for this module. + * Call guide: require this module in a page, then invoke the matching method from page event handlers or lifecycle hooks. + */ const request = require('../utils/request') module.exports = { diff --git a/WeChatProgram/api/comment.js b/WeChatProgram/api/comment.js index 8c7430c3..e5e25f8f 100644 --- a/WeChatProgram/api/comment.js +++ b/WeChatProgram/api/comment.js @@ -1,3 +1,7 @@ +/** + * Mini program API wrapper for this module. + * Call guide: require this module in a page, then invoke the matching method from page event handlers or lifecycle hooks. + */ const request = require('../utils/request') module.exports = { diff --git a/WeChatProgram/api/coupon.js b/WeChatProgram/api/coupon.js index 74ae6a59..ff845f85 100644 --- a/WeChatProgram/api/coupon.js +++ b/WeChatProgram/api/coupon.js @@ -1,3 +1,7 @@ +/** + * Mini program API wrapper for this module. + * Call guide: require this module in a page, then invoke the matching method from page event handlers or lifecycle hooks. + */ const request = require('../utils/request') module.exports = { diff --git a/WeChatProgram/api/file.js b/WeChatProgram/api/file.js index ce367e8b..72df1890 100644 --- a/WeChatProgram/api/file.js +++ b/WeChatProgram/api/file.js @@ -1,3 +1,7 @@ +/** + * Mini program API wrapper for this module. + * Call guide: require this module in a page, then invoke the matching method from page event handlers or lifecycle hooks. + */ const request = require('../utils/request') module.exports = { diff --git a/WeChatProgram/api/order.js b/WeChatProgram/api/order.js index 8a915364..b90e01c6 100644 --- a/WeChatProgram/api/order.js +++ b/WeChatProgram/api/order.js @@ -1,3 +1,7 @@ +/** + * Mini program API wrapper for this module. + * Call guide: require this module in a page, then invoke the matching method from page event handlers or lifecycle hooks. + */ const request = require('../utils/request') module.exports = { diff --git a/WeChatProgram/api/product-like.js b/WeChatProgram/api/product-like.js index c8ff0c9c..12094240 100644 --- a/WeChatProgram/api/product-like.js +++ b/WeChatProgram/api/product-like.js @@ -1,3 +1,7 @@ +/** + * Mini program API wrapper for this module. + * Call guide: require this module in a page, then invoke the matching method from page event handlers or lifecycle hooks. + */ const request = require('../utils/request') module.exports = { diff --git a/WeChatProgram/api/product.js b/WeChatProgram/api/product.js index d80eb67a..3db0bc7a 100644 --- a/WeChatProgram/api/product.js +++ b/WeChatProgram/api/product.js @@ -1,3 +1,7 @@ +/** + * Mini program API wrapper for this module. + * Call guide: require this module in a page, then invoke the matching method from page event handlers or lifecycle hooks. + */ const request = require('../utils/request') module.exports = { diff --git a/WeChatProgram/api/shop.js b/WeChatProgram/api/shop.js index 8ccdf068..7efbdf4a 100644 --- a/WeChatProgram/api/shop.js +++ b/WeChatProgram/api/shop.js @@ -1,3 +1,7 @@ +/** + * Mini program API wrapper for this module. + * Call guide: require this module in a page, then invoke the matching method from page event handlers or lifecycle hooks. + */ const request = require('../utils/request') module.exports = { diff --git a/WeChatProgram/api/tag.js b/WeChatProgram/api/tag.js index f7927da0..451139f2 100644 --- a/WeChatProgram/api/tag.js +++ b/WeChatProgram/api/tag.js @@ -1,3 +1,7 @@ +/** + * Mini program API wrapper for this module. + * Call guide: require this module in a page, then invoke the matching method from page event handlers or lifecycle hooks. + */ const request = require('../utils/request') module.exports = { diff --git a/WeChatProgram/api/user.js b/WeChatProgram/api/user.js index 72ad07cd..9b203ea9 100644 --- a/WeChatProgram/api/user.js +++ b/WeChatProgram/api/user.js @@ -1,3 +1,7 @@ +/** + * Mini program API wrapper for this module. + * Call guide: require this module in a page, then invoke the matching method from page event handlers or lifecycle hooks. + */ const request = require('../utils/request') const actionGuard = require('../utils/action-guard') const { API_BASE_URL, REQUEST_TIMEOUT } = require('../utils/config') @@ -39,6 +43,86 @@ module.exports = { }) }, + // 我的页常用数据: + // 资产、余额流水、消息、公告、VIP 充值档位和所属关系都从这里拿。 + getMyAsset() { + return request({ + url: '/user/asset/me' + }) + }, + + getMyBalanceHistory() { + return request({ + url: '/user/balance/history/me' + }) + }, + + listMyMessages() { + return request({ + url: '/system-message/my/list' + }) + }, + + listMyPopupMessages() { + return request({ + url: '/system-message/my/popup' + }) + }, + + getMyUnreadMessageCount() { + return request({ + url: '/system-message/my/unread-count' + }) + }, + + markMessagePopupShown(id) { + return request({ + url: `/system-message/my/${id}/popup-shown`, + method: 'PUT', + data: {} + }) + }, + + markMessageRead(id) { + return request({ + url: `/system-message/my/${id}/read`, + method: 'PUT', + data: {} + }) + }, + + listMyAnnouncements() { + return request({ + url: '/announcement/my/list' + }) + }, + + // 这里只是“展示型充值档位”,不发起支付、不改余额。 + listMyVipRechargePlans() { + return request({ + url: '/vip-recharge-plan/my/list' + }) + }, + + getShopManagerContact(shopId) { + return request({ + url: `/contact-info/shop/${shopId}/manager` + }) + }, + + getProductArtistContact(productId, artistId) { + return request({ + url: `/contact-info/product/${productId}/artist/${artistId}` + }) + }, + + getOrderArtistContact(orderId, artistId) { + return request({ + url: `/contact-info/order/${orderId}/artist`, + data: artistId ? { artistId } : {} + }) + }, + updateUserInfo(data) { return request({ url: '/user/update', diff --git a/WeChatProgram/api/wishlist.js b/WeChatProgram/api/wishlist.js index 0cbcab94..800f6bcb 100644 --- a/WeChatProgram/api/wishlist.js +++ b/WeChatProgram/api/wishlist.js @@ -1,3 +1,7 @@ +/** + * Mini program API wrapper for this module. + * Call guide: require this module in a page, then invoke the matching method from page event handlers or lifecycle hooks. + */ const request = require('../utils/request') module.exports = { diff --git a/WeChatProgram/app.json b/WeChatProgram/app.json index 00c35001..83bd2349 100644 --- a/WeChatProgram/app.json +++ b/WeChatProgram/app.json @@ -11,6 +11,8 @@ "pages/orders/index", "pages/wishlist/index", "pages/coupons/index", + "pages/vip-center/index", + "pages/notifications/index", "pages/settings/index" ], "window": { diff --git a/WeChatProgram/components/navigation-bar/navigation-bar.js b/WeChatProgram/components/navigation-bar/navigation-bar.js index 579d25a0..f38f7589 100644 --- a/WeChatProgram/components/navigation-bar/navigation-bar.js +++ b/WeChatProgram/components/navigation-bar/navigation-bar.js @@ -52,7 +52,9 @@ Component({ show: { type: Boolean, value: true, - observer: '_showChange', + observer(show) { + this._showChange(show) + }, }, delta: { type: Number, @@ -64,7 +66,9 @@ Component({ }, }, observers: { - 'back, showBack, isTabPage': 'updateResolvedBack', + 'back, showBack, isTabPage': function () { + this.updateResolvedBack() + }, }, data: { displayStyle: '', diff --git a/WeChatProgram/components/product-card/product-card.wxml b/WeChatProgram/components/product-card/product-card.wxml index 7013ef40..7609f721 100644 --- a/WeChatProgram/components/product-card/product-card.wxml +++ b/WeChatProgram/components/product-card/product-card.wxml @@ -6,6 +6,7 @@ {{item.displayTitle}} + {{item.shopNameText}} {{item.metaText}} {{item}} diff --git a/WeChatProgram/components/product-card/product-card.wxss b/WeChatProgram/components/product-card/product-card.wxss index 04208aa2..f3d2529c 100644 --- a/WeChatProgram/components/product-card/product-card.wxss +++ b/WeChatProgram/components/product-card/product-card.wxss @@ -215,3 +215,13 @@ font-weight: 700; white-space: nowrap; } + +.product-shop { + margin-top: 6rpx; + color: #8f6e7a; + font-size: 22rpx; + line-height: 1.45; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} diff --git a/WeChatProgram/pages/auth/index.js b/WeChatProgram/pages/auth/index.js index 91f4e60d..372b22d0 100644 --- a/WeChatProgram/pages/auth/index.js +++ b/WeChatProgram/pages/auth/index.js @@ -16,6 +16,10 @@ const { const phoneRegex = /^1[3-9]\d{9}$/ +/** + * auth page logic. + * Call guide: page data drives the WXML template, and each method is called by user events or lifecycle callbacks. + */ Page({ data: Object.assign(createKeyboardSafeData({ cursorSpacing: 108 @@ -54,6 +58,10 @@ Page({ miniShopDisplayName: '', miniShopNewUser: false, miniShopSubmitting: false, + agreementAccepted: false, + agreements: [], + agreementModalVisible: false, + selectedAgreement: null, form: { account: '', password: '', @@ -71,6 +79,10 @@ Page({ } }), + /** + * `onLoad` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ onLoad(options) { this.ensureKeyboardSafe() this.setData({ @@ -79,20 +91,33 @@ Page({ }) this.detectWechatMiniCapability() this.loadShopOptions() + this.loadAgreements() this.consumePendingWechatMiniLogin() this.waitForPendingWechatMiniAutoLogin() }, + /** + * `onShow` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ onShow() { this.ensureKeyboardSafe() this.consumePendingWechatMiniLogin() }, + /** + * `onHide` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ onHide() { resetKeyboardSafe(this) detachKeyboardSafe(this) }, + /** + * `onUnload` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ onUnload() { resetKeyboardSafe(this) detachKeyboardSafe(this) @@ -100,6 +125,10 @@ Page({ noop() {}, + /** + * `ensureKeyboardSafe` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ ensureKeyboardSafe() { attachKeyboardSafe(this, { cursorSpacing: 108, @@ -107,14 +136,26 @@ Page({ }) }, + /** + * `handleKeyboardFocus` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleKeyboardFocus(event) { handleKeyboardFocus(this, event) }, + /** + * `handleKeyboardBlur` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleKeyboardBlur() { handleKeyboardBlur(this) }, + /** + * `detectWechatMiniCapability` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ detectWechatMiniCapability() { let supported = false let disabledReason = '' @@ -122,6 +163,10 @@ Page({ try { supported = wx.canIUse('button.open-type.getPhoneNumber') const systemInfo = wx.getSystemInfoSync() + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (systemInfo && systemInfo.platform === 'devtools') { supported = false disabledReason = '当前环境无法使用微信手机号登录,请使用账号密码或验证码登录' @@ -130,6 +175,10 @@ Page({ supported = false } + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!supported && !disabledReason) { disabledReason = '当前环境无法使用微信手机号登录,请使用账号密码或验证码登录' } @@ -140,6 +189,10 @@ Page({ }) }, + /** + * `waitForPendingWechatMiniAutoLogin` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ waitForPendingWechatMiniAutoLogin() { const app = getApp() if ( @@ -167,13 +220,25 @@ Page({ }) }, + /** + * `consumePendingWechatMiniLogin` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ consumePendingWechatMiniLogin() { const app = getApp() + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!app || typeof app.consumePendingWechatMiniLogin !== 'function') { return } const pending = app.consumePendingWechatMiniLogin() + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (pending && pending.status === 'SELECT_SHOP') { this.openMiniShopSelector(pending) } @@ -193,6 +258,87 @@ Page({ } }, + async loadAgreements() { + try { + const agreements = await authApi.getCurrentAgreements() + this.setData({ + agreements: Array.isArray(agreements) ? agreements : [] + }) + } catch (error) { + wx.showToast({ + title: '协议内容加载失败,请稍后重试', + icon: 'none' + }) + } + }, + + buildAgreementPayload() { + const agreementVersions = {} + ;(this.data.agreements || []).forEach((item) => { + if (item && item.agreementType && item.version) { + agreementVersions[item.agreementType] = item.version + } + }) + return { + agreementAccepted: !!this.data.agreementAccepted, + agreementVersions, + clientType: 'WECHAT_MINI' + } + }, + + ensureAgreementAccepted() { + if (!this.data.agreementAccepted) { + wx.showToast({ + title: '请先阅读并同意用户协议和隐私政策', + icon: 'none' + }) + return false + } + + const versions = this.buildAgreementPayload().agreementVersions + if (!versions.USER_TERMS || !versions.PRIVACY_POLICY) { + wx.showToast({ + title: '协议版本加载中,请稍后再试', + icon: 'none' + }) + return false + } + return true + }, + + handleAgreementToggle() { + this.setData({ + agreementAccepted: !this.data.agreementAccepted + }) + }, + + openAgreement(event) { + const type = event.currentTarget.dataset.type + const selectedAgreement = (this.data.agreements || []).find((item) => item.agreementType === type) + if (!selectedAgreement) { + wx.showToast({ + title: '协议内容暂不可用', + icon: 'none' + }) + return + } + this.setData({ + selectedAgreement, + agreementModalVisible: true + }) + }, + + closeAgreementModal() { + this.setData({ + agreementModalVisible: false, + selectedAgreement: null + }) + }, + + /** + * `handleTabChange` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleTabChange(event) { const tab = event.currentTarget.dataset.tab resetKeyboardSafe(this) @@ -210,6 +356,10 @@ Page({ }) }, + /** + * `handleLoginTypeChange` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleLoginTypeChange(event) { const type = event.currentTarget.dataset.type resetKeyboardSafe(this) @@ -227,6 +377,10 @@ Page({ }) }, + /** + * `handleShowTraditionalLogin` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleShowTraditionalLogin() { resetKeyboardSafe(this) this.setData({ @@ -235,6 +389,10 @@ Page({ }) }, + /** + * `handleToggleResetPanel` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleToggleResetPanel() { resetKeyboardSafe(this) this.setData({ @@ -242,6 +400,10 @@ Page({ }) }, + /** + * `handleInputChange` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleInputChange(event) { const field = event.currentTarget.dataset.field const value = event.detail.value @@ -249,7 +411,15 @@ Page({ [`form.${field}`]: value } + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (field === 'account') { + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (this.data.activeTab === 'login') { patch.loginAccountStatusText = '' patch.loginAccountStatusType = '' @@ -267,7 +437,15 @@ Page({ } } + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (field === 'phone') { + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (this.data.activeTab === 'register') { patch.registerPhoneStatusText = '' patch.registerPhoneStatusType = '' @@ -284,6 +462,10 @@ Page({ this.setData(patch) }, + /** + * `handleResetInputChange` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleResetInputChange(event) { const field = event.currentTarget.dataset.field this.setData({ @@ -291,6 +473,10 @@ Page({ }) }, + /** + * `handleRegisterShopChange` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleRegisterShopChange(event) { const index = Number(event.detail.value) const shop = this.data.shops[index] @@ -301,6 +487,10 @@ Page({ }) }, + /** + * `handleLoginShopChange` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleLoginShopChange(event) { const index = Number(event.detail.value) const shop = this.data.loginShops[index] @@ -311,6 +501,10 @@ Page({ }) }, + /** + * `handleMiniShopChange` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleMiniShopChange(event) { const index = Number(event.detail.value) const shop = this.data.miniShops[index] @@ -320,7 +514,15 @@ Page({ }) }, + /** + * `handleCloseMiniShopSelector` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleCloseMiniShopSelector() { + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (this.data.miniShopSubmitting) { return } @@ -329,7 +531,15 @@ Page({ }) }, + /** + * `handleResumeMiniShopSelector` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleResumeMiniShopSelector() { + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!this.data.miniShopTicket || !this.data.miniShops.length) { return } @@ -342,15 +552,27 @@ Page({ async handleAccountBlur() { this.handleKeyboardBlur() const account = this.data.form.account.trim() + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!account) { return } + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (this.data.activeTab === 'register') { await this.checkRegisterAccountAvailability() return } + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (this.data.loginType !== 'password') { return } @@ -364,10 +586,18 @@ Page({ async handlePhoneBlur() { this.handleKeyboardBlur() const phone = this.data.form.phone.trim() + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!phone) { return } + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (this.data.activeTab === 'register') { if (phoneRegex.test(phone)) { await this.checkRegisterPhoneAvailability() @@ -382,6 +612,10 @@ Page({ await this.loadLoginShopsByPhone() }, + /** + * `applyLoginShopSelection` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ applyLoginShopSelection(selection) { const shops = Array.isArray(selection && selection.shops) ? selection.shops : [] const allowLoginShopless = Boolean(selection && selection.allowShoplessLogin) @@ -389,6 +623,10 @@ Page({ let loginShopDisplayName = '' let shopId = '' + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!allowLoginShopless && shops.length === 1) { loginShopIndex = 0 loginShopDisplayName = shops[0].shopName || '' @@ -482,6 +720,10 @@ Page({ } }, + /** + * `startCountdown` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ startCountdown(fieldName) { this.setData({ [fieldName]: 60 @@ -493,6 +735,10 @@ Page({ [fieldName]: nextValue }) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (nextValue <= 0) { clearInterval(timer) } @@ -500,6 +746,10 @@ Page({ }, async handleSendCode() { + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (this.data.countdown > 0) { return } @@ -513,8 +763,16 @@ Page({ return } + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (this.data.activeTab === 'register') { const phoneAvailable = await this.checkRegisterPhoneAvailability() + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!phoneAvailable) { wx.showToast({ title: this.data.registerPhoneStatusText || '该手机号已被注册', @@ -525,7 +783,10 @@ Page({ } try { - await runWithLoading(() => userApi.sendVerificationCode({ phone })) + await runWithLoading(() => userApi.sendVerificationCode({ + phone, + sceneCode: this.data.activeTab === 'register' ? 'USER_REGISTER_SMS_CODE' : 'USER_LOGIN_SMS_CODE' + })) wx.showToast({ title: '验证码已发送', icon: 'none' @@ -540,6 +801,10 @@ Page({ }, async handleSendForgotCode() { + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (this.data.forgotCountdown > 0) { return } @@ -554,7 +819,10 @@ Page({ } try { - await runWithLoading(() => authApi.sendVerificationCode({ phone })) + await runWithLoading(() => authApi.sendVerificationCode({ + phone, + sceneCode: 'USER_RESET_PASSWORD_SMS_CODE' + })) wx.showToast({ title: '验证码已发送', icon: 'none' @@ -568,8 +836,16 @@ Page({ } }, + /** + * `validateLoginForm` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ validateLoginForm() { const form = this.data.form + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (this.data.loginType === 'password') { if (!form.account.trim() || !form.password) { return '请输入账号和密码' @@ -578,6 +854,10 @@ Page({ return '请输入正确的手机号和验证码' } + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!this.data.allowLoginShopless && this.data.loginShops.length && !form.shopId) { return '请选择登录门店' } @@ -599,12 +879,24 @@ Page({ if (!form.verificationCode.trim()) { return '请输入验证码' } + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!form.password || form.password.length < 6) { return '密码至少 6 位' } + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (form.password !== form.confirmPassword) { return '两次输入的密码不一致' } + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!form.shopId) { return '请选择门店' } @@ -614,6 +906,10 @@ Page({ this.checkRegisterPhoneAvailability() ]) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!accountAvailable || !phoneAvailable) { return '请先处理注册信息中的占用问题' } @@ -622,30 +918,45 @@ Page({ }, async handleSubmit() { + if (!this.ensureAgreementAccepted()) { + return + } + this.setData({ loading: true }) try { + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (this.data.activeTab === 'login') { const loginError = this.validateLoginForm() + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (loginError) { throw new Error(loginError) } let payload await runWithLoading(async () => { + const agreementPayload = this.buildAgreementPayload() payload = this.data.loginType === 'phone' ? await authApi.phoneLogin({ phone: this.data.form.phone.trim(), verificationCode: this.data.form.verificationCode.trim(), - shopId: this.data.form.shopId || undefined + shopId: this.data.form.shopId || undefined, + ...agreementPayload }) : await authApi.login({ account: this.data.form.account.trim(), password: this.data.form.password, rememberMe: true, - shopId: this.data.form.shopId || undefined + shopId: this.data.form.shopId || undefined, + ...agreementPayload }) }) @@ -654,6 +965,10 @@ Page({ } const registerError = await this.validateRegisterForm() + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (registerError) { throw new Error(registerError) } @@ -664,7 +979,8 @@ Page({ nickname: this.data.form.nickname.trim(), phone: this.data.form.phone.trim(), verificationCode: this.data.form.verificationCode.trim(), - shopId: this.data.form.shopId + shopId: this.data.form.shopId, + ...this.buildAgreementPayload() })) wx.showToast({ @@ -708,6 +1024,10 @@ Page({ }) return } + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!form.newPassword || form.newPassword.length < 6) { wx.showToast({ title: '新密码至少 6 位', @@ -750,6 +1070,10 @@ Page({ } }, + /** + * `handleWechatMiniUnavailableTap` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleWechatMiniUnavailableTap() { wx.showToast({ title: this.data.wechatMiniDisabledReason || '请使用账号密码或验证码登录', @@ -758,12 +1082,24 @@ Page({ }, async handleWechatMiniPhoneLogin(event) { + if (!this.ensureAgreementAccepted()) { + return + } + + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!this.data.wechatMiniSupported || this.data.wechatMiniLoading) { this.handleWechatMiniUnavailableTap() return } const detail = event.detail || {} + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!detail.code) { wx.showToast({ title: this.resolveWechatAuthorizeError(detail), @@ -781,7 +1117,8 @@ Page({ const result = await runWithLoading(() => authApi.wechatMiniPhoneLogin({ wxCode, phoneCode: detail.code, - preferredShopId: authStore.getPreferredMiniLoginShopId() || undefined + preferredShopId: authStore.getPreferredMiniLoginShopId() || undefined, + ...this.buildAgreementPayload() })) await this.handleWechatMiniResult(result) } catch (error) { @@ -797,7 +1134,15 @@ Page({ }, async handleConfirmMiniShopLogin() { + if (!this.ensureAgreementAccepted()) { + return + } + const shop = this.data.miniShops[this.data.miniShopIndex] + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!this.data.miniShopTicket) { wx.showToast({ title: '登录票据已失效,请重新发起微信登录', @@ -805,6 +1150,10 @@ Page({ }) return } + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!shop || !shop.id) { wx.showToast({ title: '请选择门店', @@ -820,8 +1169,13 @@ Page({ try { const result = await runWithLoading(() => authApi.confirmWechatMiniLogin({ ticket: this.data.miniShopTicket, - shopId: shop.id + shopId: shop.id, + ...this.buildAgreementPayload() })) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!result || result.status !== 'SUCCESS') { throw new Error((result && result.message) || '确认登录失败') } @@ -839,6 +1193,10 @@ Page({ } }, + /** + * `resolveWechatAuthorizeError` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ resolveWechatAuthorizeError(detail) { const errMsg = String((detail && detail.errMsg) || '') if (errMsg.includes('user deny') || errMsg.includes('user cancel')) { @@ -850,8 +1208,16 @@ Page({ return '未获取到微信手机号授权,请稍后重试。' }, + /** + * `requestWechatMiniCode` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ requestWechatMiniCode() { const app = getApp() + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (app && typeof app.requestWechatMiniCode === 'function') { return app.requestWechatMiniCode() } @@ -859,6 +1225,10 @@ Page({ return new Promise((resolve, reject) => { wx.login({ success: res => { + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (res && res.code) { resolve(res.code) return @@ -871,15 +1241,27 @@ Page({ }, async handleWechatMiniResult(result) { + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!result) { throw new Error('微信登录未返回结果') } + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (result.status === 'SUCCESS') { await this.finishLogin(result, result.newUser ? '注册并登录成功' : '登录成功') return } + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (result.status === 'SELECT_SHOP') { this.openMiniShopSelector(result) return @@ -891,9 +1273,17 @@ Page({ }) }, + /** + * `openMiniShopSelector` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ openMiniShopSelector(result) { resetKeyboardSafe(this) const shops = Array.isArray(result && result.shops) ? result.shops : [] + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!shops.length) { wx.showToast({ title: result && result.message ? result.message : '暂无可选门店,请稍后重试', @@ -917,6 +1307,10 @@ Page({ }) }, + /** + * `clearMiniShopSelector` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ clearMiniShopSelector() { this.setData({ showMiniShopSelector: false, @@ -951,10 +1345,22 @@ Page({ } }, + /** + * `buildAuthHelperText` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ buildAuthHelperText(activeTab, loginType) { + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (activeTab === 'register') { return '注册前请先选门店' } + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (loginType === 'phone') { return '未注册手机号会先选门店' } diff --git a/WeChatProgram/pages/auth/index.wxml b/WeChatProgram/pages/auth/index.wxml index 499971f4..2033791b 100644 --- a/WeChatProgram/pages/auth/index.wxml +++ b/WeChatProgram/pages/auth/index.wxml @@ -37,6 +37,16 @@ + + + {{agreementAccepted ? '✓' : ''}} + + 我已阅读并同意 + 《用户协议》 + 和 + 《隐私政策》 + + - {{activeTab === 'login' ? '立即登录' : '完成注册'}} + + {{agreementAccepted ? '✓' : ''}} + + 我已阅读并同意 + 《用户协议》 + 和 + 《隐私政策》 + + + + {{activeTab === 'login' ? '立即登录' : '完成注册'}} @@ -303,10 +323,31 @@ 首次登录会自动注册并绑定手机号。 + + {{agreementAccepted ? '✓' : ''}} + + 我已阅读并同意 + 《用户协议》 + 和 + 《隐私政策》 + + + 稍后再选 {{miniShopSubmitting ? '确认中...' : '确认登录'}} + + + + {{selectedAgreement.title || '协议详情'}} + 版本:{{selectedAgreement.version || '-'}} + + {{selectedAgreement.content || '暂无协议内容'}} + + 我知道了 + + diff --git a/WeChatProgram/pages/auth/index.wxss b/WeChatProgram/pages/auth/index.wxss index 4decb5e9..4e88ca6d 100644 --- a/WeChatProgram/pages/auth/index.wxss +++ b/WeChatProgram/pages/auth/index.wxss @@ -238,6 +238,110 @@ margin-top: 24rpx; } +.submit-btn.disabled { + opacity: 0.52; +} + +.agreement-row { + display: flex; + align-items: flex-start; + gap: 14rpx; + margin-top: 22rpx; + color: #7a6871; + font-size: 23rpx; + line-height: 1.6; +} + +.agreement-check { + display: flex; + align-items: center; + justify-content: center; + width: 34rpx; + height: 34rpx; + margin-top: 2rpx; + border: 2rpx solid #d9b8c4; + border-radius: 10rpx; + color: #ffffff; + font-size: 22rpx; + font-weight: 800; + flex-shrink: 0; +} + +.agreement-check.checked { + border-color: #c6597d; + background: #c6597d; +} + +.agreement-copy { + flex: 1; + min-width: 0; +} + +.agreement-link { + color: #c6597d; + font-weight: 700; +} + +.mini-shop-agreement { + margin-top: 22rpx; +} + +.wechat-agreement { + width: 100%; + margin-top: 18rpx; + text-align: left; +} + +.agreement-mask { + position: fixed; + inset: 0; + z-index: 80; + display: flex; + align-items: center; + justify-content: center; + padding: 28rpx; + background: rgba(45, 36, 48, 0.42); +} + +.agreement-modal { + width: 100%; + max-width: 690rpx; + max-height: 82vh; + padding: 30rpx 28rpx; + border-radius: 32rpx; + background: #ffffff; +} + +.agreement-modal-title { + font-size: 32rpx; + line-height: 1.35; + font-weight: 800; + color: #2d2430; +} + +.agreement-modal-meta { + margin-top: 10rpx; + font-size: 22rpx; + color: #9a8590; +} + +.agreement-modal-body { + height: 640rpx; + max-height: 56vh; + margin-top: 22rpx; + padding: 20rpx; + border-radius: 22rpx; + background: #fff7f8; + color: #5a4a52; + font-size: 24rpx; + line-height: 1.85; + box-sizing: border-box; +} + +.agreement-modal-close { + margin-top: 22rpx; +} + .mini-shop-mask { position: fixed; inset: 0; diff --git a/WeChatProgram/pages/cart/index.js b/WeChatProgram/pages/cart/index.js index 30aaa61d..e26a22f8 100644 --- a/WeChatProgram/pages/cart/index.js +++ b/WeChatProgram/pages/cart/index.js @@ -27,6 +27,10 @@ function getCouponDisplay(coupon) { } function calculateCouponDiscount(coupon, amount) { + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!coupon || amount <= 0) { return 0 } @@ -47,32 +51,56 @@ function buildCheckoutIssues(items) { const issues = [] const selectedItems = items.filter(item => item.selected) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!selectedItems.length) { issues.push('请先勾选要结算的作品') return issues } const missingArtist = selectedItems.find(item => !item.artistId) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (missingArtist) { issues.push(`请先为“${missingArtist.productTitle}”选择美甲师`) } const missingTime = selectedItems.find(item => !item.appointmentValue) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (missingTime) { issues.push(`请先为“${missingTime.productTitle}”选择预约时间`) } const expiredTime = selectedItems.find(item => item.appointmentValue && isPastAppointment(item.appointmentValue)) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (expiredTime) { issues.push(`“${expiredTime.productTitle}”的预约时间已过,请重新选择`) } const shopIds = Array.from(new Set(selectedItems.map(item => item.shopId).filter(Boolean))) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (shopIds.length > 1) { issues.push('跨门店作品请分开结算') } const artistIds = Array.from(new Set(selectedItems.map(item => item.artistId).filter(Boolean))) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (artistIds.length > 1) { issues.push('不同美甲师的项目请分开结算') } @@ -80,6 +108,10 @@ function buildCheckoutIssues(items) { return issues } +/** + * cart page logic. + * Call guide: page data drives the WXML template, and each method is called by user events or lifecycle callbacks. + */ Page({ data: { isLoggedIn: false, @@ -98,6 +130,10 @@ Page({ submittingOrder: false }, + /** + * `onShow` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ onShow() { this.loadCartItems() }, @@ -107,14 +143,26 @@ Page({ wx.stopPullDownRefresh() }, + /** + * `getSelectedItems` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ getSelectedItems() { return this.data.cartItems.filter(item => item.selected) }, + /** + * `getSelectedCoupon` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ getSelectedCoupon() { return this.data.availableCoupons.find(item => item.key === this.data.selectedCouponKey) || null }, + /** + * `refreshSummary` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ refreshSummary() { const selectedItems = this.getSelectedItems() const selectedCoupon = this.getSelectedCoupon() @@ -143,6 +191,10 @@ Page({ loading: isLoggedIn }) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!isLoggedIn) { this.setData({ cartItems: [], @@ -163,7 +215,10 @@ Page({ const availableArtists = Array.isArray(item.availableArtists) ? item.availableArtists.map(artist => ({ id: artist.id, name: artist.name, - avatar: artist.avatar + avatar: artist.avatar, + userType: artist.userType, + roleLabel: artist.roleLabel, + participateProduction: artist.participateProduction })) : [] const artist = availableArtists.find(current => String(current.id) === String(item.artistId || '')) @@ -204,6 +259,10 @@ Page({ async loadAvailableCoupons() { const selectedItems = this.getSelectedItems() + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!selectedItems.length) { this.setData({ availableCoupons: [], @@ -241,9 +300,17 @@ Page({ selectedCouponKey = NO_COUPON_KEY } + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (selectedCouponKey === NO_COUPON_KEY) { const bestCoupons = list .sort((left, right) => calculateCouponDiscount(right, subtotalAmount) - calculateCouponDiscount(left, subtotalAmount)) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (bestCoupons.length) { selectedCouponKey = bestCoupons[0].key } @@ -263,10 +330,18 @@ Page({ } }, + /** + * `handleOpenAuth` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleOpenAuth() { navigation.openAuth('/pages/cart/index') }, + /** + * `handleBrowseProducts` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleBrowseProducts() { navigation.switchTab('/pages/products/index') }, @@ -275,6 +350,10 @@ Page({ const index = Number(event.currentTarget.dataset.index) const cartItems = this.data.cartItems.slice() const item = cartItems[index] + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!item) { return } @@ -296,11 +375,19 @@ Page({ const delta = Number(event.currentTarget.dataset.delta) const cartItems = this.data.cartItems.slice() const item = cartItems[index] + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!item) { return } const nextQuantity = Number(item.quantity || 0) + delta + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (nextQuantity < 1 || nextQuantity > 99) { return } @@ -337,6 +424,10 @@ Page({ const index = Number(event.currentTarget.dataset.index) const cartItems = this.data.cartItems.slice() const item = cartItems[index] + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!item) { return } @@ -349,6 +440,10 @@ Page({ }) }) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!confirmed) { return } @@ -369,8 +464,16 @@ Page({ } }, + /** + * `handleOpenProduct` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleOpenProduct(event) { const productId = event.currentTarget.dataset.productId + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!productId) { return } @@ -384,10 +487,18 @@ Page({ const index = Number(event.currentTarget.dataset.index) const cartItems = this.data.cartItems.slice() const item = cartItems[index] + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!item) { return } + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!item.availableArtists.length) { wx.showToast({ title: '当前作品暂时没有可预约美甲师', @@ -398,29 +509,41 @@ Page({ const tapIndex = await new Promise(resolve => { wx.showActionSheet({ - itemList: item.availableArtists.map(artist => artist.name), + itemList: item.availableArtists.map(artist => artist.roleLabel ? `${artist.name}(${artist.roleLabel})` : artist.name), success: res => resolve(res.tapIndex), fail: () => resolve(-1) }) }) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (tapIndex < 0 || tapIndex >= item.availableArtists.length) { return } const artist = item.availableArtists[tapIndex] item.artistId = artist.id - item.artistName = artist.name + item.artistName = artist.roleLabel ? `${artist.name}(${artist.roleLabel})` : artist.name this.setData({ cartItems }) this.refreshSummary() }, + /** + * `handleDateChange` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleDateChange(event) { const index = Number(event.currentTarget.dataset.index) const cartItems = this.data.cartItems.slice() const item = cartItems[index] + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!item) { return } @@ -433,10 +556,18 @@ Page({ this.refreshSummary() }, + /** + * `handleTimeChange` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleTimeChange(event) { const index = Number(event.currentTarget.dataset.index) const cartItems = this.data.cartItems.slice() const item = cartItems[index] + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!item) { return } @@ -449,6 +580,10 @@ Page({ this.refreshSummary() }, + /** + * `handleCouponChange` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleCouponChange(event) { this.setData({ selectedCouponKey: event.detail.value @@ -457,12 +592,20 @@ Page({ }, async handleCheckout() { + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (this.data.submittingOrder) { return } const selectedItems = this.getSelectedItems() const checkoutIssues = buildCheckoutIssues(this.data.cartItems) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (checkoutIssues.length) { wx.showToast({ title: checkoutIssues[0], diff --git a/WeChatProgram/pages/coupons/index.js b/WeChatProgram/pages/coupons/index.js index 804f3e1d..78609d31 100644 --- a/WeChatProgram/pages/coupons/index.js +++ b/WeChatProgram/pages/coupons/index.js @@ -9,6 +9,10 @@ function getBenefitText(coupon) { return `满 ${coupon.minAmount} 减 ${coupon.reduceAmount}` } +/** + * coupons page logic. + * Call guide: page data drives the WXML template, and each method is called by user events or lifecycle callbacks. + */ Page({ data: { loading: false, @@ -24,6 +28,10 @@ Page({ ] }, + /** + * `onShow` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ onShow() { this.loadCoupons() }, @@ -35,6 +43,10 @@ Page({ loading: isLoggedIn }) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!isLoggedIn) { this.setData({ coupons: [], @@ -74,11 +86,19 @@ Page({ } }, + /** + * `applyFilter` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ applyFilter(filterValue, sourceCoupons) { const activeFilter = filterValue || 'all' const coupons = Array.isArray(sourceCoupons) ? sourceCoupons : this.data.coupons let filteredCoupons = coupons + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (activeFilter === 'available') { filteredCoupons = coupons.filter(item => Number(item.status) === 1) } else if (activeFilter === 'used') { @@ -93,18 +113,34 @@ Page({ }) }, + /** + * `handleFilterChange` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleFilterChange(event) { const value = event.currentTarget.dataset.value + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!value || value === this.data.activeFilter) { return } this.applyFilter(value) }, + /** + * `handleOpenAuth` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleOpenAuth() { navigation.openAuth('/pages/coupons/index') }, + /** + * `handleBack` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleBack() { navigation.goBack('/pages/profile/index') } diff --git a/WeChatProgram/pages/home/index.js b/WeChatProgram/pages/home/index.js index 3cfa18c9..152f91ac 100644 --- a/WeChatProgram/pages/home/index.js +++ b/WeChatProgram/pages/home/index.js @@ -16,6 +16,10 @@ const productApi = require('../../api/product') const shopApi = require('../../api/shop') const userApi = require('../../api/user') +/** + * home page logic. + * Call guide: page data drives the WXML template, and each method is called by user events or lifecycle callbacks. + */ Page({ data: Object.assign(createKeyboardSafeData({ cursorSpacing: 96 @@ -32,31 +36,52 @@ Page({ bannerImages: [], featuredItems: [], popularItems: [], + announcements: [], popularPage: 1, pageSize: 6, hasMore: false, popularTotal: 0 }), + /** + * `onLoad` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ onLoad() { this.homeRequestId = 0 this.ensureKeyboardSafe() this.loadHomeData() }, + /** + * `onShow` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ onShow() { this.ensureKeyboardSafe() this.syncUserState() + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (this.data.initialized && this.data.isLoggedIn) { this.loadUserProfile() } }, + /** + * `onHide` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ onHide() { resetKeyboardSafe(this) detachKeyboardSafe(this) }, + /** + * `onUnload` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ onUnload() { resetKeyboardSafe(this) detachKeyboardSafe(this) @@ -68,13 +93,25 @@ Page({ wx.stopPullDownRefresh() }, + /** + * `onReachBottom` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ onReachBottom() { + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!this.data.hasMore || this.data.loadingMore) { return } this.loadPopularProducts(false) }, + /** + * `ensureKeyboardSafe` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ ensureKeyboardSafe() { attachKeyboardSafe(this, { cursorSpacing: 96, @@ -82,6 +119,10 @@ Page({ }) }, + /** + * `syncUserState` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ syncUserState() { const app = getApp() const userInfo = auth.getStoredUserInfo() @@ -89,6 +130,10 @@ Page({ const navTitle = userInfo && String(userInfo.shopName || '').trim() ? String(userInfo.shopName).trim() : '游客模式' + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (app) { app.globalData.userInfo = userInfo app.globalData.isLoggedIn = isLoggedIn @@ -118,6 +163,24 @@ Page({ } catch (error) {} }, + async loadAnnouncements() { + if (!auth.isLoggedIn()) { + this.setData({ announcements: [] }) + return + } + try { + const list = await userApi.listMyAnnouncements() + this.setData({ + announcements: Array.isArray(list) ? list.map(item => ({ + ...item, + displayText: `${item.publisherName || '平台'}:${item.content || ''}` + })) : [] + }) + } catch (error) { + this.setData({ announcements: [] }) + } + }, + async loadHomeData() { const requestId = ++this.homeRequestId this.setData({ loading: true }) @@ -126,11 +189,16 @@ Page({ try { await Promise.all([ this.loadUserProfile(), + this.loadAnnouncements(), this.loadBannerImages(requestId), this.loadFeaturedProducts(requestId), this.loadPopularProducts(true, requestId) ]) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (requestId === this.homeRequestId) { this.setData({ initialized: true @@ -142,6 +210,10 @@ Page({ icon: 'none' }) } finally { + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (requestId === this.homeRequestId) { this.setData({ loading: false }) } @@ -166,6 +238,10 @@ Page({ return resolved.filter(item => item.imageUrl) }) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (requestId === this.homeRequestId) { this.setData({ bannerImages: Array.isArray(banners) ? banners : [] @@ -183,6 +259,10 @@ Page({ return buildProductCards(result && result.list ? result.list : []) }) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (requestId === this.homeRequestId) { this.setData({ featuredItems: Array.isArray(items) ? items : [] @@ -203,6 +283,10 @@ Page({ tag: '热门' }) const cards = await buildProductCards(result && result.list ? result.list : []) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (currentRequestId !== this.homeRequestId) { return } @@ -215,6 +299,10 @@ Page({ hasMore: mergedItems.length < total }) } catch (error) { + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (currentRequestId !== this.homeRequestId) { return } @@ -223,6 +311,10 @@ Page({ icon: 'none' }) } finally { + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (currentRequestId === this.homeRequestId) { this.setData({ loadingMore: false @@ -231,20 +323,36 @@ Page({ } }, + /** + * `handleSearchInput` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleSearchInput(event) { this.setData({ searchKeyword: event.detail.value }) }, + /** + * `handleSearchFocus` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleSearchFocus(event) { handleKeyboardFocus(this, event) }, + /** + * `handleSearchBlur` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleSearchBlur() { handleKeyboardBlur(this) }, + /** + * `handleSearchConfirm` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleSearchConfirm() { resetKeyboardSafe(this) navigation.openProducts({ @@ -252,8 +360,16 @@ Page({ }) }, + /** + * `handleBannerTap` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleBannerTap(event) { const shopId = event.currentTarget.dataset.shopId + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!shopId) { return } @@ -264,7 +380,15 @@ Page({ }) }, + /** + * `handleProfileTap` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleProfileTap() { + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (this.data.isLoggedIn) { navigation.switchTab('/pages/profile/index') return @@ -273,8 +397,16 @@ Page({ navigation.openAuth() }, + /** + * `handleProductSelect` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleProductSelect(event) { const product = event.detail || {} + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!product.id) { return } @@ -284,12 +416,20 @@ Page({ }) }, + /** + * `handleSeeAllFeatured` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleSeeAllFeatured() { navigation.openProducts({ tag: '精选' }) }, + /** + * `handleSeeAllPopular` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleSeeAllPopular() { navigation.openProducts({ tag: '热门' diff --git a/WeChatProgram/pages/home/index.wxml b/WeChatProgram/pages/home/index.wxml index 299a63a8..209bca94 100644 --- a/WeChatProgram/pages/home/index.wxml +++ b/WeChatProgram/pages/home/index.wxml @@ -32,6 +32,12 @@ 搜索 + + + {{item.displayText}} + + + 门店橱窗 diff --git a/WeChatProgram/pages/home/index.wxss b/WeChatProgram/pages/home/index.wxss index a3d37fd9..0f72d443 100644 --- a/WeChatProgram/pages/home/index.wxss +++ b/WeChatProgram/pages/home/index.wxss @@ -94,6 +94,26 @@ background: rgba(255, 255, 255, 0.9); } +.announcement-strip { + height: 58rpx; + margin-top: 18rpx; + border-radius: 16rpx; + background: #fff7ed; + border: 1rpx solid #fed7aa; + overflow: hidden; +} + +.announcement-item { + height: 58rpx; + line-height: 58rpx; + padding: 0 22rpx; + font-size: 24rpx; + color: #7c2d12; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; +} + .banner-badge { display: inline-flex; align-items: center; diff --git a/WeChatProgram/pages/index/index.js b/WeChatProgram/pages/index/index.js index b2f7b47e..aede9054 100644 --- a/WeChatProgram/pages/index/index.js +++ b/WeChatProgram/pages/index/index.js @@ -1,10 +1,18 @@ const auth = require('../../utils/auth') +/** + * index page logic. + * Call guide: page data drives the WXML template, and each method is called by user events or lifecycle callbacks. + */ Page({ data: { navTitle: '游客模式' }, + /** + * `onLoad` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ onLoad() { this.syncNavTitle() wx.switchTab({ @@ -12,10 +20,18 @@ Page({ }) }, + /** + * `onShow` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ onShow() { this.syncNavTitle() }, + /** + * `syncNavTitle` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ syncNavTitle() { const userInfo = auth.getStoredUserInfo() const navTitle = userInfo && String(userInfo.shopName || '').trim() diff --git a/WeChatProgram/pages/notifications/index.js b/WeChatProgram/pages/notifications/index.js new file mode 100644 index 00000000..1e722332 --- /dev/null +++ b/WeChatProgram/pages/notifications/index.js @@ -0,0 +1,117 @@ +const userApi = require('../../api/user') +const navigation = require('../../utils/navigation') + +/** + * notifications page logic. + * Call guide: page data drives the WXML template, and each method is called by user events or lifecycle callbacks. + */ +Page({ + data: { + loading: false, + messages: [], + unreadCount: 0, + detailVisible: false, + currentMessage: null + }, + + /** + * `onShow` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ + onShow() { + this.loadMessages() + }, + + async loadMessages() { + if (!navigation.ensureLogin('查看消息通知')) { + return + } + this.setData({ loading: true }) + try { + const messages = await userApi.listMyMessages() + const list = Array.isArray(messages) ? messages : [] + this.setData({ + messages: list, + unreadCount: list.filter(item => item.readStatus !== 1).length + }) + } catch (error) { + wx.showToast({ + title: error.message || '消息加载失败', + icon: 'none' + }) + } finally { + this.setData({ loading: false }) + } + }, + + async handleOpenMessage(event) { + const id = event.currentTarget.dataset.id + const item = this.data.messages.find(message => String(message.id) === String(id)) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ + if (!item) { + return + } + this.setData({ + currentMessage: item, + detailVisible: true + }) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ + if (item.readStatus !== 1) { + try { + await userApi.markMessageRead(item.id) + await this.loadMessages() + } catch (error) { + wx.showToast({ + title: error.message || '标记已读失败', + icon: 'none' + }) + } + } + }, + + /** + * `handleCloseDetail` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ + handleCloseDetail() { + this.setData({ + detailVisible: false, + currentMessage: null + }) + }, + + /** + * `handlePreviewImage` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ + handlePreviewImage() { + const imageUrl = this.data.currentMessage && this.data.currentMessage.imageUrl + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ + if (!imageUrl) { + return + } + wx.previewImage({ + current: imageUrl, + urls: [imageUrl] + }) + }, + + noop() {}, + + /** + * `handleBack` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ + handleBack() { + navigation.goBack('/pages/profile/index') + } +}) diff --git a/WeChatProgram/pages/notifications/index.json b/WeChatProgram/pages/notifications/index.json new file mode 100644 index 00000000..3e9557e9 --- /dev/null +++ b/WeChatProgram/pages/notifications/index.json @@ -0,0 +1,6 @@ +{ + "navigationStyle": "custom", + "usingComponents": { + "navigation-bar": "/components/navigation-bar/navigation-bar" + } +} diff --git a/WeChatProgram/pages/notifications/index.wxml b/WeChatProgram/pages/notifications/index.wxml new file mode 100644 index 00000000..d6cb98e8 --- /dev/null +++ b/WeChatProgram/pages/notifications/index.wxml @@ -0,0 +1,50 @@ + + + + + 消息通知 + {{unreadCount}} 条未读消息 + + + + + + + {{item.title}} + {{item.publisherName || '系统消息'}} · {{item.publishTime || item.createTime}} + 含图片 + + > + + + + + 暂无消息 + + + + + + + {{currentMessage.title}} + {{currentMessage.publisherName || '系统消息'}} · {{currentMessage.publishTime || currentMessage.createTime}} + + + + {{currentMessage.content}} + + + + diff --git a/WeChatProgram/pages/notifications/index.wxss b/WeChatProgram/pages/notifications/index.wxss new file mode 100644 index 00000000..795b482e --- /dev/null +++ b/WeChatProgram/pages/notifications/index.wxss @@ -0,0 +1,152 @@ +.notifications-page { + min-height: 100vh; + padding: 176rpx 28rpx 40rpx; + background: #fff7f8; + box-sizing: border-box; +} + +.summary-card, +.message-item, +.empty-card { + border-radius: 18rpx; + background: #ffffff; + box-shadow: 0 16rpx 40rpx rgba(150, 82, 105, 0.08); +} + +.summary-card { + padding: 34rpx; + margin-bottom: 22rpx; +} + +.summary-title { + color: #2d2430; + font-size: 38rpx; + font-weight: 800; +} + +.summary-desc { + margin-top: 8rpx; + color: #927f88; + font-size: 26rpx; +} + +.message-list { + display: flex; + flex-direction: column; + gap: 18rpx; +} + +.message-item { + display: flex; + align-items: center; + gap: 18rpx; + padding: 28rpx; +} + +.message-dot { + width: 16rpx; + height: 16rpx; + border-radius: 50%; + background: #d7c9cf; +} + +.message-item.unread .message-dot { + background: #ff5c8a; +} + +.message-copy { + flex: 1; + min-width: 0; +} + +.message-title { + color: #2d2430; + font-size: 30rpx; + font-weight: 700; +} + +.message-meta { + margin-top: 8rpx; + color: #9b8d94; + font-size: 24rpx; +} + +.message-badge { + display: inline-block; + margin-top: 10rpx; + padding: 4rpx 16rpx; + border-radius: 999rpx; + background: #fff0f4; + color: #d74270; + font-size: 22rpx; +} + +.message-arrow { + color: #c3aab4; +} + +.empty-card { + padding: 60rpx; + color: #9b8d94; + text-align: center; +} + +.detail-mask { + position: fixed; + inset: 0; + z-index: 1000; + display: flex; + align-items: flex-end; + background: rgba(26, 18, 24, 0.45); +} + +.detail-panel { + width: 100%; + max-height: 82vh; + padding: 34rpx 30rpx 46rpx; + border-radius: 28rpx 28rpx 0 0; + background: #fff; + box-sizing: border-box; + overflow-y: auto; +} + +.detail-header { + display: flex; + gap: 20rpx; + align-items: flex-start; + justify-content: space-between; +} + +.detail-title { + color: #2d2430; + font-size: 34rpx; + font-weight: 800; +} + +.detail-meta { + margin-top: 8rpx; + color: #9b8d94; + font-size: 24rpx; +} + +.detail-close { + margin: 0; + border-radius: 999rpx; +} + +.detail-content { + margin-top: 28rpx; + color: #4b4048; + font-size: 28rpx; + line-height: 1.8; + white-space: pre-wrap; +} + +.detail-image { + width: 100%; + min-height: 320rpx; + max-height: 760rpx; + margin-top: 24rpx; + border-radius: 18rpx; + background: #fff7f8; +} diff --git a/WeChatProgram/pages/orders/index.js b/WeChatProgram/pages/orders/index.js index 344b0c14..3ae6ebb1 100644 --- a/WeChatProgram/pages/orders/index.js +++ b/WeChatProgram/pages/orders/index.js @@ -6,6 +6,10 @@ const { resolveLegacyImage } = require('../../utils/file') const { formatDateTime, formatPrice, getOrderStatusClass, getOrderStatusText } = require('../../utils/format') const { runWithLoading } = require('../../utils/loading') +/** + * orders page logic. + * Call guide: page data drives the WXML template, and each method is called by user events or lifecycle callbacks. + */ Page({ data: { loading: false, @@ -13,6 +17,10 @@ Page({ orders: [] }, + /** + * `onShow` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ onShow() { this.loadOrders() }, @@ -24,6 +32,10 @@ Page({ loading: isLoggedIn }) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!isLoggedIn) { this.setData({ orders: [], @@ -39,6 +51,7 @@ Page({ ...order, statusText: getOrderStatusText(order), statusClass: getOrderStatusClass(order), + shopNameText: order.shopName ? `所属店铺:${order.shopName}` : '', actualAmountText: `\u00a5${formatPrice(order.actualAmount)}`, items: await Promise.all((order.items || []).map(async item => ({ ...item, @@ -66,16 +79,28 @@ Page({ } }, + /** + * `handleOpenAuth` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleOpenAuth() { navigation.openAuth('/pages/orders/index') }, + /** + * `handleBack` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleBack() { navigation.goBack('/pages/profile/index') }, async handleCancelOrder(event) { const orderId = event.currentTarget.dataset.orderId + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!orderId) { return } @@ -90,6 +115,10 @@ Page({ }) }) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!confirmed) { return } diff --git a/WeChatProgram/pages/orders/index.wxml b/WeChatProgram/pages/orders/index.wxml index 8e8a3f40..c98ddb71 100644 --- a/WeChatProgram/pages/orders/index.wxml +++ b/WeChatProgram/pages/orders/index.wxml @@ -23,6 +23,7 @@ {{item.statusText}} + {{item.shopNameText}} diff --git a/WeChatProgram/pages/orders/index.wxss b/WeChatProgram/pages/orders/index.wxss index 4b9c630b..20e311a5 100644 --- a/WeChatProgram/pages/orders/index.wxss +++ b/WeChatProgram/pages/orders/index.wxss @@ -23,6 +23,13 @@ border-bottom: 2rpx solid #f3e7eb; } +.order-shop { + margin: 14rpx 0 0; + color: #8f6e7a; + font-size: 24rpx; + line-height: 1.5; +} + .order-head-copy { flex: 1; min-width: 0; diff --git a/WeChatProgram/pages/product-detail/index.js b/WeChatProgram/pages/product-detail/index.js index 2aab32ec..11647bf9 100644 --- a/WeChatProgram/pages/product-detail/index.js +++ b/WeChatProgram/pages/product-detail/index.js @@ -13,11 +13,19 @@ const { formatPrice, getProductTitle, splitCsv } = require('../../utils/format') const { runWithLoading } = require('../../utils/loading') function parseTimeRange(businessHours) { + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!businessHours) { return null } const matched = String(businessHours).replace(/\s+/g, '').match(/(\d{1,2}:\d{2}).*?(\d{1,2}:\d{2})/) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!matched) { return null } @@ -30,6 +38,10 @@ function parseTimeRange(businessHours) { function estimateEarliestBookable(businessHours) { const range = parseTimeRange(businessHours) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!range) { return businessHours || '以门店安排为准' } @@ -43,10 +55,18 @@ function estimateEarliestBookable(businessHours) { openTime.setHours(startParts[0], startParts[1], 0, 0) closeTime.setHours(endParts[0], endParts[1], 0, 0) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (next <= openTime) { return `今天 ${range.start}` } + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (next >= closeTime) { return `明天 ${range.start}` } @@ -58,6 +78,10 @@ function estimateEarliestBookable(businessHours) { return `${month}-${date} ${hour}:${minute}` } +/** + * product-detail page logic. + * Call guide: page data drives the WXML template, and each method is called by user events or lifecycle callbacks. + */ Page({ data: { loading: true, @@ -75,6 +99,10 @@ Page({ earliestBookableText: '以门店安排为准' }, + /** + * `onLoad` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ onLoad(options) { this.setData({ productId: options && options.id ? options.id : '' @@ -90,6 +118,10 @@ Page({ async loadProductDetail() { const productId = this.data.productId + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!productId) { this.setData({ loading: false, @@ -148,6 +180,10 @@ Page({ async loadInteractionStatus() { const product = this.data.product + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!product || !product.id) { return } @@ -166,6 +202,10 @@ Page({ async loadComments() { const product = this.data.product + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!product || !product.id) { this.setData({ comments: [] }) return @@ -180,12 +220,24 @@ Page({ } }, + /** + * `handleBack` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleBack() { navigation.goBack('/pages/products/index') }, + /** + * `handlePreviewImage` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handlePreviewImage(event) { const current = event.currentTarget.dataset.url + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!current) { return } @@ -196,8 +248,16 @@ Page({ }) }, + /** + * `handleOpenShop` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleOpenShop() { const shopInfo = this.data.shopInfo + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!shopInfo || !shopInfo.id) { return } @@ -217,6 +277,10 @@ Page({ try { await actionGuard.run(this, `wishlist:toggle:${product.id}`, async () => { const nextFavorite = !this.data.isFavorite + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (this.data.isFavorite) { await runWithLoading(() => wishlistApi.removeFromWishlist(product.id)) product.collectCount = Math.max(0, Number(product.collectCount || 0) - 1) @@ -257,6 +321,10 @@ Page({ try { await actionGuard.run(this, `like:toggle:${product.id}`, async () => { const nextLiked = !this.data.isLiked + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (this.data.isLiked) { await runWithLoading(() => productLikeApi.unlikeProduct(product.id)) product.likeCount = Math.max(0, Number(product.likeCount || 0) - 1) @@ -346,12 +414,20 @@ Page({ } , + /** + * `handleCommentInput` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleCommentInput(event) { this.setData({ commentText: event.detail.value }) }, + /** + * `handleReply` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleReply(event) { const comment = event.currentTarget.dataset.comment this.setData({ @@ -365,6 +441,10 @@ Page({ if (!product || !product.id || !navigation.ensureLogin('发表评论')) { return } + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!content) { wx.showToast({ title: '请输入评论内容', icon: 'none' }) return diff --git a/WeChatProgram/pages/products/index.js b/WeChatProgram/pages/products/index.js index cadf1b1f..a56baf90 100644 --- a/WeChatProgram/pages/products/index.js +++ b/WeChatProgram/pages/products/index.js @@ -21,6 +21,10 @@ const ALL_CATEGORY = '\u5168\u90e8' const FILTER_BUSY_MESSAGE = '\u7b5b\u9009\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c' const CART_BUSY_MESSAGE = '\u8d2d\u7269\u8f66\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c' +/** + * products page logic. + * Call guide: page data drives the WXML template, and each method is called by user events or lifecycle callbacks. + */ Page({ data: Object.assign(createKeyboardSafeData({ cursorSpacing: 96 @@ -39,6 +43,10 @@ Page({ hasMore: false }), + /** + * `onLoad` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ onLoad(options) { this.filterRequestId = 0 this.ensureKeyboardSafe() @@ -51,6 +59,10 @@ Page({ const pendingFilter = app && app.globalData ? app.globalData.pendingProductFilter : null if (this.data.initialized && pendingFilter && (pendingFilter.keyword || pendingFilter.tag)) { + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (app && app.globalData) { app.globalData.pendingProductFilter = null } @@ -58,16 +70,28 @@ Page({ return } + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (this.data.initialized) { await this.syncProductCartState() } }, + /** + * `onHide` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ onHide() { resetKeyboardSafe(this) detachKeyboardSafe(this) }, + /** + * `onUnload` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ onUnload() { resetKeyboardSafe(this) detachKeyboardSafe(this) @@ -78,13 +102,25 @@ Page({ wx.stopPullDownRefresh() }, + /** + * `onReachBottom` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ onReachBottom() { + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!this.data.hasMore || this.data.loadingMore) { return } this.loadProducts(false) }, + /** + * `ensureKeyboardSafe` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ ensureKeyboardSafe() { attachKeyboardSafe(this, { cursorSpacing: 96, @@ -127,6 +163,10 @@ Page({ const app = getApp() const pendingFilter = app && app.globalData ? app.globalData.pendingProductFilter : null if (pendingFilter && (pendingFilter.keyword || pendingFilter.tag)) { + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (app && app.globalData) { app.globalData.pendingProductFilter = null } @@ -169,6 +209,10 @@ Page({ }) const cards = await buildProductCards(result && result.list ? result.list : []) const displayCards = await this.attachCartState(cards) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (requestId !== this.filterRequestId) { return } @@ -183,9 +227,17 @@ Page({ filterSummaryText: this.buildFilterSummary(keyword, tag, total) }) } catch (error) { + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (requestId !== this.filterRequestId) { return } + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (reset) { this.setData({ products: [], @@ -199,6 +251,10 @@ Page({ icon: 'none' }) } finally { + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (requestId === this.filterRequestId) { this.setData({ loading: false, @@ -208,11 +264,23 @@ Page({ } }, + /** + * `buildFilterSummary` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ buildFilterSummary(keyword, tag, total) { const chips = [] + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (tag) { chips.push(tag) } + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (keyword) { chips.push(`\u641c\u7d22\uff1a${keyword}`) } @@ -220,6 +288,10 @@ Page({ return chips.join(' \u00b7 ') }, + /** + * `normalizeId` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ normalizeId(value) { return value === undefined || value === null ? '' : String(value) }, @@ -250,6 +322,10 @@ Page({ return this.markCardsInCart(cards, idSet) }, + /** + * `markCardsInCart` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ markCardsInCart(cards, idSet) { const productIdSet = idSet || new Set() return (Array.isArray(cards) ? cards : []).map(item => ({ @@ -265,8 +341,16 @@ Page({ }) }, + /** + * `markProductInCart` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ markProductInCart(productId) { const normalizedId = this.normalizeId(productId) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!normalizedId) { return } @@ -286,16 +370,28 @@ Page({ }) }, + /** + * `handleSearchInput` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleSearchInput(event) { this.setData({ searchKeyword: event.detail.value }) }, + /** + * `handleSearchFocus` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleSearchFocus(event) { handleKeyboardFocus(this, event) }, + /** + * `handleSearchBlur` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleSearchBlur() { handleKeyboardBlur(this) }, @@ -372,8 +468,16 @@ Page({ } }, + /** + * `handleProductSelect` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleProductSelect(event) { const product = event.detail || {} + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!product.id) { return } @@ -386,6 +490,10 @@ Page({ async handleQuickAdd(event) { const product = event.detail || {} const productId = this.normalizeId(product.id) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!productId) { return } diff --git a/WeChatProgram/pages/profile/index.js b/WeChatProgram/pages/profile/index.js index c367b9a9..0abfdeeb 100644 --- a/WeChatProgram/pages/profile/index.js +++ b/WeChatProgram/pages/profile/index.js @@ -9,6 +9,10 @@ const navigation = require('../../utils/navigation') const { DEFAULT_AVATAR } = require('../../utils/config') const { runWithLoading } = require('../../utils/loading') +/** + * profile page logic. + * Call guide: page data drives the WXML template, and each method is called by user events or lifecycle callbacks. + */ Page({ data: { isLoggedIn: false, @@ -18,9 +22,14 @@ Page({ orderCount: 0, couponCount: 0, wishlistCount: 0, + unreadMessageCount: 0, defaultAvatar: DEFAULT_AVATAR }, + /** + * `onShow` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ onShow() { this.loadProfile() }, @@ -34,6 +43,10 @@ Page({ loading: isLoggedIn }) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!isLoggedIn) { this.setData({ userInfo: null, @@ -46,11 +59,12 @@ Page({ } try { - const [userInfo, orders, coupons, wishlist] = await Promise.all([ + const [userInfo, orders, coupons, wishlist, unreadMessages] = await Promise.all([ userApi.getUserInfo(), orderApi.getOrderList(), couponApi.listUserCoupons(), - wishlistApi.getWishlist() + wishlistApi.getWishlist(), + userApi.getMyUnreadMessageCount() ]) getApp().refreshUserInfo(userInfo) @@ -58,8 +72,10 @@ Page({ userInfo, orderCount: Array.isArray(orders) ? orders.length : 0, couponCount: Array.isArray(coupons) ? coupons.length : 0, - wishlistCount: Array.isArray(wishlist) ? wishlist.length : 0 + wishlistCount: Array.isArray(wishlist) ? wishlist.length : 0, + unreadMessageCount: Number((unreadMessages && unreadMessages.unreadCount) || 0) }) + await this.checkPopupMessages() } catch (error) { wx.showToast({ title: error.message || '\u4e2a\u4eba\u4e2d\u5fc3\u52a0\u8f7d\u5931\u8d25', @@ -72,11 +88,23 @@ Page({ } }, + /** + * `handleOpenAuth` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleOpenAuth() { navigation.openAuth('/pages/profile/index') }, + /** + * `handleOpenSettings` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleOpenSettings() { + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!this.data.isLoggedIn) { this.handleOpenAuth() return @@ -84,6 +112,10 @@ Page({ navigation.navigate('/pages/settings/index') }, + /** + * `handleOpenOrders` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleOpenOrders() { if (!navigation.ensureLogin('\u67e5\u770b\u8ba2\u5355')) { return @@ -91,6 +123,10 @@ Page({ navigation.navigate('/pages/orders/index') }, + /** + * `handleOpenWishlist` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleOpenWishlist() { if (!navigation.ensureLogin('\u67e5\u770b\u6536\u85cf')) { return @@ -98,6 +134,10 @@ Page({ navigation.navigate('/pages/wishlist/index') }, + /** + * `handleOpenCoupons` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleOpenCoupons() { if (!navigation.ensureLogin('\u67e5\u770b\u4f18\u60e0\u5238')) { return @@ -105,6 +145,62 @@ Page({ navigation.navigate('/pages/coupons/index') }, + /** + * `handleOpenVipCenter` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ + handleOpenVipCenter() { + if (!navigation.ensureLogin('查看 VIP 中心')) { + return + } + navigation.navigate('/pages/vip-center/index') + }, + + /** + * `handleOpenNotifications` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ + handleOpenNotifications() { + if (!navigation.ensureLogin('查看消息通知')) { + return + } + navigation.navigate('/pages/notifications/index') + }, + + async checkPopupMessages() { + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ + if (this._checkingPopupMessages) { + return + } + this._checkingPopupMessages = true + try { + const messages = await userApi.listMyPopupMessages() + /** + * `for` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ + for (const item of messages || []) { + await new Promise(resolve => { + wx.showModal({ + title: item.title || '消息通知', + content: item.content || '', + showCancel: false, + confirmText: '我知道了', + complete: resolve + }) + }) + await userApi.markMessagePopupShown(item.id) + } + } catch (error) { + console.error('加载待弹窗消息失败', error) + } finally { + this._checkingPopupMessages = false + } + }, + async handleSwitchShop() { if (!navigation.ensureLogin('\u5207\u6362\u95e8\u5e97')) { return @@ -114,6 +210,10 @@ Page({ const shopIds = userInfo && Array.isArray(userInfo.shopIds) ? userInfo.shopIds : [] const shopNames = userInfo && Array.isArray(userInfo.shopNames) ? userInfo.shopNames : [] + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!shopIds.length) { wx.showToast({ title: '\u5f53\u524d\u8d26\u53f7\u8fd8\u6ca1\u6709\u53ef\u7528\u95e8\u5e97', @@ -122,6 +222,10 @@ Page({ return } + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (shopIds.length === 1) { navigation.navigate('/pages/shop-detail/index', { id: shopIds[0], @@ -140,6 +244,10 @@ Page({ }) }) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (selection < 0 || selection >= shopIds.length) { return } @@ -168,6 +276,10 @@ Page({ }, async handleLogout() { + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!this.data.isLoggedIn) { this.handleOpenAuth() return @@ -183,6 +295,10 @@ Page({ }) }) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!confirmed) { return } @@ -209,10 +325,18 @@ Page({ async handleAvatarError() { const currentAvatar = this.data.userInfo && this.data.userInfo.avatar + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!currentAvatar) { return } + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (this._avatarReloadSource === currentAvatar) { this.setData({ 'userInfo.avatar': '' @@ -225,6 +349,10 @@ Page({ try { const userInfo = await userApi.getUserInfo() getApp().refreshUserInfo(userInfo) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!userInfo || !userInfo.avatar || userInfo.avatar === currentAvatar) { this.setData({ 'userInfo.avatar': '' diff --git a/WeChatProgram/pages/profile/index.wxml b/WeChatProgram/pages/profile/index.wxml index 9c7fd8ab..c702cad6 100644 --- a/WeChatProgram/pages/profile/index.wxml +++ b/WeChatProgram/pages/profile/index.wxml @@ -67,6 +67,15 @@ 我的优惠券 > + + VIP 中心 + > + + + 消息通知 + {{unreadMessageCount}} + > + 设置中心 > diff --git a/WeChatProgram/pages/profile/index.wxss b/WeChatProgram/pages/profile/index.wxss index 1489bc7f..2fa97750 100644 --- a/WeChatProgram/pages/profile/index.wxss +++ b/WeChatProgram/pages/profile/index.wxss @@ -161,6 +161,23 @@ color: #c3aab4; } +.menu-badge { + margin-left: auto; + min-width: 36rpx; + height: 36rpx; + padding: 0 10rpx; + border-radius: 18rpx; + background: #ff5c8a; + color: #ffffff; + font-size: 22rpx; + line-height: 36rpx; + text-align: center; +} + +.menu-badge + .menu-arrow { + margin-left: 16rpx; +} + .logout-item { color: #d5536f; font-weight: 700; diff --git a/WeChatProgram/pages/settings/index.js b/WeChatProgram/pages/settings/index.js index 4615e5f4..f0262081 100644 --- a/WeChatProgram/pages/settings/index.js +++ b/WeChatProgram/pages/settings/index.js @@ -18,6 +18,10 @@ const phoneRegex = /^1[3-9]\d{9}$/ const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@$!%*#?&]{8,}$/ const SETTINGS_DRAFT_KEY = 'user-settings' +/** + * settings page logic. + * Call guide: page data drives the WXML template, and each method is called by user events or lifecycle callbacks. + */ Page({ data: Object.assign(createKeyboardSafeData({ cursorSpacing: 108 @@ -53,15 +57,27 @@ Page({ } }), + /** + * `onLoad` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ onLoad() { this.ensureKeyboardSafe() }, + /** + * `onShow` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ onShow() { this.ensureKeyboardSafe() this.loadSettings() }, + /** + * `onHide` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ onHide() { resetKeyboardSafe(this) detachKeyboardSafe(this) @@ -69,6 +85,10 @@ Page({ clearDraftTimer(this) }, + /** + * `onUnload` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ onUnload() { resetKeyboardSafe(this) detachKeyboardSafe(this) @@ -76,6 +96,10 @@ Page({ clearDraftTimer(this) }, + /** + * `ensureKeyboardSafe` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ ensureKeyboardSafe() { attachKeyboardSafe(this, { cursorSpacing: 108, @@ -83,21 +107,41 @@ Page({ }) }, + /** + * `handleKeyboardFocus` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleKeyboardFocus(event) { handleKeyboardFocus(this, event) }, + /** + * `handleKeyboardBlur` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleKeyboardBlur() { handleKeyboardBlur(this) }, + /** + * `clearCountdown` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ clearCountdown() { + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (this.countdownTimer) { clearInterval(this.countdownTimer) this.countdownTimer = null } }, + /** + * `resetSecurityForms` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ resetSecurityForms() { this.setData({ bindPhoneForm: { @@ -116,8 +160,16 @@ Page({ }) }, + /** + * `restoreDraftValues` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ restoreDraftValues() { const draft = getDraftValue(SETTINGS_DRAFT_KEY, null) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!draft || typeof draft !== 'object') { return } @@ -131,6 +183,10 @@ Page({ }) }, + /** + * `scheduleSettingsDraft` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ scheduleSettingsDraft() { scheduleDraftSave(this, SETTINGS_DRAFT_KEY, () => ({ activeSecurityPanel: this.data.activeSecurityPanel, @@ -147,6 +203,10 @@ Page({ })) }, + /** + * `startCountdown` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ startCountdown() { this.clearCountdown() this.setData({ @@ -155,6 +215,10 @@ Page({ this.countdownTimer = setInterval(() => { const next = this.data.countdown - 1 + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (next <= 0) { this.clearCountdown() this.setData({ @@ -177,6 +241,10 @@ Page({ loading: isLoggedIn }) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!isLoggedIn) { this.clearCountdown() this.setData({ @@ -209,14 +277,26 @@ Page({ } }, + /** + * `handleBack` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleBack() { navigation.goBack('/pages/profile/index') }, + /** + * `handleOpenAuth` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleOpenAuth() { navigation.openAuth('/pages/settings/index') }, + /** + * `handleFormInput` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleFormInput(event) { const field = event.currentTarget.dataset.field this.setData({ @@ -225,26 +305,46 @@ Page({ this.scheduleSettingsDraft() }, + /** + * `handleBindPhoneInput` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleBindPhoneInput(event) { const field = event.currentTarget.dataset.field this.setData({ [`bindPhoneForm.${field}`]: event.detail.value }) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (field === 'phone') { this.scheduleSettingsDraft() } }, + /** + * `handleChangePhoneInput` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleChangePhoneInput(event) { const field = event.currentTarget.dataset.field this.setData({ [`changePhoneForm.${field}`]: event.detail.value }) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (field === 'newPhone') { this.scheduleSettingsDraft() } }, + /** + * `handlePasswordInput` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handlePasswordInput(event) { const field = event.currentTarget.dataset.field this.setData({ @@ -252,6 +352,10 @@ Page({ }) }, + /** + * `handleToggleSecurityPanel` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleToggleSecurityPanel(event) { const panel = event.currentTarget.dataset.panel const nextPanel = this.data.activeSecurityPanel === panel ? '' : panel @@ -265,6 +369,10 @@ Page({ this.scheduleSettingsDraft() }, + /** + * `handleCloseSecurityPanel` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleCloseSecurityPanel() { resetKeyboardSafe(this) this.resetSecurityForms() @@ -312,7 +420,15 @@ Page({ } }, + /** + * `handleChooseAvatar` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleChooseAvatar() { + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (this.data.uploadingAvatar) { return } @@ -323,6 +439,10 @@ Page({ sourceType: ['album', 'camera'], success: async res => { const filePath = Array.isArray(res.tempFilePaths) ? res.tempFilePaths[0] : '' + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!filePath) { return } @@ -353,6 +473,10 @@ Page({ }, async handleDeleteAvatar() { + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!this.data.userInfo || !this.data.userInfo.avatar) { return } @@ -365,6 +489,10 @@ Page({ }) }) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!confirmed) { return } @@ -395,6 +523,10 @@ Page({ const shopIds = userInfo && Array.isArray(userInfo.shopIds) ? userInfo.shopIds : [] const shopNames = userInfo && Array.isArray(userInfo.shopNames) ? userInfo.shopNames : [] + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!shopIds.length) { wx.showToast({ title: '当前账号还没有可用门店', @@ -403,6 +535,10 @@ Page({ return } + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (shopIds.length === 1) { navigation.navigate('/pages/shop-detail/index', { id: shopIds[0], @@ -419,6 +555,10 @@ Page({ }) }) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (selection < 0 || selection >= shopIds.length) { return } @@ -442,6 +582,10 @@ Page({ }, async handleSendBindPhoneCode() { + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (this.data.countdown > 0) { return } @@ -456,7 +600,10 @@ Page({ } try { - await runWithLoading(() => userApi.sendVerificationCode({ phone })) + await runWithLoading(() => userApi.sendVerificationCode({ + phone, + sceneCode: 'USER_BIND_PHONE_SMS_CODE' + })) wx.showToast({ title: '验证码已发送', icon: 'none' @@ -482,6 +629,10 @@ Page({ return } + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!verificationCode) { wx.showToast({ title: '请输入验证码', @@ -519,6 +670,10 @@ Page({ }, async handleSendChangePhoneCode() { + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (this.data.countdown > 0) { return } @@ -533,7 +688,10 @@ Page({ } try { - await runWithLoading(() => userApi.sendVerificationCode({ phone: newPhone })) + await runWithLoading(() => userApi.sendVerificationCode({ + phone: newPhone, + sceneCode: 'USER_CHANGE_PHONE_SMS_CODE' + })) wx.showToast({ title: '验证码已发送', icon: 'none' @@ -553,6 +711,10 @@ Page({ const newPhone = String(this.data.changePhoneForm.newPhone || '').trim() const verificationCode = String(this.data.changePhoneForm.verificationCode || '').trim() + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!oldPhone) { wx.showToast({ title: '请先绑定手机号', @@ -569,6 +731,10 @@ Page({ return } + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!verificationCode) { wx.showToast({ title: '请输入验证码', @@ -607,12 +773,20 @@ Page({ }, async handleSendPasswordCode() { + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (this.data.countdown > 0) { return } const userInfo = this.data.userInfo || {} const phone = String(userInfo.phone || '').trim() + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!phone) { wx.showToast({ title: '请先绑定手机号', @@ -622,7 +796,10 @@ Page({ } try { - await runWithLoading(() => authApi.sendVerificationCode({ phone })) + await runWithLoading(() => authApi.sendVerificationCode({ + phone, + sceneCode: 'USER_CHANGE_PASSWORD_SMS_CODE' + })) wx.showToast({ title: '验证码已发送', icon: 'none' @@ -642,6 +819,10 @@ Page({ const confirmPassword = String(this.data.passwordForm.confirmPassword || '') const userInfo = this.data.userInfo || {} + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!userInfo.phone) { wx.showToast({ title: '请先绑定手机号', @@ -650,6 +831,10 @@ Page({ return } + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!verificationCode) { wx.showToast({ title: '请输入验证码', @@ -666,6 +851,10 @@ Page({ return } + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (password !== confirmPassword) { wx.showToast({ title: '两次输入的密码不一致', @@ -704,6 +893,10 @@ Page({ }, async handleDeactivateAccount() { + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (this.data.deactivating) { return } @@ -717,6 +910,10 @@ Page({ }) }) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!confirmed) { return } @@ -757,6 +954,10 @@ Page({ }) }) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!confirmed) { return } @@ -778,10 +979,18 @@ Page({ async handleAvatarError() { const currentAvatar = this.data.userInfo && this.data.userInfo.avatar + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!currentAvatar) { return } + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (this._avatarReloadSource === currentAvatar) { this.setData({ 'userInfo.avatar': '' @@ -794,6 +1003,10 @@ Page({ try { const userInfo = await userApi.getUserInfo() getApp().refreshUserInfo(userInfo) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!userInfo || !userInfo.avatar || userInfo.avatar === currentAvatar) { this.setData({ 'userInfo.avatar': '' diff --git a/WeChatProgram/pages/shop-detail/index.js b/WeChatProgram/pages/shop-detail/index.js index 3fdb1398..0f9b572e 100644 --- a/WeChatProgram/pages/shop-detail/index.js +++ b/WeChatProgram/pages/shop-detail/index.js @@ -3,6 +3,10 @@ const navigation = require('../../utils/navigation') const { resolveImageList } = require('../../utils/file') const { DEFAULT_SHOP_IMAGE } = require('../../utils/config') +/** + * shop-detail page logic. + * Call guide: page data drives the WXML template, and each method is called by user events or lifecycle callbacks. + */ Page({ data: { loading: true, @@ -10,9 +14,14 @@ Page({ shopId: '', returnTo: '/pages/home/index', shopInfo: null, + distanceText: '', shopImages: [] }, + /** + * `onLoad` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ onLoad(options) { this.setData({ shopId: options && options.id ? options.id : '', @@ -27,6 +36,10 @@ Page({ }, async loadShopDetail() { + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!this.data.shopId) { this.setData({ loading: false, @@ -45,8 +58,10 @@ Page({ const shopImages = await resolveImageList(shopInfo.imageFileIds || shopInfo.coverImageFileId, DEFAULT_SHOP_IMAGE) this.setData({ shopInfo, - shopImages + shopImages, + distanceText: '' }) + this.loadCurrentDistance() } catch (error) { this.setData({ loadError: error.message || '门店详情加载失败' @@ -58,12 +73,24 @@ Page({ } }, + /** + * `handleBack` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleBack() { navigation.goBack(this.data.returnTo || '/pages/home/index') }, + /** + * `handlePreviewImage` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handlePreviewImage(event) { const url = event.currentTarget.dataset.url + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!url) { return } @@ -74,8 +101,16 @@ Page({ }) }, + /** + * `handleCopyName` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleCopyName() { const shopInfo = this.data.shopInfo + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!shopInfo || !shopInfo.shopName) { return } @@ -85,8 +120,16 @@ Page({ }) }, + /** + * `handleCopyAddress` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleCopyAddress() { const shopInfo = this.data.shopInfo + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!shopInfo || !shopInfo.address) { return } @@ -94,5 +137,73 @@ Page({ wx.setClipboardData({ data: shopInfo.address }) + }, + + handleOpenLocation() { + const shopInfo = this.data.shopInfo + if (!shopInfo || !shopInfo.latitude || !shopInfo.longitude) { + wx.showToast({ + title: '店铺暂未设置地图位置', + icon: 'none' + }) + return + } + + wx.openLocation({ + latitude: Number(shopInfo.latitude), + longitude: Number(shopInfo.longitude), + name: shopInfo.shopName || '店铺位置', + address: shopInfo.address || '', + scale: 16 + }) + }, + + handleOpenAmapNavigation() { + const shopInfo = this.data.shopInfo + const amapUrl = shopInfo && shopInfo.navigationUrls && shopInfo.navigationUrls.AMAP + if (!amapUrl) { + wx.showToast({ + title: '店铺暂未设置地图位置', + icon: 'none' + }) + return + } + wx.setClipboardData({ + data: amapUrl, + success: () => { + wx.showToast({ + title: '高德导航链接已复制', + icon: 'none' + }) + } + }) + }, + + loadCurrentDistance() { + const shopInfo = this.data.shopInfo + if (!shopInfo || !shopInfo.latitude || !shopInfo.longitude || typeof wx.getLocation !== 'function') { + return + } + wx.getLocation({ + type: 'gcj02', + success: (res) => { + this.setData({ + distanceText: this.formatDistance(res.latitude, res.longitude, Number(shopInfo.latitude), Number(shopInfo.longitude)) + }) + } + }) + }, + + formatDistance(currentLat, currentLng, shopLat, shopLng) { + if (![currentLat, currentLng, shopLat, shopLng].every(Number.isFinite)) { + return '' + } + const toRad = value => value * Math.PI / 180 + const earthRadius = 6371000 + const dLat = toRad(shopLat - currentLat) + const dLng = toRad(shopLng - currentLng) + const a = Math.sin(dLat / 2) ** 2 + Math.cos(toRad(currentLat)) * Math.cos(toRad(shopLat)) * Math.sin(dLng / 2) ** 2 + const meters = 2 * earthRadius * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)) + return meters >= 1000 ? `距你约 ${(meters / 1000).toFixed(1)} km` : `距你约 ${Math.round(meters)} m` } }) diff --git a/WeChatProgram/pages/shop-detail/index.wxml b/WeChatProgram/pages/shop-detail/index.wxml index 9d49dd29..a4a5e1ee 100644 --- a/WeChatProgram/pages/shop-detail/index.wxml +++ b/WeChatProgram/pages/shop-detail/index.wxml @@ -19,6 +19,7 @@ 门店详情 {{shopInfo.shopName}} {{shopInfo.address || '门店地址待补充'}} + {{distanceText}} @@ -47,6 +48,11 @@ 复制门店名 复制地址 + + + 查看地图位置 + 复制高德导航链接 + diff --git a/WeChatProgram/pages/shop-detail/index.wxss b/WeChatProgram/pages/shop-detail/index.wxss index 56baa0b3..257a55a0 100644 --- a/WeChatProgram/pages/shop-detail/index.wxss +++ b/WeChatProgram/pages/shop-detail/index.wxss @@ -46,6 +46,13 @@ line-height: 1.7; } +.shop-distance { + margin-top: 8rpx; + color: #8f6e7a; + font-size: 24rpx; + line-height: 1.5; +} + .shop-summary { margin-top: 24rpx; } @@ -77,6 +84,17 @@ margin-top: 26rpx; } +.map-row { + display: grid; + grid-template-columns: 1fr; + gap: 16rpx; + margin-top: 18rpx; +} + +.map-btn { + width: 100%; +} + .gallery-list { display: flex; flex-wrap: wrap; diff --git a/WeChatProgram/pages/vip-center/index.js b/WeChatProgram/pages/vip-center/index.js new file mode 100644 index 00000000..2e268344 --- /dev/null +++ b/WeChatProgram/pages/vip-center/index.js @@ -0,0 +1,114 @@ +const userApi = require('../../api/user') +const navigation = require('../../utils/navigation') + +function money(value) { + return Number(value || 0).toFixed(2) +} + +function formatTime(value) { + return value ? String(value).replace('T', ' ').slice(0, 16) : '--' +} + +function sceneText(scene) { + const map = { + MANUAL_RECHARGE: '手工充值', + MANUAL_DEDUCT: '手工扣减', + ORDER_PAY: '订单消费', + ORDER_REFUND: '订单退款', + RECHARGE: '充值', + CONSUME: '消费' + } + return map[scene] || scene || '余额变动' +} + +/** + * vip-center page logic. + * Call guide: page data drives the WXML template, and each method is called by user events or lifecycle callbacks. + */ +Page({ + data: { + asset: { + vipLevel: '普通', + balanceText: '0.00', + totalRechargeText: '0.00', + lastRechargeText: '--', + vipStartText: '--', + manualOverride: false + }, + history: [], + rechargePlans: [], + rechargePanelVisible: false + }, + + /** + * `onShow` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ + onShow() { + if (!navigation.ensureLogin('查看 VIP 中心')) { + return + } + this.loadData() + }, + + async loadData() { + try { + const [asset, history, plans] = await Promise.all([ + userApi.getMyAsset(), + userApi.getMyBalanceHistory(), + userApi.listMyVipRechargePlans().catch(() => []) + ]) + this.setData({ + asset: { + ...asset, + balanceText: money(asset && asset.balance), + totalRechargeText: money(asset && asset.totalRechargeAmount), + lastRechargeText: formatTime(asset && asset.lastRechargeTime), + vipStartText: formatTime(asset && asset.vipStartTime) + }, + history: (Array.isArray(history) ? history : []).map(item => { + const amountNumber = Number(item.amount || 0) + return { + ...item, + amountNumber, + amountText: `${amountNumber > 0 ? '+' : ''}¥${money(amountNumber)}`, + sceneText: sceneText(item.changeScene || item.type), + changeTimeText: formatTime(item.changeTime) + } + }), + rechargePlans: (Array.isArray(plans) ? plans : []).map(item => ({ + ...item, + amountText: `充 ${money(item.rechargeAmount)} 送 ${money(item.giftAmount)}` + })) + }) + } catch (error) { + wx.showToast({ + title: error.message || 'VIP 信息加载失败', + icon: 'none' + }) + } + }, + + /** + * `openRechargePanel` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ + openRechargePanel() { + this.setData({ rechargePanelVisible: true }) + }, + + /** + * `closeRechargePanel` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ + closeRechargePanel() { + this.setData({ rechargePanelVisible: false }) + }, + + /** + * `noop` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ + noop() { + } +}) diff --git a/WeChatProgram/pages/vip-center/index.json b/WeChatProgram/pages/vip-center/index.json new file mode 100644 index 00000000..8632c9b0 --- /dev/null +++ b/WeChatProgram/pages/vip-center/index.json @@ -0,0 +1,5 @@ +{ + "usingComponents": { + "navigation-bar": "/components/navigation-bar/navigation-bar" + } +} diff --git a/WeChatProgram/pages/vip-center/index.wxml b/WeChatProgram/pages/vip-center/index.wxml new file mode 100644 index 00000000..1d8189d6 --- /dev/null +++ b/WeChatProgram/pages/vip-center/index.wxml @@ -0,0 +1,61 @@ + + + + 会员等级 + {{asset.vipLevel || '普通'}} + {{asset.benefitInfo || '暂无额外权益说明'}} + + + + + 余额 + ¥{{asset.balanceText}} + + + 累计充值 + ¥{{asset.totalRechargeText}} + + + + 去充值 / 查看充值说明 + + + 会员信息 + 最近充值{{asset.lastRechargeText}} + 生效时间{{asset.vipStartText}} + 等级来源{{asset.manualOverride ? '后台指定' : '自动计算'}} + + + + 余额变动 + + + + {{item.sceneText}} + {{item.changeTimeText}} + {{item.remark}} + + {{item.amountText}} + + + 暂无余额变动 + + + + + 充值档位展示 + + + + {{item.title}} + {{item.vipLevel}} + + {{item.amountText}} + {{item.description || '该档位仅展示,暂不发起支付。'}} + + + 暂无可展示充值档位 + 关闭 + + + diff --git a/WeChatProgram/pages/vip-center/index.wxss b/WeChatProgram/pages/vip-center/index.wxss new file mode 100644 index 00000000..591d049b --- /dev/null +++ b/WeChatProgram/pages/vip-center/index.wxss @@ -0,0 +1,162 @@ +.vip-page { + min-height: 100vh; + padding: 24rpx; + background: #f7f4f1; + box-sizing: border-box; +} + +.vip-hero { + display: flex; + flex-direction: column; + gap: 10rpx; + padding: 36rpx; + border-radius: 16rpx; + color: #fff; + background: linear-gradient(135deg, #2b2522, #8a704e); +} + +.vip-kicker, .vip-benefit { + color: rgba(255,255,255,.76); + font-size: 24rpx; +} + +.vip-level { + font-size: 56rpx; + font-weight: 700; +} + +.metric-grid { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 16rpx; + margin-top: 20rpx; +} + +.metric, .section { + padding: 28rpx; + border-radius: 16rpx; + background: #fff; +} + +.metric { + display: flex; + flex-direction: column; + gap: 10rpx; + color: #7f7470; +} + +.metric-value { + color: #2d2927; + font-size: 36rpx; + font-weight: 700; +} + +.section { + margin-top: 20rpx; +} + +.section-title { + margin-bottom: 20rpx; + color: #2d2927; + font-size: 32rpx; + font-weight: 700; +} + +.info-row, .history-row { + display: flex; + justify-content: space-between; + gap: 20rpx; + padding: 18rpx 0; + border-bottom: 1rpx solid #f0ece8; +} + +.info-row:last-child, .history-row:last-child { + border-bottom: 0; +} + +.history-title, .history-time, .history-remark { + display: block; +} + +.history-title { + color: #2d2927; + font-weight: 600; +} + +.history-time, .history-remark, .empty { + margin-top: 6rpx; + color: #9a918d; + font-size: 24rpx; +} + +.history-amount { + color: #2d2927; + font-weight: 700; + white-space: nowrap; +} + +.history-amount.income { + color: #0f8f63; +} + +.recharge-entry { + margin-top: 20rpx; + padding: 20rpx; + border-radius: 16rpx; + background: #fff7ed; + color: #9a5b2e; + font-weight: 700; + text-align: center; +} + +.recharge-mask { + position: fixed; + inset: 0; + background: rgba(0, 0, 0, 0.4); + z-index: 30; + display: flex; + align-items: flex-end; +} + +.recharge-panel { + width: 100%; + max-height: 75vh; + overflow: auto; + border-radius: 24rpx 24rpx 0 0; + background: #fff; + padding: 24rpx; +} + +.recharge-plan { + padding: 18rpx 0; + border-bottom: 1rpx solid #f0ece8; +} + +.plan-head { + display: flex; + justify-content: space-between; + gap: 18rpx; + color: #2d2927; + font-weight: 700; +} + +.plan-amount { + display: block; + margin-top: 10rpx; + color: #9a5b2e; +} + +.plan-desc { + display: block; + margin-top: 6rpx; + color: #9a918d; + font-size: 24rpx; +} + +.recharge-close { + margin-top: 18rpx; + padding: 18rpx; + border-radius: 16rpx; + background: #f4f0eb; + text-align: center; +} diff --git a/WeChatProgram/pages/wishlist/index.js b/WeChatProgram/pages/wishlist/index.js index 18b7a546..ab9a56ff 100644 --- a/WeChatProgram/pages/wishlist/index.js +++ b/WeChatProgram/pages/wishlist/index.js @@ -6,6 +6,10 @@ const navigation = require('../../utils/navigation') const { buildProductCard } = require('../../utils/product') const { runWithLoading } = require('../../utils/loading') +/** + * wishlist page logic. + * Call guide: page data drives the WXML template, and each method is called by user events or lifecycle callbacks. + */ Page({ data: { loading: false, @@ -13,6 +17,10 @@ Page({ wishlist: [] }, + /** + * `onShow` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ onShow() { this.loadWishlist() }, @@ -24,6 +32,10 @@ Page({ loading: isLoggedIn }) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!isLoggedIn) { this.cartProductIdSet = new Set() this.setData({ @@ -63,6 +75,10 @@ Page({ } }, + /** + * `normalizeId` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ normalizeId(value) { return value === undefined || value === null ? '' : String(value) }, @@ -83,6 +99,10 @@ Page({ } }, + /** + * `markCardInCart` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ markCardInCart(card, idSet) { return { ...card, @@ -90,8 +110,16 @@ Page({ } }, + /** + * `markWishlistProductInCart` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ markWishlistProductInCart(productId) { const normalizedId = this.normalizeId(productId) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!normalizedId) { return } @@ -114,12 +142,24 @@ Page({ }) }, + /** + * `handleOpenAuth` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleOpenAuth() { navigation.openAuth('/pages/wishlist/index') }, + /** + * `handleProductSelect` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleProductSelect(event) { const product = event.detail || {} + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!product.id) { return } @@ -132,6 +172,10 @@ Page({ async handleQuickAdd(event) { const product = event.detail || {} const productId = this.normalizeId(product.id) + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!productId) { return } @@ -174,6 +218,10 @@ Page({ async handleRemove(event) { const productId = event.currentTarget.dataset.productId + /** + * `if` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ if (!productId) { return } @@ -198,6 +246,10 @@ Page({ } }, + /** + * `handleBack` page method. Use this from WXML event bindings or lifecycle hooks. + * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. + */ handleBack() { navigation.goBack('/pages/profile/index') } diff --git a/WeChatProgram/utils/product.js b/WeChatProgram/utils/product.js index 6a76ff20..124b9554 100644 --- a/WeChatProgram/utils/product.js +++ b/WeChatProgram/utils/product.js @@ -19,7 +19,8 @@ async function buildProductCard(product) { ...product, displayTitle: getProductTitle(product), priceText: `¥${formatPrice(product && product.price)}`, - metaText: (product && (product.approximateDuration || product.shopName)) || '支持预约', + metaText: (product && product.approximateDuration) || '支持预约', + shopNameText: product && product.shopName ? `所属店铺:${product.shopName}` : '', coverUrl: images[0], imageUrls: images, tagsPreview: getProductTags(product), diff --git a/WeChatProgram/utils/request.js b/WeChatProgram/utils/request.js index 6fc9b4ce..6d40b177 100644 --- a/WeChatProgram/utils/request.js +++ b/WeChatProgram/utils/request.js @@ -36,6 +36,7 @@ function isWhitelistedPath(url) { '/user/phone-login', '/user/wechat-mini/', '/user/reset-password-by-phone', + '/legal-agreement/current', '/product/get/', '/product/list/', '/comment/list/product/', diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/AuthInterceptor.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/AuthInterceptor.java index 2c238ed6..9f481a83 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/AuthInterceptor.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/AuthInterceptor.java @@ -91,11 +91,22 @@ public class AuthInterceptor implements HandlerInterceptor { if (!canAccessShop) { String message = currentShopId == null || currentShopId <= 0 ? "当前登录未选择可用店铺,请重新登录" - : "当前登录店铺已停用或账号已失去该店铺访问权限"; + : (userShopBindingSupport.isShopEnabledIgnoringAuthorization(currentShopId) + && userShopBindingSupport.isShopAuthorizationExpired(currentShopId) + ? "店铺已被冻结" + : "当前登录店铺已停用或账号已失去该店铺访问权限"); writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, message); return false; } + if (adminPath + && !Integer.valueOf(4).equals(currentUser.getType()) + && userShopBindingSupport.isShopAuthorizationExpired(currentShopId) + && !isExpiredAdminAllowedPath(path)) { + writeJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, "授权已到期,请联系管理员"); + return false; + } + if (requiresSignature(request)) { try { requestSignatureService.validateRequest(request, token, userId); @@ -142,6 +153,14 @@ public class AuthInterceptor implements HandlerInterceptor { return path.startsWith("/admin/") || path.startsWith("/order/admin/"); } + private boolean isExpiredAdminAllowedPath(String path) { + return path.startsWith("/admin/auth/") + || path.equals("/admin/user/info") + || path.equals("/permission/list/user/current") + || path.equals("/api/permission/list/user/current") + || path.startsWith("/admin/shops/"); + } + private void writeJsonResponse(HttpServletResponse response, int status, String message) throws Exception { response.setStatus(status); response.setContentType("application/json;charset=UTF-8"); diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/LoginLockProperties.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/LoginLockProperties.java new file mode 100644 index 00000000..ff5ba5a0 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/LoginLockProperties.java @@ -0,0 +1,17 @@ +package com.xiaowang.yuminailcore.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +@Data +@Configuration +@ConfigurationProperties(prefix = "yuminail.security.login-lock") +public class LoginLockProperties { + + private int maxFailures = 5; + + private long windowSeconds = 600; + + private long lockSeconds = 900; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/RateLimitProperties.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/RateLimitProperties.java index 1954bb98..c85d146a 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/RateLimitProperties.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/RateLimitProperties.java @@ -14,10 +14,16 @@ public class RateLimitProperties { private LimitRule login = new LimitRule(10, 60); + private LimitRule register = new LimitRule(5, 300); + private LimitRule sendCode = new LimitRule(5, 60); private LimitRule resetPassword = new LimitRule(5, 600); + private LimitRule wechatMiniLogin = new LimitRule(10, 60); + + private LimitRule agreementRead = new LimitRule(60, 60); + private LimitRule authenticatedWrite = new LimitRule(80, 60); private LimitRule orderCreate = new LimitRule(10, 60); diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/SecurityHeadersFilter.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/SecurityHeadersFilter.java new file mode 100644 index 00000000..80dac6f5 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/SecurityHeadersFilter.java @@ -0,0 +1,26 @@ +package com.xiaowang.yuminailcore.config; + +import org.springframework.stereotype.Component; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +@Component +public class SecurityHeadersFilter implements Filter { + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + if (response instanceof HttpServletResponse httpResponse) { + httpResponse.setHeader("X-Content-Type-Options", "nosniff"); + httpResponse.setHeader("X-Frame-Options", "DENY"); + httpResponse.setHeader("Referrer-Policy", "strict-origin-when-cross-origin"); + httpResponse.setHeader("Content-Security-Policy", "default-src 'self'; img-src 'self' data: blob: http: https:; style-src 'self' 'unsafe-inline'; script-src 'self'; connect-src 'self' http: https:"); + } + chain.doFilter(request, response); + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/UploadSecurityProperties.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/UploadSecurityProperties.java new file mode 100644 index 00000000..670a5ee7 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/UploadSecurityProperties.java @@ -0,0 +1,23 @@ +package com.xiaowang.yuminailcore.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +import java.util.ArrayList; +import java.util.List; + +@Data +@Configuration +@ConfigurationProperties(prefix = "yuminail.security.upload") +public class UploadSecurityProperties { + + private long maxSize = 10 * 1024 * 1024; + + private List allowedMimeTypes = new ArrayList<>(List.of( + "image/jpeg", + "image/png", + "image/webp", + "image/gif" + )); +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/WebMvcConfig.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/WebMvcConfig.java index 85b8cbbc..3d851d7f 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/WebMvcConfig.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/WebMvcConfig.java @@ -30,6 +30,10 @@ public class WebMvcConfig implements WebMvcConfigurer { "/user/phone-login", "/user/wechat-mini/**", "/user/reset-password-by-phone", + "/legal-agreement/current", + "/legal-agreement/current/**", + "/api/legal-agreement/current", + "/api/legal-agreement/current/**", "/product/get/**", "/product/list/**", "/comment/list/product/**", diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminAuthController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminAuthController.java index 3352914c..78bd8840 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminAuthController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminAuthController.java @@ -6,6 +6,7 @@ import com.xiaowang.yuminailcore.dto.LoginRequestDTO; import com.xiaowang.yuminailcore.dto.RefreshTokenRequestDTO; import com.xiaowang.yuminailcore.dto.SwitchShopRequestDTO; import com.xiaowang.yuminailcore.service.UserService; +import com.xiaowang.yuminailcore.service.SecurityAuditLogService; import com.xiaowang.yuminailcore.support.security.RequestThrottleService; import com.xiaowang.yuminailcore.support.security.OperationGuardStrategy; import com.xiaowang.yuminailcore.utils.AccountValidationUtils; @@ -20,26 +21,64 @@ import javax.servlet.http.HttpServletRequest; @RestController @RequestMapping("/admin/auth") @RequiredArgsConstructor +/** + * AdminAuthController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ public class AdminAuthController { - + /** + * Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final UserService userService; + /** + * Variable `requestThrottleService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final RequestThrottleService requestThrottleService; + private final SecurityAuditLogService securityAuditLogService; @PostMapping("/login") @OperationGuard(action = "admin-login", ttlSeconds = 8, message = "登录处理中,请勿重复提交") + /** + * Run the login flow. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param loginRequestDTO parameter `loginRequestDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result login(HttpServletRequest request, @Valid @RequestBody LoginRequestDTO loginRequestDTO) { requestThrottleService.checkLogin(request, loginRequestDTO.getAccount()); - LoginResponseVO loginResponseVO = userService.adminLogin(loginRequestDTO); - return Result.success(loginResponseVO); + try { + LoginResponseVO loginResponseVO = userService.adminLogin(loginRequestDTO); + requestThrottleService.clearLoginFailure(request, loginRequestDTO.getAccount()); + securityAuditLogService.record(loginResponseVO.getUserInfo().getId(), loginRequestDTO.getAccount(), "ADMIN_LOGIN", "SUCCESS", null, request); + return Result.success(loginResponseVO); + } catch (RuntimeException exception) { + requestThrottleService.recordLoginFailure(request, loginRequestDTO.getAccount()); + securityAuditLogService.record(null, loginRequestDTO.getAccount(), "ADMIN_LOGIN", "FAIL", exception.getMessage(), request); + throw exception; + } } @GetMapping("/login-shops/{account}") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param account parameter `account` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result getLoginShops(@PathVariable String account) { return Result.success(userService.getAdminLoginShopSelection(AccountValidationUtils.requireValidAccount(account))); } @PostMapping("/switch-shop") @OperationGuard(action = "admin-switch-shop", ttlSeconds = 10, message = "门店切换中,请勿重复操作") + /** + * Run business method `switchShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param switchShopRequestDTO parameter `switchShopRequestDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result switchShop(HttpServletRequest request, @RequestBody SwitchShopRequestDTO switchShopRequestDTO) { Long userId = (Long) request.getAttribute("userId"); return Result.success(userService.switchAdminShop(userId, switchShopRequestDTO.getShopId(), (String) request.getAttribute("sessionId"))); @@ -47,16 +86,33 @@ public class AdminAuthController { @PostMapping("/logout") @OperationGuard(action = "admin-logout", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 5) + /** + * Run business method `logout`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result logout(HttpServletRequest request) { return Result.success(userService.logout((String) request.getAttribute("sessionId"))); } @PostMapping("/refresh") + /** + * Run business method `refreshToken`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param refreshTokenRequestDTO parameter `refreshTokenRequestDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result refreshToken(@RequestBody RefreshTokenRequestDTO refreshTokenRequestDTO) { LoginResponseVO loginResponseVO = userService.refreshToken(refreshTokenRequestDTO.getRefreshToken()); if (loginResponseVO.getUserInfo() == null || loginResponseVO.getUserInfo().getType() == null || loginResponseVO.getUserInfo().getType() < 2) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("您没有后台管理权限"); } return Result.success(loginResponseVO); diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminCommentController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminCommentController.java index de372499..21f1db1f 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminCommentController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminCommentController.java @@ -20,9 +20,18 @@ import java.util.List; @RestController @RequestMapping("/admin/comment") @RequiredArgsConstructor +/** + * AdminCommentController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ public class AdminCommentController { - + /** + * Variable `commentService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final CommentService commentService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final AdminScopeHelper adminScopeHelper; @GetMapping("/list") @@ -41,6 +50,13 @@ public class AdminCommentController { @DeleteMapping("/delete/{id}") @RequirePermission("comment:delete") + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result deleteComment(HttpServletRequest request, @PathVariable Long id) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); Long managedShopId = adminScopeHelper.resolveShopScope(currentUser, null); diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminCouponController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminCouponController.java index f68ed184..6901e521 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminCouponController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminCouponController.java @@ -25,9 +25,17 @@ import java.util.stream.Collectors; @RequestMapping("/admin/coupon") @RequiredArgsConstructor public class AdminCouponController { - + /** + * Variable `couponService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final CouponService couponService; + /** + * Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final UserService userService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final AdminScopeHelper adminScopeHelper; /** diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminLegalAgreementController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminLegalAgreementController.java new file mode 100644 index 00000000..e0e3b4a1 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminLegalAgreementController.java @@ -0,0 +1,73 @@ +package com.xiaowang.yuminailcore.controller; + +import com.xiaowang.yuminailcore.annotation.OperationGuard; +import com.xiaowang.yuminailcore.annotation.RequirePermission; +import com.xiaowang.yuminailcore.common.Result; +import com.xiaowang.yuminailcore.dto.LegalAgreementDTO; +import com.xiaowang.yuminailcore.entity.UserDO; +import com.xiaowang.yuminailcore.service.LegalAgreementService; +import com.xiaowang.yuminailcore.service.SecurityAuditLogService; +import com.xiaowang.yuminailcore.support.AdminScopeHelper; +import com.xiaowang.yuminailcore.vo.LegalAgreementVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import java.util.List; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/admin/legal-agreement") +public class AdminLegalAgreementController { + + private final LegalAgreementService legalAgreementService; + private final AdminScopeHelper adminScopeHelper; + private final SecurityAuditLogService securityAuditLogService; + + @GetMapping("/list") + @RequirePermission("legal_agreement:manage") + public Result> list(HttpServletRequest request) { + return Result.success(legalAgreementService.listAdminAgreements(adminScopeHelper.getCurrentUser(request))); + } + + @PostMapping("/create") + @RequirePermission("legal_agreement:manage") + @OperationGuard(action = "admin-legal-agreement-create", ttlSeconds = 8, message = "协议保存处理中,请勿重复提交") + public Result create(HttpServletRequest request, @Valid @RequestBody LegalAgreementDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Long id = legalAgreementService.createAgreement(currentUser, dto); + securityAuditLogService.record(currentUser.getId(), currentUser.getAccount(), "LEGAL_AGREEMENT_CREATE", "SUCCESS", dto.getAgreementType(), request); + return Result.success(id); + } + + @PutMapping("/{id}") + @RequirePermission("legal_agreement:manage") + @OperationGuard(action = "admin-legal-agreement-update", ttlSeconds = 8, message = "协议保存处理中,请勿重复提交") + public Result update(HttpServletRequest request, @PathVariable Long id, @Valid @RequestBody LegalAgreementDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Boolean result = legalAgreementService.updateAgreement(currentUser, id, dto); + securityAuditLogService.record(currentUser.getId(), currentUser.getAccount(), "LEGAL_AGREEMENT_UPDATE", "SUCCESS", String.valueOf(id), request); + return Result.success(result); + } + + @PutMapping("/{id}/publish") + @RequirePermission("legal_agreement:manage") + @OperationGuard(action = "admin-legal-agreement-publish", ttlSeconds = 8, message = "协议发布处理中,请勿重复提交") + public Result publish(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Boolean result = legalAgreementService.publishAgreement(currentUser, id); + securityAuditLogService.record(currentUser.getId(), currentUser.getAccount(), "LEGAL_AGREEMENT_PUBLISH", "SUCCESS", String.valueOf(id), request); + return Result.success(result); + } + + @PutMapping("/{id}/disable") + @RequirePermission("legal_agreement:manage") + @OperationGuard(action = "admin-legal-agreement-disable", ttlSeconds = 8, message = "协议停用处理中,请勿重复提交") + public Result disable(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Boolean result = legalAgreementService.disableAgreement(currentUser, id); + securityAuditLogService.record(currentUser.getId(), currentUser.getAccount(), "LEGAL_AGREEMENT_DISABLE", "SUCCESS", String.valueOf(id), request); + return Result.success(result); + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminNailArtistController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminNailArtistController.java index 3de2852d..8f32e65e 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminNailArtistController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminNailArtistController.java @@ -21,17 +21,32 @@ import java.util.List; @RestController @RequestMapping("/admin/nail-artist") @RequiredArgsConstructor +/** + * AdminNailArtistController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ public class AdminNailArtistController { private static final String USER_NOT_FOUND_MESSAGE = "用户信息不存在"; private static final String VIEW_SCOPE_MESSAGE = "当前登录店铺无权查看该美甲师,请切换到所属店铺后重试"; private static final String EDIT_SCOPE_MESSAGE = "当前登录店铺无权编辑该美甲师,请切换到所属店铺后重试"; - + /** + * Variable `nailArtistInfoService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final NailArtistInfoService nailArtistInfoService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final AdminScopeHelper adminScopeHelper; @RequirePermission("nail_artist:view") @GetMapping("/list") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ public Result> getAllNailArtists(HttpServletRequest request) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); if (currentUser == null) { @@ -52,6 +67,13 @@ public class AdminNailArtistController { @RequirePermission("nail_artist:view") @GetMapping("/get/{userId}") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result getNailArtistInfo(@PathVariable Long userId, HttpServletRequest request) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); if (currentUser == null) { @@ -77,6 +99,13 @@ public class AdminNailArtistController { @RequirePermission("nail_artist:edit") @PostMapping("/save") @OperationGuard(action = "admin-nail-artist-save", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + /** + * Save submitted data. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param nailArtistInfoDTO parameter `nailArtistInfoDTO` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result saveNailArtistInfo(@RequestBody NailArtistInfoDTO nailArtistInfoDTO, HttpServletRequest request) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); if (currentUser == null) { diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminOrderController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminOrderController.java index 511fd207..752dbc06 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminOrderController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminOrderController.java @@ -21,8 +21,13 @@ import java.util.List; @RequestMapping("/admin/order") @RequiredArgsConstructor public class AdminOrderController { - + /** + * Variable `orderService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final OrderService orderService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final AdminScopeHelper adminScopeHelper; /** @@ -87,6 +92,11 @@ public class AdminOrderController { UserDO currentUser = adminScopeHelper.getCurrentUser(request); if (Integer.valueOf(3).equals(currentUser.getType())) { if (!Integer.valueOf(2).equals(status)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("美甲师只能完成属于自己的订单"); } orderService.completeArtistOrder(id, currentUser.getId()); diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminPermissionController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminPermissionController.java index 981b049c..14363999 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminPermissionController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminPermissionController.java @@ -19,15 +19,34 @@ import java.util.List; @RestController @RequestMapping("/admin/permission") @RequiredArgsConstructor +/** + * AdminPermissionController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ public class AdminPermissionController { - + /** + * Variable `permissionService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final PermissionService permissionService; + /** + * Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final UserService userService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final AdminScopeHelper adminScopeHelper; @PostMapping("/create") @RequirePermission("permission:create") @OperationGuard(action = "admin-permission-create", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param permissionDTO parameter `permissionDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result createPermission(HttpServletRequest request, @RequestBody PermissionDTO permissionDTO) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以维护权限定义"); @@ -38,6 +57,14 @@ public class AdminPermissionController { @PutMapping("/update/{id}") @RequirePermission("permission:edit") @OperationGuard(action = "admin-permission-update", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param permissionDTO parameter `permissionDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result updatePermission(HttpServletRequest request, @PathVariable Long id, @RequestBody PermissionDTO permissionDTO) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以维护权限定义"); @@ -48,6 +75,13 @@ public class AdminPermissionController { @DeleteMapping("/delete/{id}") @RequirePermission("permission:delete") @OperationGuard(action = "admin-permission-delete", ttlSeconds = 10, message = "操作处理中,请勿重复提交") + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result deletePermission(HttpServletRequest request, @PathVariable Long id) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以维护权限定义"); @@ -57,6 +91,12 @@ public class AdminPermissionController { @GetMapping("/get/{id}") @RequirePermission("permission:view") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result getPermissionById(@PathVariable Long id) { PermissionVO permissionVO = permissionService.getPermissionById(id); return Result.success(permissionVO); @@ -64,6 +104,11 @@ public class AdminPermissionController { @GetMapping("/list/all") @RequirePermission("permission:view") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return Result> result consumed by the caller or returned to the frontend + */ public Result> listAllPermissions() { List permissionVOs = permissionService.listAllPermissions(); return Result.success(permissionVOs); @@ -71,6 +116,12 @@ public class AdminPermissionController { @GetMapping("/list/group/{permissionGroup}") @RequirePermission("permission:view") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param permissionGroup parameter `permissionGroup` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ public Result> listPermissionsByGroup(@PathVariable String permissionGroup) { List permissionVOs = permissionService.listPermissionsByGroup(permissionGroup); return Result.success(permissionVOs); @@ -78,11 +129,23 @@ public class AdminPermissionController { @GetMapping("/user/{userId}") @RequirePermission("permission:view") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ public Result> listUserPermissions(HttpServletRequest request, @PathVariable Long userId) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); if (!adminScopeHelper.isPlatformAdmin(currentUser)) { UserDO targetUser = userService.getById(userId); if (targetUser == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("目标用户不存在"); } adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权查看其他店铺用户权限"); @@ -93,6 +156,13 @@ public class AdminPermissionController { @GetMapping("/assignable/{userId}") @RequirePermission("permission:assign") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ public Result> listAssignablePermissionIds(HttpServletRequest request, @PathVariable Long userId) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); if (!adminScopeHelper.isPlatformAdmin(currentUser)) { @@ -103,6 +173,12 @@ public class AdminPermissionController { } @GetMapping("/user/current") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ public Result> getCurrentUserPermissions(HttpServletRequest request) { Long userId = (Long) request.getAttribute("userId"); userService.syncManagedPermissions(userId); diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminProductController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminProductController.java index 4e809fd9..e5ce2985 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminProductController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminProductController.java @@ -18,9 +18,18 @@ import java.util.List; @RestController @RequestMapping("/admin/product") @RequiredArgsConstructor +/** + * AdminProductController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ public class AdminProductController { - + /** + * Variable `productService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final ProductService productService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final AdminScopeHelper adminScopeHelper; @GetMapping("/list") @@ -41,6 +50,13 @@ public class AdminProductController { @PostMapping("/create") @RequirePermission("product:create") @OperationGuard(action = "admin-product-create", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param productDTO parameter `productDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result createProduct(HttpServletRequest request, @RequestBody ProductDTO productDTO) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); productDTO.setShopId(adminScopeHelper.resolveShopScope(currentUser, productDTO.getShopId())); @@ -51,6 +67,14 @@ public class AdminProductController { @PutMapping("/update/{id}") @RequirePermission("product:edit") @OperationGuard(action = "admin-product-update", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param productDTO parameter `productDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result updateProduct(HttpServletRequest request, @PathVariable Long id, @RequestBody ProductDTO productDTO) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); ProductVO productVO = productService.getProductById(id); @@ -67,6 +91,13 @@ public class AdminProductController { @DeleteMapping("/delete/{id}") @RequirePermission("product:delete") @OperationGuard(action = "admin-product-delete", ttlSeconds = 10, message = "操作处理中,请勿重复提交") + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result deleteProduct(HttpServletRequest request, @PathVariable Long id) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); ProductVO productVO = productService.getProductById(id); @@ -80,6 +111,12 @@ public class AdminProductController { @GetMapping("/list/all") @RequirePermission("product:view") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ public Result> listAllProducts(HttpServletRequest request) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); Long shopId = adminScopeHelper.resolveShopScope(currentUser, null); diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminShopController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminShopController.java index 0fbca040..7bd4f283 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminShopController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminShopController.java @@ -19,9 +19,18 @@ import java.util.List; @RestController @RequestMapping("/admin/shops") @RequiredArgsConstructor +/** + * AdminShopController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ public class AdminShopController { - + /** + * Variable `shopService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final ShopService shopService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final AdminScopeHelper adminScopeHelper; @GetMapping("/list") @@ -42,6 +51,13 @@ public class AdminShopController { @PostMapping("/create") @RequirePermission("shop:create") @OperationGuard(action = "admin-shop-create", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param shopDTO parameter `shopDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result createShop(HttpServletRequest request, @RequestBody ShopDTO shopDTO) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以创建店铺"); @@ -52,6 +68,14 @@ public class AdminShopController { @PutMapping("/update/{id}") @RequirePermission("shop:edit") @OperationGuard(action = "admin-shop-update", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param shopDTO parameter `shopDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result updateShop(HttpServletRequest request, @PathVariable Long id, @RequestBody ShopDTO shopDTO) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); ShopVO shopVO = shopService.getShopById(id); @@ -59,6 +83,9 @@ public class AdminShopController { return Result.success(false); } adminScopeHelper.ensureShopAccessible(currentUser, shopVO.getId(), "无权编辑其他店铺信息"); + if (!adminScopeHelper.isPlatformAdmin(currentUser)) { + shopDTO.setAuthorizationExpireTime(shopVO.getAuthorizationExpireTime()); + } boolean success = shopService.updateShop(id, shopDTO); return Result.success(success); } @@ -66,6 +93,13 @@ public class AdminShopController { @DeleteMapping("/delete/{id}") @RequirePermission("shop:delete") @OperationGuard(action = "admin-shop-delete", ttlSeconds = 10, message = "操作处理中,请勿重复提交") + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result deleteShop(HttpServletRequest request, @PathVariable Long id) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以删除店铺"); @@ -76,6 +110,14 @@ public class AdminShopController { @PutMapping("/status/{id}") @RequirePermission("shop:edit") @OperationGuard(action = "admin-shop-status", ttlSeconds = 10, message = "操作处理中,请勿重复提交") + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param statusRequest parameter `statusRequest` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result updateShopStatus(HttpServletRequest request, @PathVariable Long id, @RequestBody StatusRequest statusRequest) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以启停店铺"); @@ -85,6 +127,12 @@ public class AdminShopController { @GetMapping("/list/all") @RequirePermission("shop:view") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ public Result> listAllShops(HttpServletRequest request) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); List shops; @@ -99,6 +147,13 @@ public class AdminShopController { @GetMapping("/{id}") @RequirePermission("shop:view") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result getShop(HttpServletRequest request, @PathVariable Long id) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); adminScopeHelper.ensureShopAccessible(currentUser, id, "无权查看其他店铺信息"); diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminShopRoleController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminShopRoleController.java new file mode 100644 index 00000000..089adb97 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminShopRoleController.java @@ -0,0 +1,182 @@ +package com.xiaowang.yuminailcore.controller; + +import com.xiaowang.yuminailcore.annotation.RequirePermission; +import com.xiaowang.yuminailcore.common.Result; +import com.xiaowang.yuminailcore.dto.InviteCodeDTO; +import com.xiaowang.yuminailcore.dto.ShopRoleDTO; +import com.xiaowang.yuminailcore.entity.UserDO; +import com.xiaowang.yuminailcore.service.PermissionService; +import com.xiaowang.yuminailcore.service.ShopRoleService; +import com.xiaowang.yuminailcore.support.AdminScopeHelper; +import com.xiaowang.yuminailcore.vo.InviteCodeVO; +import com.xiaowang.yuminailcore.vo.PermissionVO; +import com.xiaowang.yuminailcore.vo.ShopRoleVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import java.util.List; + +@RestController +@RequestMapping("/admin/shop-role") +@RequiredArgsConstructor +/** + * AdminShopRoleController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class AdminShopRoleController { + /** + * Variable `shopRoleService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopRoleService shopRoleService; + /** + * Variable `permissionService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final PermissionService permissionService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + + @GetMapping("/list") + @RequirePermission("role:view") + // 店铺角色是“只在本店生效”的角色,不是全局后台角色; + // 所以这里要先按当前登录人的店铺范围裁剪,再返回列表。 + public Result> list(HttpServletRequest request, @RequestParam(required = false) Long shopId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(shopRoleService.listRoles(currentUser, shopId)); + } + + @PostMapping("/create") + @RequirePermission("role:create") + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result create(HttpServletRequest request, @Valid @RequestBody ShopRoleDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(shopRoleService.createRole(currentUser, dto)); + } + + @PutMapping("/{id}") + @RequirePermission("role:edit") + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result update(HttpServletRequest request, @PathVariable Long id, @RequestBody ShopRoleDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(shopRoleService.updateRole(currentUser, id, dto)); + } + + @DeleteMapping("/{id}") + @RequirePermission("role:delete") + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result delete(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(shopRoleService.deleteRole(currentUser, id)); + } + + @PostMapping("/{id}/permissions") + @RequirePermission("role:edit") + /** + * Run business method `assignPermissions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param permissionIds parameter `permissionIds` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result assignPermissions(HttpServletRequest request, @PathVariable Long id, @RequestBody List permissionIds) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(shopRoleService.assignPermissions(currentUser, id, permissionIds)); + } + + @PostMapping("/{id}/users") + @RequirePermission("role:edit") + /** + * Run business method `assignUsers`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param userIds parameter `userIds` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result assignUsers(HttpServletRequest request, @PathVariable Long id, @RequestBody List userIds) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(shopRoleService.assignUsers(currentUser, id, userIds)); + } + + @GetMapping("/permission-options") + @RequirePermission("role:view") + /** + * Run business method `permissionOptions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> permissionOptions() { + return Result.success(permissionService.listAllPermissions()); + } + + @GetMapping("/invite-code/list") + @RequirePermission("user:relation:view") + public Result> listInviteCodes(HttpServletRequest request, @RequestParam(required = false) Long shopId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(shopRoleService.listInviteCodes(currentUser, shopId)); + } + + @PostMapping("/invite-code/create") + @RequirePermission("user:relation:edit") + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result createInviteCode(HttpServletRequest request, @Valid @RequestBody InviteCodeDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(shopRoleService.createInviteCode(currentUser, dto)); + } + + @PutMapping("/invite-code/{id}/status") + @RequirePermission("user:relation:edit") + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param status parameter `status` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result updateInviteCodeStatus(HttpServletRequest request, @PathVariable Long id, @RequestParam Integer status) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(shopRoleService.updateInviteCodeStatus(currentUser, id, status)); + } + + @GetMapping("/invite-code/resolve") + // 注册页输入邀请码时调用这个接口,用来提前展示“会归属到谁、哪个店”。 + /** + * Run business method `resolve`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param code parameter `code` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result resolve(@RequestParam String code) { + return Result.success(shopRoleService.resolveInviteCode(code)); + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminTagController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminTagController.java index 5dfa4835..ddbf789e 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminTagController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminTagController.java @@ -21,8 +21,13 @@ import java.util.List; @RequestMapping("/admin/tag") @RequiredArgsConstructor public class AdminTagController { - + /** + * Variable `tagService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final TagService tagService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final AdminScopeHelper adminScopeHelper; /** diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminUserController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminUserController.java index 9f1d720b..c0db8643 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminUserController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminUserController.java @@ -6,13 +6,18 @@ import com.xiaowang.yuminailcore.common.Result; import com.xiaowang.yuminailcore.dto.AdminUserBalanceChangeDTO; import com.xiaowang.yuminailcore.dto.AdminUserVipOverrideDTO; import com.xiaowang.yuminailcore.dto.UserDTO; +import com.xiaowang.yuminailcore.dto.UserRelationUpdateDTO; import com.xiaowang.yuminailcore.entity.UserDO; import com.xiaowang.yuminailcore.service.UserAssetService; import com.xiaowang.yuminailcore.service.UserService; +import com.xiaowang.yuminailcore.service.ShopRoleService; import com.xiaowang.yuminailcore.support.AdminScopeHelper; +import com.xiaowang.yuminailcore.support.BookableArtistSupport; import com.xiaowang.yuminailcore.vo.BalanceChangeDetailVO; import com.xiaowang.yuminailcore.vo.PageResultVO; +import com.xiaowang.yuminailcore.vo.UserStatisticsVO; import com.xiaowang.yuminailcore.vo.UserAssetVO; +import com.xiaowang.yuminailcore.vo.UserRelationVO; import com.xiaowang.yuminailcore.vo.UserVO; import lombok.Data; import lombok.RequiredArgsConstructor; @@ -26,11 +31,31 @@ import java.util.stream.Collectors; @RestController @RequestMapping("/admin/user") @RequiredArgsConstructor +/** + * AdminUserController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ public class AdminUserController { - + /** + * Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final UserService userService; + /** + * Variable `userAssetService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final UserAssetService userAssetService; + /** + * Variable `shopRoleService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopRoleService shopRoleService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final AdminScopeHelper adminScopeHelper; + /** + * Variable `bookableArtistSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final BookableArtistSupport bookableArtistSupport; @GetMapping("/list") @RequirePermission("user:view") @@ -40,17 +65,87 @@ public class AdminUserController { @RequestParam(defaultValue = "10") Integer size, @RequestParam(required = false) String keyword, @RequestParam(required = false) Long shopId, - @RequestParam(required = false) Integer type + @RequestParam(required = false) Integer type, + @RequestParam(required = false) Long roleId, + @RequestParam(required = false) Long parentUserId, + @RequestParam(required = false) String sourceType, + @RequestParam(required = false) Integer status, + @RequestParam(required = false) String vipLevel, + @RequestParam(required = false) String createdFrom, + @RequestParam(required = false) String createdTo, + @RequestParam(required = false) Boolean hasPhone, + @RequestParam(required = false) Boolean hasOrder ) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); shopId = adminScopeHelper.resolveShopScope(currentUser, shopId); - PageResultVO result = userService.pageUsers(page, size, keyword, shopId, type); + PageResultVO result = userService.pageUsers(page, size, keyword, shopId, type, roleId, parentUserId, sourceType, status, vipLevel, createdFrom, createdTo, hasPhone, hasOrder); return Result.success(result); } + @GetMapping("/statistics") + @RequirePermission("user:view") + public Result statisticsUsers(HttpServletRequest request, + @RequestParam(required = false) String keyword, + @RequestParam(required = false) Long shopId, + @RequestParam(required = false) Integer type, + @RequestParam(required = false) Long roleId, + @RequestParam(required = false) Long parentUserId, + @RequestParam(required = false) String sourceType, + @RequestParam(required = false) Integer status, + @RequestParam(required = false) String vipLevel, + @RequestParam(required = false) String createdFrom, + @RequestParam(required = false) String createdTo, + @RequestParam(required = false) Boolean hasPhone, + @RequestParam(required = false) Boolean hasOrder) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + shopId = adminScopeHelper.resolveShopScope(currentUser, shopId); + return Result.success(userService.statisticsUsers(keyword, shopId, type, roleId, parentUserId, sourceType, status, vipLevel, createdFrom, createdTo, hasPhone, hasOrder)); + } + + @GetMapping("/relation/me") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result getMyRelation(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(userService.getCurrentUserRelation(userId)); + } + + @GetMapping("/relation/options") + @RequirePermission("user:relation:view") + public Result> relationOptions(HttpServletRequest request, @RequestParam(required = false) Long shopId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(shopRoleService.listRelationOptions(currentUser, shopId)); + } + + @PutMapping("/{id}/relation") + @RequirePermission("user:relation:edit") + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result updateRelation(HttpServletRequest request, @PathVariable Long id, @RequestBody UserRelationUpdateDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(shopRoleService.updateUserRelation(currentUser, id, dto)); + } + @PostMapping("/create") @RequirePermission("user:create") @OperationGuard(action = "admin-user-create", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param userDTO parameter `userDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result createUser(HttpServletRequest request, @Valid @RequestBody UserDTO userDTO) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); adminScopeHelper.ensureAssignableUserType(currentUser, userDTO.getType()); @@ -66,6 +161,14 @@ public class AdminUserController { @PutMapping("/update/{id}") @RequirePermission("user:edit") @OperationGuard(action = "admin-user-update", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param userDTO parameter `userDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result updateUser(HttpServletRequest request, @PathVariable Long id, @Valid @RequestBody UserDTO userDTO) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); UserVO targetUser = userService.getUserById(id); @@ -87,6 +190,14 @@ public class AdminUserController { @PutMapping("/status/{id}") @RequirePermission("user:disable") @OperationGuard(action = "admin-user-status", ttlSeconds = 10, message = "操作处理中,请勿重复提交") + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param httpRequest parameter `httpRequest` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result updateUserStatus(HttpServletRequest httpRequest, @PathVariable Long id, @RequestBody StatusRequest request) { UserDO currentUser = adminScopeHelper.getCurrentUser(httpRequest); adminScopeHelper.requirePlatformAdmin(currentUser, "仅系统管理员可以停用用户"); @@ -96,6 +207,11 @@ public class AdminUserController { } adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, id, "无权变更其他店铺用户状态"); if (Integer.valueOf(4).equals(targetUser.getType())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("管理员账号不允许停用"); } boolean success = userService.updateUserStatus(id, request.getStatus()); @@ -105,6 +221,13 @@ public class AdminUserController { @PostMapping("/reset-password/{userId}") @RequirePermission("user:reset_password") @OperationGuard(action = "admin-user-reset-password", ttlSeconds = 10, message = "操作处理中,请勿重复提交") + /** + * Run business method `resetPassword`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result resetPassword(HttpServletRequest request, @PathVariable Long userId) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); UserVO targetUser = userService.getUserById(userId); @@ -120,6 +243,13 @@ public class AdminUserController { @DeleteMapping("/delete/{id}") @RequirePermission("user:delete") @OperationGuard(action = "admin-user-delete", ttlSeconds = 10, message = "操作处理中,请勿重复提交") + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result deleteUser(HttpServletRequest request, @PathVariable Long id) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); adminScopeHelper.requirePlatformAdmin(currentUser, "仅系统管理员可以删除用户"); @@ -128,6 +258,11 @@ public class AdminUserController { return Result.success(false); } if (Integer.valueOf(4).equals(targetUser.getType())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("管理员账号不允许删除"); } boolean success = userService.deleteUser(id); @@ -137,6 +272,13 @@ public class AdminUserController { @PutMapping("/unbind/{id}") @RequirePermission("user:unbind") @OperationGuard(action = "admin-user-unbind", ttlSeconds = 10, message = "操作处理中,请勿重复提交") + /** + * Run business method `unbindUser`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result unbindUser(HttpServletRequest request, @PathVariable Long id) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); UserVO targetUser = userService.getUserById(id); @@ -146,6 +288,11 @@ public class AdminUserController { adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, id, "无权解绑其他店铺用户"); adminScopeHelper.ensureAssignableUserType(currentUser, targetUser.getType()); if (Integer.valueOf(4).equals(targetUser.getType())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("管理员账号不允许解绑"); } boolean success = userService.unbindUserInShopWithOperator(id, currentUser.getShopId(), currentUser.getType()); @@ -154,6 +301,13 @@ public class AdminUserController { @GetMapping("/{id}/asset") @RequirePermission("user:balance:view") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result getUserAsset(HttpServletRequest request, @PathVariable Long id) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); UserVO targetUser = requireAccessibleUser(currentUser, id, "无权查看其他店铺用户资产"); @@ -163,6 +317,13 @@ public class AdminUserController { @GetMapping("/{id}/balance/history") @RequirePermission("user:balance:view") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ public Result> getUserBalanceHistory(HttpServletRequest request, @PathVariable Long id) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); UserVO targetUser = requireAccessibleUser(currentUser, id, "无权查看其他店铺用户余额流水"); @@ -201,6 +362,13 @@ public class AdminUserController { @PostMapping("/{id}/vip/recalculate") @RequirePermission("user:vip:manage") @OperationGuard(action = "admin-user-vip-recalculate", ttlSeconds = 15, message = "操作处理中,请勿重复提交") + /** + * Run business method `recalculateUserVip`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result recalculateUserVip(HttpServletRequest request, @PathVariable Long id) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); UserVO targetUser = requireAccessibleUser(currentUser, id, "无权重算其他店铺用户 VIP"); @@ -209,6 +377,12 @@ public class AdminUserController { } @GetMapping("/info") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result getUserInfo(HttpServletRequest request) { Long userId = (Long) request.getAttribute("userId"); UserVO userVO = userService.getUserById(userId); @@ -239,8 +413,12 @@ public class AdminUserController { public Result> listArtists(HttpServletRequest request, @RequestParam(required = false) Long shopId) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); shopId = adminScopeHelper.resolveShopScope(currentUser, shopId); + final Long resolvedScopeShopId = shopId; + List artists = userService.listAllUsers().stream() + .filter(user -> Integer.valueOf(2).equals(user.getType()) || Integer.valueOf(3).equals(user.getType())) + .filter(user -> bookableArtistSupport.isValidBookableArtist(resolvedScopeShopId, user.getId())) + .collect(Collectors.toList()); // 用户类型 3 表示美甲师 - List artists = userService.listUsersByType(3); // 如果指定了店铺ID,则过滤该店铺的美甲师 if (shopId != null) { final Long resolvedShopId = shopId; @@ -251,9 +429,22 @@ public class AdminUserController { return Result.success(artists); } + /** + * Run business method `requireAccessibleUser`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @param message parameter `message` supplied by the caller + * @return private UserVO result consumed by the caller or returned to the frontend + */ private UserVO requireAccessibleUser(UserDO currentUser, Long userId, String message) { UserVO targetUser = userService.getUserById(userId); if (targetUser == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("目标用户不存在"); } adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, message); diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AnnouncementController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AnnouncementController.java new file mode 100644 index 00000000..d64a73a7 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AnnouncementController.java @@ -0,0 +1,119 @@ +package com.xiaowang.yuminailcore.controller; + +import com.xiaowang.yuminailcore.annotation.OperationGuard; +import com.xiaowang.yuminailcore.annotation.RequirePermission; +import com.xiaowang.yuminailcore.common.Result; +import com.xiaowang.yuminailcore.dto.AnnouncementCreateDTO; +import com.xiaowang.yuminailcore.entity.UserDO; +import com.xiaowang.yuminailcore.service.AnnouncementService; +import com.xiaowang.yuminailcore.support.AdminScopeHelper; +import com.xiaowang.yuminailcore.vo.AnnouncementVO; +import com.xiaowang.yuminailcore.vo.MessageTargetOptionsVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import java.util.List; + +@RestController +@RequiredArgsConstructor +@RequestMapping({"/announcement", "/api/announcement"}) +/** + * AnnouncementController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class AnnouncementController { + /** + * Variable `announcementService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AnnouncementService announcementService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + + @PostMapping("/admin/create") + @RequirePermission("announcement:create") + @OperationGuard(action = "announcement-create", ttlSeconds = 8, message = "公告发布处理中,请勿重复提交") + // 后台发布公告时,targetType 决定“全平台 / 指定店铺 / 指定用户”的范围。 + // 前端只需要按 target-options 返回值组装表单即可。 + /** + * Run business method `publish`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result publish(HttpServletRequest request, @Valid @RequestBody AnnouncementCreateDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(announcementService.publishAnnouncement(currentUser, dto)); + } + + @GetMapping("/admin/list") + @RequirePermission("announcement:view") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listAdmin(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(announcementService.listAdminAnnouncements(currentUser)); + } + + @GetMapping("/admin/{id}") + @RequirePermission("announcement:view") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result getAdmin(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(announcementService.getAdminAnnouncement(currentUser, id)); + } + + @PutMapping("/admin/{id}/revoke") + @RequirePermission("announcement:delete") + @OperationGuard(action = "announcement-revoke", ttlSeconds = 8, message = "公告撤回处理中,请勿重复操作") + /** + * Run business method `revoke`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result revoke(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(announcementService.revokeAnnouncement(currentUser, id)); + } + + @GetMapping("/admin/target-options") + @RequirePermission("announcement:create") + /** + * Run business method `targetOptions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result targetOptions(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(announcementService.listTargetOptions(currentUser)); + } + + @GetMapping("/my/list") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listMy(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(announcementService.listMyAnnouncements(userId)); + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/BalanceChangeDetailController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/BalanceChangeDetailController.java index d16135a0..4755a668 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/BalanceChangeDetailController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/BalanceChangeDetailController.java @@ -20,7 +20,9 @@ import java.util.List; @RequestMapping({"/balance-change-detail", "/api/balance-change-detail"}) @RequiredArgsConstructor public class BalanceChangeDetailController { - + /** + * Variable `balanceChangeDetailService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final BalanceChangeDetailService balanceChangeDetailService; /** diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/BalanceController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/BalanceController.java index 900ff893..89f2b1b1 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/BalanceController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/BalanceController.java @@ -20,7 +20,9 @@ import java.util.List; @RequestMapping({"/balance", "/api/balance"}) @RequiredArgsConstructor public class BalanceController { - + /** + * Variable `balanceService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final BalanceService balanceService; /** diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/CartController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/CartController.java index f2ffdc25..67e7049e 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/CartController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/CartController.java @@ -14,6 +14,10 @@ import java.util.List; @RestController @RequestMapping("/cart") +/** + * CartController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ public class CartController { @Resource @@ -21,6 +25,13 @@ public class CartController { @PostMapping("/add") @OperationGuard(action = "cart-add", ttlSeconds = 10, message = "购物车处理中,请勿重复操作") + /** + * Add a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param cartDTO parameter `cartDTO` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result addToCart(@RequestBody CartDTO cartDTO, HttpServletRequest request) { Long userId = (Long) request.getAttribute("userId"); cartService.addToCart(userId, cartDTO); @@ -29,6 +40,13 @@ public class CartController { @DeleteMapping("/remove/{productId}") @OperationGuard(action = "cart-remove", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) + /** + * Remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productId parameter `productId` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result removeFromCart(@PathVariable Long productId, HttpServletRequest request) { Long userId = (Long) request.getAttribute("userId"); cartService.removeFromCart(userId, productId); @@ -37,6 +55,13 @@ public class CartController { @PostMapping("/batch-remove") @OperationGuard(action = "cart-batch-remove", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) + /** + * Run business method `batchRemoveFromCart`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param cartItemIds parameter `cartItemIds` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result batchRemoveFromCart(@RequestBody List cartItemIds, HttpServletRequest request) { Long userId = (Long) request.getAttribute("userId"); cartService.batchRemoveFromCart(userId, cartItemIds); @@ -45,6 +70,13 @@ public class CartController { @PutMapping("/update") @OperationGuard(action = "cart-update", ttlSeconds = 10, message = "购物车处理中,请勿重复操作") + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param cartDTO parameter `cartDTO` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result updateCartQuantity(@RequestBody CartDTO cartDTO, HttpServletRequest request) { Long userId = (Long) request.getAttribute("userId"); cartService.updateCartQuantity(userId, cartDTO); @@ -52,6 +84,12 @@ public class CartController { } @GetMapping("/list") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ public Result> getCartList(HttpServletRequest request) { Long userId = (Long) request.getAttribute("userId"); List cartList = cartService.getCartList(userId); @@ -60,6 +98,12 @@ public class CartController { @DeleteMapping("/clear") @OperationGuard(action = "cart-clear", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) + /** + * Run business method `clearCart`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result clearCart(HttpServletRequest request) { Long userId = (Long) request.getAttribute("userId"); cartService.clearCart(userId); diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/CommentController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/CommentController.java index 78a82839..59e46782 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/CommentController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/CommentController.java @@ -21,7 +21,9 @@ import java.util.List; @RequestMapping({"/comment", "/api/comment"}) @RequiredArgsConstructor public class CommentController { - + /** + * Variable `commentService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final CommentService commentService; /** diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/ContactInfoController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/ContactInfoController.java new file mode 100644 index 00000000..f03c9503 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/ContactInfoController.java @@ -0,0 +1,66 @@ +package com.xiaowang.yuminailcore.controller; + +import com.xiaowang.yuminailcore.common.Result; +import com.xiaowang.yuminailcore.service.ContactInfoService; +import com.xiaowang.yuminailcore.vo.ContactInfoVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; + +@RestController +@RequiredArgsConstructor +@RequestMapping({"/contact-info", "/api/contact-info"}) +/** + * ContactInfoController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class ContactInfoController { + /** + * Variable `contactInfoService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ContactInfoService contactInfoService; + + @GetMapping("/shop/{shopId}/manager") + /** + * Run business method `shopManager`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result shopManager(HttpServletRequest request, @PathVariable Long shopId) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(contactInfoService.getShopManagerContact(userId, shopId)); + } + + @GetMapping("/product/{productId}/artist/{artistId}") + /** + * Run business method `productArtist`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param productId parameter `productId` supplied by the caller + * @param artistId parameter `artistId` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result productArtist(HttpServletRequest request, @PathVariable Long productId, @PathVariable Long artistId) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(contactInfoService.getProductArtistContact(userId, productId, artistId)); + } + + @GetMapping("/order/{orderId}/artist") + public Result orderArtist(HttpServletRequest request, @PathVariable Long orderId, @RequestParam(required = false) Long artistId) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(contactInfoService.getOrderArtistContact(userId, orderId, artistId)); + } + + @GetMapping("/platform") + /** + * Run business method `platform`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return Result result consumed by the caller or returned to the frontend + */ + public Result platform() { + return Result.success(contactInfoService.getPlatformContact()); + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/CouponController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/CouponController.java index e7b61b60..8a22ea71 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/CouponController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/CouponController.java @@ -24,9 +24,17 @@ import java.util.List; @RequestMapping("/coupon") @RequiredArgsConstructor public class CouponController { - + /** + * Variable `couponService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final CouponService couponService; + /** + * Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final UserService userService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final AdminScopeHelper adminScopeHelper; /** diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/DashboardController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/DashboardController.java index 21df8f19..7a4701b2 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/DashboardController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/DashboardController.java @@ -38,21 +38,60 @@ import java.util.stream.Collectors; @RestController @RequestMapping("/admin/dashboard") @RequiredArgsConstructor +/** + * DashboardController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ public class DashboardController { - + /** + * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final UserMapper userMapper; + /** + * Variable `productMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final ProductMapper productMapper; + /** + * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final ShopMapper shopMapper; + /** + * Variable `commentMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final CommentMapper commentMapper; + /** + * Variable `orderMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final OrderMapper orderMapper; + /** + * Variable `orderItemMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final OrderItemMapper orderItemMapper; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final AdminScopeHelper adminScopeHelper; + /** + * Variable `userShopBindingSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final UserShopBindingSupport userShopBindingSupport; + /** + * Variable `multiLevelCacheService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final MultiLevelCacheService multiLevelCacheService; + /** + * Variable `appCacheProperties`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final AppCacheProperties appCacheProperties; @GetMapping("/stats") @RequirePermission("dashboard:view") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result getDashboardStats(HttpServletRequest request) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); Long shopIdScope = resolveShopScope(currentUser); @@ -69,6 +108,13 @@ public class DashboardController { return Result.success(stats); } + /** + * Run business method `buildDashboardStats`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param shopIdScope parameter `shopIdScope` supplied by the caller + * @return private DashboardStatsVO result consumed by the caller or returned to the frontend + */ private DashboardStatsVO buildDashboardStats(UserDO currentUser, Long shopIdScope) { DashboardStatsVO stats = new DashboardStatsVO(); @@ -110,6 +156,12 @@ public class DashboardController { return stats; } + /** + * Run business method `resolveShopScope`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ private Long resolveShopScope(UserDO currentUser) { if (currentUser == null || currentUser.getType() == 4) { return null; @@ -117,6 +169,12 @@ public class DashboardController { return currentUser.getShopId(); } + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ private Long getTodayOrders(Long shopId) { // 获取今天的开始时间 LocalDateTime todayStart = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0); @@ -133,6 +191,12 @@ public class DashboardController { } } + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ private List getHotProducts(Long shopId) { // 通过订单商品表统计每个商品的订单数量,按订单数量排序 // 使用SQL查询获取商品及其订单数量 @@ -180,6 +244,12 @@ public class DashboardController { return hotProducts; } + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ private List getRecentActivities(Long shopId) { List activities = new ArrayList<>(); diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/EffectDiagramController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/EffectDiagramController.java index 3779b2fe..9a366373 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/EffectDiagramController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/EffectDiagramController.java @@ -20,7 +20,9 @@ import java.util.List; @RequestMapping({"/effect-diagram", "/api/effect-diagram"}) @RequiredArgsConstructor public class EffectDiagramController { - + /** + * Variable `effectDiagramService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final EffectDiagramService effectDiagramService; /** diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/FrontendFileController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/FrontendFileController.java index c02fc27b..154f0a09 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/FrontendFileController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/FrontendFileController.java @@ -19,9 +19,17 @@ import org.springframework.web.bind.annotation.RestController; @RequestMapping("/file") @RequiredArgsConstructor public class FrontendFileController { - + /** + * Variable `objectStorageFileService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final ObjectStorageFileService objectStorageFileService; + /** + * Variable `minioService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final MinioService minioService; + /** + * Variable `objectStorageUrlSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final ObjectStorageUrlSupport objectStorageUrlSupport; /** diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/HealthController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/HealthController.java index 911fc0b3..ecf16e50 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/HealthController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/HealthController.java @@ -27,10 +27,21 @@ import java.util.Map; @RequestMapping("/health") @RequiredArgsConstructor public class HealthController { - + /** + * Variable `dataSource`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final DataSource dataSource; + /** + * Variable `stringRedisTemplate`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final StringRedisTemplate stringRedisTemplate; + /** + * Variable `discoveryClient`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final DiscoveryClient discoveryClient; + /** + * Variable `environment`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final Environment environment; /** @@ -42,6 +53,11 @@ public class HealthController { } @GetMapping("/diagnostics") + /** + * Run business method `diagnostics`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return Result> result consumed by the caller or returned to the frontend + */ public Result> diagnostics() { Map diagnostics = new LinkedHashMap<>(); diagnostics.put("service", environment.getProperty("spring.application.name", "yumi-nail-core")); @@ -52,6 +68,11 @@ public class HealthController { return Result.success(diagnostics); } + /** + * Run business method `checkDatabase`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private Map result consumed by the caller or returned to the frontend + */ private Map checkDatabase() { Map result = new LinkedHashMap<>(); try (Connection connection = dataSource.getConnection()) { @@ -65,6 +86,11 @@ public class HealthController { return result; } + /** + * Run business method `checkRedis`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private Map result consumed by the caller or returned to the frontend + */ private Map checkRedis() { Map result = new LinkedHashMap<>(); try (RedisConnection connection = stringRedisTemplate.getConnectionFactory().getConnection()) { @@ -77,6 +103,11 @@ public class HealthController { return result; } + /** + * Run business method `checkDiscovery`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private Map result consumed by the caller or returned to the frontend + */ private Map checkDiscovery() { Map result = new LinkedHashMap<>(); try { diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/LegalAgreementController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/LegalAgreementController.java new file mode 100644 index 00000000..d2b53507 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/LegalAgreementController.java @@ -0,0 +1,95 @@ +package com.xiaowang.yuminailcore.controller; + +import com.xiaowang.yuminailcore.annotation.OperationGuard; +import com.xiaowang.yuminailcore.annotation.RequirePermission; +import com.xiaowang.yuminailcore.common.Result; +import com.xiaowang.yuminailcore.dto.LegalAgreementDTO; +import com.xiaowang.yuminailcore.entity.UserDO; +import com.xiaowang.yuminailcore.service.LegalAgreementService; +import com.xiaowang.yuminailcore.service.SecurityAuditLogService; +import com.xiaowang.yuminailcore.support.AdminScopeHelper; +import com.xiaowang.yuminailcore.support.security.RequestThrottleService; +import com.xiaowang.yuminailcore.vo.LegalAgreementVO; +import com.xiaowang.yuminailcore.vo.UserAgreementConsentVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import java.util.List; + +@RestController +@RequiredArgsConstructor +@RequestMapping({"/legal-agreement", "/api/legal-agreement"}) +public class LegalAgreementController { + + private final LegalAgreementService legalAgreementService; + private final AdminScopeHelper adminScopeHelper; + private final SecurityAuditLogService securityAuditLogService; + private final RequestThrottleService requestThrottleService; + + @GetMapping("/current") + public Result> listCurrent(HttpServletRequest request) { + requestThrottleService.checkAgreementRead(request, "ALL"); + return Result.success(legalAgreementService.listCurrentAgreements()); + } + + @GetMapping("/current/{type}") + public Result getCurrent(HttpServletRequest request, @PathVariable String type) { + requestThrottleService.checkAgreementRead(request, type); + return Result.success(legalAgreementService.getCurrentAgreement(type)); + } + + @GetMapping("/admin/list") + @RequirePermission("legal_agreement:manage") + public Result> listAdmin(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(legalAgreementService.listAdminAgreements(currentUser)); + } + + @PostMapping("/admin/create") + @RequirePermission("legal_agreement:manage") + @OperationGuard(action = "legal-agreement-create", ttlSeconds = 8, message = "协议保存处理中,请勿重复提交") + public Result create(HttpServletRequest request, @Valid @RequestBody LegalAgreementDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Long id = legalAgreementService.createAgreement(currentUser, dto); + securityAuditLogService.record(currentUser.getId(), currentUser.getAccount(), "LEGAL_AGREEMENT_CREATE", "SUCCESS", dto.getAgreementType(), request); + return Result.success(id); + } + + @PutMapping("/admin/{id}") + @RequirePermission("legal_agreement:manage") + @OperationGuard(action = "legal-agreement-update", ttlSeconds = 8, message = "协议保存处理中,请勿重复提交") + public Result update(HttpServletRequest request, @PathVariable Long id, @Valid @RequestBody LegalAgreementDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Boolean result = legalAgreementService.updateAgreement(currentUser, id, dto); + securityAuditLogService.record(currentUser.getId(), currentUser.getAccount(), "LEGAL_AGREEMENT_UPDATE", "SUCCESS", String.valueOf(id), request); + return Result.success(result); + } + + @PutMapping("/admin/{id}/publish") + @RequirePermission("legal_agreement:manage") + @OperationGuard(action = "legal-agreement-publish", ttlSeconds = 8, message = "协议发布处理中,请勿重复提交") + public Result publish(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Boolean result = legalAgreementService.publishAgreement(currentUser, id); + securityAuditLogService.record(currentUser.getId(), currentUser.getAccount(), "LEGAL_AGREEMENT_PUBLISH", "SUCCESS", String.valueOf(id), request); + return Result.success(result); + } + + @PutMapping("/admin/{id}/disable") + @RequirePermission("legal_agreement:manage") + @OperationGuard(action = "legal-agreement-disable", ttlSeconds = 8, message = "协议停用处理中,请勿重复提交") + public Result disable(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Boolean result = legalAgreementService.disableAgreement(currentUser, id); + securityAuditLogService.record(currentUser.getId(), currentUser.getAccount(), "LEGAL_AGREEMENT_DISABLE", "SUCCESS", String.valueOf(id), request); + return Result.success(result); + } + + @GetMapping("/user/agreement-consent/me") + public Result getMyConsent(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(legalAgreementService.getMyConsent(userId)); + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/LoginIdentityController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/LoginIdentityController.java index a52586a8..b8e02f8f 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/LoginIdentityController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/LoginIdentityController.java @@ -20,7 +20,9 @@ import java.util.List; @RequestMapping({"/login-identity", "/api/login-identity"}) @RequiredArgsConstructor public class LoginIdentityController { - + /** + * Variable `loginIdentityService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final LoginIdentityService loginIdentityService; /** diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/MessageHubPushConfigController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/MessageHubPushConfigController.java new file mode 100644 index 00000000..d610058f --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/MessageHubPushConfigController.java @@ -0,0 +1,110 @@ +package com.xiaowang.yuminailcore.controller; + +import com.xiaowang.yuminailcore.annotation.OperationGuard; +import com.xiaowang.yuminailcore.annotation.RequirePermission; +import com.xiaowang.yuminailcore.common.Result; +import com.xiaowang.yuminailcore.dto.MessageHubPushConfigDTO; +import com.xiaowang.yuminailcore.dto.MessageHubPushTestDTO; +import com.xiaowang.yuminailcore.entity.UserDO; +import com.xiaowang.yuminailcore.service.MessageHubPushConfigService; +import com.xiaowang.yuminailcore.support.AdminScopeHelper; +import com.xiaowang.yuminailcore.vo.MessageHubPushConfigVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import java.util.List; + +@RestController +@RequiredArgsConstructor +@RequestMapping({"/messagehub-push-config", "/api/messagehub-push-config"}) +/** + * MessageHubPushConfigController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class MessageHubPushConfigController { + /** + * Variable `configService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final MessageHubPushConfigService configService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + + @GetMapping("/admin/list") + @RequirePermission("messagehub:config:manage") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> list(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(configService.listConfigs(currentUser)); + } + + @PostMapping("/admin/create") + @RequirePermission("messagehub:config:manage") + @OperationGuard(action = "messagehub-push-config-create", ttlSeconds = 8, message = "配置保存处理中,请勿重复提交") + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result create(HttpServletRequest request, @Valid @RequestBody MessageHubPushConfigDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(configService.createConfig(currentUser, dto)); + } + + @PutMapping("/admin/{id}") + @RequirePermission("messagehub:config:manage") + @OperationGuard(action = "messagehub-push-config-update", ttlSeconds = 8, message = "配置保存处理中,请勿重复提交") + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result update(HttpServletRequest request, @PathVariable Long id, @Valid @RequestBody MessageHubPushConfigDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(configService.updateConfig(currentUser, id, dto)); + } + + @PutMapping("/admin/{id}/status") + @RequirePermission("messagehub:config:manage") + /** + * Change the enabled/status flag of one record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param enabled parameter `enabled` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result updateStatus(HttpServletRequest request, @PathVariable Long id, @RequestParam Integer enabled) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(configService.updateStatus(currentUser, id, enabled)); + } + + @PostMapping("/admin/{id}/test") + @RequirePermission("messagehub:config:manage") + @OperationGuard(action = "messagehub-push-config-test", ttlSeconds = 8, message = "测试投递处理中,请勿重复提交") + /** + * Run a test call without changing normal business data. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result test(HttpServletRequest request, @PathVariable Long id, @Valid @RequestBody MessageHubPushTestDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(configService.testConfig(currentUser, id, dto)); + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/ObjectStorageFileController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/ObjectStorageFileController.java index e5f4b1ac..317a1cb3 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/ObjectStorageFileController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/ObjectStorageFileController.java @@ -11,6 +11,7 @@ import com.xiaowang.yuminailcore.service.ObjectStorageFileService; import com.xiaowang.yuminailcore.support.ObjectStorageUrlSupport; import com.xiaowang.yuminailcore.support.id.TimeOrderedSnowflakeIdGenerator; import com.xiaowang.yuminailcore.support.security.OperationGuardStrategy; +import com.xiaowang.yuminailcore.support.security.UploadSecurityValidator; import com.xiaowang.yuminailcore.vo.ChunkUploadSessionVO; import com.xiaowang.yuminailcore.vo.ObjectStorageFileVO; import lombok.RequiredArgsConstructor; @@ -39,18 +40,34 @@ import java.util.List; @RequiredArgsConstructor @Validated public class ObjectStorageFileController { - + /** + * Variable `objectStorageFileService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final ObjectStorageFileService objectStorageFileService; + /** + * Variable `minioService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final MinioService minioService; + /** + * Variable `chunkUploadService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final ChunkUploadService chunkUploadService; + /** + * Variable `objectStorageUrlSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final ObjectStorageUrlSupport objectStorageUrlSupport; + /** + * Variable `snowflakeIdGenerator`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; + private final UploadSecurityValidator uploadSecurityValidator; @PostMapping("/upload/init") @OperationGuard(action = "admin-upload-init", ttlSeconds = 10, message = "上传处理中,请勿重复操作") public Result initChunkUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadInitRequestDTO requestDTO) { Long userId = (Long) request.getAttribute("userId"); + uploadSecurityValidator.validateMetadata(requestDTO.getFileName(), requestDTO.getContentType(), requestDTO.getFileSize()); return Result.success(chunkUploadService.initAdminObjectStorageUpload(userId, requestDTO)); } @@ -62,6 +79,7 @@ public class ObjectStorageFileController { @RequestParam("totalChunks") Integer totalChunks, @RequestParam("chunk") MultipartFile chunkFile) { Long userId = (Long) request.getAttribute("userId"); + uploadSecurityValidator.validate(chunkFile); chunkUploadService.uploadAdminObjectStorageChunk(userId, uploadId, chunkIndex, totalChunks, chunkFile); return Result.success(true); } @@ -101,6 +119,13 @@ public class ObjectStorageFileController { @DeleteMapping("/upload/{uploadId}") @OperationGuard(action = "admin-upload-cancel", ttlSeconds = 30, message = "上传处理中,请勿重复操作") + /** + * Run business method `cancelChunkUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result cancelChunkUpload(HttpServletRequest request, @PathVariable String uploadId) { Long userId = (Long) request.getAttribute("userId"); chunkUploadService.clearAdminObjectStorageUpload(userId, uploadId); @@ -114,6 +139,7 @@ public class ObjectStorageFileController { @OperationGuard(action = "admin-upload-direct", ttlSeconds = 30, message = "上传处理中,请勿重复操作") public Result uploadFile(@RequestParam("file") MultipartFile file) { try { + uploadSecurityValidator.validate(file); String originalFilename = file.getOriginalFilename(); String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); String objectName = snowflakeIdGenerator.nextIdString() + fileExtension; @@ -160,6 +186,12 @@ public class ObjectStorageFileController { @PostMapping("/create") @OperationGuard(action = "admin-file-create", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param objectStorageFileDTO parameter `objectStorageFileDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result createObjectStorageFile(@RequestBody ObjectStorageFileDTO objectStorageFileDTO) { Long id = objectStorageFileService.createObjectStorageFile(objectStorageFileDTO); return Result.success(id); @@ -175,24 +207,47 @@ public class ObjectStorageFileController { @DeleteMapping("/delete/{id}") @OperationGuard(action = "admin-file-delete", ttlSeconds = 10, message = "操作处理中,请勿重复提交") + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result deleteObjectStorageFile(@PathVariable Long id) { boolean success = objectStorageFileService.deleteObjectStorageFile(id); return Result.success(success); } @GetMapping("/get/{id}") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result getObjectStorageFileById(@PathVariable Long id) { ObjectStorageFileVO objectStorageFileVO = objectStorageFileService.getObjectStorageFileById(id); return Result.success(objectStorageFileVO); } @GetMapping("/list/all") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return Result> result consumed by the caller or returned to the frontend + */ public Result> listAllObjectStorageFiles() { List objectStorageFileVOs = objectStorageFileService.listAllObjectStorageFiles(); return Result.success(objectStorageFileVOs); } @GetMapping("/list/status/{status}") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param status parameter `status` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ public Result> listObjectStorageFilesByStatus(@PathVariable Integer status) { List objectStorageFileVOs = objectStorageFileService.listObjectStorageFilesByStatus(status); return Result.success(objectStorageFileVOs); diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/OrderController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/OrderController.java index 9795fe42..50f54eda 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/OrderController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/OrderController.java @@ -8,14 +8,20 @@ import com.xiaowang.yuminailcore.service.OrderService; import com.xiaowang.yuminailcore.service.UserService; import com.xiaowang.yuminailcore.vo.OrderVO; import com.xiaowang.yuminailcore.vo.UserVO; +import org.springframework.format.annotation.DateTimeFormat; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; +import java.time.LocalDate; import java.util.List; @RestController @RequestMapping("/order") +/** + * OrderController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ public class OrderController { @Resource @@ -26,6 +32,13 @@ public class OrderController { @PostMapping("/create") @OperationGuard(action = "order-create", ttlSeconds = 15, message = "订单正在提交中,请勿重复点击") + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderDTO parameter `orderDTO` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result createOrder(@RequestBody OrderDTO orderDTO, HttpServletRequest request) { Long userId = (Long) request.getAttribute("userId"); OrderVO orderVO = orderService.createOrder(userId, orderDTO); @@ -33,6 +46,12 @@ public class OrderController { } @GetMapping("/list") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ public Result> getOrderList(HttpServletRequest request) { Long userId = (Long) request.getAttribute("userId"); List orderList = orderService.getOrderList(userId); @@ -40,6 +59,13 @@ public class OrderController { } @GetMapping("/detail/{orderId}") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderId parameter `orderId` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result getOrderDetail(@PathVariable Long orderId, HttpServletRequest request) { Long userId = (Long) request.getAttribute("userId"); OrderVO orderVO = orderService.getOrderDetail(orderId, userId); @@ -48,6 +74,13 @@ public class OrderController { @PutMapping("/cancel/{orderId}") @OperationGuard(action = "order-cancel", ttlSeconds = 15, message = "操作进行中,请勿重复点击") + /** + * Run business method `cancelOrder`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderId parameter `orderId` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result cancelOrder(@PathVariable Long orderId, HttpServletRequest request) { Long userId = (Long) request.getAttribute("userId"); orderService.cancelOrder(orderId, userId); @@ -57,6 +90,12 @@ public class OrderController { // 后台管理接口 @RequirePermission("order:view") @GetMapping("/admin/list") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ public Result> getAllOrders(HttpServletRequest request) { Long userId = (Long) request.getAttribute("userId"); Integer userType = (Integer) request.getAttribute("userType"); @@ -69,6 +108,11 @@ public class OrderController { if (!Integer.valueOf(4).equals(userType) && !Integer.valueOf(3).equals(userType)) { UserVO currentUser = userService.getUserById(userId); if (currentUser == null || currentUser.getShopId() == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("当前账号未绑定店铺"); } orderList = orderList.stream() @@ -81,11 +125,24 @@ public class OrderController { @RequirePermission("order:process") @PutMapping("/admin/process/{orderId}") @OperationGuard(action = "admin-order-process", ttlSeconds = 15, message = "操作处理中,请勿重复提交") + /** + * Run business method `processOrder`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderId parameter `orderId` supplied by the caller + * @param status parameter `status` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result processOrder(@PathVariable Long orderId, @RequestParam Integer status, HttpServletRequest request) { Long userId = (Long) request.getAttribute("userId"); Integer userType = (Integer) request.getAttribute("userType"); if (Integer.valueOf(3).equals(userType)) { if (!Integer.valueOf(2).equals(status)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("美甲师只能完成属于自己的订单"); } orderService.completeArtistOrder(orderId, userId); @@ -94,6 +151,11 @@ public class OrderController { if (!Integer.valueOf(4).equals(userType)) { UserVO currentUser = userService.getUserById(userId); if (currentUser == null || currentUser.getShopId() == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("当前账号未绑定店铺"); } OrderVO orderVO = orderService.getAllOrders().stream() @@ -101,6 +163,11 @@ public class OrderController { .findFirst() .orElse(null); if (orderVO == null || !currentUser.getShopId().equals(orderVO.getShopId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("无权处理其他店铺订单"); } } @@ -111,23 +178,70 @@ public class OrderController { // 美甲师查看自己的订单 @RequirePermission("order:view") @GetMapping("/artist/list") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ public Result> getArtistOrders(HttpServletRequest request) { Long userId = (Long) request.getAttribute("userId"); Integer userType = (Integer) request.getAttribute("userType"); - if (!Integer.valueOf(3).equals(userType)) { + if (!Integer.valueOf(3).equals(userType) && !Integer.valueOf(2).equals(userType)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("仅美甲师可查看自己的订单"); } - List orderList = orderService.getOrdersByArtistId(userId); + List orderList = orderService.getArtistWorkbenchOrders(userId); return Result.success(orderList); } + @RequirePermission("order:view") + @GetMapping("/artist/calendar/recent") + // 调用示例:GET /order/artist/calendar/recent?days=7 + // 只返回当前登录美甲师/参与制作店长自己的预约,前端不用再做二次过滤。 + public Result getArtistCalendarRecent(@RequestParam(value = "days", required = false) Integer days, + HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + Integer userType = (Integer) request.getAttribute("userType"); + return Result.success(orderService.getArtistCalendarRecent(userId, userType, days)); + } + + @RequirePermission("order:view") + @GetMapping("/artist/calendar/day") + // 调用示例:GET /order/artist/calendar/day?date=2026-05-17 + // date 使用 yyyy-MM-dd,适合日历点选某一天后拉取详情。 + public Result getArtistCalendarDay(@RequestParam("date") + @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) + LocalDate date, + HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + Integer userType = (Integer) request.getAttribute("userType"); + return Result.success(orderService.getArtistCalendarDay(userId, userType, date)); + } + @RequirePermission("order:process") @PutMapping("/artist/complete/{orderId}") @OperationGuard(action = "artist-order-complete", ttlSeconds = 15, message = "操作处理中,请勿重复提交") + /** + * Complete a business action. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderId parameter `orderId` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result completeArtistOrder(@PathVariable Long orderId, HttpServletRequest request) { Long userId = (Long) request.getAttribute("userId"); Integer userType = (Integer) request.getAttribute("userType"); - if (!Integer.valueOf(3).equals(userType)) { + if (!Integer.valueOf(3).equals(userType) && !Integer.valueOf(2).equals(userType)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("仅美甲师可完成自己的订单"); } orderService.completeArtistOrder(orderId, userId); diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/PermissionController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/PermissionController.java index 96b27216..ae7c3942 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/PermissionController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/PermissionController.java @@ -26,9 +26,17 @@ import java.util.List; @RequestMapping({"/permission", "/api/permission"}) @RequiredArgsConstructor public class PermissionController { - + /** + * Variable `permissionService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final PermissionService permissionService; + /** + * Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final UserService userService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final AdminScopeHelper adminScopeHelper; /** @@ -128,6 +136,11 @@ public class PermissionController { if (!adminScopeHelper.isPlatformAdmin(currentUser)) { UserDO targetUser = userService.getById(userId); if (targetUser == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("目标用户不存在"); } adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权查看其他店铺用户权限"); @@ -149,6 +162,11 @@ public class PermissionController { if (!adminScopeHelper.isPlatformAdmin(currentUser)) { UserDO targetUser = userService.getById(userPermissionDTO.getUserId()); if (targetUser == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("目标用户不存在"); } adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userPermissionDTO.getUserId(), "无权给其他店铺用户分配权限"); diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/ProductController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/ProductController.java index f44a9281..f9726410 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/ProductController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/ProductController.java @@ -17,13 +17,29 @@ import java.util.List; @RestController @RequestMapping("/product") @RequiredArgsConstructor +/** + * ProductController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ public class ProductController { - + /** + * Variable `productService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final ProductService productService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final AdminScopeHelper adminScopeHelper; @PostMapping("/create") @RequirePermission("product:create") + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param productDTO parameter `productDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result createProduct(HttpServletRequest request, @RequestBody ProductDTO productDTO) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); productDTO.setShopId(adminScopeHelper.resolveShopScope(currentUser, productDTO.getShopId())); @@ -33,6 +49,14 @@ public class ProductController { @PutMapping("/update/{id}") @RequirePermission("product:edit") + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param productDTO parameter `productDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result updateProduct(HttpServletRequest request, @PathVariable Long id, @RequestBody ProductDTO productDTO) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); ProductVO productVO = productService.getProductById(id); @@ -48,6 +72,13 @@ public class ProductController { @DeleteMapping("/delete/{id}") @RequirePermission("product:delete") + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result deleteProduct(HttpServletRequest request, @PathVariable Long id) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); ProductVO productVO = productService.getProductById(id); @@ -60,24 +91,47 @@ public class ProductController { } @GetMapping("/get/{id}") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result getProductById(@PathVariable Long id) { ProductVO productVO = productService.getProductById(id); return Result.success(productVO); } @GetMapping("/list/all") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return Result> result consumed by the caller or returned to the frontend + */ public Result> listAllProducts() { List productVOs = productService.listAllProducts(); return Result.success(productVOs); } @GetMapping("/list/shop/{shopId}") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ public Result> listProductsByShopId(@PathVariable Long shopId) { List productVOs = productService.listProductsByShopId(shopId); return Result.success(productVOs); } @GetMapping("/list/tag/{tag}") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tag parameter `tag` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ public Result> listProductsByTag(@PathVariable String tag) { List productVOs = productService.listProductsByTag(tag); return Result.success(productVOs); diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/ProductLikeController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/ProductLikeController.java index fc5edad8..87cbf19e 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/ProductLikeController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/ProductLikeController.java @@ -17,7 +17,9 @@ import org.springframework.web.bind.annotation.*; @RequestMapping("/product-like") @RequiredArgsConstructor public class ProductLikeController { - + /** + * Variable `productLikeService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final ProductLikeService productLikeService; /** diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/ShopController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/ShopController.java index 81c4dd8f..44cef7d7 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/ShopController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/ShopController.java @@ -19,13 +19,29 @@ import java.util.stream.Collectors; @RestController @RequestMapping("/shop") @RequiredArgsConstructor +/** + * ShopController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ public class ShopController { - + /** + * Variable `shopService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final ShopService shopService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final AdminScopeHelper adminScopeHelper; @PostMapping("/create") @RequirePermission("shop:create") + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param shopDTO parameter `shopDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result createShop(HttpServletRequest request, @RequestBody ShopDTO shopDTO) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); adminScopeHelper.requirePlatformAdmin(currentUser, "鍙湁骞冲彴绠$悊鍛樺彲浠ュ垱寤哄簵閾?"); @@ -35,6 +51,14 @@ public class ShopController { @PutMapping("/update/{id}") @RequirePermission("shop:edit") + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param shopDTO parameter `shopDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result updateShop(HttpServletRequest request, @PathVariable Long id, @RequestBody ShopDTO shopDTO) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); ShopVO shopVO = shopService.getShopById(id); @@ -42,12 +66,22 @@ public class ShopController { return Result.success(false); } adminScopeHelper.ensureShopAccessible(currentUser, shopVO.getId(), "无权编辑其他店铺信息"); + if (!adminScopeHelper.isPlatformAdmin(currentUser)) { + shopDTO.setAuthorizationExpireTime(shopVO.getAuthorizationExpireTime()); + } boolean success = shopService.updateShop(id, shopDTO); return Result.success(success); } @DeleteMapping("/delete/{id}") @RequirePermission("shop:delete") + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result deleteShop(HttpServletRequest request, @PathVariable Long id) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); adminScopeHelper.requirePlatformAdmin(currentUser, "鍙湁骞冲彴绠$悊鍛樺彲浠ュ垹闄ゅ簵閾?"); @@ -57,6 +91,14 @@ public class ShopController { @PutMapping("/status/{id}") @RequirePermission("shop:edit") + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param statusRequest parameter `statusRequest` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result updateShopStatus(HttpServletRequest request, @PathVariable Long id, @RequestBody StatusRequest statusRequest) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以启停店铺"); @@ -65,6 +107,12 @@ public class ShopController { } @GetMapping("/get/{id}") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result getShopById(@PathVariable Long id) { ShopVO shopVO = shopService.getShopById(id); return Result.success(shopVO); @@ -72,6 +120,12 @@ public class ShopController { @GetMapping("/list/all") @RequirePermission("shop:view") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ public Result> listAllShops(HttpServletRequest request) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); List shopVOs; @@ -85,12 +139,23 @@ public class ShopController { } @GetMapping("/list/shopName/{shopName}") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopName parameter `shopName` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ public Result> listShopsByShopName(@PathVariable String shopName) { List shopVOs = shopService.listShopsByShopName(shopName); return Result.success(shopVOs); } @GetMapping("/list/simple") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return Result> result consumed by the caller or returned to the frontend + */ public Result> listShopsSimple() { List shopVOs = shopService.listAllShops(); List simpleVOs = shopVOs.stream() @@ -100,6 +165,11 @@ public class ShopController { } @GetMapping("/list/public") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return Result> result consumed by the caller or returned to the frontend + */ public Result> listPublicShops() { return Result.success(shopService.listAllShops()); } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/SystemMessageController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/SystemMessageController.java new file mode 100644 index 00000000..eff2a0ff --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/SystemMessageController.java @@ -0,0 +1,181 @@ +package com.xiaowang.yuminailcore.controller; + +import com.xiaowang.yuminailcore.annotation.OperationGuard; +import com.xiaowang.yuminailcore.annotation.RequirePermission; +import com.xiaowang.yuminailcore.common.Result; +import com.xiaowang.yuminailcore.dto.SystemMessageCreateDTO; +import com.xiaowang.yuminailcore.entity.UserDO; +import com.xiaowang.yuminailcore.service.SystemMessageService; +import com.xiaowang.yuminailcore.support.AdminScopeHelper; +import com.xiaowang.yuminailcore.vo.MessageTargetOptionsVO; +import com.xiaowang.yuminailcore.vo.MessageUnreadCountVO; +import com.xiaowang.yuminailcore.vo.SystemMessageVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import java.util.List; + +@RestController +@RequiredArgsConstructor +@RequestMapping({"/system-message", "/api/system-message"}) +/** + * SystemMessageController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class SystemMessageController { + /** + * Variable `systemMessageService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final SystemMessageService systemMessageService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + + @PostMapping("/admin/create") + @RequirePermission("message:create") + @OperationGuard(action = "system-message-create", ttlSeconds = 8, message = "消息发布处理中,请勿重复提交") + /** + * Run business method `publish`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result publish(HttpServletRequest request, @Valid @RequestBody SystemMessageCreateDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(systemMessageService.publishMessage(currentUser, dto)); + } + + @GetMapping("/admin/list") + @RequirePermission("message:view") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listAdminMessages(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(systemMessageService.listAdminMessages(currentUser)); + } + + @GetMapping("/admin/{id}") + @RequirePermission("message:view") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result getAdminMessage(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(systemMessageService.getAdminMessage(currentUser, id)); + } + + @PutMapping("/admin/{id}/revoke") + @RequirePermission("message:delete") + @OperationGuard(action = "system-message-revoke", ttlSeconds = 8, message = "消息撤回处理中,请勿重复操作") + /** + * Run business method `revoke`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result revoke(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(systemMessageService.revokeMessage(currentUser, id)); + } + + @GetMapping("/admin/target-options") + @RequirePermission("message:create") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result listTargetOptions(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(systemMessageService.listTargetOptions(currentUser)); + } + + @GetMapping("/my/list") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listMyMessages(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(systemMessageService.listMyMessages(userId)); + } + + @GetMapping("/my/popup") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listMyPopupMessages(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(systemMessageService.listMyPopupMessages(userId)); + } + + @GetMapping("/my/unread-count") + /** + * Run business method `countMyUnreadMessages`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result countMyUnreadMessages(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(new MessageUnreadCountVO(systemMessageService.countMyUnreadMessages(userId))); + } + + @GetMapping("/my/{id}") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result getMyMessage(HttpServletRequest request, @PathVariable Long id) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(systemMessageService.getMyMessage(userId, id)); + } + + @PutMapping("/my/{id}/popup-shown") + /** + * Mark user state such as read or popup shown. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result markPopupShown(HttpServletRequest request, @PathVariable Long id) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(systemMessageService.markPopupShown(userId, id)); + } + + @PutMapping("/my/{id}/read") + /** + * Mark user state such as read or popup shown. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result markRead(HttpServletRequest request, @PathVariable Long id) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(systemMessageService.markRead(userId, id)); + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/SystemParameterConfigController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/SystemParameterConfigController.java new file mode 100644 index 00000000..4b7711dc --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/SystemParameterConfigController.java @@ -0,0 +1,52 @@ +package com.xiaowang.yuminailcore.controller; + +import com.xiaowang.yuminailcore.annotation.OperationGuard; +import com.xiaowang.yuminailcore.annotation.RequirePermission; +import com.xiaowang.yuminailcore.common.Result; +import com.xiaowang.yuminailcore.dto.SystemParameterConfigDTO; +import com.xiaowang.yuminailcore.entity.UserDO; +import com.xiaowang.yuminailcore.service.SystemParameterConfigService; +import com.xiaowang.yuminailcore.support.AdminScopeHelper; +import com.xiaowang.yuminailcore.vo.SystemParameterConfigVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@RestController +@RequiredArgsConstructor +@RequestMapping({"/system-parameter-config", "/api/system-parameter-config"}) +public class SystemParameterConfigController { + + private final SystemParameterConfigService configService; + private final AdminScopeHelper adminScopeHelper; + + @GetMapping("/admin/list") + @RequirePermission("messagehub:config:manage") + public Result> list(HttpServletRequest request, + @RequestParam(required = false) String configGroup) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(configService.listConfigs(currentUser, configGroup)); + } + + @PostMapping("/admin/save") + @RequirePermission("messagehub:config:manage") + @OperationGuard(action = "system-parameter-config-save", ttlSeconds = 8, message = "系统参数保存处理中,请勿重复提交") + public Result save(HttpServletRequest request, @Valid @RequestBody SystemParameterConfigDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(configService.saveConfig(currentUser, dto)); + } + + @GetMapping("/admin/tencent-map") + @RequirePermission("messagehub:config:manage") + public Result> getTencentMapKey(HttpServletRequest request) { + adminScopeHelper.getCurrentUser(request); + Map result = new HashMap<>(); + result.put("key", configService.getEnabledValue("MAP", "TENCENT_MAP_KEY")); + return Result.success(result); + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/TagController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/TagController.java index d0ed2f2f..4d6a36c4 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/TagController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/TagController.java @@ -24,8 +24,13 @@ import java.util.List; @RequestMapping("/tag") @RequiredArgsConstructor public class TagController { - + /** + * Variable `tagService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final TagService tagService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final AdminScopeHelper adminScopeHelper; /** diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/UserController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/UserController.java index 014fec14..fdad2d1e 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/UserController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/UserController.java @@ -11,12 +11,20 @@ import com.xiaowang.yuminailcore.support.AdminScopeHelper; import com.xiaowang.yuminailcore.vo.ChunkUploadSessionVO; import com.xiaowang.yuminailcore.vo.LoginShopSelectionVO; import com.xiaowang.yuminailcore.vo.LoginResponseVO; +import com.xiaowang.yuminailcore.vo.BalanceChangeDetailVO; +import com.xiaowang.yuminailcore.vo.UserAssetVO; +import com.xiaowang.yuminailcore.vo.UserRelationVO; import com.xiaowang.yuminailcore.vo.UserVO; +import com.xiaowang.yuminailcore.vo.InviteCodeVO; import com.xiaowang.yuminailcore.vo.WechatMiniLoginResultVO; import com.xiaowang.yuminailcore.service.MinioService; +import com.xiaowang.yuminailcore.service.UserAssetService; import com.xiaowang.yuminailcore.service.UserService; +import com.xiaowang.yuminailcore.service.ShopRoleService; import com.xiaowang.yuminailcore.service.VerificationCodeService; import com.xiaowang.yuminailcore.service.WechatMiniAuthService; +import com.xiaowang.yuminailcore.service.LegalAgreementService; +import com.xiaowang.yuminailcore.service.SecurityAuditLogService; import com.xiaowang.yuminailcore.support.id.TimeOrderedSnowflakeIdGenerator; import com.xiaowang.yuminailcore.support.ObjectStorageUrlSupport; import com.xiaowang.yuminailcore.support.security.RequestThrottleService; @@ -44,17 +52,56 @@ import java.util.stream.Collectors; @RequestMapping("/user") @RequiredArgsConstructor public class UserController { - + /** + * Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final UserService userService; + /** + * Variable `userAssetService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserAssetService userAssetService; + /** + * Variable `minioService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final MinioService minioService; + /** + * Variable `chunkUploadService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final ChunkUploadService chunkUploadService; + /** + * Variable `verificationCodeService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final VerificationCodeService verificationCodeService; + /** + * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final UserMapper userMapper; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final AdminScopeHelper adminScopeHelper; + /** + * Variable `shopRoleService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopRoleService shopRoleService; + /** + * Variable `snowflakeIdGenerator`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; + /** + * Variable `wechatMiniAuthService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final WechatMiniAuthService wechatMiniAuthService; + /** + * Variable `objectStorageUrlSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final ObjectStorageUrlSupport objectStorageUrlSupport; + /** + * Variable `requestThrottleService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final RequestThrottleService requestThrottleService; + private final LegalAgreementService legalAgreementService; + private final SecurityAuditLogService securityAuditLogService; /** * 创建用户 @@ -115,6 +162,11 @@ public class UserController { adminScopeHelper.requirePlatformAdmin(currentUser, "仅系统管理员可以删除用户"); UserVO targetUser = requireAccessibleUser(currentUser, id, "无权删除其他店铺用户"); if (Integer.valueOf(4).equals(targetUser.getType())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("管理员账号不允许删除"); } boolean success = userService.deleteUser(id); @@ -124,17 +176,53 @@ public class UserController { @PutMapping("/unbind/{id}") @RequirePermission("user:unbind") @OperationGuard(action = "admin-user-unbind", ttlSeconds = 10, message = "操作进行中,请勿重复点击") + /** + * Run business method `unbindUser`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result unbindUser(HttpServletRequest request, @PathVariable Long id) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); UserVO targetUser = requireAccessibleUser(currentUser, id, "无权解绑其他店铺用户"); adminScopeHelper.ensureAssignableUserType(currentUser, targetUser.getType()); if (Integer.valueOf(4).equals(targetUser.getType())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("管理员账号不允许解绑"); } boolean success = userService.unbindUserInShopWithOperator(id, currentUser.getShopId(), currentUser.getType()); return Result.success(success); } + @GetMapping("/asset/me") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result getMyAsset(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(userAssetService.getUserAsset(userId)); + } + + @GetMapping("/balance/history/me") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> getMyBalanceHistory(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(userAssetService.listBalanceHistory(userId)); + } + /** * 根据ID查询用户 * @@ -188,6 +276,11 @@ public class UserController { @GetMapping("/list/type/{type}") public Result> listUsersByType(@PathVariable Integer type) { if (!Integer.valueOf(3).equals(type)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("仅支持查询可预约的美甲师列表"); } List userVOs = userService.listUsersByType(type).stream() @@ -215,6 +308,12 @@ public class UserController { } @GetMapping("/check/account/{account}") + /** + * Run business method `checkAccountAvailability`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param account parameter `account` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result checkAccountAvailability(@PathVariable String account) { String normalizedAccount = AccountValidationUtils.requireValidAccount(account); UserDO userDO = userMapper.selectOne( @@ -227,6 +326,12 @@ public class UserController { } @GetMapping("/check/login-account/{account}") + /** + * Run business method `checkLoginAccountAvailability`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param account parameter `account` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result checkLoginAccountAvailability(@PathVariable String account) { String normalizedAccount = AccountValidationUtils.requireValidAccount(account); UserDO userDO = userMapper.selectOne( @@ -244,16 +349,34 @@ public class UserController { } @GetMapping("/check/login-shops/account/{account}") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param account parameter `account` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result getLoginShopsByAccount(@PathVariable String account) { return Result.success(userService.getLoginShopSelectionByAccount(AccountValidationUtils.requireValidAccount(account))); } @GetMapping("/check/login-shops/phone/{phone}") + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result getLoginShopsByPhone(@PathVariable String phone) { return Result.success(userService.getLoginShopSelectionByPhone(phone)); } @GetMapping("/check/phone/{phone}") + /** + * Run business method `checkPhoneAvailability`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result checkPhoneAvailability(@PathVariable String phone) { UserDO userDO = userMapper.selectOne( com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class) @@ -275,8 +398,18 @@ public class UserController { @OperationGuard(action = "user-login", ttlSeconds = 8, message = "登录处理中,请勿重复提交") public Result login(HttpServletRequest request, @Valid @RequestBody LoginRequestDTO loginRequestDTO) { requestThrottleService.checkLogin(request, loginRequestDTO.getAccount()); - LoginResponseVO loginResponseVO = userService.login(loginRequestDTO); - return Result.success(loginResponseVO); + legalAgreementService.requireAccepted(loginRequestDTO); + try { + LoginResponseVO loginResponseVO = userService.login(loginRequestDTO); + legalAgreementService.recordConsent(loginResponseVO.getUserInfo().getId(), loginRequestDTO, "USER_PASSWORD_LOGIN", request); + requestThrottleService.clearLoginFailure(request, loginRequestDTO.getAccount()); + securityAuditLogService.record(loginResponseVO.getUserInfo().getId(), loginRequestDTO.getAccount(), "USER_LOGIN", "SUCCESS", null, request); + return Result.success(loginResponseVO); + } catch (RuntimeException exception) { + requestThrottleService.recordLoginFailure(request, loginRequestDTO.getAccount()); + securityAuditLogService.record(null, loginRequestDTO.getAccount(), "USER_LOGIN", "FAIL", exception.getMessage(), request); + throw exception; + } } /** @@ -289,30 +422,73 @@ public class UserController { @OperationGuard(action = "user-phone-login", ttlSeconds = 8, message = "登录处理中,请勿重复提交") public Result phoneLogin(HttpServletRequest request, @RequestBody PhoneLoginRequestDTO phoneLoginRequestDTO) { requestThrottleService.checkLogin(request, phoneLoginRequestDTO.getPhone()); - LoginResponseVO loginResponseVO = userService.phoneLogin(phoneLoginRequestDTO); - return Result.success(loginResponseVO); + legalAgreementService.requireAccepted(phoneLoginRequestDTO); + try { + LoginResponseVO loginResponseVO = userService.phoneLogin(phoneLoginRequestDTO); + legalAgreementService.recordConsent(loginResponseVO.getUserInfo().getId(), phoneLoginRequestDTO, "USER_PHONE_LOGIN", request); + requestThrottleService.clearLoginFailure(request, phoneLoginRequestDTO.getPhone()); + securityAuditLogService.record(loginResponseVO.getUserInfo().getId(), phoneLoginRequestDTO.getPhone(), "USER_PHONE_LOGIN", "SUCCESS", null, request); + return Result.success(loginResponseVO); + } catch (RuntimeException exception) { + requestThrottleService.recordLoginFailure(request, phoneLoginRequestDTO.getPhone()); + securityAuditLogService.record(null, phoneLoginRequestDTO.getPhone(), "USER_PHONE_LOGIN", "FAIL", exception.getMessage(), request); + throw exception; + } } @PostMapping("/wechat-mini/auto-login") @OperationGuard(action = "wechat-mini-auto-login", ttlSeconds = 8, message = "登录处理中,请勿重复提交") + /** + * Run business method `wechatMiniAutoLogin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result wechatMiniAutoLogin(@Valid @RequestBody WechatMiniAutoLoginRequestDTO requestDTO) { return Result.success(wechatMiniAuthService.autoLogin(requestDTO)); } @PostMapping("/wechat-mini/phone-login") @OperationGuard(action = "wechat-mini-phone-login", ttlSeconds = 8, message = "登录处理中,请勿重复提交") - public Result wechatMiniPhoneLogin(@Valid @RequestBody WechatMiniPhoneLoginRequestDTO requestDTO) { - return Result.success(wechatMiniAuthService.phoneLogin(requestDTO)); + /** + * Run business method `wechatMiniPhoneLogin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result wechatMiniPhoneLogin(HttpServletRequest request, @Valid @RequestBody WechatMiniPhoneLoginRequestDTO requestDTO) { + requestThrottleService.checkWechatMiniLogin(request, "wechat-mini-phone"); + legalAgreementService.requireAccepted(requestDTO); + WechatMiniLoginResultVO result = wechatMiniAuthService.phoneLogin(requestDTO); + recordWechatConsentIfLoggedIn(result, requestDTO, "WECHAT_MINI_PHONE_LOGIN", request); + return Result.success(result); } @PostMapping("/wechat-mini/confirm-login") @OperationGuard(action = "wechat-mini-confirm-login", ttlSeconds = 8, message = "登录处理中,请勿重复提交") - public Result confirmWechatMiniLogin(@Valid @RequestBody WechatMiniConfirmLoginRequestDTO requestDTO) { - return Result.success(wechatMiniAuthService.confirmLogin(requestDTO)); + /** + * Run business method `confirmWechatMiniLogin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result confirmWechatMiniLogin(HttpServletRequest request, @Valid @RequestBody WechatMiniConfirmLoginRequestDTO requestDTO) { + requestThrottleService.checkWechatMiniLogin(request, requestDTO.getTicket()); + legalAgreementService.requireAccepted(requestDTO); + WechatMiniLoginResultVO result = wechatMiniAuthService.confirmLogin(requestDTO); + recordWechatConsentIfLoggedIn(result, requestDTO, "WECHAT_MINI_CONFIRM_LOGIN", request); + return Result.success(result); } @PostMapping("/switch-shop") @OperationGuard(action = "user-switch-shop", ttlSeconds = 10, message = "门店切换中,请勿重复操作") + /** + * Run business method `switchShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param switchShopRequestDTO parameter `switchShopRequestDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result switchShop(HttpServletRequest request, @RequestBody SwitchShopRequestDTO switchShopRequestDTO) { Long userId = (Long) request.getAttribute("userId"); return Result.success(userService.switchShop(userId, switchShopRequestDTO.getShopId(), (String) request.getAttribute("sessionId"))); @@ -326,9 +502,49 @@ public class UserController { */ @PostMapping("/register") @OperationGuard(action = "user-register", ttlSeconds = 8, message = "登录处理中,请勿重复提交") - public Result register(@Valid @RequestBody RegisterRequestDTO registerRequestDTO) { - boolean success = userService.register(registerRequestDTO); - return Result.success(success); + public Result register(HttpServletRequest request, @Valid @RequestBody RegisterRequestDTO registerRequestDTO) { + requestThrottleService.checkRegister(request, registerRequestDTO.getAccount()); + legalAgreementService.requireAccepted(registerRequestDTO); + try { + boolean success = userService.register(registerRequestDTO); + UserDO userDO = userMapper.selectOne( + com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getAccount, AccountValidationUtils.requireValidAccount(registerRequestDTO.getAccount())) + .eq(UserDO::getIsDelete, 0) + .last("limit 1") + ); + if (userDO != null) { + legalAgreementService.recordConsent(userDO.getId(), registerRequestDTO, "USER_REGISTER", request); + securityAuditLogService.record(userDO.getId(), userDO.getAccount(), "USER_REGISTER", "SUCCESS", null, request); + } + return Result.success(success); + } catch (RuntimeException exception) { + securityAuditLogService.record(null, registerRequestDTO.getAccount(), "USER_REGISTER", "FAIL", exception.getMessage(), request); + throw exception; + } + } + + @GetMapping("/relation/me") + /** + * Run business method `relationMe`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result relationMe(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(userService.getCurrentUserRelation(userId)); + } + + @GetMapping("/invite-code/resolve") + /** + * Run business method `resolveInviteCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param code parameter `code` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result resolveInviteCode(@RequestParam String code) { + return Result.success(shopRoleService.resolveInviteCode(code)); } /** @@ -342,9 +558,15 @@ public class UserController { public Result sendVerificationCode(HttpServletRequest request, @RequestBody SendVerificationCodeRequestDTO sendVerificationCodeRequestDTO) { requestThrottleService.checkSendCode(request, sendVerificationCodeRequestDTO.getPhone()); if (!verificationCodeService.canResend(sendVerificationCodeRequestDTO.getPhone())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param 1 parameter `1` supplied by the caller + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("验证码发送过于频繁,请1分钟后再试"); } - verificationCodeService.sendVerificationCode(sendVerificationCodeRequestDTO.getPhone()); + verificationCodeService.sendVerificationCode(sendVerificationCodeRequestDTO.getPhone(), sendVerificationCodeRequestDTO.getSceneCode()); return Result.success(true); } @@ -359,6 +581,7 @@ public class UserController { public Result resetPasswordByPhone(HttpServletRequest request, @RequestBody ResetPasswordRequestDTO resetPasswordRequestDTO) { requestThrottleService.checkResetPassword(request, resetPasswordRequestDTO.getPhone()); boolean success = userService.resetPasswordByPhone(resetPasswordRequestDTO); + securityAuditLogService.record(null, resetPasswordRequestDTO.getPhone(), "RESET_PASSWORD_BY_PHONE", success ? "SUCCESS" : "FAIL", null, request); return Result.success(success); } @@ -386,6 +609,22 @@ public class UserController { return Result.success(success); } + @GetMapping("/agreement-consent/me") + public Result getMyAgreementConsent(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(legalAgreementService.getMyConsent(userId)); + } + + private void recordWechatConsentIfLoggedIn(WechatMiniLoginResultVO result, + com.xiaowang.yuminailcore.dto.AgreementAwareRequest dto, + String entry, + HttpServletRequest request) { + if (result != null && result.getUserInfo() != null) { + legalAgreementService.recordConsent(result.getUserInfo().getId(), dto, entry, request); + securityAuditLogService.record(result.getUserInfo().getId(), null, entry, "SUCCESS", null, request); + } + } + /** * 获取当前用户信息 * @@ -467,6 +706,13 @@ public class UserController { @PostMapping("/upload-avatar/complete") @OperationGuard(action = "user-avatar-upload-complete", ttlSeconds = 30, message = "上传处理中,请勿重复操作") + /** + * Complete a business action. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result completeAvatarUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadCompleteRequestDTO requestDTO) { Long userId = (Long) request.getAttribute("userId"); try (ChunkUploadService.PreparedUploadFile preparedUploadFile = @@ -488,6 +734,13 @@ public class UserController { @DeleteMapping("/upload-avatar/{uploadId}") @OperationGuard(action = "user-avatar-upload-cancel", ttlSeconds = 30, message = "上传处理中,请勿重复操作") + /** + * Run business method `cancelAvatarUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ public Result cancelAvatarUpload(HttpServletRequest request, @PathVariable String uploadId) { Long userId = (Long) request.getAttribute("userId"); chunkUploadService.clearUserAvatarUpload(userId, uploadId); @@ -524,6 +777,13 @@ public class UserController { @OperationGuard(action = "admin-user-reset-password", ttlSeconds = 10, message = "操作进行中,请勿重复点击") public Result resetPassword(HttpServletRequest request, @PathVariable Long userId) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); + /** + * Run business method `requireAccessibleUser`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ requireAccessibleUser(currentUser, userId, "无权重置其他店铺用户密码"); Long currentUserId = (Long) request.getAttribute("userId"); boolean success = userService.resetPassword(userId, currentUserId); @@ -586,15 +846,34 @@ public class UserController { return Result.success(success); } + /** + * Run business method `requireAccessibleUser`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @param message parameter `message` supplied by the caller + * @return private UserVO result consumed by the caller or returned to the frontend + */ private UserVO requireAccessibleUser(UserDO currentUser, Long userId, String message) { UserVO targetUser = userService.getUserById(userId); if (targetUser == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("目标用户不存在"); } adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, message); return targetUser; } + /** + * Run business method `sanitizePublicArtist`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userVO parameter `userVO` supplied by the caller + * @return private UserVO result consumed by the caller or returned to the frontend + */ private UserVO sanitizePublicArtist(UserVO userVO) { UserVO sanitized = new UserVO(); sanitized.setId(userVO.getId()); @@ -619,14 +898,29 @@ public class UserController { @Data public static class AvailabilityVO { + /** + * Variable `available`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final boolean available; + /** + * Variable `message`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final String message; } @Data public static class LoginAccountAvailabilityVO { + /** + * Variable `exists`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final boolean exists; + /** + * Variable `nickname`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final String nickname; + /** + * Variable `message`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final String message; } } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/VipBenefitController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/VipBenefitController.java index 350c36e7..cca83162 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/VipBenefitController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/VipBenefitController.java @@ -20,7 +20,9 @@ import java.util.List; @RequestMapping({"/vip-benefit", "/api/vip-benefit"}) @RequiredArgsConstructor public class VipBenefitController { - + /** + * Variable `vipBenefitService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final VipBenefitService vipBenefitService; /** diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/VipInfoController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/VipInfoController.java index b1a65142..81b9e3f4 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/VipInfoController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/VipInfoController.java @@ -20,7 +20,9 @@ import java.util.List; @RequestMapping({"/vip-info", "/api/vip-info"}) @RequiredArgsConstructor public class VipInfoController { - + /** + * Variable `vipInfoService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final VipInfoService vipInfoService; /** diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/VipRechargePlanController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/VipRechargePlanController.java new file mode 100644 index 00000000..05335f27 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/VipRechargePlanController.java @@ -0,0 +1,99 @@ +package com.xiaowang.yuminailcore.controller; + +import com.xiaowang.yuminailcore.annotation.OperationGuard; +import com.xiaowang.yuminailcore.annotation.RequirePermission; +import com.xiaowang.yuminailcore.common.Result; +import com.xiaowang.yuminailcore.dto.VipRechargePlanDTO; +import com.xiaowang.yuminailcore.entity.UserDO; +import com.xiaowang.yuminailcore.service.VipRechargePlanService; +import com.xiaowang.yuminailcore.support.AdminScopeHelper; +import com.xiaowang.yuminailcore.vo.VipRechargePlanVO; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; +import java.util.List; + +@RestController +@RequiredArgsConstructor +@RequestMapping({"/vip-recharge-plan", "/api/vip-recharge-plan"}) +/** + * VipRechargePlanController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class VipRechargePlanController { + /** + * Variable `vipRechargePlanService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final VipRechargePlanService vipRechargePlanService; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + + @GetMapping("/admin/list") + @RequirePermission("user:vip:manage") + public Result> listAdmin(HttpServletRequest request, @RequestParam(required = false) Long shopId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(vipRechargePlanService.listAdminPlans(currentUser, shopId)); + } + + @PostMapping("/admin/create") + @RequirePermission("user:vip:manage") + @OperationGuard(action = "vip-recharge-plan-create", ttlSeconds = 8, message = "充值档位保存处理中,请勿重复提交") + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result create(HttpServletRequest request, @Valid @RequestBody VipRechargePlanDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(vipRechargePlanService.createPlan(currentUser, dto)); + } + + @PutMapping("/admin/{id}") + @RequirePermission("user:vip:manage") + @OperationGuard(action = "vip-recharge-plan-update", ttlSeconds = 8, message = "充值档位保存处理中,请勿重复提交") + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result update(HttpServletRequest request, @PathVariable Long id, @Valid @RequestBody VipRechargePlanDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(vipRechargePlanService.updatePlan(currentUser, id, dto)); + } + + @PutMapping("/admin/{id}/status") + @RequirePermission("user:vip:manage") + /** + * Change the enabled/status flag of one record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param status parameter `status` supplied by the caller + * @return Result result consumed by the caller or returned to the frontend + */ + public Result updateStatus(HttpServletRequest request, @PathVariable Long id, @RequestParam Integer status) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(vipRechargePlanService.updateStatus(currentUser, id, status)); + } + + @GetMapping("/my/list") + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller + * @return Result> result consumed by the caller or returned to the frontend + */ + public Result> listMy(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(vipRechargePlanService.listMyPlans(userId)); + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/WishlistController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/WishlistController.java index 00316f83..136a0853 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/WishlistController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/WishlistController.java @@ -13,6 +13,10 @@ import java.util.Map; @RestController @RequestMapping("/wishlist") +/** + * WishlistController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ public class WishlistController { @Autowired diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/AdminUserBalanceChangeDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/AdminUserBalanceChangeDTO.java index e2757c20..edbf60f0 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/AdminUserBalanceChangeDTO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/AdminUserBalanceChangeDTO.java @@ -5,15 +5,34 @@ import lombok.Data; import java.math.BigDecimal; @Data +/** + * AdminUserBalanceChangeDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ public class AdminUserBalanceChangeDTO { + /** + * Field `amount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private BigDecimal amount; + /** + * Field `changeScene` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String changeScene; + /** + * Field `relatedOrderId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long relatedOrderId; + /** + * Field `externalOrderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String externalOrderNo; + /** + * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String remark; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/AdminUserVipOverrideDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/AdminUserVipOverrideDTO.java index 4024c170..b3446e85 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/AdminUserVipOverrideDTO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/AdminUserVipOverrideDTO.java @@ -3,9 +3,19 @@ package com.xiaowang.yuminailcore.dto; import lombok.Data; @Data +/** + * AdminUserVipOverrideDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ public class AdminUserVipOverrideDTO { + /** + * Field `vipLevel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String vipLevel; + /** + * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String remark; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/AgreementAwareRequest.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/AgreementAwareRequest.java new file mode 100644 index 00000000..b9308d49 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/AgreementAwareRequest.java @@ -0,0 +1,12 @@ +package com.xiaowang.yuminailcore.dto; + +import java.util.Map; + +public interface AgreementAwareRequest { + + Boolean getAgreementAccepted(); + + Map getAgreementVersions(); + + String getClientType(); +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/AnnouncementCreateDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/AnnouncementCreateDTO.java new file mode 100644 index 00000000..750de88d --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/AnnouncementCreateDTO.java @@ -0,0 +1,50 @@ +package com.xiaowang.yuminailcore.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; +import java.util.List; + +@Data +/** + * AnnouncementCreateDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class AnnouncementCreateDTO { + + @NotBlank(message = "公告标题不能为空") + @Size(max = 100, message = "公告标题不能超过100个字符") + /** + * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String title; + + @NotBlank(message = "公告内容不能为空") + @Size(max = 1000, message = "公告内容不能超过1000个字符") + /** + * Field `content` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String content; + + @NotBlank(message = "公告范围不能为空") + /** + * Field `targetType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String targetType; + + /** + * Field `shopIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List shopIds; + + /** + * Field `userIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List userIds; + + /** + * Field `sortOrder` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer sortOrder = 0; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/BalanceChangeDetailDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/BalanceChangeDetailDTO.java index c57901ce..ca6e827b 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/BalanceChangeDetailDTO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/BalanceChangeDetailDTO.java @@ -34,13 +34,37 @@ public class BalanceChangeDetailDTO { * 变动后的当前余额 */ private BigDecimal currentBalance; + /** + * Field `beforeBalance` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private BigDecimal beforeBalance; + /** + * Field `afterBalance` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private BigDecimal afterBalance; + /** + * Field `changeScene` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String changeScene; + /** + * Field `relatedOrderId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long relatedOrderId; + /** + * Field `relatedOrderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String relatedOrderNo; + /** + * Field `externalOrderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String externalOrderNo; + /** + * Field `operatorId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long operatorId; + /** + * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String remark; /** diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/BalanceDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/BalanceDTO.java index 8da5f733..fd36811e 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/BalanceDTO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/BalanceDTO.java @@ -24,6 +24,12 @@ public class BalanceDTO { * 当前余额 */ private BigDecimal amount; + /** + * Field `totalRechargeAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private BigDecimal totalRechargeAmount; + /** + * Field `lastRechargeTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private LocalDateTime lastRechargeTime; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/ChunkUploadCompleteRequestDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/ChunkUploadCompleteRequestDTO.java index 9f234f99..d509b6b3 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/ChunkUploadCompleteRequestDTO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/ChunkUploadCompleteRequestDTO.java @@ -11,5 +11,8 @@ import javax.validation.constraints.NotBlank; public class ChunkUploadCompleteRequestDTO { @NotBlank(message = "上传标识不能为空") + /** + * Field `uploadId` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String uploadId; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/ChunkUploadInitRequestDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/ChunkUploadInitRequestDTO.java index baec7b86..207b1bfe 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/ChunkUploadInitRequestDTO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/ChunkUploadInitRequestDTO.java @@ -13,18 +13,33 @@ import javax.validation.constraints.NotNull; public class ChunkUploadInitRequestDTO { @NotBlank(message = "文件名不能为空") + /** + * Field `fileName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String fileName; @NotNull(message = "文件大小不能为空") @Min(value = 1, message = "文件大小不合法") + /** + * Field `fileSize` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long fileSize; @NotBlank(message = "文件类型不能为空") + /** + * Field `contentType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String contentType; @NotBlank(message = "文件指纹不能为空") + /** + * Field `fileFingerprint` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String fileFingerprint; @NotBlank(message = "上传场景不能为空") + /** + * Field `scene` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String scene; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/CouponDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/CouponDTO.java index 6f222b5b..d2913af5 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/CouponDTO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/CouponDTO.java @@ -61,8 +61,17 @@ public class CouponDTO { * 所属店铺ID */ private Long shopId; + /** + * Field `couponScene` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String couponScene; + /** + * Field `requiredVipLevel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String requiredVipLevel; + /** + * Field `autoMatch` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Integer autoMatch; /** diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/InviteCodeDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/InviteCodeDTO.java new file mode 100644 index 00000000..1abcacde --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/InviteCodeDTO.java @@ -0,0 +1,41 @@ +package com.xiaowang.yuminailcore.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import java.time.LocalDateTime; + +@Data +/** + * InviteCodeDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class InviteCodeDTO { + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + /** + * Field `ownerUserId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long ownerUserId; + + @NotBlank(message = "邀请码不能为空") + /** + * Field `inviteCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String inviteCode; + + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + /** + * Field `useCount` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer useCount; + /** + * Field `expireTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime expireTime; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/LegalAgreementDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/LegalAgreementDTO.java new file mode 100644 index 00000000..47617875 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/LegalAgreementDTO.java @@ -0,0 +1,24 @@ +package com.xiaowang.yuminailcore.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; + +@Data +public class LegalAgreementDTO { + + @NotBlank(message = "协议类型不能为空") + private String agreementType; + + @NotBlank(message = "协议标题不能为空") + @Size(max = 100, message = "协议标题不能超过100个字符") + private String title; + + @NotBlank(message = "协议版本不能为空") + @Size(max = 40, message = "协议版本不能超过40个字符") + private String version; + + @NotBlank(message = "协议内容不能为空") + private String content; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/LoginRequestDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/LoginRequestDTO.java index 9f9d4d96..4718e218 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/LoginRequestDTO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/LoginRequestDTO.java @@ -6,6 +6,7 @@ import lombok.Setter; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Pattern; +import java.util.Map; /** * 登录请求 DTO @@ -16,7 +17,7 @@ import javax.validation.constraints.Pattern; */ @Getter @Setter -public class LoginRequestDTO { +public class LoginRequestDTO implements AgreementAwareRequest { /** * 账号 @@ -39,4 +40,10 @@ public class LoginRequestDTO { * 店铺ID */ private Long shopId; + + private Boolean agreementAccepted; + + private Map agreementVersions; + + private String clientType; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/MessageHubPushConfigDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/MessageHubPushConfigDTO.java new file mode 100644 index 00000000..a63f3245 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/MessageHubPushConfigDTO.java @@ -0,0 +1,85 @@ +package com.xiaowang.yuminailcore.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; + +@Data +/** + * MessageHubPushConfigDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class MessageHubPushConfigDTO { + + @NotBlank(message = "场景编码不能为空") + @Size(max = 80, message = "场景编码不能超过80个字符") + /** + * Field `sceneCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sceneCode; + + @NotBlank(message = "场景名称不能为空") + @Size(max = 100, message = "场景名称不能超过100个字符") + /** + * Field `sceneName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sceneName; + + @NotBlank(message = "消息平台不能为空") + @Size(max = 20, message = "消息平台不能超过20个字符") + /** + * Field `platform` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String platform = "SMS"; + + @NotBlank(message = "消息类型不能为空") + @Size(max = 30, message = "消息类型不能超过30个字符") + /** + * Field `msgType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String msgType = "VERIFICATION"; + + @NotBlank(message = "队列名称不能为空") + @Size(max = 100, message = "队列名称不能超过100个字符") + /** + * Field `queueName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String queueName; + + @NotBlank(message = "来源系统不能为空") + @Size(max = 80, message = "来源系统不能超过80个字符") + /** + * Field `sourceSystem` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sourceSystem; + + @NotBlank(message = "模板编码不能为空") + @Size(max = 100, message = "模板编码不能超过100个字符") + /** + * Field `templateCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String templateCode; + + /** + * Field `channelId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long channelId; + + @Size(max = 30, message = "发送方式不能超过30个字符") + /** + * Field `sendMethod` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sendMethod; + + /** + * Field `enabled` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer enabled = 1; + + @Size(max = 255, message = "备注不能超过255个字符") + /** + * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String remark; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/MessageHubPushTestDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/MessageHubPushTestDTO.java new file mode 100644 index 00000000..0079ffe0 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/MessageHubPushTestDTO.java @@ -0,0 +1,21 @@ +package com.xiaowang.yuminailcore.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; + +@Data +/** + * MessageHubPushTestDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class MessageHubPushTestDTO { + + @NotBlank(message = "手机号不能为空") + @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") + /** + * Field `phone` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String phone; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/NailArtistInfoDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/NailArtistInfoDTO.java index b6ae5480..c0edf32b 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/NailArtistInfoDTO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/NailArtistInfoDTO.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import lombok.Data; import java.math.BigDecimal; +import java.time.LocalTime; /** * 美甲师信息DTO @@ -47,6 +48,31 @@ public class NailArtistInfoDTO { * 状态:1-营业中,0-休息中 */ private Integer status; + + /** + * Field `participateProduction` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer participateProduction; + + /** + * Field `workStartTime` (LocalTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalTime workStartTime; + + /** + * Field `workEndTime` (LocalTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalTime workEndTime; + + /** + * Field `userType` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer userType; + + /** + * Field `userTypeName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String userTypeName; /** * 作品集商品ID集合,多个ID以逗号分隔 diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/OrderDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/OrderDTO.java index 5f28c5fa..89bd104a 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/OrderDTO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/OrderDTO.java @@ -18,6 +18,9 @@ public class OrderDTO { * 优惠券ID */ private Long couponId; + /** + * Field `couponSourceType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String couponSourceType; /** diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/PhoneLoginRequestDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/PhoneLoginRequestDTO.java index b397e0de..dff6133e 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/PhoneLoginRequestDTO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/PhoneLoginRequestDTO.java @@ -3,6 +3,7 @@ package com.xiaowang.yuminailcore.dto; import lombok.Data; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Pattern; +import java.util.Map; /** * 手机号验证码登录请求 DTO @@ -11,15 +12,30 @@ import javax.validation.constraints.Pattern; * @date 2026-03-03 */ @Data -public class PhoneLoginRequestDTO { +public class PhoneLoginRequestDTO implements AgreementAwareRequest { @NotBlank(message = "手机号不能为空") @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") + /** + * Field `phone` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String phone; @NotBlank(message = "验证码不能为空") @Pattern(regexp = "^\\d{6}$", message = "验证码必须是6位数字") + /** + * Field `verificationCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String verificationCode; + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long shopId; -} \ No newline at end of file + + private Boolean agreementAccepted; + + private Map agreementVersions; + + private String clientType; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/RegisterRequestDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/RegisterRequestDTO.java index 14addb39..6bf8e97c 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/RegisterRequestDTO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/RegisterRequestDTO.java @@ -4,6 +4,7 @@ import com.xiaowang.yuminailcore.utils.AccountValidationUtils; import lombok.Data; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Pattern; +import java.util.Map; /** * 注册请求 DTO @@ -12,24 +13,53 @@ import javax.validation.constraints.Pattern; * @date 2026-02-14 */ @Data -public class RegisterRequestDTO { +public class RegisterRequestDTO implements AgreementAwareRequest { @NotBlank(message = "账号不能为空") @Pattern(regexp = AccountValidationUtils.ACCOUNT_REGEX, message = "账号只能包含字母和数字") + /** + * Field `account` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String account; @NotBlank(message = "密码不能为空") + /** + * Field `password` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String password; + /** + * Field `nickname` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String nickname; + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long shopId; + + /** + * Field `inviteCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String inviteCode; @NotBlank(message = "手机号不能为空") @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") + /** + * Field `phone` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String phone; @NotBlank(message = "验证码不能为空") @Pattern(regexp = "^\\d{6}$", message = "验证码必须是6位数字") + /** + * Field `verificationCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String verificationCode; + + private Boolean agreementAccepted; + + private Map agreementVersions; + + private String clientType; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/SendVerificationCodeRequestDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/SendVerificationCodeRequestDTO.java index f505ef95..ab494579 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/SendVerificationCodeRequestDTO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/SendVerificationCodeRequestDTO.java @@ -1,19 +1,25 @@ package com.xiaowang.yuminailcore.dto; import lombok.Data; + import javax.validation.constraints.NotBlank; import javax.validation.constraints.Pattern; /** - * 发送验证码请求 DTO - * - * @author xiaowang - * @date 2026-03-03 + * 发送验证码请求 DTO。 */ @Data public class SendVerificationCodeRequestDTO { - + @NotBlank(message = "手机号不能为空") @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") + /** + * Field `phone` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String phone; -} \ No newline at end of file + + /** + * 业务场景编码,用来选择 YumiNail 投递 MessageHub 时的配置。 + */ + private String sceneCode; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/ShopDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/ShopDTO.java index 8f34941a..e6fae1b0 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/ShopDTO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/ShopDTO.java @@ -2,6 +2,9 @@ package com.xiaowang.yuminailcore.dto; import lombok.Data; +import java.math.BigDecimal; +import java.time.LocalDateTime; + /** * 店铺信息表 DTO * 用于店铺信息的传输 @@ -27,6 +30,12 @@ public class ShopDTO { */ private String address; + private String mapProvider; + + private BigDecimal longitude; + + private BigDecimal latitude; + /** * 店铺营业时间 */ @@ -46,4 +55,9 @@ public class ShopDTO { * 店铺状态:1-启用,0-停用 */ private Integer status; + + /** + * 店铺授权有效期;为空表示长期有效。 + */ + private LocalDateTime authorizationExpireTime; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/ShopRoleDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/ShopRoleDTO.java new file mode 100644 index 00000000..1dbbdd71 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/ShopRoleDTO.java @@ -0,0 +1,45 @@ +package com.xiaowang.yuminailcore.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import java.util.List; + +@Data +/** + * ShopRoleDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class ShopRoleDTO { + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + + @NotBlank(message = "角色名不能为空") + /** + * Field `roleName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String roleName; + + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + /** + * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String remark; + /** + * Field `sortOrder` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer sortOrder; + /** + * Field `permissionIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List permissionIds; + /** + * Field `userIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List userIds; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/SwitchShopRequestDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/SwitchShopRequestDTO.java index aac36d73..a6f03d1f 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/SwitchShopRequestDTO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/SwitchShopRequestDTO.java @@ -3,7 +3,14 @@ package com.xiaowang.yuminailcore.dto; import lombok.Data; @Data +/** + * SwitchShopRequestDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ public class SwitchShopRequestDTO { + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long shopId; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/SystemMessageCreateDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/SystemMessageCreateDTO.java new file mode 100644 index 00000000..82a3925b --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/SystemMessageCreateDTO.java @@ -0,0 +1,51 @@ +package com.xiaowang.yuminailcore.dto; + +import lombok.Data; + +import javax.validation.constraints.Size; +import java.util.List; + +@Data +/** + * SystemMessageCreateDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class SystemMessageCreateDTO { + + @Size(max = 100, message = "消息标题不能超过100个字符") + /** + * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String title; + + @Size(max = 2000, message = "消息内容不能超过2000个字符") + /** + * Field `content` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String content; + + /** + * Field `targetType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String targetType; + + /** + * Field `imageFileId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long imageFileId; + + /** + * Field `shopIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List shopIds; + + /** + * Field `userIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List userIds; + + /** + * Field `popupEnabled` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer popupEnabled = 1; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/SystemParameterConfigDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/SystemParameterConfigDTO.java new file mode 100644 index 00000000..1ccc06a5 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/SystemParameterConfigDTO.java @@ -0,0 +1,30 @@ +package com.xiaowang.yuminailcore.dto; + +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; + +@Data +public class SystemParameterConfigDTO { + + @NotBlank(message = "配置分组不能为空") + @Size(max = 50, message = "配置分组不能超过50个字符") + private String configGroup; + + @NotBlank(message = "配置键不能为空") + @Size(max = 100, message = "配置键不能超过100个字符") + private String configKey; + + @NotBlank(message = "配置名称不能为空") + @Size(max = 100, message = "配置名称不能超过100个字符") + private String configName; + + @Size(max = 1000, message = "配置值不能超过1000个字符") + private String configValue; + + private Integer enabled = 1; + + @Size(max = 255, message = "备注不能超过255个字符") + private String remark; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/UserRelationUpdateDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/UserRelationUpdateDTO.java new file mode 100644 index 00000000..ea5132fa --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/UserRelationUpdateDTO.java @@ -0,0 +1,27 @@ +package com.xiaowang.yuminailcore.dto; + +import lombok.Data; + +@Data +/** + * UserRelationUpdateDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class UserRelationUpdateDTO { + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + /** + * Field `parentUserId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long parentUserId; + /** + * Field `parentRoleType` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer parentRoleType; + /** + * Field `sourceType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sourceType; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/VipBenefitDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/VipBenefitDTO.java index 5ac72642..ab7fbe4f 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/VipBenefitDTO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/VipBenefitDTO.java @@ -23,7 +23,16 @@ public class VipBenefitDTO { * 所需VIP等级 */ private String requiredVipLevel; + /** + * Field `levelRank` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Integer levelRank; + /** + * Field `rechargeThreshold` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private BigDecimal rechargeThreshold; + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Integer status; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/VipInfoDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/VipInfoDTO.java index 33cd7d37..889c902a 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/VipInfoDTO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/VipInfoDTO.java @@ -14,6 +14,9 @@ import java.time.LocalDateTime; @Data public class VipInfoDTO { + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long userId; /** @@ -40,5 +43,8 @@ public class VipInfoDTO { * 关联VIP权益信息表主键 */ private Long benefitId; + /** + * Field `manualOverride` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Integer manualOverride; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/VipRechargePlanDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/VipRechargePlanDTO.java new file mode 100644 index 00000000..a2cfb821 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/VipRechargePlanDTO.java @@ -0,0 +1,66 @@ +package com.xiaowang.yuminailcore.dto; + +import lombok.Data; + +import javax.validation.constraints.DecimalMin; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; +import java.math.BigDecimal; + +@Data +/** + * VipRechargePlanDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class VipRechargePlanDTO { + + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + + @NotBlank(message = "充值档位标题不能为空") + @Size(max = 100, message = "充值档位标题不能超过100个字符") + /** + * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String title; + + @NotNull(message = "充值金额不能为空") + @DecimalMin(value = "0.01", message = "充值金额必须大于0") + /** + * Field `rechargeAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal rechargeAmount; + + @NotNull(message = "赠送金额不能为空") + @DecimalMin(value = "0.00", message = "赠送金额不能小于0") + /** + * Field `giftAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal giftAmount; + + @NotBlank(message = "VIP等级不能为空") + @Size(max = 20, message = "VIP等级不能超过20个字符") + /** + * Field `vipLevel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String vipLevel; + + @Size(max = 255, message = "说明不能超过255个字符") + /** + * Field `description` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String description; + + /** + * Field `sortOrder` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer sortOrder = 0; + + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status = 1; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/WechatMiniAutoLoginRequestDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/WechatMiniAutoLoginRequestDTO.java index afdd6869..53c50138 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/WechatMiniAutoLoginRequestDTO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/WechatMiniAutoLoginRequestDTO.java @@ -11,7 +11,13 @@ import javax.validation.constraints.NotBlank; public class WechatMiniAutoLoginRequestDTO { @NotBlank(message = "微信登录凭证不能为空") + /** + * Field `wxCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String wxCode; + /** + * Field `preferredShopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long preferredShopId; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/WechatMiniConfirmLoginRequestDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/WechatMiniConfirmLoginRequestDTO.java index 52e389f9..b3a00174 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/WechatMiniConfirmLoginRequestDTO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/WechatMiniConfirmLoginRequestDTO.java @@ -4,16 +4,29 @@ import lombok.Data; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; +import java.util.Map; /** * 微信小程序补选店铺后确认登录请求。 */ @Data -public class WechatMiniConfirmLoginRequestDTO { +public class WechatMiniConfirmLoginRequestDTO implements AgreementAwareRequest { @NotBlank(message = "登录票据不能为空") + /** + * Field `ticket` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String ticket; @NotNull(message = "店铺不能为空") + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long shopId; + + private Boolean agreementAccepted; + + private Map agreementVersions; + + private String clientType; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/WechatMiniPhoneLoginRequestDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/WechatMiniPhoneLoginRequestDTO.java index 620a8cd0..f1a3ab81 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/WechatMiniPhoneLoginRequestDTO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/WechatMiniPhoneLoginRequestDTO.java @@ -3,18 +3,34 @@ package com.xiaowang.yuminailcore.dto; import lombok.Data; import javax.validation.constraints.NotBlank; +import java.util.Map; /** * 微信小程序手机号一键登录请求。 */ @Data -public class WechatMiniPhoneLoginRequestDTO { +public class WechatMiniPhoneLoginRequestDTO implements AgreementAwareRequest { @NotBlank(message = "微信登录凭证不能为空") + /** + * Field `wxCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String wxCode; @NotBlank(message = "手机号授权凭证不能为空") + /** + * Field `phoneCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String phoneCode; + /** + * Field `preferredShopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long preferredShopId; + + private Boolean agreementAccepted; + + private Map agreementVersions; + + private String clientType; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/AnnouncementDO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/AnnouncementDO.java new file mode 100644 index 00000000..40130a66 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/AnnouncementDO.java @@ -0,0 +1,86 @@ +package com.xiaowang.yuminailcore.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.time.LocalDateTime; + +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_announcement") +/** + * AnnouncementDO maps to a database table row. Mapper classes persist and query this object. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class AnnouncementDO extends BaseEntity { + + @TableField("title") + /** + * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String title; + + @TableField("content") + /** + * Field `content` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String content; + + @TableField("publisher_id") + /** + * Field `publisherId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long publisherId; + + @TableField("publisher_name") + /** + * Field `publisherName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String publisherName; + + @TableField("publisher_type") + /** + * Field `publisherType` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer publisherType; + + @TableField("target_type") + /** + * Field `targetType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String targetType; + + @TableField("target_ids") + /** + * Field `targetIds` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String targetIds; + + @TableField("status") + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + + @TableField("sort_order") + /** + * Field `sortOrder` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer sortOrder; + + @TableField("publish_time") + /** + * Field `publishTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime publishTime; + + @TableField("is_delete") + @TableLogic + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer isDelete; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/BalanceChangeDetailDO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/BalanceChangeDetailDO.java index 5be53de6..c71384cc 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/BalanceChangeDetailDO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/BalanceChangeDetailDO.java @@ -21,6 +21,9 @@ import java.time.LocalDateTime; public class BalanceChangeDetailDO { @TableId(type = IdType.ASSIGN_ID) + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long id; /** @@ -54,26 +57,50 @@ public class BalanceChangeDetailDO { private BigDecimal beforeBalance; @TableField("after_balance") + /** + * Field `afterBalance` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private BigDecimal afterBalance; @TableField("change_scene") + /** + * Field `changeScene` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String changeScene; @TableField("related_order_id") + /** + * Field `relatedOrderId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long relatedOrderId; @TableField("related_order_no") + /** + * Field `relatedOrderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String relatedOrderNo; @TableField("external_order_no") + /** + * Field `externalOrderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String externalOrderNo; @TableField("operator_id") + /** + * Field `operatorId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long operatorId; @TableField("remark") + /** + * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String remark; @TableField("change_time") + /** + * Field `changeTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private LocalDateTime changeTime; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/BalanceDO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/BalanceDO.java index aaa8897a..54a24586 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/BalanceDO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/BalanceDO.java @@ -39,8 +39,14 @@ public class BalanceDO extends BaseEntity { private BigDecimal totalRechargeAmount; @TableField("last_recharge_time") + /** + * Field `lastRechargeTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private LocalDateTime lastRechargeTime; @TableField("last_update_time") + /** + * Field `lastUpdateTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private LocalDateTime lastUpdateTime; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/CartDO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/CartDO.java index 1893a60a..48b593d9 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/CartDO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/CartDO.java @@ -7,11 +7,33 @@ import java.time.LocalDateTime; @Data @TableName("t_cart") +/** + * CartDO maps to a database table row. Mapper classes persist and query this object. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ public class CartDO extends BaseEntity { + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long userId; + /** + * Field `productId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long productId; + /** + * Field `quantity` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Integer quantity; + /** + * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private LocalDateTime createTime; + /** + * Field `updateTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private LocalDateTime updateTime; + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Integer isDelete; } \ No newline at end of file diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/CouponDO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/CouponDO.java index 36a3d865..d8b12b87 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/CouponDO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/CouponDO.java @@ -77,10 +77,19 @@ public class CouponDO extends BaseEntity { */ private Long shopId; + /** + * Field `couponScene` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String couponScene; + /** + * Field `requiredVipLevel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String requiredVipLevel; + /** + * Field `autoMatch` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Integer autoMatch; /** diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/LegalAgreementDO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/LegalAgreementDO.java new file mode 100644 index 00000000..bd9c7229 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/LegalAgreementDO.java @@ -0,0 +1,37 @@ +package com.xiaowang.yuminailcore.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +@Getter +@Setter +@TableName("t_legal_agreement") +public class LegalAgreementDO extends BaseEntity { + + @TableField("agreement_type") + private String agreementType; + + @TableField("title") + private String title; + + @TableField("version") + private String version; + + @TableField("content") + private String content; + + @TableField("status") + private Integer status; + + @TableField("effective_time") + private LocalDateTime effectiveTime; + + @TableField("is_delete") + @TableLogic + private Integer isDelete; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/MessageHubPushConfigDO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/MessageHubPushConfigDO.java new file mode 100644 index 00000000..aac19bda --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/MessageHubPushConfigDO.java @@ -0,0 +1,92 @@ +package com.xiaowang.yuminailcore.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + * YumiNail 调用 MessageHub 的场景级配置。 + * + *

这里不保存 Spug、阿里云等供应商密钥;这些真实通道仍由 MessageHub 自己管理。 + * 本表只描述 YumiNail 在某个业务功能里投递 MessageHub 时要携带的参数。

+ */ +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_messagehub_push_config") +public class MessageHubPushConfigDO extends BaseEntity { + + @TableField("scene_code") + /** + * Field `sceneCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sceneCode; + + @TableField("scene_name") + /** + * Field `sceneName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sceneName; + + @TableField("platform") + /** + * Field `platform` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String platform; + + @TableField("msg_type") + /** + * Field `msgType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String msgType; + + @TableField("queue_name") + /** + * Field `queueName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String queueName; + + @TableField("source_system") + /** + * Field `sourceSystem` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sourceSystem; + + @TableField("template_code") + /** + * Field `templateCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String templateCode; + + @TableField("channel_id") + /** + * Field `channelId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long channelId; + + @TableField("send_method") + /** + * Field `sendMethod` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sendMethod; + + @TableField("enabled") + /** + * Field `enabled` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer enabled; + + @TableField("remark") + /** + * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String remark; + + @TableField("is_delete") + @TableLogic + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer isDelete; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/NailArtistInfoDO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/NailArtistInfoDO.java index ee850069..616d4801 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/NailArtistInfoDO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/NailArtistInfoDO.java @@ -7,6 +7,7 @@ import lombok.Data; import lombok.EqualsAndHashCode; import java.math.BigDecimal; +import java.time.LocalTime; /** * 美甲师信息实体类 @@ -44,6 +45,24 @@ public class NailArtistInfoDO extends BaseEntity { * 状态:1-营业中,0-休息中 */ private Integer status; + + @TableField("participate_production") + /** + * Field `participateProduction` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer participateProduction; + + @TableField("work_start_time") + /** + * Field `workStartTime` (LocalTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalTime workStartTime; + + @TableField("work_end_time") + /** + * Field `workEndTime` (LocalTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalTime workEndTime; /** * 作品集商品ID集合,多个ID以逗号分隔 diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/OrderDO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/OrderDO.java index c63e47b2..4e5adb16 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/OrderDO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/OrderDO.java @@ -8,17 +8,57 @@ import java.time.LocalDateTime; @Data @TableName("t_order") +/** + * OrderDO maps to a database table row. Mapper classes persist and query this object. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ public class OrderDO extends BaseEntity { + /** + * Field `orderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String orderNo; + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long userId; + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long shopId; + /** + * Field `totalAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private BigDecimal totalAmount; + /** + * Field `actualAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private BigDecimal actualAmount; + /** + * Field `couponId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long couponId; + /** + * Field `userCouponId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long userCouponId; + /** + * Field `couponSourceType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String couponSourceType; + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Integer status; + /** + * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private LocalDateTime createTime; + /** + * Field `updateTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private LocalDateTime updateTime; + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Integer isDelete; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/OrderItemDO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/OrderItemDO.java index d7346499..ccfd38db 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/OrderItemDO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/OrderItemDO.java @@ -9,17 +9,48 @@ import java.time.LocalDateTime; @Data @TableName("t_order_item") +/** + * OrderItemDO maps to a database table row. Mapper classes persist and query this object. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ public class OrderItemDO extends BaseEntity { + /** + * Field `orderId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long orderId; + /** + * Field `productId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long productId; + /** + * Field `quantity` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Integer quantity; + /** + * Field `price` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private BigDecimal price; + /** + * Field `artistId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long artistId; @TableField("appointment_time") + /** + * Field `appointmentTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private LocalDateTime appointmentTime; + /** + * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private LocalDateTime createTime; + /** + * Field `updateTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private LocalDateTime updateTime; + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Integer isDelete; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/SecurityAuditLogDO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/SecurityAuditLogDO.java new file mode 100644 index 00000000..2fe37d08 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/SecurityAuditLogDO.java @@ -0,0 +1,38 @@ +package com.xiaowang.yuminailcore.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +@Getter +@Setter +@TableName("t_security_audit_log") +public class SecurityAuditLogDO extends BaseEntity { + + @TableField("user_id") + private Long userId; + + @TableField("account") + private String account; + + @TableField("action") + private String action; + + @TableField("result") + private String result; + + @TableField("reason") + private String reason; + + @TableField("ip_address") + private String ipAddress; + + @TableField("device_id") + private String deviceId; + + @TableField("operate_time") + private LocalDateTime operateTime; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/ShopDO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/ShopDO.java index b0d8cd20..ce136909 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/ShopDO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/ShopDO.java @@ -8,6 +8,9 @@ import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import lombok.EqualsAndHashCode; +import java.math.BigDecimal; +import java.time.LocalDateTime; + /** * 店铺信息表 DO * 对应数据库表 t_shop @@ -44,6 +47,15 @@ public class ShopDO extends BaseEntity { @TableField("address") private String address; + @TableField("map_provider") + private String mapProvider; + + @TableField("longitude") + private BigDecimal longitude; + + @TableField("latitude") + private BigDecimal latitude; + /** * 店铺营业时间 */ @@ -68,6 +80,12 @@ public class ShopDO extends BaseEntity { @TableField("status") private Integer status; + /** + * 店铺授权有效期;为空表示长期有效。 + */ + @TableField("authorization_expire_time") + private LocalDateTime authorizationExpireTime; + /** * 逻辑删除:0-未删,1-已删 */ diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/ShopRoleDO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/ShopRoleDO.java new file mode 100644 index 00000000..9ba00205 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/ShopRoleDO.java @@ -0,0 +1,60 @@ +package com.xiaowang.yuminailcore.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_shop_role") +/** + * ShopRoleDO maps to a database table row. Mapper classes persist and query this object. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class ShopRoleDO extends BaseEntity { + + @TableField("shop_id") + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + + @TableField("role_name") + /** + * Field `roleName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String roleName; + + @TableField("creator_id") + /** + * Field `creatorId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long creatorId; + + @TableField("status") + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + + @TableField("remark") + /** + * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String remark; + + @TableField("sort_order") + /** + * Field `sortOrder` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer sortOrder; + + @TableField("is_delete") + @TableLogic + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer isDelete; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/ShopRolePermissionDO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/ShopRolePermissionDO.java new file mode 100644 index 00000000..c83271d2 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/ShopRolePermissionDO.java @@ -0,0 +1,36 @@ +package com.xiaowang.yuminailcore.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_shop_role_permission") +/** + * ShopRolePermissionDO maps to a database table row. Mapper classes persist and query this object. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class ShopRolePermissionDO extends BaseEntity { + + @TableField("role_id") + /** + * Field `roleId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long roleId; + + @TableField("permission_id") + /** + * Field `permissionId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long permissionId; + + @TableField("is_delete") + @TableLogic + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer isDelete; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/SystemMessageDO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/SystemMessageDO.java new file mode 100644 index 00000000..cb61e78e --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/SystemMessageDO.java @@ -0,0 +1,92 @@ +package com.xiaowang.yuminailcore.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +@Getter +@Setter +@TableName("t_system_message") +/** + * SystemMessageDO maps to a database table row. Mapper classes persist and query this object. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class SystemMessageDO extends BaseEntity { + + @TableField("title") + /** + * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String title; + + @TableField("content") + /** + * Field `content` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String content; + + @TableField("image_file_id") + /** + * Field `imageFileId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long imageFileId; + + @TableField("publisher_id") + /** + * Field `publisherId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long publisherId; + + @TableField("publisher_name") + /** + * Field `publisherName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String publisherName; + + @TableField("publisher_type") + /** + * Field `publisherType` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer publisherType; + + @TableField("target_type") + /** + * Field `targetType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String targetType; + + @TableField("target_ids") + /** + * Field `targetIds` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String targetIds; + + @TableField("popup_enabled") + /** + * Field `popupEnabled` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer popupEnabled; + + @TableField("status") + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + + @TableField("publish_time") + /** + * Field `publishTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime publishTime; + + @TableField("is_delete") + @TableLogic + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer isDelete; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/SystemMessageUserStateDO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/SystemMessageUserStateDO.java new file mode 100644 index 00000000..d7b9738b --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/SystemMessageUserStateDO.java @@ -0,0 +1,62 @@ +package com.xiaowang.yuminailcore.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +@Getter +@Setter +@TableName("t_system_message_user_state") +/** + * SystemMessageUserStateDO maps to a database table row. Mapper classes persist and query this object. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class SystemMessageUserStateDO extends BaseEntity { + + @TableField("message_id") + /** + * Field `messageId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long messageId; + + @TableField("user_id") + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long userId; + + @TableField("popup_shown") + /** + * Field `popupShown` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer popupShown; + + @TableField("read_status") + /** + * Field `readStatus` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer readStatus; + + @TableField("popup_time") + /** + * Field `popupTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime popupTime; + + @TableField("read_time") + /** + * Field `readTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime readTime; + + @TableField("is_delete") + @TableLogic + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer isDelete; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/SystemParameterConfigDO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/SystemParameterConfigDO.java new file mode 100644 index 00000000..06008e72 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/SystemParameterConfigDO.java @@ -0,0 +1,35 @@ +package com.xiaowang.yuminailcore.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_system_parameter_config") +public class SystemParameterConfigDO extends BaseEntity { + + @TableField("config_group") + private String configGroup; + + @TableField("config_key") + private String configKey; + + @TableField("config_name") + private String configName; + + @TableField("config_value") + private String configValue; + + @TableField("enabled") + private Integer enabled; + + @TableField("remark") + private String remark; + + @TableField("is_delete") + @TableLogic + private Integer isDelete; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/UserAgreementConsentDO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/UserAgreementConsentDO.java new file mode 100644 index 00000000..281cad7c --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/UserAgreementConsentDO.java @@ -0,0 +1,38 @@ +package com.xiaowang.yuminailcore.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +@Getter +@Setter +@TableName("t_user_agreement_consent") +public class UserAgreementConsentDO extends BaseEntity { + + @TableField("user_id") + private Long userId; + + @TableField("agreement_type") + private String agreementType; + + @TableField("version") + private String version; + + @TableField("entry") + private String entry; + + @TableField("client_type") + private String clientType; + + @TableField("ip_address") + private String ipAddress; + + @TableField("device_id") + private String deviceId; + + @TableField("consent_time") + private LocalDateTime consentTime; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/UserInviteCodeDO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/UserInviteCodeDO.java new file mode 100644 index 00000000..48af7fc7 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/UserInviteCodeDO.java @@ -0,0 +1,62 @@ +package com.xiaowang.yuminailcore.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.time.LocalDateTime; + +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_user_invite_code") +/** + * UserInviteCodeDO maps to a database table row. Mapper classes persist and query this object. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class UserInviteCodeDO extends BaseEntity { + + @TableField("invite_code") + /** + * Field `inviteCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String inviteCode; + + @TableField("owner_user_id") + /** + * Field `ownerUserId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long ownerUserId; + + @TableField("shop_id") + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + + @TableField("status") + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + + @TableField("use_count") + /** + * Field `useCount` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer useCount; + + @TableField("expire_time") + /** + * Field `expireTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime expireTime; + + @TableField("is_delete") + @TableLogic + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer isDelete; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/UserRelationDO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/UserRelationDO.java new file mode 100644 index 00000000..813ef74f --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/UserRelationDO.java @@ -0,0 +1,60 @@ +package com.xiaowang.yuminailcore.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_user_relation") +/** + * UserRelationDO maps to a database table row. Mapper classes persist and query this object. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class UserRelationDO extends BaseEntity { + + @TableField("user_id") + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long userId; + + @TableField("shop_id") + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + + @TableField("parent_user_id") + /** + * Field `parentUserId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long parentUserId; + + @TableField("parent_role_type") + /** + * Field `parentRoleType` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer parentRoleType; + + @TableField("source_type") + /** + * Field `sourceType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sourceType; + + @TableField("creator_id") + /** + * Field `creatorId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long creatorId; + + @TableField("is_delete") + @TableLogic + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer isDelete; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/UserShopBindingDO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/UserShopBindingDO.java index 5d230391..543a5ab8 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/UserShopBindingDO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/UserShopBindingDO.java @@ -17,12 +17,21 @@ import lombok.Setter; public class UserShopBindingDO extends BaseEntity { @TableId(type = IdType.ASSIGN_ID) + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long id; @TableField("user_id") + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long userId; @TableField("shop_id") + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long shopId; /** @@ -33,5 +42,8 @@ public class UserShopBindingDO extends BaseEntity { @TableField("is_delete") @TableLogic + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Integer isDelete; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/UserShopRoleDO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/UserShopRoleDO.java new file mode 100644 index 00000000..82a1e1cf --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/UserShopRoleDO.java @@ -0,0 +1,48 @@ +package com.xiaowang.yuminailcore.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_user_shop_role") +/** + * UserShopRoleDO maps to a database table row. Mapper classes persist and query this object. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class UserShopRoleDO extends BaseEntity { + + @TableField("user_id") + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long userId; + + @TableField("shop_id") + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + + @TableField("role_id") + /** + * Field `roleId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long roleId; + + @TableField("status") + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + + @TableField("is_delete") + @TableLogic + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer isDelete; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/VipBenefitDO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/VipBenefitDO.java index e0d77537..dba53034 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/VipBenefitDO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/VipBenefitDO.java @@ -30,11 +30,20 @@ public class VipBenefitDO extends BaseEntity { private String requiredVipLevel; @TableField("level_rank") + /** + * Field `levelRank` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Integer levelRank; @TableField("recharge_threshold") + /** + * Field `rechargeThreshold` (java.math.BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private java.math.BigDecimal rechargeThreshold; @TableField("status") + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Integer status; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/VipInfoDO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/VipInfoDO.java index 68d85a96..01d3b787 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/VipInfoDO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/VipInfoDO.java @@ -20,6 +20,9 @@ import java.time.LocalDateTime; public class VipInfoDO extends BaseEntity { @TableField("user_id") + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long userId; /** @@ -53,5 +56,8 @@ public class VipInfoDO extends BaseEntity { private Long benefitId; @TableField("manual_override") + /** + * Field `manualOverride` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Integer manualOverride; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/VipRechargePlanDO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/VipRechargePlanDO.java new file mode 100644 index 00000000..6ba9e4c3 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/VipRechargePlanDO.java @@ -0,0 +1,74 @@ +package com.xiaowang.yuminailcore.entity; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.math.BigDecimal; + +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("t_vip_recharge_plan") +/** + * VipRechargePlanDO maps to a database table row. Mapper classes persist and query this object. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class VipRechargePlanDO extends BaseEntity { + + @TableField("shop_id") + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + + @TableField("title") + /** + * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String title; + + @TableField("recharge_amount") + /** + * Field `rechargeAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal rechargeAmount; + + @TableField("gift_amount") + /** + * Field `giftAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal giftAmount; + + @TableField("vip_level") + /** + * Field `vipLevel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String vipLevel; + + @TableField("description") + /** + * Field `description` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String description; + + @TableField("sort_order") + /** + * Field `sortOrder` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer sortOrder; + + @TableField("status") + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + + @TableField("is_delete") + @TableLogic + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer isDelete; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/WechatMiniBindingDO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/WechatMiniBindingDO.java index d5e3c62f..266638c4 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/WechatMiniBindingDO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/WechatMiniBindingDO.java @@ -16,20 +16,38 @@ import lombok.Setter; public class WechatMiniBindingDO extends BaseEntity { @TableId(type = IdType.ASSIGN_ID) + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long id; @TableField("user_id") + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long userId; @TableField("app_id") + /** + * Field `appId` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String appId; @TableField("openid") + /** + * Field `openId` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String openId; @TableField("unionid") + /** + * Field `unionId` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String unionId; @TableField("status") + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Integer status; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/WishlistDO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/WishlistDO.java index c8810c21..d52f19f7 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/WishlistDO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/WishlistDO.java @@ -6,10 +6,23 @@ import lombok.Data; @Data @TableName("t_wishlist") +/** + * WishlistDO maps to a database table row. Mapper classes persist and query this object. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ public class WishlistDO extends BaseEntity { + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long userId; + /** + * Field `productId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long productId; @TableField("is_delete") + /** + * Field `isDelete` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Integer isDelete; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/AnnouncementMapper.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/AnnouncementMapper.java new file mode 100644 index 00000000..57c444e7 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/AnnouncementMapper.java @@ -0,0 +1,11 @@ +package com.xiaowang.yuminailcore.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.yuminailcore.entity.AnnouncementDO; + +/** + * AnnouncementMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public interface AnnouncementMapper extends BaseMapper { +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/CartMapper.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/CartMapper.java index 160917ca..416afbe1 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/CartMapper.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/CartMapper.java @@ -9,6 +9,10 @@ import org.apache.ibatis.annotations.Select; import java.util.List; @Mapper +/** + * CartMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ public interface CartMapper extends BaseMapper { @Select("SELECT * FROM t_cart WHERE user_id = #{userId} AND is_delete = 0") List selectByUserId(@Param("userId") Long userId); diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/LegalAgreementMapper.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/LegalAgreementMapper.java new file mode 100644 index 00000000..6b2399e2 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/LegalAgreementMapper.java @@ -0,0 +1,9 @@ +package com.xiaowang.yuminailcore.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.yuminailcore.entity.LegalAgreementDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface LegalAgreementMapper extends BaseMapper { +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/MessageHubPushConfigMapper.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/MessageHubPushConfigMapper.java new file mode 100644 index 00000000..fae538c7 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/MessageHubPushConfigMapper.java @@ -0,0 +1,11 @@ +package com.xiaowang.yuminailcore.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.yuminailcore.entity.MessageHubPushConfigDO; + +/** + * MessageHubPushConfigMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public interface MessageHubPushConfigMapper extends BaseMapper { +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/OrderItemMapper.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/OrderItemMapper.java index 28c75e47..9b3ca350 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/OrderItemMapper.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/OrderItemMapper.java @@ -10,6 +10,10 @@ import java.time.LocalDateTime; import java.util.List; @Mapper +/** + * OrderItemMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ public interface OrderItemMapper extends BaseMapper { @Select("SELECT * FROM t_order_item WHERE order_id = #{orderId}") List selectByOrderId(@Param("orderId") Long orderId); @@ -22,6 +26,19 @@ public interface OrderItemMapper extends BaseMapper { "AND o.status <> 3 " + "AND oi.appointment_time IS NOT NULL") List selectActiveAppointmentItemsByArtistId(@Param("artistId") Long artistId); + + @Select("SELECT oi.* FROM t_order_item oi " + + "INNER JOIN t_order o ON o.id = oi.order_id " + + "WHERE oi.artist_id = #{artistId} " + + "AND oi.is_delete = 0 " + + "AND o.is_delete = 0 " + + "AND o.status <> 3 " + + "AND oi.appointment_time >= #{startTime} " + + "AND oi.appointment_time < #{endTime} " + + "ORDER BY oi.appointment_time ASC, oi.id ASC") + List selectArtistCalendarItems(@Param("artistId") Long artistId, + @Param("startTime") LocalDateTime startTime, + @Param("endTime") LocalDateTime endTime); @Select("SELECT COUNT(DISTINCT oi.order_id) as count FROM t_order_item oi " + "JOIN t_product p ON oi.product_id = p.id " + diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/OrderMapper.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/OrderMapper.java index 094ef287..07cf1959 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/OrderMapper.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/OrderMapper.java @@ -9,6 +9,10 @@ import org.apache.ibatis.annotations.Select; import java.util.List; @Mapper +/** + * OrderMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ public interface OrderMapper extends BaseMapper { @Select("SELECT * FROM t_order WHERE user_id = #{userId}") List selectByUserId(@Param("userId") Long userId); diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/SecurityAuditLogMapper.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/SecurityAuditLogMapper.java new file mode 100644 index 00000000..dd9c1819 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/SecurityAuditLogMapper.java @@ -0,0 +1,9 @@ +package com.xiaowang.yuminailcore.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.yuminailcore.entity.SecurityAuditLogDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface SecurityAuditLogMapper extends BaseMapper { +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/ShopRoleMapper.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/ShopRoleMapper.java new file mode 100644 index 00000000..59653991 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/ShopRoleMapper.java @@ -0,0 +1,11 @@ +package com.xiaowang.yuminailcore.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.yuminailcore.entity.ShopRoleDO; + +/** + * ShopRoleMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public interface ShopRoleMapper extends BaseMapper { +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/ShopRolePermissionMapper.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/ShopRolePermissionMapper.java new file mode 100644 index 00000000..1d038304 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/ShopRolePermissionMapper.java @@ -0,0 +1,11 @@ +package com.xiaowang.yuminailcore.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.yuminailcore.entity.ShopRolePermissionDO; + +/** + * ShopRolePermissionMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public interface ShopRolePermissionMapper extends BaseMapper { +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/SystemMessageMapper.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/SystemMessageMapper.java new file mode 100644 index 00000000..1c784e5f --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/SystemMessageMapper.java @@ -0,0 +1,13 @@ +package com.xiaowang.yuminailcore.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.yuminailcore.entity.SystemMessageDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +/** + * SystemMessageMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public interface SystemMessageMapper extends BaseMapper { +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/SystemMessageUserStateMapper.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/SystemMessageUserStateMapper.java new file mode 100644 index 00000000..68c73fb2 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/SystemMessageUserStateMapper.java @@ -0,0 +1,13 @@ +package com.xiaowang.yuminailcore.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.yuminailcore.entity.SystemMessageUserStateDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +/** + * SystemMessageUserStateMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public interface SystemMessageUserStateMapper extends BaseMapper { +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/SystemParameterConfigMapper.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/SystemParameterConfigMapper.java new file mode 100644 index 00000000..d023aa4a --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/SystemParameterConfigMapper.java @@ -0,0 +1,9 @@ +package com.xiaowang.yuminailcore.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.yuminailcore.entity.SystemParameterConfigDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface SystemParameterConfigMapper extends BaseMapper { +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/UserAgreementConsentMapper.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/UserAgreementConsentMapper.java new file mode 100644 index 00000000..603df175 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/UserAgreementConsentMapper.java @@ -0,0 +1,9 @@ +package com.xiaowang.yuminailcore.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.yuminailcore.entity.UserAgreementConsentDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface UserAgreementConsentMapper extends BaseMapper { +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/UserInviteCodeMapper.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/UserInviteCodeMapper.java new file mode 100644 index 00000000..4203029b --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/UserInviteCodeMapper.java @@ -0,0 +1,11 @@ +package com.xiaowang.yuminailcore.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.yuminailcore.entity.UserInviteCodeDO; + +/** + * UserInviteCodeMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public interface UserInviteCodeMapper extends BaseMapper { +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/UserRelationMapper.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/UserRelationMapper.java new file mode 100644 index 00000000..306d7dcd --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/UserRelationMapper.java @@ -0,0 +1,11 @@ +package com.xiaowang.yuminailcore.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.yuminailcore.entity.UserRelationDO; + +/** + * UserRelationMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public interface UserRelationMapper extends BaseMapper { +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/UserShopBindingMapper.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/UserShopBindingMapper.java index 5f86846c..8ac45c72 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/UserShopBindingMapper.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/UserShopBindingMapper.java @@ -3,5 +3,9 @@ package com.xiaowang.yuminailcore.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.xiaowang.yuminailcore.entity.UserShopBindingDO; +/** + * UserShopBindingMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ public interface UserShopBindingMapper extends BaseMapper { } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/UserShopRoleMapper.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/UserShopRoleMapper.java new file mode 100644 index 00000000..1322bc1d --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/UserShopRoleMapper.java @@ -0,0 +1,11 @@ +package com.xiaowang.yuminailcore.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.yuminailcore.entity.UserShopRoleDO; + +/** + * UserShopRoleMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public interface UserShopRoleMapper extends BaseMapper { +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/VipRechargePlanMapper.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/VipRechargePlanMapper.java new file mode 100644 index 00000000..07701188 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/VipRechargePlanMapper.java @@ -0,0 +1,11 @@ +package com.xiaowang.yuminailcore.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.yuminailcore.entity.VipRechargePlanDO; + +/** + * VipRechargePlanMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public interface VipRechargePlanMapper extends BaseMapper { +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/WishlistMapper.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/WishlistMapper.java index 0622f53c..b46dcdab 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/WishlistMapper.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/WishlistMapper.java @@ -5,5 +5,9 @@ import com.xiaowang.yuminailcore.entity.WishlistDO; import org.apache.ibatis.annotations.Mapper; @Mapper +/** + * WishlistMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ public interface WishlistMapper extends BaseMapper { } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/AnnouncementService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/AnnouncementService.java new file mode 100644 index 00000000..a7369029 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/AnnouncementService.java @@ -0,0 +1,61 @@ +package com.xiaowang.yuminailcore.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.yuminailcore.dto.AnnouncementCreateDTO; +import com.xiaowang.yuminailcore.entity.AnnouncementDO; +import com.xiaowang.yuminailcore.entity.UserDO; +import com.xiaowang.yuminailcore.vo.AnnouncementVO; +import com.xiaowang.yuminailcore.vo.MessageTargetOptionsVO; + +import java.util.List; +/** + * AnnouncementService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public interface AnnouncementService extends IService { + /** + * Run business method `publishAnnouncement`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + Long publishAnnouncement(UserDO currentUser, AnnouncementCreateDTO dto); + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List listAdminAnnouncements(UserDO currentUser); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return AnnouncementVO result consumed by the caller or returned to the frontend + */ + AnnouncementVO getAdminAnnouncement(UserDO currentUser, Long id); + /** + * Run business method `revokeAnnouncement`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean revokeAnnouncement(UserDO currentUser, Long id); + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return MessageTargetOptionsVO result consumed by the caller or returned to the frontend + */ + MessageTargetOptionsVO listTargetOptions(UserDO currentUser); + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List listMyAnnouncements(Long userId); +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/CartService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/CartService.java index dc92ebae..4309d4ef 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/CartService.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/CartService.java @@ -4,12 +4,50 @@ import com.xiaowang.yuminailcore.dto.CartDTO; import com.xiaowang.yuminailcore.vo.CartVO; import java.util.List; - +/** + * CartService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ public interface CartService { + /** + * Add a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param cartDTO parameter `cartDTO` supplied by the caller + */ void addToCart(Long userId, CartDTO cartDTO); + /** + * Remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param productId parameter `productId` supplied by the caller + */ void removeFromCart(Long userId, Long productId); + /** + * Run business method `batchRemoveFromCart`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param cartItemIds parameter `cartItemIds` supplied by the caller + */ void batchRemoveFromCart(Long userId, List cartItemIds); + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param cartDTO parameter `cartDTO` supplied by the caller + */ void updateCartQuantity(Long userId, CartDTO cartDTO); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ List getCartList(Long userId); + /** + * Run business method `clearCart`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + */ void clearCart(Long userId); } \ No newline at end of file diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/ChunkUploadService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/ChunkUploadService.java index 9bdb48b9..1dc3fc98 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/ChunkUploadService.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/ChunkUploadService.java @@ -5,36 +5,124 @@ import com.xiaowang.yuminailcore.vo.ChunkUploadSessionVO; import org.springframework.web.multipart.MultipartFile; import java.io.File; - +/** + * ChunkUploadService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ public interface ChunkUploadService { + /** + * Run business method `initAdminObjectStorageUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return ChunkUploadSessionVO result consumed by the caller or returned to the frontend + */ ChunkUploadSessionVO initAdminObjectStorageUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO); + /** + * Run business method `initUserAvatarUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return ChunkUploadSessionVO result consumed by the caller or returned to the frontend + */ ChunkUploadSessionVO initUserAvatarUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO); + /** + * Run business method `uploadAdminObjectStorageChunk`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @param chunkIndex parameter `chunkIndex` supplied by the caller + * @param totalChunks parameter `totalChunks` supplied by the caller + * @param chunkFile parameter `chunkFile` supplied by the caller + */ void uploadAdminObjectStorageChunk(Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile); + /** + * Run business method `uploadUserAvatarChunk`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @param chunkIndex parameter `chunkIndex` supplied by the caller + * @param totalChunks parameter `totalChunks` supplied by the caller + * @param chunkFile parameter `chunkFile` supplied by the caller + */ void uploadUserAvatarChunk(Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile); + /** + * Run business method `prepareAdminObjectStorageFile`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return PreparedUploadFile result consumed by the caller or returned to the frontend + */ PreparedUploadFile prepareAdminObjectStorageFile(Long ownerId, String uploadId); + /** + * Run business method `prepareUserAvatarFile`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return PreparedUploadFile result consumed by the caller or returned to the frontend + */ PreparedUploadFile prepareUserAvatarFile(Long ownerId, String uploadId); + /** + * Run business method `clearAdminObjectStorageUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + */ void clearAdminObjectStorageUpload(Long ownerId, String uploadId); + /** + * Run business method `clearUserAvatarUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + */ void clearUserAvatarUpload(Long ownerId, String uploadId); - +/** + * PreparedUploadFile declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ interface PreparedUploadFile extends AutoCloseable { + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return File result consumed by the caller or returned to the frontend + */ File getFile(); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return String result consumed by the caller or returned to the frontend + */ String getFileName(); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return String result consumed by the caller or returned to the frontend + */ String getContentType(); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return long result consumed by the caller or returned to the frontend + */ long getFileSize(); @Override + /** + * Run business method `close`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + */ void close(); } } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/CommentService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/CommentService.java index 82fe9b28..69dd4ab3 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/CommentService.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/CommentService.java @@ -24,6 +24,13 @@ public interface CommentService extends IService { */ Long createComment(CommentDTO commentDTO); + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUserId parameter `currentUserId` supplied by the caller + * @param commentDTO parameter `commentDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ Long createComment(Long currentUserId, CommentDTO commentDTO); /** @@ -35,6 +42,14 @@ public interface CommentService extends IService { */ boolean updateComment(Long id, CommentDTO commentDTO); + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param currentUserId parameter `currentUserId` supplied by the caller + * @param commentDTO parameter `commentDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ boolean updateComment(Long id, Long currentUserId, CommentDTO commentDTO); /** @@ -45,10 +60,33 @@ public interface CommentService extends IService { */ boolean deleteComment(Long id); + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param currentUserId parameter `currentUserId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ boolean deleteComment(Long id, Long currentUserId); + /** + * Run business method `adminDeleteComment`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param managedShopId parameter `managedShopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ boolean adminDeleteComment(Long id, Long managedShopId); + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productId parameter `productId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ List listAdminComments(Long productId, Long userId, Long shopId, String keyword); /** diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/ContactInfoService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/ContactInfoService.java new file mode 100644 index 00000000..40f20ba4 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/ContactInfoService.java @@ -0,0 +1,41 @@ +package com.xiaowang.yuminailcore.service; + +import com.xiaowang.yuminailcore.vo.ContactInfoVO; +/** + * ContactInfoService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public interface ContactInfoService { + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return ContactInfoVO result consumed by the caller or returned to the frontend + */ + ContactInfoVO getShopManagerContact(Long userId, Long shopId); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param productId parameter `productId` supplied by the caller + * @param artistId parameter `artistId` supplied by the caller + * @return ContactInfoVO result consumed by the caller or returned to the frontend + */ + ContactInfoVO getProductArtistContact(Long userId, Long productId, Long artistId); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param orderId parameter `orderId` supplied by the caller + * @param artistId parameter `artistId` supplied by the caller + * @return ContactInfoVO result consumed by the caller or returned to the frontend + */ + ContactInfoVO getOrderArtistContact(Long userId, Long orderId, Long artistId); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return ContactInfoVO result consumed by the caller or returned to the frontend + */ + ContactInfoVO getPlatformContact(); +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/LegalAgreementService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/LegalAgreementService.java new file mode 100644 index 00000000..a3c2a7bb --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/LegalAgreementService.java @@ -0,0 +1,33 @@ +package com.xiaowang.yuminailcore.service; + +import com.xiaowang.yuminailcore.dto.AgreementAwareRequest; +import com.xiaowang.yuminailcore.dto.LegalAgreementDTO; +import com.xiaowang.yuminailcore.entity.UserDO; +import com.xiaowang.yuminailcore.vo.LegalAgreementVO; +import com.xiaowang.yuminailcore.vo.UserAgreementConsentVO; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; + +public interface LegalAgreementService { + + List listAdminAgreements(UserDO currentUser); + + Long createAgreement(UserDO currentUser, LegalAgreementDTO dto); + + Boolean updateAgreement(UserDO currentUser, Long id, LegalAgreementDTO dto); + + Boolean publishAgreement(UserDO currentUser, Long id); + + Boolean disableAgreement(UserDO currentUser, Long id); + + List listCurrentAgreements(); + + LegalAgreementVO getCurrentAgreement(String agreementType); + + UserAgreementConsentVO getMyConsent(Long userId); + + void requireAccepted(AgreementAwareRequest request); + + void recordConsent(Long userId, AgreementAwareRequest request, String entry, HttpServletRequest httpRequest); +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/MapService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/MapService.java new file mode 100644 index 00000000..76d924e4 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/MapService.java @@ -0,0 +1,11 @@ +package com.xiaowang.yuminailcore.service; + +import java.math.BigDecimal; +import java.util.Map; + +public interface MapService { + + String normalizeProvider(String provider); + + Map buildNavigationUrls(String shopName, String address, BigDecimal longitude, BigDecimal latitude); +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/MessageHubClientService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/MessageHubClientService.java index 6b320083..d65e896d 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/MessageHubClientService.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/MessageHubClientService.java @@ -9,5 +9,20 @@ package com.xiaowang.yuminailcore.service; */ public interface MessageHubClientService { + /** + * Send or dispatch a message. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param code parameter `code` supplied by the caller + */ void sendSmsVerificationCode(String phone, String code); -} \ No newline at end of file + + /** + * Send or dispatch a message. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sceneCode parameter `sceneCode` supplied by the caller + * @param phone parameter `phone` supplied by the caller + * @param code parameter `code` supplied by the caller + */ + void sendSmsVerificationCode(String sceneCode, String phone, String code); +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/MessageHubPushConfigService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/MessageHubPushConfigService.java new file mode 100644 index 00000000..d07f4eb4 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/MessageHubPushConfigService.java @@ -0,0 +1,70 @@ +package com.xiaowang.yuminailcore.service; + +import com.xiaowang.yuminailcore.dto.MessageHubPushConfigDTO; +import com.xiaowang.yuminailcore.dto.MessageHubPushTestDTO; +import com.xiaowang.yuminailcore.entity.MessageHubPushConfigDO; +import com.xiaowang.yuminailcore.entity.UserDO; +import com.xiaowang.yuminailcore.vo.MessageHubPushConfigVO; + +import java.util.List; +/** + * MessageHubPushConfigService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public interface MessageHubPushConfigService { + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List listConfigs(UserDO currentUser); + + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + Long createConfig(UserDO currentUser, MessageHubPushConfigDTO dto); + + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean updateConfig(UserDO currentUser, Long id, MessageHubPushConfigDTO dto); + + /** + * Change the enabled/status flag of one record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param enabled parameter `enabled` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean updateStatus(UserDO currentUser, Long id, Integer enabled); + + /** + * Run a test call without changing normal business data. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean testConfig(UserDO currentUser, Long id, MessageHubPushTestDTO dto); + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sceneCode parameter `sceneCode` supplied by the caller + * @return MessageHubPushConfigDO result consumed by the caller or returned to the frontend + */ + MessageHubPushConfigDO getEnabledConfig(String sceneCode); +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/MinioService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/MinioService.java index 13cb0d1e..6c6b685b 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/MinioService.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/MinioService.java @@ -2,22 +2,76 @@ package com.xiaowang.yuminailcore.service; import org.springframework.web.multipart.MultipartFile; import java.io.InputStream; - +/** + * MinioService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ public interface MinioService { + /** + * Run business method `uploadFile`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param file parameter `file` supplied by the caller + * @param objectName parameter `objectName` supplied by the caller + * @return String result consumed by the caller or returned to the frontend + */ String uploadFile(MultipartFile file, String objectName) throws Exception; + /** + * Run business method `uploadStream`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param inputStream parameter `inputStream` supplied by the caller + * @param fileSize parameter `fileSize` supplied by the caller + * @param contentType parameter `contentType` supplied by the caller + * @param objectName parameter `objectName` supplied by the caller + * @return String result consumed by the caller or returned to the frontend + */ String uploadStream(InputStream inputStream, long fileSize, String contentType, String objectName) throws Exception; + /** + * Run business method `downloadFile`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param objectName parameter `objectName` supplied by the caller + * @return InputStream result consumed by the caller or returned to the frontend + */ InputStream downloadFile(String objectName) throws Exception; + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param objectName parameter `objectName` supplied by the caller + */ void deleteFile(String objectName) throws Exception; + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param objectName parameter `objectName` supplied by the caller + * @return String result consumed by the caller or returned to the frontend + */ String getFileUrl(String objectName); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param objectName parameter `objectName` supplied by the caller + * @param expiryTimeInMinutes parameter `expiryTimeInMinutes` supplied by the caller + * @return String result consumed by the caller or returned to the frontend + */ String getPresignedUrl(String objectName, int expiryTimeInMinutes) throws Exception; + /** + * Run business method `bucketExists`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param bucketName parameter `bucketName` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ boolean bucketExists(String bucketName) throws Exception; + /** + * Run business method `makeBucket`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param bucketName parameter `bucketName` supplied by the caller + */ void makeBucket(String bucketName) throws Exception; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/OrderService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/OrderService.java index c3e9155d..485eb4d8 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/OrderService.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/OrderService.java @@ -1,17 +1,96 @@ package com.xiaowang.yuminailcore.service; import com.xiaowang.yuminailcore.dto.OrderDTO; +import com.xiaowang.yuminailcore.vo.ArtistCalendarAppointmentVO; import com.xiaowang.yuminailcore.vo.OrderVO; +import java.time.LocalDate; import java.util.List; - +/** + * OrderService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ public interface OrderService { + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param orderDTO parameter `orderDTO` supplied by the caller + * @return OrderVO result consumed by the caller or returned to the frontend + */ OrderVO createOrder(Long userId, OrderDTO orderDTO); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ List getOrderList(Long userId); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderId parameter `orderId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return OrderVO result consumed by the caller or returned to the frontend + */ OrderVO getOrderDetail(Long orderId, Long userId); + /** + * Run business method `cancelOrder`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderId parameter `orderId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + */ void cancelOrder(Long orderId, Long userId); + /** + * Run business method `processOrder`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderId parameter `orderId` supplied by the caller + * @param status parameter `status` supplied by the caller + */ void processOrder(Long orderId, Integer status); + /** + * Complete a business action. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderId parameter `orderId` supplied by the caller + * @param artistId parameter `artistId` supplied by the caller + */ void completeArtistOrder(Long orderId, Long artistId); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ List getAllOrders(); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param artistId parameter `artistId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ List getOrdersByArtistId(Long artistId); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param artistId parameter `artistId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List getArtistWorkbenchOrders(Long artistId); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userType parameter `userType` supplied by the caller + * @param days parameter `days` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List getArtistCalendarRecent(Long userId, Integer userType, Integer days); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userType parameter `userType` supplied by the caller + * @param date parameter `date` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List getArtistCalendarDay(Long userId, Integer userType, LocalDate date); } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/ProductService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/ProductService.java index 267a33b8..84271c78 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/ProductService.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/ProductService.java @@ -107,5 +107,14 @@ public interface ProductService extends IService { */ PageResultVO pageProducts(Integer page, Integer size, String keyword, Long shopId); + /** + * Query paged records. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @param size parameter `size` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @param tag parameter `tag` supplied by the caller + * @return PageResultVO result consumed by the caller or returned to the frontend + */ PageResultVO pagePublicProducts(Integer page, Integer size, String keyword, String tag); } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/SecurityAuditLogService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/SecurityAuditLogService.java new file mode 100644 index 00000000..6539ceac --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/SecurityAuditLogService.java @@ -0,0 +1,8 @@ +package com.xiaowang.yuminailcore.service; + +import javax.servlet.http.HttpServletRequest; + +public interface SecurityAuditLogService { + + void record(Long userId, String account, String action, String result, String reason, HttpServletRequest request); +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/ShopRoleService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/ShopRoleService.java new file mode 100644 index 00000000..a44bd5e3 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/ShopRoleService.java @@ -0,0 +1,119 @@ +package com.xiaowang.yuminailcore.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.yuminailcore.dto.InviteCodeDTO; +import com.xiaowang.yuminailcore.dto.ShopRoleDTO; +import com.xiaowang.yuminailcore.dto.UserRelationUpdateDTO; +import com.xiaowang.yuminailcore.entity.ShopRoleDO; +import com.xiaowang.yuminailcore.entity.UserDO; +import com.xiaowang.yuminailcore.vo.InviteCodeVO; +import com.xiaowang.yuminailcore.vo.ShopRoleVO; +import com.xiaowang.yuminailcore.vo.UserRelationVO; + +import java.util.List; +/** + * ShopRoleService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public interface ShopRoleService extends IService { + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List listRoles(UserDO currentUser, Long shopId); + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + Long createRole(UserDO currentUser, ShopRoleDTO dto); + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean updateRole(UserDO currentUser, Long id, ShopRoleDTO dto); + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean deleteRole(UserDO currentUser, Long id); + /** + * Run business method `assignPermissions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param permissionIds parameter `permissionIds` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean assignPermissions(UserDO currentUser, Long id, List permissionIds); + /** + * Run business method `assignUsers`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param userIds parameter `userIds` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean assignUsers(UserDO currentUser, Long id, List userIds); + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List listRelationOptions(UserDO currentUser, Long shopId); + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean updateUserRelation(UserDO currentUser, Long userId, UserRelationUpdateDTO dto); + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List listInviteCodes(UserDO currentUser, Long shopId); + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + Long createInviteCode(UserDO currentUser, InviteCodeDTO dto); + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param status parameter `status` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean updateInviteCodeStatus(UserDO currentUser, Long id, Integer status); + /** + * Run business method `resolveInviteCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param code parameter `code` supplied by the caller + * @return InviteCodeVO result consumed by the caller or returned to the frontend + */ + InviteCodeVO resolveInviteCode(String code); +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/ShopService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/ShopService.java index 44289211..b1b9a1a7 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/ShopService.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/ShopService.java @@ -90,4 +90,14 @@ public interface ShopService extends IService { * @return 是否成功 */ boolean updateShopStatus(Long id, Integer status); + + /** + * 店铺是否已超过授权有效期。 + */ + boolean isAuthorizationExpired(Long shopId); + + /** + * 前台可用:未删除、启用、且授权未到期。 + */ + boolean isFrontendAvailable(Long shopId); } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/SystemMessageService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/SystemMessageService.java new file mode 100644 index 00000000..cd365392 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/SystemMessageService.java @@ -0,0 +1,110 @@ +package com.xiaowang.yuminailcore.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.yuminailcore.dto.SystemMessageCreateDTO; +import com.xiaowang.yuminailcore.entity.SystemMessageDO; +import com.xiaowang.yuminailcore.entity.UserDO; +import com.xiaowang.yuminailcore.vo.MessageTargetOptionsVO; +import com.xiaowang.yuminailcore.vo.SystemMessageVO; + +import java.util.List; +/** + * SystemMessageService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public interface SystemMessageService extends IService { + + /** + * Run business method `publishMessage`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + Long publishMessage(UserDO currentUser, SystemMessageCreateDTO dto); + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List listAdminMessages(UserDO currentUser); + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param messageId parameter `messageId` supplied by the caller + * @return SystemMessageVO result consumed by the caller or returned to the frontend + */ + SystemMessageVO getAdminMessage(UserDO currentUser, Long messageId); + + /** + * Run business method `revokeMessage`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param messageId parameter `messageId` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean revokeMessage(UserDO currentUser, Long messageId); + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return MessageTargetOptionsVO result consumed by the caller or returned to the frontend + */ + MessageTargetOptionsVO listTargetOptions(UserDO currentUser); + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List listMyMessages(Long userId); + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List listMyPopupMessages(Long userId); + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param messageId parameter `messageId` supplied by the caller + * @return SystemMessageVO result consumed by the caller or returned to the frontend + */ + SystemMessageVO getMyMessage(Long userId, Long messageId); + + /** + * Run business method `countMyUnreadMessages`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + Long countMyUnreadMessages(Long userId); + + /** + * Mark user state such as read or popup shown. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param messageId parameter `messageId` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean markPopupShown(Long userId, Long messageId); + + /** + * Mark user state such as read or popup shown. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param messageId parameter `messageId` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean markRead(Long userId, Long messageId); +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/SystemParameterConfigService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/SystemParameterConfigService.java new file mode 100644 index 00000000..c04e0b7d --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/SystemParameterConfigService.java @@ -0,0 +1,16 @@ +package com.xiaowang.yuminailcore.service; + +import com.xiaowang.yuminailcore.dto.SystemParameterConfigDTO; +import com.xiaowang.yuminailcore.entity.UserDO; +import com.xiaowang.yuminailcore.vo.SystemParameterConfigVO; + +import java.util.List; + +public interface SystemParameterConfigService { + + List listConfigs(UserDO currentUser, String configGroup); + + Boolean saveConfig(UserDO currentUser, SystemParameterConfigDTO dto); + + String getEnabledValue(String configGroup, String configKey); +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/UserAssetService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/UserAssetService.java index 4aaca776..a5cff7cf 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/UserAssetService.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/UserAssetService.java @@ -6,16 +6,54 @@ import com.xiaowang.yuminailcore.vo.BalanceChangeDetailVO; import com.xiaowang.yuminailcore.vo.UserAssetVO; import java.util.List; - +/** + * UserAssetService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ public interface UserAssetService { + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return UserAssetVO result consumed by the caller or returned to the frontend + */ UserAssetVO getUserAsset(Long userId); + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ List listBalanceHistory(Long userId); + /** + * Run business method `changeBalance`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param operatorId parameter `operatorId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return UserAssetVO result consumed by the caller or returned to the frontend + */ UserAssetVO changeBalance(Long operatorId, Long userId, AdminUserBalanceChangeDTO request); + /** + * Run business method `overrideVip`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param operatorId parameter `operatorId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return UserAssetVO result consumed by the caller or returned to the frontend + */ UserAssetVO overrideVip(Long operatorId, Long userId, AdminUserVipOverrideDTO request); + /** + * Run business method `recalculateVip`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param operatorId parameter `operatorId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return UserAssetVO result consumed by the caller or returned to the frontend + */ UserAssetVO recalculateVip(Long operatorId, Long userId); } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/UserService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/UserService.java index a1c79012..bf792d69 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/UserService.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/UserService.java @@ -13,83 +13,381 @@ import com.xiaowang.yuminailcore.entity.UserDO; import com.xiaowang.yuminailcore.vo.LoginShopSelectionVO; import com.xiaowang.yuminailcore.vo.LoginResponseVO; import com.xiaowang.yuminailcore.vo.PageResultVO; +import com.xiaowang.yuminailcore.vo.UserStatisticsVO; +import com.xiaowang.yuminailcore.vo.UserRelationVO; import com.xiaowang.yuminailcore.vo.UserVO; import java.util.List; - +/** + * UserService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ public interface UserService extends IService { + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDTO parameter `userDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ Long createUser(UserDTO userDTO); + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param userDTO parameter `userDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ boolean updateUser(Long id, UserDTO userDTO); + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ boolean deleteUser(Long id); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return UserVO result consumed by the caller or returned to the frontend + */ UserVO getUserById(Long id); + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ List listAllUsers(); + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ List listUsersByShopId(Long shopId); + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param type parameter `type` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ List listUsersByType(Integer type); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param account parameter `account` supplied by the caller + * @return UserVO result consumed by the caller or returned to the frontend + */ UserVO getUserByAccount(String account); + /** + * Run the login flow. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param loginRequestDTO parameter `loginRequestDTO` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ LoginResponseVO login(LoginRequestDTO loginRequestDTO); + /** + * Run business method `phoneLogin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phoneLoginRequestDTO parameter `phoneLoginRequestDTO` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ LoginResponseVO phoneLogin(PhoneLoginRequestDTO phoneLoginRequestDTO); + /** + * Run the login flow. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ LoginResponseVO loginByVerifiedPhone(String phone, Long shopId); + /** + * Run the login flow. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ LoginResponseVO loginByUserId(Long userId, Long shopId); + /** + * Run business method `adminLogin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param loginRequestDTO parameter `loginRequestDTO` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ LoginResponseVO adminLogin(LoginRequestDTO loginRequestDTO); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param account parameter `account` supplied by the caller + * @return LoginShopSelectionVO result consumed by the caller or returned to the frontend + */ LoginShopSelectionVO getLoginShopSelectionByAccount(String account); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @return LoginShopSelectionVO result consumed by the caller or returned to the frontend + */ LoginShopSelectionVO getLoginShopSelectionByPhone(String phone); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param account parameter `account` supplied by the caller + * @return LoginShopSelectionVO result consumed by the caller or returned to the frontend + */ LoginShopSelectionVO getAdminLoginShopSelection(String account); + /** + * Run business method `switchShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param previousSessionId parameter `previousSessionId` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ LoginResponseVO switchShop(Long userId, Long shopId, String previousSessionId); + /** + * Run business method `switchAdminShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param previousSessionId parameter `previousSessionId` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ LoginResponseVO switchAdminShop(Long userId, Long shopId, String previousSessionId); + /** + * Run business method `syncManagedPermissions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + */ void syncManagedPermissions(Long userId); + /** + * Run the registration flow. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param registerRequestDTO parameter `registerRequestDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ boolean register(RegisterRequestDTO registerRequestDTO); + /** + * Run business method `refreshToken`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param refreshToken parameter `refreshToken` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ LoginResponseVO refreshToken(String refreshToken); + /** + * Run business method `logout`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionId parameter `sessionId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ boolean logout(String sessionId); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return UserVO result consumed by the caller or returned to the frontend + */ UserVO getCurrentUserInfo(); + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userDTO parameter `userDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ boolean updateCurrentUserInfo(Long userId, UserDTO userDTO); + /** + * Run business method `bindPhone`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param bindPhoneRequestDTO parameter `bindPhoneRequestDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ boolean bindPhone(Long userId, BindPhoneRequestDTO bindPhoneRequestDTO); + /** + * Run business method `bindEmail`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param bindEmailRequestDTO parameter `bindEmailRequestDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ boolean bindEmail(Long userId, BindEmailRequestDTO bindEmailRequestDTO); + /** + * Run business method `resetPassword`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetUserId parameter `targetUserId` supplied by the caller + * @param currentUserId parameter `currentUserId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ boolean resetPassword(Long targetUserId, Long currentUserId); + /** + * Run business method `resetPasswordByPhone`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param resetPasswordRequestDTO parameter `resetPasswordRequestDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ boolean resetPasswordByPhone(ResetPasswordRequestDTO resetPasswordRequestDTO); + /** + * Query paged records. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @param size parameter `size` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param type parameter `type` supplied by the caller + * @return PageResultVO result consumed by the caller or returned to the frontend + */ PageResultVO pageUsers(Integer page, Integer size, String keyword, Long shopId, Integer type); + + /** + * Query paged records. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @param size parameter `size` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param type parameter `type` supplied by the caller + * @param roleId parameter `roleId` supplied by the caller + * @param parentUserId parameter `parentUserId` supplied by the caller + * @param sourceType parameter `sourceType` supplied by the caller + * @param status parameter `status` supplied by the caller + * @param vipLevel parameter `vipLevel` supplied by the caller + * @param createdFrom parameter `createdFrom` supplied by the caller + * @param createdTo parameter `createdTo` supplied by the caller + * @param hasPhone parameter `hasPhone` supplied by the caller + * @param hasOrder parameter `hasOrder` supplied by the caller + * @return PageResultVO result consumed by the caller or returned to the frontend + */ + PageResultVO pageUsers(Integer page, Integer size, String keyword, Long shopId, Integer type, Long roleId, Long parentUserId, String sourceType, Integer status, String vipLevel, String createdFrom, String createdTo, Boolean hasPhone, Boolean hasOrder); + + /** + * Run business method `statisticsUsers`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param keyword parameter `keyword` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param type parameter `type` supplied by the caller + * @param roleId parameter `roleId` supplied by the caller + * @param parentUserId parameter `parentUserId` supplied by the caller + * @param sourceType parameter `sourceType` supplied by the caller + * @param status parameter `status` supplied by the caller + * @param vipLevel parameter `vipLevel` supplied by the caller + * @param createdFrom parameter `createdFrom` supplied by the caller + * @param createdTo parameter `createdTo` supplied by the caller + * @param hasPhone parameter `hasPhone` supplied by the caller + * @param hasOrder parameter `hasOrder` supplied by the caller + * @return UserStatisticsVO result consumed by the caller or returned to the frontend + */ + UserStatisticsVO statisticsUsers(String keyword, Long shopId, Integer type, Long roleId, Long parentUserId, String sourceType, Integer status, String vipLevel, String createdFrom, String createdTo, Boolean hasPhone, Boolean hasOrder); + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return UserRelationVO result consumed by the caller or returned to the frontend + */ + UserRelationVO getCurrentUserRelation(Long userId); + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param status parameter `status` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ boolean updateUserStatus(Long id, Integer status); + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param status parameter `status` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ boolean updateUserStatusInShop(Long id, Integer status, Long shopId); + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ boolean deleteUserInShop(Long id, Long shopId); + /** + * Run business method `unbindUserInShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ boolean unbindUserInShop(Long id, Long shopId); + /** + * Run business method `unbindUserInShopWithOperator`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param operatorType parameter `operatorType` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ boolean unbindUserInShopWithOperator(Long id, Long shopId, Integer operatorType); + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param avatarUrl parameter `avatarUrl` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ boolean updateUserAvatar(Long userId, String avatarUrl); + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param password parameter `password` supplied by the caller + * @param verificationCode parameter `verificationCode` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ boolean updatePassword(Long userId, String password, String verificationCode); + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param updatePhoneDTO parameter `updatePhoneDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ boolean updatePhone(Long userId, UpdatePhoneRequestDTO updatePhoneDTO); } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/VerificationCodeService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/VerificationCodeService.java index 492564d4..c54481a9 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/VerificationCodeService.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/VerificationCodeService.java @@ -8,11 +8,42 @@ package com.xiaowang.yuminailcore.service; */ public interface VerificationCodeService { + /** + * Run business method `generateVerificationCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return String result consumed by the caller or returned to the frontend + */ String generateVerificationCode(); + /** + * Send or dispatch a message. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + */ void sendVerificationCode(String phone); + /** + * Send or dispatch a message. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param sceneCode parameter `sceneCode` supplied by the caller + */ + void sendVerificationCode(String phone, String sceneCode); + + /** + * Run business method `verifyCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param code parameter `code` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ boolean verifyCode(String phone, String code); + /** + * Run business method `canResend`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ boolean canResend(String phone); -} \ No newline at end of file +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/VipRechargePlanService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/VipRechargePlanService.java new file mode 100644 index 00000000..f6dfe0a5 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/VipRechargePlanService.java @@ -0,0 +1,56 @@ +package com.xiaowang.yuminailcore.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.xiaowang.yuminailcore.dto.VipRechargePlanDTO; +import com.xiaowang.yuminailcore.entity.UserDO; +import com.xiaowang.yuminailcore.entity.VipRechargePlanDO; +import com.xiaowang.yuminailcore.vo.VipRechargePlanVO; + +import java.util.List; +/** + * VipRechargePlanService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public interface VipRechargePlanService extends IService { + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + Long createPlan(UserDO currentUser, VipRechargePlanDTO dto); + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean updatePlan(UserDO currentUser, Long id, VipRechargePlanDTO dto); + /** + * Change the enabled/status flag of one record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param status parameter `status` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + Boolean updateStatus(UserDO currentUser, Long id, Integer status); + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List listAdminPlans(UserDO currentUser, Long shopId); + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + List listMyPlans(Long userId); +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/WechatMiniAuthService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/WechatMiniAuthService.java index ee36afbf..978f3367 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/WechatMiniAuthService.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/WechatMiniAuthService.java @@ -10,11 +10,34 @@ import com.xiaowang.yuminailcore.vo.WechatMiniLoginResultVO; */ public interface WechatMiniAuthService { + /** + * Run business method `autoLogin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return WechatMiniLoginResultVO result consumed by the caller or returned to the frontend + */ WechatMiniLoginResultVO autoLogin(WechatMiniAutoLoginRequestDTO requestDTO); + /** + * Run business method `phoneLogin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return WechatMiniLoginResultVO result consumed by the caller or returned to the frontend + */ WechatMiniLoginResultVO phoneLogin(WechatMiniPhoneLoginRequestDTO requestDTO); + /** + * Run business method `confirmLogin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return WechatMiniLoginResultVO result consumed by the caller or returned to the frontend + */ WechatMiniLoginResultVO confirmLogin(WechatMiniConfirmLoginRequestDTO requestDTO); + /** + * Run business method `invalidateBindingsByUserId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + */ void invalidateBindingsByUserId(Long userId); } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/WechatMiniClientService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/WechatMiniClientService.java index 95445a37..9a75c701 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/WechatMiniClientService.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/WechatMiniClientService.java @@ -5,12 +5,37 @@ package com.xiaowang.yuminailcore.service; */ public interface WechatMiniClientService { + /** + * Run business method `code2Session`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param wxCode parameter `wxCode` supplied by the caller + * @return SessionInfo result consumed by the caller or returned to the frontend + */ SessionInfo code2Session(String wxCode); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phoneCode parameter `phoneCode` supplied by the caller + * @return String result consumed by the caller or returned to the frontend + */ String getPhoneNumber(String phoneCode); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return String result consumed by the caller or returned to the frontend + */ String getConfiguredAppId(); + /** + * Run business method `SessionInfo`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param openId parameter `openId` supplied by the caller + * @param unionId parameter `unionId` supplied by the caller + * @param sessionKey parameter `sessionKey` supplied by the caller + * @return record result consumed by the caller or returned to the frontend + */ record SessionInfo(String openId, String unionId, String sessionKey) { } } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/WishlistService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/WishlistService.java index 9008b5af..766c478c 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/WishlistService.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/WishlistService.java @@ -5,10 +5,38 @@ import com.xiaowang.yuminailcore.dto.WishlistDTO; import com.xiaowang.yuminailcore.entity.WishlistDO; import java.util.List; - +/** + * WishlistService declares the business contract used by controllers. Implementations live in the matching ServiceImpl class. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ public interface WishlistService extends IService { + /** + * Add a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param productId parameter `productId` supplied by the caller + */ void addToWishlist(Long userId, Long productId); + /** + * Remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param productId parameter `productId` supplied by the caller + */ void removeFromWishlist(Long userId, Long productId); + /** + * Run business method `isInWishlist`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param productId parameter `productId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ boolean isInWishlist(Long userId, Long productId); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ List getWishlistByUserId(Long userId); } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/AnnouncementServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/AnnouncementServiceImpl.java new file mode 100644 index 00000000..fdb5d340 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/AnnouncementServiceImpl.java @@ -0,0 +1,483 @@ +package com.xiaowang.yuminailcore.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.xiaowang.yuminailcore.dto.AnnouncementCreateDTO; +import com.xiaowang.yuminailcore.entity.AnnouncementDO; +import com.xiaowang.yuminailcore.entity.ShopDO; +import com.xiaowang.yuminailcore.entity.UserDO; +import com.xiaowang.yuminailcore.entity.UserShopBindingDO; +import com.xiaowang.yuminailcore.mapper.AnnouncementMapper; +import com.xiaowang.yuminailcore.mapper.ShopMapper; +import com.xiaowang.yuminailcore.mapper.UserMapper; +import com.xiaowang.yuminailcore.mapper.UserShopBindingMapper; +import com.xiaowang.yuminailcore.service.AnnouncementService; +import com.xiaowang.yuminailcore.support.AdminScopeHelper; +import com.xiaowang.yuminailcore.vo.AnnouncementVO; +import com.xiaowang.yuminailcore.vo.MessageTargetOptionsVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.CollectionUtils; +import org.springframework.util.StringUtils; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +/** + * AnnouncementServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class AnnouncementServiceImpl extends ServiceImpl implements AnnouncementService { + + private static final String TARGET_PLATFORM_ALL = "PLATFORM_ALL"; + private static final String TARGET_CURRENT_SHOP_ALL = "CURRENT_SHOP_ALL"; + private static final String TARGET_SHOP_ALL = "SHOP_ALL"; + private static final String TARGET_SELECTED_SHOPS = "SELECTED_SHOPS"; + private static final String TARGET_SELECTED_USERS = "SELECTED_USERS"; + /** + * Variable `announcementMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AnnouncementMapper announcementMapper; + /** + * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserMapper userMapper; + /** + * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopMapper shopMapper; + /** + * Variable `userShopBindingMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserShopBindingMapper userShopBindingMapper; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Run business method `publishAnnouncement`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long publishAnnouncement(UserDO currentUser, AnnouncementCreateDTO dto) { + String targetType = normalizeTargetType(dto.getTargetType()); + List targetIds = resolveAndValidateTargets(currentUser, targetType, dto); + AnnouncementDO announcement = new AnnouncementDO(); + announcement.setTitle(dto.getTitle().trim()); + announcement.setContent(dto.getContent().trim()); + announcement.setPublisherId(currentUser.getId()); + announcement.setPublisherName(resolvePublisherName(currentUser)); + announcement.setPublisherType(currentUser.getType()); + announcement.setTargetType(targetType); + announcement.setTargetIds(joinIds(targetIds)); + announcement.setStatus(1); + announcement.setSortOrder(dto.getSortOrder() == null ? 0 : dto.getSortOrder()); + announcement.setPublishTime(LocalDateTime.now()); + announcement.setIsDelete(0); + announcementMapper.insert(announcement); + return announcement.getId(); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listAdminAnnouncements(UserDO currentUser) { + return announcementMapper.selectList(new LambdaQueryWrapper() + .eq(AnnouncementDO::getIsDelete, 0) + .orderByDesc(AnnouncementDO::getPublishTime)) + .stream() + .filter(item -> canAdminSee(currentUser, item)) + .map(this::toVO) + .collect(Collectors.toList()); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return AnnouncementVO result consumed by the caller or returned to the frontend + */ + public AnnouncementVO getAdminAnnouncement(UserDO currentUser, Long id) { + AnnouncementDO announcement = requireAnnouncement(id); + if (!canAdminSee(currentUser, announcement)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("无权查看该公告"); + } + /** + * Run business method `toVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param announcement parameter `announcement` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return toVO(announcement); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Run business method `revokeAnnouncement`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean revokeAnnouncement(UserDO currentUser, Long id) { + AnnouncementDO announcement = requireAnnouncement(id); + if (!canAdminSee(currentUser, announcement)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("无权撤回该公告"); + } + announcement.setStatus(0); + announcementMapper.updateById(announcement); + return true; + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return MessageTargetOptionsVO result consumed by the caller or returned to the frontend + */ + public MessageTargetOptionsVO listTargetOptions(UserDO currentUser) { + MessageTargetOptionsVO options = new MessageTargetOptionsVO(); + List shops = adminScopeHelper.isPlatformAdmin(currentUser) + ? shopMapper.selectList(new LambdaQueryWrapper().eq(ShopDO::getIsDelete, 0).eq(ShopDO::getStatus, 1)) + : shopMapper.selectList(new LambdaQueryWrapper().eq(ShopDO::getId, adminScopeHelper.getManagedShopId(currentUser)).eq(ShopDO::getIsDelete, 0)); + Map shopNameMap = shops.stream().collect(Collectors.toMap(ShopDO::getId, ShopDO::getShopName, (a, b) -> a)); + List shopIds = shops.stream().map(ShopDO::getId).collect(Collectors.toList()); + List users = shopIds.isEmpty() + ? List.of() + : userMapper.selectList(new LambdaQueryWrapper() + .eq(UserDO::getIsDelete, 0) + .eq(UserDO::getStatus, 1) + .in(UserDO::getShopId, shopIds) + .orderByAsc(UserDO::getType) + .orderByAsc(UserDO::getNickname)); + options.setShops(shops.stream().map(shop -> { + MessageTargetOptionsVO.ShopOptionVO vo = new MessageTargetOptionsVO.ShopOptionVO(); + vo.setId(shop.getId()); + vo.setShopName(shop.getShopName()); + return vo; + }).collect(Collectors.toList())); + options.setUsers(users.stream().map(user -> { + MessageTargetOptionsVO.UserOptionVO vo = new MessageTargetOptionsVO.UserOptionVO(); + vo.setId(user.getId()); + vo.setNickname(user.getNickname()); + vo.setAccount(user.getAccount()); + vo.setShopId(user.getShopId()); + vo.setShopName(shopNameMap.get(user.getShopId())); + vo.setType(user.getType()); + return vo; + }).collect(Collectors.toList())); + return options; + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listMyAnnouncements(Long userId) { + UserDO user = requireUser(userId); + return announcementMapper.selectList(new LambdaQueryWrapper() + .eq(AnnouncementDO::getIsDelete, 0) + .eq(AnnouncementDO::getStatus, 1) + .orderByDesc(AnnouncementDO::getSortOrder) + .orderByDesc(AnnouncementDO::getPublishTime)) + .stream() + .filter(item -> isVisibleToUser(item, user)) + .map(this::toVO) + .collect(Collectors.toList()); + } + + /** + * Run business method `resolveAndValidateTargets`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param targetType parameter `targetType` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List resolveAndValidateTargets(UserDO currentUser, String targetType, AnnouncementCreateDTO dto) { + if (adminScopeHelper.isPlatformAdmin(currentUser)) { + if (TARGET_PLATFORM_ALL.equals(targetType)) return List.of(); + if (TARGET_SHOP_ALL.equals(targetType) || TARGET_SELECTED_SHOPS.equals(targetType)) { + List shopIds = normalizeIds(dto.getShopIds()); + if (shopIds.isEmpty()) throw new RuntimeException("请选择公告店铺"); + /** + * Run business method `assertShopsExist`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopIds parameter `shopIds` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertShopsExist(shopIds); + return shopIds; + } + if (TARGET_SELECTED_USERS.equals(targetType)) { + List userIds = normalizeIds(dto.getUserIds()); + if (userIds.isEmpty()) throw new RuntimeException("请选择公告用户"); + /** + * Run business method `assertUsersExist`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userIds parameter `userIds` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertUsersExist(userIds); + return userIds; + } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("公告范围不正确"); + } + if (!Integer.valueOf(2).equals(currentUser.getType())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("只有管理员或店长可以发布公告"); + } + Long managedShopId = adminScopeHelper.getManagedShopId(currentUser); + if (TARGET_CURRENT_SHOP_ALL.equals(targetType) || TARGET_SHOP_ALL.equals(targetType)) { + return List.of(managedShopId); + } + if (TARGET_SELECTED_USERS.equals(targetType)) { + List userIds = normalizeIds(dto.getUserIds()); + if (userIds.isEmpty()) throw new RuntimeException("请选择公告用户"); + userIds.forEach(userId -> adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权选择其他店铺用户")); + return userIds; + } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("店长只能发布本店公告或本店指定用户公告"); + } + + /** + * Run business method `isVisibleToUser`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param item parameter `item` supplied by the caller + * @param user parameter `user` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean isVisibleToUser(AnnouncementDO item, UserDO user) { + String targetType = item.getTargetType(); + Set targetIds = parseIds(item.getTargetIds()); + if (TARGET_PLATFORM_ALL.equals(targetType)) return true; + if (TARGET_SELECTED_USERS.equals(targetType)) return targetIds.contains(user.getId()); + if (TARGET_CURRENT_SHOP_ALL.equals(targetType) || TARGET_SHOP_ALL.equals(targetType) || TARGET_SELECTED_SHOPS.equals(targetType)) { + return getUserShopIds(user).stream().anyMatch(targetIds::contains); + } + return false; + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param user parameter `user` supplied by the caller + * @return private Set result consumed by the caller or returned to the frontend + */ + private Set getUserShopIds(UserDO user) { + LinkedHashSet ids = new LinkedHashSet<>(); + if (user.getShopId() != null && user.getShopId() > 0) ids.add(user.getShopId()); + userShopBindingMapper.selectList(new LambdaQueryWrapper() + .eq(UserShopBindingDO::getUserId, user.getId()) + .eq(UserShopBindingDO::getIsDelete, 0) + .eq(UserShopBindingDO::getStatus, 1)) + .forEach(binding -> { + if (binding.getShopId() != null && binding.getShopId() > 0) ids.add(binding.getShopId()); + }); + return ids; + } + + /** + * Run business method `canAdminSee`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param item parameter `item` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean canAdminSee(UserDO currentUser, AnnouncementDO item) { + if (adminScopeHelper.isPlatformAdmin(currentUser)) return true; + Long managedShopId = adminScopeHelper.getManagedShopId(currentUser); + if (TARGET_CURRENT_SHOP_ALL.equals(item.getTargetType()) || TARGET_SHOP_ALL.equals(item.getTargetType()) || TARGET_SELECTED_SHOPS.equals(item.getTargetType())) { + return parseIds(item.getTargetIds()).contains(managedShopId); + } + return Objects.equals(item.getPublisherId(), currentUser.getId()); + } + + /** + * Run business method `toVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param item parameter `item` supplied by the caller + * @return private AnnouncementVO result consumed by the caller or returned to the frontend + */ + private AnnouncementVO toVO(AnnouncementDO item) { + AnnouncementVO vo = new AnnouncementVO(); + vo.setId(item.getId()); + vo.setTitle(item.getTitle()); + vo.setContent(item.getContent()); + vo.setPublisherId(item.getPublisherId()); + vo.setPublisherName(item.getPublisherName()); + vo.setPublisherType(item.getPublisherType()); + vo.setTargetType(item.getTargetType()); + vo.setTargetTypeName(targetTypeName(item.getTargetType())); + vo.setTargetIds(new ArrayList<>(parseIds(item.getTargetIds()))); + vo.setStatus(item.getStatus()); + vo.setSortOrder(item.getSortOrder()); + vo.setPublishTime(item.getPublishTime()); + vo.setCreateTime(item.getCreateTime()); + return vo; + } + + /** + * Run business method `requireAnnouncement`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return private AnnouncementDO result consumed by the caller or returned to the frontend + */ + private AnnouncementDO requireAnnouncement(Long id) { + AnnouncementDO item = announcementMapper.selectById(id); + if (item == null || Integer.valueOf(1).equals(item.getIsDelete())) throw new RuntimeException("公告不存在"); + return item; + } + + /** + * Run business method `requireUser`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return private UserDO result consumed by the caller or returned to the frontend + */ + private UserDO requireUser(Long userId) { + UserDO user = userMapper.selectById(userId); + if (user == null || Integer.valueOf(1).equals(user.getIsDelete())) throw new RuntimeException("用户不存在"); + return user; + } + + /** + * Run business method `assertShopsExist`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopIds parameter `shopIds` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void assertShopsExist(List shopIds) { + Long count = shopMapper.selectCount(new LambdaQueryWrapper().in(ShopDO::getId, shopIds).eq(ShopDO::getIsDelete, 0)); + if (count == null || count < shopIds.size()) throw new RuntimeException("存在无效店铺"); + } + + /** + * Run business method `assertUsersExist`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userIds parameter `userIds` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void assertUsersExist(List userIds) { + Long count = userMapper.selectCount(new LambdaQueryWrapper().in(UserDO::getId, userIds).eq(UserDO::getIsDelete, 0)); + if (count == null || count < userIds.size()) throw new RuntimeException("存在无效用户"); + } + + /** + * Run business method `normalizeTargetType`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetType parameter `targetType` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String normalizeTargetType(String targetType) { + if (!StringUtils.hasText(targetType)) throw new RuntimeException("公告范围不能为空"); + return targetType.trim().toUpperCase(); + } + + /** + * Run business method `normalizeIds`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ids parameter `ids` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List normalizeIds(List ids) { + if (CollectionUtils.isEmpty(ids)) return List.of(); + return ids.stream().filter(Objects::nonNull).filter(id -> id > 0).distinct().collect(Collectors.toList()); + } + + /** + * Run business method `parseIds`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ids parameter `ids` supplied by the caller + * @return private Set result consumed by the caller or returned to the frontend + */ + private Set parseIds(String ids) { + if (!StringUtils.hasText(ids)) return Set.of(); + return java.util.Arrays.stream(ids.split(",")).map(String::trim).filter(StringUtils::hasText).map(Long::valueOf).collect(Collectors.toCollection(LinkedHashSet::new)); + } + + /** + * Run business method `joinIds`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ids parameter `ids` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String joinIds(List ids) { + return ids.stream().map(String::valueOf).collect(Collectors.joining(",")); + } + + /** + * Run business method `targetTypeName`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetType parameter `targetType` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String targetTypeName(String targetType) { + return switch (targetType) { + case TARGET_PLATFORM_ALL -> "全平台"; + case TARGET_CURRENT_SHOP_ALL, TARGET_SHOP_ALL -> "指定店铺全员"; + case TARGET_SELECTED_SHOPS -> "多个店铺"; + case TARGET_SELECTED_USERS -> "指定用户"; + default -> targetType; + }; + } + + /** + * Run business method `resolvePublisherName`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String resolvePublisherName(UserDO currentUser) { + return StringUtils.hasText(currentUser.getNickname()) ? currentUser.getNickname() : currentUser.getAccount(); + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/BalanceChangeDetailServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/BalanceChangeDetailServiceImpl.java index 7607f597..fba29d40 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/BalanceChangeDetailServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/BalanceChangeDetailServiceImpl.java @@ -23,10 +23,18 @@ import java.util.stream.Collectors; @Service @RequiredArgsConstructor public class BalanceChangeDetailServiceImpl extends ServiceImpl implements BalanceChangeDetailService { - + /** + * Variable `balanceChangeDetailMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final BalanceChangeDetailMapper balanceChangeDetailMapper; @Override + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param balanceChangeDetailDTO parameter `balanceChangeDetailDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ public Long createBalanceChangeDetail(BalanceChangeDetailDTO balanceChangeDetailDTO) { BalanceChangeDetailDO balanceChangeDetailDO = new BalanceChangeDetailDO(); balanceChangeDetailDO.setUserId(balanceChangeDetailDTO.getUserId()); @@ -47,6 +55,13 @@ public class BalanceChangeDetailServiceImpl extends ServiceImpl 0; } @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return BalanceChangeDetailVO result consumed by the caller or returned to the frontend + */ public BalanceChangeDetailVO getBalanceChangeDetailById(Long id) { BalanceChangeDetailDO balanceChangeDetailDO = balanceChangeDetailMapper.selectById(id); if (balanceChangeDetailDO == null) { return null; } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param balanceChangeDetailDO parameter `balanceChangeDetailDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ return convertToVO(balanceChangeDetailDO); } @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ public List listAllBalanceChangeDetails() { List balanceChangeDetailDOs = balanceChangeDetailMapper.selectList(null); return balanceChangeDetailDOs.stream() @@ -91,6 +129,12 @@ public class BalanceChangeDetailServiceImpl extends ServiceImpl result consumed by the caller or returned to the frontend + */ public List listBalanceChangeDetailsByUserId(Long userId) { List balanceChangeDetailDOs = balanceChangeDetailMapper.selectList( Wrappers.lambdaQuery(BalanceChangeDetailDO.class) diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/BalanceServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/BalanceServiceImpl.java index 30faf39e..5bafd60d 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/BalanceServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/BalanceServiceImpl.java @@ -24,10 +24,18 @@ import java.util.stream.Collectors; @Service @RequiredArgsConstructor public class BalanceServiceImpl extends ServiceImpl implements BalanceService { - + /** + * Variable `balanceMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final BalanceMapper balanceMapper; @Override + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param balanceDTO parameter `balanceDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ public Long createBalance(BalanceDTO balanceDTO) { BalanceDO balanceDO = new BalanceDO(); balanceDO.setUserId(balanceDTO.getUserId()); @@ -40,6 +48,13 @@ public class BalanceServiceImpl extends ServiceImpl im } @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param balanceDTO parameter `balanceDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ public boolean updateBalance(Long id, BalanceDTO balanceDTO) { BalanceDO balanceDO = balanceMapper.selectById(id); if (balanceDO == null) { @@ -54,20 +69,43 @@ public class BalanceServiceImpl extends ServiceImpl im } @Override + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ public boolean deleteBalance(Long id) { return balanceMapper.deleteById(id) > 0; } @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return BalanceVO result consumed by the caller or returned to the frontend + */ public BalanceVO getBalanceById(Long id) { BalanceDO balanceDO = balanceMapper.selectById(id); if (balanceDO == null) { return null; } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param balanceDO parameter `balanceDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ return convertToVO(balanceDO); } @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ public List listAllBalances() { List balanceDOs = balanceMapper.selectList(null); return balanceDOs.stream() @@ -76,6 +114,12 @@ public class BalanceServiceImpl extends ServiceImpl im } @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return BalanceVO result consumed by the caller or returned to the frontend + */ public BalanceVO getBalanceByUserId(Long userId) { BalanceDO balanceDO = balanceMapper.selectOne( Wrappers.lambdaQuery(BalanceDO.class) @@ -84,6 +128,12 @@ public class BalanceServiceImpl extends ServiceImpl im if (balanceDO == null) { return null; } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param balanceDO parameter `balanceDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ return convertToVO(balanceDO); } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/CartServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/CartServiceImpl.java index dd6eef1c..151683f7 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/CartServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/CartServiceImpl.java @@ -30,6 +30,10 @@ import java.util.Objects; import java.util.stream.Collectors; @Service +/** + * CartServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ public class CartServiceImpl implements CartService { @Resource @@ -55,11 +59,22 @@ public class CartServiceImpl implements CartService { @Override @Transactional + /** + * Add a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param cartDTO parameter `cartDTO` supplied by the caller + */ public void addToCart(Long userId, CartDTO cartDTO) { validateQuantity(cartDTO.getQuantity()); ProductDO product = productMapper.selectById(cartDTO.getProductId()); if (product == null || Integer.valueOf(1).equals(product.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("商品不存在"); } @@ -80,6 +95,12 @@ public class CartServiceImpl implements CartService { @Override @Transactional + /** + * Remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param productId parameter `productId` supplied by the caller + */ public void removeFromCart(Long userId, Long productId) { QueryWrapper wrapper = new QueryWrapper<>(); wrapper.eq("user_id", userId) @@ -90,6 +111,12 @@ public class CartServiceImpl implements CartService { @Override @Transactional + /** + * Run business method `batchRemoveFromCart`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param cartItemIds parameter `cartItemIds` supplied by the caller + */ public void batchRemoveFromCart(Long userId, List cartItemIds) { if (cartItemIds == null || cartItemIds.isEmpty()) { return; @@ -103,6 +130,12 @@ public class CartServiceImpl implements CartService { @Override @Transactional + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param cartDTO parameter `cartDTO` supplied by the caller + */ public void updateCartQuantity(Long userId, CartDTO cartDTO) { validateQuantity(cartDTO.getQuantity()); CartDO cart = cartMapper.selectByUserIdAndProductId(userId, cartDTO.getProductId()); @@ -112,10 +145,21 @@ public class CartServiceImpl implements CartService { return; } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("购物车商品不存在"); } @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ public List getCartList(Long userId) { List cartList = cartMapper.selectByUserId(userId); List cartVOList = new ArrayList<>(); @@ -164,6 +208,11 @@ public class CartServiceImpl implements CartService { @Override @Transactional + /** + * Run business method `clearCart`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + */ public void clearCart(Long userId) { QueryWrapper wrapper = new QueryWrapper<>(); wrapper.eq("user_id", userId) @@ -171,12 +220,29 @@ public class CartServiceImpl implements CartService { cartMapper.delete(wrapper); } + /** + * Run business method `validateQuantity`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param quantity parameter `quantity` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void validateQuantity(Integer quantity) { if (quantity == null || quantity < 1 || quantity > 99) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("购物车数量必须在 1 到 99 之间"); } } + /** + * Run business method `resolveTagNames`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagIds parameter `tagIds` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ private String resolveTagNames(String tagIds) { if (!StringUtils.hasText(tagIds)) { return ""; @@ -197,6 +263,14 @@ public class CartServiceImpl implements CartService { .collect(Collectors.joining(",")); } + /** + * Run business method `resolveAvailableArtists`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @param rawBookableArtists parameter `rawBookableArtists` supplied by the caller + * @param validBookableArtists parameter `validBookableArtists` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ private List resolveAvailableArtists(Long shopId, String rawBookableArtists, String validBookableArtists) { LinkedHashSet candidateArtistIds = new LinkedHashSet<>(); if (StringUtils.hasText(validBookableArtists)) { @@ -221,7 +295,7 @@ public class CartServiceImpl implements CartService { List artistUsers = userMapper.selectList( new QueryWrapper() .in("id", candidateArtistIds) - .eq("type", 3) + .in("type", List.of(2, 3)) .eq("status", 1) .eq("is_delete", 0) ); @@ -235,15 +309,25 @@ public class CartServiceImpl implements CartService { return candidateArtistIds.stream() .map(artistMap::get) .filter(Objects::nonNull) + .filter(bookableArtistSupport::isBookableServiceUser) .map(this::buildCartArtist) .collect(Collectors.toList()); } + /** + * Run business method `buildCartArtist`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param artist parameter `artist` supplied by the caller + * @return private CartArtistVO result consumed by the caller or returned to the frontend + */ private CartArtistVO buildCartArtist(UserDO artist) { CartArtistVO cartArtistVO = new CartArtistVO(); cartArtistVO.setId(artist.getId()); cartArtistVO.setName(artist.getNickname()); cartArtistVO.setAvatar(objectStorageUrlSupport.toAccessibleUrl(artist.getAvatar())); + cartArtistVO.setUserType(artist.getType()); + cartArtistVO.setRoleLabel(Integer.valueOf(2).equals(artist.getType()) ? "店长 · 参与制作" : "美甲师"); + cartArtistVO.setParticipateProduction(Integer.valueOf(2).equals(artist.getType())); return cartArtistVO; } } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/ChunkUploadServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/ChunkUploadServiceImpl.java index 501a6fca..bfa0d528 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/ChunkUploadServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/ChunkUploadServiceImpl.java @@ -31,6 +31,10 @@ import java.util.Objects; @Slf4j @Service @RequiredArgsConstructor +/** + * ChunkUploadServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ public class ChunkUploadServiceImpl implements ChunkUploadService { // Keep each chunk comfortably below the common 1 MB gateway/body limit. @@ -39,51 +43,201 @@ public class ChunkUploadServiceImpl implements ChunkUploadService { private static final String METADATA_FILE_NAME = "metadata.json"; private static final String CHUNK_FILE_PREFIX = "chunk-"; private static final String CHUNK_FILE_SUFFIX = ".part"; - + /** + * Variable `objectMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final ObjectMapper objectMapper; @Override + /** + * Run business method `initAdminObjectStorageUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return ChunkUploadSessionVO result consumed by the caller or returned to the frontend + */ public ChunkUploadSessionVO initAdminObjectStorageUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO) { + /** + * Run business method `initUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param UploadTargetTypeADMIN_OBJECT_STORAGE parameter `UploadTargetTypeADMIN_OBJECT_STORAGE` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ return initUpload(UploadTargetType.ADMIN_OBJECT_STORAGE, ownerId, requestDTO); } @Override + /** + * Run business method `initUserAvatarUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return ChunkUploadSessionVO result consumed by the caller or returned to the frontend + */ public ChunkUploadSessionVO initUserAvatarUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO) { + /** + * Run business method `initUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param UploadTargetTypeUSER_AVATAR parameter `UploadTargetTypeUSER_AVATAR` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ return initUpload(UploadTargetType.USER_AVATAR, ownerId, requestDTO); } @Override + /** + * Run business method `uploadAdminObjectStorageChunk`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @param chunkIndex parameter `chunkIndex` supplied by the caller + * @param totalChunks parameter `totalChunks` supplied by the caller + * @param chunkFile parameter `chunkFile` supplied by the caller + */ public void uploadAdminObjectStorageChunk(Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile) { + /** + * Run business method `uploadChunk`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param UploadTargetTypeADMIN_OBJECT_STORAGE parameter `UploadTargetTypeADMIN_OBJECT_STORAGE` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @param chunkIndex parameter `chunkIndex` supplied by the caller + * @param totalChunks parameter `totalChunks` supplied by the caller + * @param chunkFile parameter `chunkFile` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ uploadChunk(UploadTargetType.ADMIN_OBJECT_STORAGE, ownerId, uploadId, chunkIndex, totalChunks, chunkFile); } @Override + /** + * Run business method `uploadUserAvatarChunk`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @param chunkIndex parameter `chunkIndex` supplied by the caller + * @param totalChunks parameter `totalChunks` supplied by the caller + * @param chunkFile parameter `chunkFile` supplied by the caller + */ public void uploadUserAvatarChunk(Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile) { + /** + * Run business method `uploadChunk`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param UploadTargetTypeUSER_AVATAR parameter `UploadTargetTypeUSER_AVATAR` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @param chunkIndex parameter `chunkIndex` supplied by the caller + * @param totalChunks parameter `totalChunks` supplied by the caller + * @param chunkFile parameter `chunkFile` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ uploadChunk(UploadTargetType.USER_AVATAR, ownerId, uploadId, chunkIndex, totalChunks, chunkFile); } @Override + /** + * Run business method `prepareAdminObjectStorageFile`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return PreparedUploadFile result consumed by the caller or returned to the frontend + */ public PreparedUploadFile prepareAdminObjectStorageFile(Long ownerId, String uploadId) { + /** + * Run business method `prepareMergedFile`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param UploadTargetTypeADMIN_OBJECT_STORAGE parameter `UploadTargetTypeADMIN_OBJECT_STORAGE` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ return prepareMergedFile(UploadTargetType.ADMIN_OBJECT_STORAGE, ownerId, uploadId); } @Override + /** + * Run business method `prepareUserAvatarFile`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return PreparedUploadFile result consumed by the caller or returned to the frontend + */ public PreparedUploadFile prepareUserAvatarFile(Long ownerId, String uploadId) { + /** + * Run business method `prepareMergedFile`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param UploadTargetTypeUSER_AVATAR parameter `UploadTargetTypeUSER_AVATAR` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ return prepareMergedFile(UploadTargetType.USER_AVATAR, ownerId, uploadId); } @Override + /** + * Run business method `clearAdminObjectStorageUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + */ public void clearAdminObjectStorageUpload(Long ownerId, String uploadId) { + /** + * Run business method `clearUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param UploadTargetTypeADMIN_OBJECT_STORAGE parameter `UploadTargetTypeADMIN_OBJECT_STORAGE` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ clearUpload(UploadTargetType.ADMIN_OBJECT_STORAGE, ownerId, uploadId); } @Override + /** + * Run business method `clearUserAvatarUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + */ public void clearUserAvatarUpload(Long ownerId, String uploadId) { + /** + * Run business method `clearUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param UploadTargetTypeUSER_AVATAR parameter `UploadTargetTypeUSER_AVATAR` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ clearUpload(UploadTargetType.USER_AVATAR, ownerId, uploadId); } + /** + * Run business method `initUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetType parameter `targetType` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return private ChunkUploadSessionVO result consumed by the caller or returned to the frontend + */ private ChunkUploadSessionVO initUpload(UploadTargetType targetType, Long ownerId, ChunkUploadInitRequestDTO requestDTO) { + /** + * Run business method `validateInitRequest`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ validateInitRequest(ownerId, requestDTO); + /** + * Run business method `cleanupExpiredSessionsQuietly`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return result consumed by the caller or returned to the frontend + */ cleanupExpiredSessionsQuietly(); String uploadId = buildUploadId(targetType, ownerId, requestDTO); @@ -95,6 +249,12 @@ public class ChunkUploadServiceImpl implements ChunkUploadService { UploadMetadata metadata = readMetadataIfExists(sessionDir); if (metadata != null && !isCompatible(metadata, targetType, ownerId, requestDTO, totalChunks)) { + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionDir parameter `sessionDir` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ deleteDirectory(sessionDir); Files.createDirectories(sessionDir); metadata = null; @@ -115,6 +275,13 @@ public class ChunkUploadServiceImpl implements ChunkUploadService { metadata.setCreatedAt(Instant.now().toEpochMilli()); } metadata.setUpdatedAt(Instant.now().toEpochMilli()); + /** + * Run business method `writeMetadata`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionDir parameter `sessionDir` supplied by the caller + * @param metadata parameter `metadata` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ writeMetadata(sessionDir, metadata); ChunkUploadSessionVO sessionVO = new ChunkUploadSessionVO(); @@ -125,33 +292,84 @@ public class ChunkUploadServiceImpl implements ChunkUploadService { return sessionVO; } catch (IOException e) { log.error("初始化分片上传失败, uploadId={}", uploadId, e); + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("初始化上传失败"); } } + /** + * Run business method `uploadChunk`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetType parameter `targetType` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @param chunkIndex parameter `chunkIndex` supplied by the caller + * @param totalChunks parameter `totalChunks` supplied by the caller + * @param chunkFile parameter `chunkFile` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void uploadChunk(UploadTargetType targetType, Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile) { if (ownerId == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("未获取到上传用户信息"); } if (!StringUtils.hasText(uploadId)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("上传标识不能为空"); } if (chunkIndex == null || chunkIndex < 0) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("分片序号不合法"); } if (totalChunks == null || totalChunks <= 0) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("分片总数不合法"); } if (chunkFile == null || chunkFile.isEmpty()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("上传分片不能为空"); } Path sessionDir = getSessionDir(uploadId); UploadMetadata metadata = readAndValidateMetadata(sessionDir, targetType, ownerId, uploadId); if (!Objects.equals(metadata.getTotalChunks(), totalChunks)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("分片总数不匹配,请重新上传"); } if (chunkIndex >= metadata.getTotalChunks()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("分片序号超出范围"); } @@ -163,18 +381,43 @@ public class ChunkUploadServiceImpl implements ChunkUploadService { } Files.move(tempChunkPath, chunkPath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); metadata.setUpdatedAt(Instant.now().toEpochMilli()); + /** + * Run business method `writeMetadata`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionDir parameter `sessionDir` supplied by the caller + * @param metadata parameter `metadata` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ writeMetadata(sessionDir, metadata); } catch (IOException e) { log.error("保存分片失败, uploadId={}, chunkIndex={}", uploadId, chunkIndex, e); + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("上传分片失败"); } } + /** + * Run business method `prepareMergedFile`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetType parameter `targetType` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return private PreparedUploadFile result consumed by the caller or returned to the frontend + */ private PreparedUploadFile prepareMergedFile(UploadTargetType targetType, Long ownerId, String uploadId) { Path sessionDir = getSessionDir(uploadId); UploadMetadata metadata = readAndValidateMetadata(sessionDir, targetType, ownerId, uploadId); List uploadedChunks = getUploadedChunks(sessionDir, metadata.getTotalChunks()); if (uploadedChunks.size() != metadata.getTotalChunks()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("文件尚未上传完成,请稍后再试"); } @@ -184,6 +427,11 @@ public class ChunkUploadServiceImpl implements ChunkUploadService { for (int chunkIndex = 0; chunkIndex < metadata.getTotalChunks(); chunkIndex++) { Path chunkPath = getChunkPath(sessionDir, chunkIndex); if (!Files.exists(chunkPath)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("缺少上传分片,请重新上传"); } Files.copy(chunkPath, outputStream); @@ -192,54 +440,158 @@ public class ChunkUploadServiceImpl implements ChunkUploadService { return new LocalPreparedUploadFile(mergedFilePath.toFile(), metadata.getFileName(), metadata.getContentType(), metadata.getFileSize()); } catch (IOException e) { log.error("合并上传文件失败, uploadId={}", uploadId, e); + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("合并上传文件失败"); } } + /** + * Run business method `clearUpload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetType parameter `targetType` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void clearUpload(UploadTargetType targetType, Long ownerId, String uploadId) { Path sessionDir = getSessionDir(uploadId); + /** + * Run business method `readAndValidateMetadata`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionDir parameter `sessionDir` supplied by the caller + * @param targetType parameter `targetType` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ readAndValidateMetadata(sessionDir, targetType, ownerId, uploadId); + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionDir parameter `sessionDir` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ deleteDirectory(sessionDir); } + /** + * Run business method `readAndValidateMetadata`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionDir parameter `sessionDir` supplied by the caller + * @param targetType parameter `targetType` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param uploadId parameter `uploadId` supplied by the caller + * @return private UploadMetadata result consumed by the caller or returned to the frontend + */ private UploadMetadata readAndValidateMetadata(Path sessionDir, UploadTargetType targetType, Long ownerId, String uploadId) { UploadMetadata metadata = readMetadataIfExists(sessionDir); if (metadata == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("上传会话不存在,请重新上传"); } if (!targetType.name().equals(metadata.getTargetType()) || !Objects.equals(ownerId, metadata.getOwnerId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("无权操作该上传会话"); } if (!uploadId.equals(metadata.getUploadId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("上传会话不匹配"); } return metadata; } + /** + * Run business method `validateInitRequest`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ownerId parameter `ownerId` supplied by the caller + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void validateInitRequest(Long ownerId, ChunkUploadInitRequestDTO requestDTO) { if (ownerId == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("未获取到上传用户信息"); } if (requestDTO == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("上传参数不能为空"); } if (!StringUtils.hasText(requestDTO.getFileName())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("文件名不能为空"); } if (!StringUtils.hasText(requestDTO.getContentType())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("文件类型不能为空"); } if (!StringUtils.hasText(requestDTO.getFileFingerprint())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("文件指纹不能为空"); } if (!StringUtils.hasText(requestDTO.getScene())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("上传场景不能为空"); } if (requestDTO.getFileSize() == null || requestDTO.getFileSize() <= 0) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("文件大小不合法"); } } + /** + * Run business method `isCompatible`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param metadata parameter `metadata` supplied by the caller + * @param targetType parameter `targetType` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param requestDTO parameter `requestDTO` supplied by the caller + * @param totalChunks parameter `totalChunks` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ private boolean isCompatible(UploadMetadata metadata, UploadTargetType targetType, Long ownerId, ChunkUploadInitRequestDTO requestDTO, int totalChunks) { return targetType.name().equals(metadata.getTargetType()) && Objects.equals(ownerId, metadata.getOwnerId()) @@ -249,23 +601,55 @@ public class ChunkUploadServiceImpl implements ChunkUploadService { && Objects.equals(metadata.getScene(), requestDTO.getScene()); } + /** + * Run business method `buildUploadId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetType parameter `targetType` supplied by the caller + * @param ownerId parameter `ownerId` supplied by the caller + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ private String buildUploadId(UploadTargetType targetType, Long ownerId, ChunkUploadInitRequestDTO requestDTO) { String raw = targetType.name() + "|" + ownerId + "|" + requestDTO.getScene() + "|" + requestDTO.getFileFingerprint(); return DigestUtils.md5DigestAsHex(raw.getBytes(StandardCharsets.UTF_8)); } + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param uploadId parameter `uploadId` supplied by the caller + * @return private Path result consumed by the caller or returned to the frontend + */ private Path getSessionDir(String uploadId) { return getUploadRoot().resolve(uploadId); } + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private Path result consumed by the caller or returned to the frontend + */ private Path getUploadRoot() { return Path.of(System.getProperty("java.io.tmpdir"), "yuminail", "chunk-upload"); } + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionDir parameter `sessionDir` supplied by the caller + * @param chunkIndex parameter `chunkIndex` supplied by the caller + * @return private Path result consumed by the caller or returned to the frontend + */ private Path getChunkPath(Path sessionDir, int chunkIndex) { return sessionDir.resolve(CHUNK_FILE_PREFIX + String.format("%05d", chunkIndex) + CHUNK_FILE_SUFFIX); } + /** + * Run business method `readMetadataIfExists`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionDir parameter `sessionDir` supplied by the caller + * @return private UploadMetadata result consumed by the caller or returned to the frontend + */ private UploadMetadata readMetadataIfExists(Path sessionDir) { Path metadataPath = sessionDir.resolve(METADATA_FILE_NAME); if (!Files.exists(metadataPath)) { @@ -279,11 +663,25 @@ public class ChunkUploadServiceImpl implements ChunkUploadService { } } + /** + * Run business method `writeMetadata`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionDir parameter `sessionDir` supplied by the caller + * @param metadata parameter `metadata` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void writeMetadata(Path sessionDir, UploadMetadata metadata) throws IOException { Path metadataPath = sessionDir.resolve(METADATA_FILE_NAME); objectMapper.writeValue(metadataPath.toFile(), metadata); } + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionDir parameter `sessionDir` supplied by the caller + * @param totalChunks parameter `totalChunks` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ private List getUploadedChunks(Path sessionDir, int totalChunks) { List uploadedChunks = new ArrayList<>(); for (int chunkIndex = 0; chunkIndex < totalChunks; chunkIndex++) { @@ -294,6 +692,11 @@ public class ChunkUploadServiceImpl implements ChunkUploadService { return uploadedChunks; } + /** + * Run business method `cleanupExpiredSessionsQuietly`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private void result consumed by the caller or returned to the frontend + */ private void cleanupExpiredSessionsQuietly() { try { Path uploadRoot = getUploadRoot(); @@ -311,18 +714,43 @@ public class ChunkUploadServiceImpl implements ChunkUploadService { } } + /** + * Run business method `cleanupExpiredSession`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionDir parameter `sessionDir` supplied by the caller + * @param expireAt parameter `expireAt` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void cleanupExpiredSession(Path sessionDir, Instant expireAt) { UploadMetadata metadata = readMetadataIfExists(sessionDir); if (metadata == null) { + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionDir parameter `sessionDir` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ deleteDirectory(sessionDir); return; } Instant updatedAt = Instant.ofEpochMilli(metadata.getUpdatedAt() == null ? 0L : metadata.getUpdatedAt()); if (updatedAt.isBefore(expireAt)) { + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionDir parameter `sessionDir` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ deleteDirectory(sessionDir); } } + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param directory parameter `directory` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void deleteDirectory(Path directory) { if (directory == null || !Files.exists(directory)) { return; @@ -362,12 +790,32 @@ public class ChunkUploadServiceImpl implements ChunkUploadService { } private static class LocalPreparedUploadFile implements PreparedUploadFile { - + /** + * Variable `file`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final File file; + /** + * Variable `fileName`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final String fileName; + /** + * Variable `contentType`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final String contentType; + /** + * Variable `fileSize`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final long fileSize; + /** + * Run business method `LocalPreparedUploadFile`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param file parameter `file` supplied by the caller + * @param fileName parameter `fileName` supplied by the caller + * @param contentType parameter `contentType` supplied by the caller + * @param fileSize parameter `fileSize` supplied by the caller + * @return private result consumed by the caller or returned to the frontend + */ private LocalPreparedUploadFile(File file, String fileName, String contentType, long fileSize) { this.file = file; this.fileName = fileName; @@ -376,26 +824,50 @@ public class ChunkUploadServiceImpl implements ChunkUploadService { } @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return File result consumed by the caller or returned to the frontend + */ public File getFile() { return file; } @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return String result consumed by the caller or returned to the frontend + */ public String getFileName() { return fileName; } @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return String result consumed by the caller or returned to the frontend + */ public String getContentType() { return contentType; } @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return long result consumed by the caller or returned to the frontend + */ public long getFileSize() { return fileSize; } @Override + /** + * Run business method `close`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + */ public void close() { if (file != null && file.exists() && !file.delete()) { log.warn("删除合并后的临时文件失败: {}", file.getAbsolutePath()); diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/CommentServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/CommentServiceImpl.java index b40acb08..3cd74a35 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/CommentServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/CommentServiceImpl.java @@ -35,43 +35,97 @@ import java.util.stream.Collectors; @Service @RequiredArgsConstructor public class CommentServiceImpl extends ServiceImpl implements CommentService { - + /** + * Variable `commentMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final CommentMapper commentMapper; + /** + * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final UserMapper userMapper; + /** + * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final ShopMapper shopMapper; + /** + * Variable `productMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final ProductMapper productMapper; @Override + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param commentDTO parameter `commentDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ public Long createComment(CommentDTO commentDTO) { if (commentDTO == null || commentDTO.getUserId() == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("请先登录后再评论"); } return createComment(commentDTO.getUserId(), commentDTO); } @Override + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUserId parameter `currentUserId` supplied by the caller + * @param commentDTO parameter `commentDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ public Long createComment(Long currentUserId, CommentDTO commentDTO) { if (currentUserId == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("请先登录后再评论"); } if (commentDTO == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("评论内容不能为空"); } String content = sanitizeContent(commentDTO.getCommentContent()); Long productId = normalizeId(commentDTO.getProductId()); Long parentCommentId = normalizeId(commentDTO.getParentCommentId()); if (productId == null && parentCommentId == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("请选择要评论的作品"); } CommentDO parentComment = null; if (parentCommentId != null) { parentComment = commentMapper.selectById(parentCommentId); if (parentComment == null || Integer.valueOf(1).equals(parentComment.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("回复的评论不存在"); } if (productId == null) { productId = parentComment.getProductId(); } else if (parentComment.getProductId() != null && !productId.equals(parentComment.getProductId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("回复内容与作品不匹配"); } } @@ -95,6 +149,13 @@ public class CommentServiceImpl extends ServiceImpl im } @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param commentDTO parameter `commentDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ public boolean updateComment(Long id, CommentDTO commentDTO) { CommentDO commentDO = commentMapper.selectById(id); if (commentDO == null) { @@ -106,6 +167,12 @@ public class CommentServiceImpl extends ServiceImpl im } @Override + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ public boolean deleteComment(Long id) { CommentDO commentDO = commentMapper.selectById(id); if (commentDO == null) { @@ -116,12 +183,25 @@ public class CommentServiceImpl extends ServiceImpl im } @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param currentUserId parameter `currentUserId` supplied by the caller + * @param commentDTO parameter `commentDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ public boolean updateComment(Long id, Long currentUserId, CommentDTO commentDTO) { CommentDO commentDO = commentMapper.selectById(id); if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete())) { return false; } if (currentUserId == null || !currentUserId.equals(commentDO.getUserId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("只能修改自己的评论"); } commentDO.setCommentContent(sanitizeContent(commentDTO.getCommentContent())); @@ -130,12 +210,24 @@ public class CommentServiceImpl extends ServiceImpl im } @Override + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param currentUserId parameter `currentUserId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ public boolean deleteComment(Long id, Long currentUserId) { CommentDO commentDO = commentMapper.selectById(id); if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete())) { return false; } if (currentUserId == null || !currentUserId.equals(commentDO.getUserId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("只能删除自己的评论"); } commentDO.setIsDelete(1); @@ -144,12 +236,24 @@ public class CommentServiceImpl extends ServiceImpl im } @Override + /** + * Run business method `adminDeleteComment`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param managedShopId parameter `managedShopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ public boolean adminDeleteComment(Long id, Long managedShopId) { CommentDO commentDO = commentMapper.selectById(id); if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete())) { return false; } if (managedShopId != null && !managedShopId.equals(commentDO.getShopId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("无权删除其他门店评论"); } commentDO.setIsDelete(1); @@ -158,20 +262,43 @@ public class CommentServiceImpl extends ServiceImpl im } @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return CommentVO result consumed by the caller or returned to the frontend + */ public CommentVO getCommentById(Long id) { CommentDO commentDO = commentMapper.selectById(id); if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete())) { return null; } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param commentDO parameter `commentDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ return convertToVO(commentDO); } @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ public List listAllComments() { return toCommentVOList(activeQuery().orderByDesc(CommentDO::getCreateTime)); } @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ public List listCommentsByUserId(Long userId) { List commentDOs = commentMapper.selectList( Wrappers.lambdaQuery(CommentDO.class) @@ -185,6 +312,12 @@ public class CommentServiceImpl extends ServiceImpl im } @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ public List listCommentsByShopId(Long shopId) { List commentDOs = commentMapper.selectList( Wrappers.lambdaQuery(CommentDO.class) @@ -198,6 +331,12 @@ public class CommentServiceImpl extends ServiceImpl im } @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productId parameter `productId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ public List listCommentsByProductId(Long productId) { List commentDOs = commentMapper.selectList( Wrappers.lambdaQuery(CommentDO.class) @@ -205,10 +344,22 @@ public class CommentServiceImpl extends ServiceImpl im .eq(CommentDO::getIsDelete, 0) .orderByDesc(CommentDO::getCreateTime) ); + /** + * Run business method `buildTree`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param commentDOs parameter `commentDOs` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ return buildTree(commentDOs); } @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param parentCommentId parameter `parentCommentId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ public List listCommentsByParentCommentId(Long parentCommentId) { List commentDOs = commentMapper.selectList( Wrappers.lambdaQuery(CommentDO.class) @@ -222,6 +373,15 @@ public class CommentServiceImpl extends ServiceImpl im } @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productId parameter `productId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ public List listAdminComments(Long productId, Long userId, Long shopId, String keyword) { List commentDOs = commentMapper.selectList( Wrappers.lambdaQuery(CommentDO.class) @@ -252,14 +412,33 @@ public class CommentServiceImpl extends ServiceImpl im commentVO.setLikeCount(commentDO.getLikeCount()); commentVO.setCreateTime(commentDO.getCreateTime()); commentVO.setUpdateTime(commentDO.getUpdateTime()); + /** + * Run business method `fillDisplayFields`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param commentVO parameter `commentVO` supplied by the caller + * @param commentDO parameter `commentDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ fillDisplayFields(commentVO, commentDO); return commentVO; } + /** + * Run business method `toCommentVOList`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param wrapper parameter `wrapper` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ private List toCommentVOList(com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper wrapper) { return commentMapper.selectList(wrapper).stream().map(this::convertToVO).collect(Collectors.toList()); } + /** + * Run business method `buildTree`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param commentDOs parameter `commentDOs` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ private List buildTree(List commentDOs) { Map rootMap = new HashMap<>(); List roots = new ArrayList<>(); @@ -285,6 +464,13 @@ public class CommentServiceImpl extends ServiceImpl im return roots; } + /** + * Run business method `fillDisplayFields`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param commentVO parameter `commentVO` supplied by the caller + * @param commentDO parameter `commentDO` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void fillDisplayFields(CommentVO commentVO, CommentDO commentDO) { UserDO user = commentDO.getUserId() == null ? null : userMapper.selectById(commentDO.getUserId()); if (user != null) { @@ -306,24 +492,56 @@ public class CommentServiceImpl extends ServiceImpl im } } + /** + * Run business method `activeQuery`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper result consumed by the caller or returned to the frontend + */ private com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper activeQuery() { return Wrappers.lambdaQuery(CommentDO.class).eq(CommentDO::getIsDelete, 0); } + /** + * Run business method `normalizeId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ private Long normalizeId(Long id) { return id == null || id <= 0 ? null : id; } + /** + * Run business method `sanitizeContent`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param content parameter `content` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ private String sanitizeContent(String content) { if (!StringUtils.hasText(content)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("评论内容不能为空"); } String sanitized = content.replaceAll("[\\p{Cntrl}&&[^\r\n\t]]", "").trim(); sanitized = sanitized.replaceAll("<[^>]*>", ""); if (!StringUtils.hasText(sanitized)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("评论内容不能为空"); } if (sanitized.length() > 300) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("评论最多输入 300 个字"); } return sanitized; diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/ContactInfoServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/ContactInfoServiceImpl.java new file mode 100644 index 00000000..a522dc96 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/ContactInfoServiceImpl.java @@ -0,0 +1,205 @@ +package com.xiaowang.yuminailcore.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.xiaowang.yuminailcore.entity.OrderDO; +import com.xiaowang.yuminailcore.entity.OrderItemDO; +import com.xiaowang.yuminailcore.entity.ProductDO; +import com.xiaowang.yuminailcore.entity.UserDO; +import com.xiaowang.yuminailcore.mapper.OrderItemMapper; +import com.xiaowang.yuminailcore.mapper.OrderMapper; +import com.xiaowang.yuminailcore.mapper.ProductMapper; +import com.xiaowang.yuminailcore.mapper.UserMapper; +import com.xiaowang.yuminailcore.service.ContactInfoService; +import com.xiaowang.yuminailcore.support.UserShopBindingSupport; +import com.xiaowang.yuminailcore.vo.ContactInfoVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +@Service +@RequiredArgsConstructor +/** + * ContactInfoServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class ContactInfoServiceImpl implements ContactInfoService { + /** + * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserMapper userMapper; + /** + * Variable `productMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ProductMapper productMapper; + /** + * Variable `orderMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final OrderMapper orderMapper; + /** + * Variable `orderItemMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final OrderItemMapper orderItemMapper; + /** + * Variable `userShopBindingSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserShopBindingSupport userShopBindingSupport; + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return ContactInfoVO result consumed by the caller or returned to the frontend + */ + public ContactInfoVO getShopManagerContact(Long userId, Long shopId) { + if (shopId == null || shopId <= 0) throw new RuntimeException("店铺ID不能为空"); + /** + * Run business method `ensureUserCanSeeShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensureUserCanSeeShop(userId, shopId); + UserDO manager = userMapper.selectOne(new LambdaQueryWrapper() + .eq(UserDO::getType, 2) + .eq(UserDO::getShopId, shopId) + .eq(UserDO::getIsDelete, 0) + .eq(UserDO::getStatus, 1) + .last("LIMIT 1")); + /** + * Run business method `toContact`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param manager parameter `manager` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return toContact(manager, "店长"); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param productId parameter `productId` supplied by the caller + * @param artistId parameter `artistId` supplied by the caller + * @return ContactInfoVO result consumed by the caller or returned to the frontend + */ + public ContactInfoVO getProductArtistContact(Long userId, Long productId, Long artistId) { + ProductDO product = productMapper.selectById(productId); + if (product == null || Integer.valueOf(1).equals(product.getIsDelete())) throw new RuntimeException("作品不存在"); + if (artistId == null || artistId <= 0) throw new RuntimeException("请选择美甲师"); + ensureArtistAllowed(product.getBookableArtists(), artistId); + return toContact(userMapper.selectById(artistId), "美甲师"); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param orderId parameter `orderId` supplied by the caller + * @param artistId parameter `artistId` supplied by the caller + * @return ContactInfoVO result consumed by the caller or returned to the frontend + */ + public ContactInfoVO getOrderArtistContact(Long userId, Long orderId, Long artistId) { + OrderDO order = orderMapper.selectById(orderId); + if (order == null || Integer.valueOf(1).equals(order.getIsDelete()) || !userId.equals(order.getUserId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("订单不存在或无权查看"); + } + OrderItemDO item = orderItemMapper.selectList(new LambdaQueryWrapper() + .eq(OrderItemDO::getOrderId, orderId) + .eq(OrderItemDO::getIsDelete, 0) + .eq(artistId != null && artistId > 0, OrderItemDO::getArtistId, artistId) + .isNotNull(OrderItemDO::getArtistId) + .last("LIMIT 1")) + .stream() + .findFirst() + .orElseThrow(() -> new RuntimeException("订单暂无可联系美甲师")); + return toContact(userMapper.selectById(item.getArtistId()), "美甲师"); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return ContactInfoVO result consumed by the caller or returned to the frontend + */ + public ContactInfoVO getPlatformContact() { + UserDO admin = userMapper.selectOne(new LambdaQueryWrapper() + .eq(UserDO::getType, 4) + .eq(UserDO::getIsDelete, 0) + .eq(UserDO::getStatus, 1) + .isNotNull(UserDO::getPhone) + .last("LIMIT 1")); + /** + * Run business method `toContact`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param admin parameter `admin` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return toContact(admin, "平台客服"); + } + + /** + * Run business method `ensureUserCanSeeShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void ensureUserCanSeeShop(Long userId, Long shopId) { + if (userId == null) return; + UserDO user = userMapper.selectById(userId); + if (user != null && shopId.equals(user.getShopId())) return; + if (!userShopBindingSupport.hasActiveBinding(userId, shopId)) { + // 店铺详情是公开入口,未绑定用户仍允许看联系方式。 + } + } + + /** + * Run business method `ensureArtistAllowed`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param rawBookableArtists parameter `rawBookableArtists` supplied by the caller + * @param artistId parameter `artistId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void ensureArtistAllowed(String rawBookableArtists, Long artistId) { + if (!StringUtils.hasText(rawBookableArtists)) return; + boolean allowed = java.util.Arrays.stream(rawBookableArtists.split(",")) + .map(String::trim) + .filter(StringUtils::hasText) + .anyMatch(id -> id.equals(String.valueOf(artistId))); + if (!allowed) throw new RuntimeException("该美甲师不可预约当前作品"); + } + + /** + * Run business method `toContact`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param user parameter `user` supplied by the caller + * @param roleLabel parameter `roleLabel` supplied by the caller + * @return private ContactInfoVO result consumed by the caller or returned to the frontend + */ + private ContactInfoVO toContact(UserDO user, String roleLabel) { + ContactInfoVO vo = new ContactInfoVO(); + vo.setPlatformContactAvailable(false); + vo.setPlatformContactText("平台联系暂未接入"); + vo.setRoleLabel(roleLabel); + if (user == null) { + vo.setContactName(roleLabel); + vo.setPhoneAvailable(false); + return vo; + } + vo.setContactUserId(user.getId()); + vo.setContactName(StringUtils.hasText(user.getNickname()) ? user.getNickname() : user.getAccount()); + vo.setPhone(user.getPhone()); + vo.setPhoneAvailable(StringUtils.hasText(user.getPhone())); + return vo; + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/CouponServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/CouponServiceImpl.java index f12fdeae..13735140 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/CouponServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/CouponServiceImpl.java @@ -54,17 +54,44 @@ public class CouponServiceImpl extends ServiceImpl imple new VipAutoCouponTemplate("GOLD_90", "黄金VIP自动90折券", "黄金", BigDecimal.valueOf(9.0)) ); private static final String VIP_LEVEL_NORMAL = "普通"; - + /** + * Variable `couponTagMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final CouponTagMapper couponTagMapper; + /** + * Variable `userCouponMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final UserCouponMapper userCouponMapper; + /** + * Variable `tagMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final TagMapper tagMapper; + /** + * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final ShopMapper shopMapper; + /** + * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final UserMapper userMapper; + /** + * Variable `userShopBindingSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final UserShopBindingSupport userShopBindingSupport; + /** + * Variable `snowflakeIdGenerator`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; @Override @Transactional + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDTO parameter `couponDTO` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ public Long createCoupon(CouponDTO couponDTO, Long shopId) { // 创建优惠券 CouponDO couponDO = new CouponDO(); @@ -83,6 +110,12 @@ public class CouponServiceImpl extends ServiceImpl imple couponDO.setCouponScene(couponDTO.getCouponScene()); couponDO.setRequiredVipLevel(couponDTO.getRequiredVipLevel()); couponDO.setAutoMatch(couponDTO.getAutoMatch()); + /** + * Save submitted data. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ save(couponDO); // 处理标签关联 @@ -93,6 +126,14 @@ public class CouponServiceImpl extends ServiceImpl imple @Override @Transactional + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param couponDTO parameter `couponDTO` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ public boolean updateCoupon(Long id, CouponDTO couponDTO, Long shopId) { // 更新优惠券 CouponDO couponDO = getById(id); @@ -113,7 +154,19 @@ public class CouponServiceImpl extends ServiceImpl imple couponDO.setCouponScene(couponDTO.getCouponScene()); couponDO.setRequiredVipLevel(couponDTO.getRequiredVipLevel()); couponDO.setAutoMatch(couponDTO.getAutoMatch()); + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ updateById(couponDO); + /** + * Run business method `refreshCouponDistributionStatus`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ refreshCouponDistributionStatus(id); // 处理标签关联 @@ -124,6 +177,13 @@ public class CouponServiceImpl extends ServiceImpl imple @Override @Transactional + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ public boolean deleteCoupon(Long id, Long shopId) { // 删除优惠券 CouponDO couponDO = getById(id); @@ -131,19 +191,45 @@ public class CouponServiceImpl extends ServiceImpl imple return false; } couponDO.setIsDelete(1); + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ return updateById(couponDO); } @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return CouponVO result consumed by the caller or returned to the frontend + */ public CouponVO getCouponById(Long id) { CouponDO couponDO = getById(id); if (couponDO == null || couponDO.getIsDelete() == 1) { return null; } + /** + * Run business method `convertToCouponVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ return convertToCouponVO(couponDO); } @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @param size parameter `size` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return PageResultVO result consumed by the caller or returned to the frontend + */ public PageResultVO listCoupons(Integer page, Integer size, Long shopId) { Page pageInfo = new Page<>(page, size); LambdaQueryWrapper wrapper = new LambdaQueryWrapper() @@ -168,6 +254,11 @@ public class CouponServiceImpl extends ServiceImpl imple } @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ public List listAllCoupons() { List couponDOs = list(new LambdaQueryWrapper() .eq(CouponDO::getIsDelete, 0) @@ -180,6 +271,14 @@ public class CouponServiceImpl extends ServiceImpl imple @Override @Transactional + /** + * Run business method `assignCouponToUser`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param couponId parameter `couponId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ public boolean assignCouponToUser(Long userId, Long couponId, Long shopId) { // 检查优惠券是否存在 CouponDO couponDO = getById(couponId); @@ -195,6 +294,11 @@ public class CouponServiceImpl extends ServiceImpl imple return false; } if (isVipAutoCoupon(couponDO)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("VIP 自动券为系统模板券,不支持手动发放"); } if (!isUserEligibleForCouponDistribution(userId, couponDO, shopId)) { @@ -221,12 +325,25 @@ public class CouponServiceImpl extends ServiceImpl imple userCouponDO.setStatus(1); userCouponDO.setObtainTime(LocalDateTime.now()); userCouponMapper.insert(userCouponDO); + /** + * Run business method `refreshCouponDistributionStatus`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponId parameter `couponId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ refreshCouponDistributionStatus(couponId); return true; } @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param status parameter `status` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ public List listUserCoupons(Long userId, Integer status) { LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper() .eq(UserCouponDO::getUserId, userId) @@ -248,6 +365,13 @@ public class CouponServiceImpl extends ServiceImpl imple @Override @Transactional + /** + * Run business method `useCoupon`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userCouponId parameter `userCouponId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ public boolean useCoupon(Long userCouponId, Long userId) { // 检查用户优惠券是否存在 UserCouponDO userCouponDO = userCouponMapper.selectById(userCouponId); @@ -283,6 +407,15 @@ public class CouponServiceImpl extends ServiceImpl imple } @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param productTags parameter `productTags` supplied by the caller + * @param productPrice parameter `productPrice` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ public List getAvailableCoupons(Long userId, String productTags, Double productPrice, Long shopId) { BigDecimal orderAmount = productPrice == null ? BigDecimal.ZERO : BigDecimal.valueOf(productPrice); LocalDateTime now = LocalDateTime.now(); @@ -323,6 +456,11 @@ public class CouponServiceImpl extends ServiceImpl imple @Override @Transactional + /** + * Run business method `initializeDefaultVipAutoCoupons`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + */ public void initializeDefaultVipAutoCoupons(Long shopId) { if (shopId == null || shopId <= 0) { return; @@ -355,12 +493,27 @@ public class CouponServiceImpl extends ServiceImpl imple couponDO.setRequiredVipLevel(template.requiredVipLevel()); couponDO.setAutoMatch(1); couponDO.setIsDelete(0); + /** + * Save submitted data. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ save(couponDO); } } @Override @Transactional + /** + * Run business method `distributeCoupon`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponId parameter `couponId` supplied by the caller + * @param userIds parameter `userIds` supplied by the caller + * @param quantity parameter `quantity` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ public boolean distributeCoupon(Long couponId, List userIds, Integer quantity, Long shopId) { // 检查优惠券是否存在 CouponDO couponDO = getById(couponId); @@ -373,6 +526,11 @@ public class CouponServiceImpl extends ServiceImpl imple return false; } if (isVipAutoCoupon(couponDO)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("VIP 自动券为系统模板券,不支持手动发放"); } @@ -384,6 +542,11 @@ public class CouponServiceImpl extends ServiceImpl imple return false; } if (quantity > 1) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("当前用户券受唯一索引限制,同一用户同一模板只能发放 1 张"); } List targetUserIds = userIds.stream() @@ -403,6 +566,11 @@ public class CouponServiceImpl extends ServiceImpl imple .eq(UserCouponDO::getCouponId, couponId) .eq(UserCouponDO::getIsDelete, 0)); if (existing != null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("用户已持有该优惠券,不能重复发放"); } } @@ -422,6 +590,12 @@ public class CouponServiceImpl extends ServiceImpl imple userCouponDO.setObtainTime(obtainTime); userCouponMapper.insert(userCouponDO); } + /** + * Run business method `refreshCouponDistributionStatus`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponId parameter `couponId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ refreshCouponDistributionStatus(couponId); return true; @@ -575,6 +749,12 @@ public class CouponServiceImpl extends ServiceImpl imple return list(buildVipAutoCouponQuery(requiredVipLevel)); } + /** + * Run business method `buildVipAutoCouponQuery`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requiredVipLevel parameter `requiredVipLevel` supplied by the caller + * @return private LambdaQueryWrapper result consumed by the caller or returned to the frontend + */ private LambdaQueryWrapper buildVipAutoCouponQuery(String requiredVipLevel) { return new LambdaQueryWrapper() .eq(CouponDO::getIsDelete, 0) @@ -586,17 +766,42 @@ public class CouponServiceImpl extends ServiceImpl imple .orderByAsc(CouponDO::getEndTime); } + /** + * Run business method `buildShopVipAutoCouponCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @param codeSuffix parameter `codeSuffix` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ private String buildShopVipAutoCouponCode(Long shopId, String codeSuffix) { return String.format("VIP_AUTO_SHOP_%d_%s", shopId, codeSuffix); } + /** + * Run business method `resolveCouponCodeForCreate`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requestedCode parameter `requestedCode` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ private String resolveCouponCodeForCreate(String requestedCode) { if (StringUtils.hasText(requestedCode)) { return requestedCode.trim(); } + /** + * Run business method `generateUniqueManualCouponCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return return result consumed by the caller or returned to the frontend + */ return generateUniqueManualCouponCode(); } + /** + * Run business method `resolveCouponCodeForUpdate`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param existingCode parameter `existingCode` supplied by the caller + * @param requestedCode parameter `requestedCode` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ private String resolveCouponCodeForUpdate(String existingCode, String requestedCode) { if (StringUtils.hasText(requestedCode)) { return requestedCode.trim(); @@ -604,9 +809,19 @@ public class CouponServiceImpl extends ServiceImpl imple if (StringUtils.hasText(existingCode)) { return existingCode.trim(); } + /** + * Run business method `generateUniqueManualCouponCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return return result consumed by the caller or returned to the frontend + */ return generateUniqueManualCouponCode(); } + /** + * Run business method `generateUniqueManualCouponCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private String result consumed by the caller or returned to the frontend + */ private String generateUniqueManualCouponCode() { for (int attempt = 0; attempt < 10; attempt++) { String candidate = "CPN_" + snowflakeIdGenerator.nextBase36String(13); @@ -614,9 +829,20 @@ public class CouponServiceImpl extends ServiceImpl imple return candidate; } } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("生成优惠券编码失败,请稍后重试"); } + /** + * Run business method `convertToCouponVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @return private CouponVO result consumed by the caller or returned to the frontend + */ private CouponVO convertToCouponVO(CouponDO couponDO) { CouponVO couponVO = new CouponVO(); couponVO.setId(couponDO.getId()); @@ -713,6 +939,12 @@ public class CouponServiceImpl extends ServiceImpl imple return userCouponVO; } + /** + * Run business method `convertToSystemVipCouponVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @return private UserCouponVO result consumed by the caller or returned to the frontend + */ private UserCouponVO convertToSystemVipCouponVO(CouponDO couponDO) { UserCouponVO userCouponVO = buildCouponOption(couponDO.getId(), couponDO, COUPON_SOURCE_SYSTEM_VIP, true); userCouponVO.setStatus(1); @@ -720,6 +952,15 @@ public class CouponServiceImpl extends ServiceImpl imple return userCouponVO; } + /** + * Run business method `buildCouponOption`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param optionId parameter `optionId` supplied by the caller + * @param couponDO parameter `couponDO` supplied by the caller + * @param sourceType parameter `sourceType` supplied by the caller + * @param autoMatched parameter `autoMatched` supplied by the caller + * @return private UserCouponVO result consumed by the caller or returned to the frontend + */ private UserCouponVO buildCouponOption(Long optionId, CouponDO couponDO, String sourceType, boolean autoMatched) { UserCouponVO userCouponVO = new UserCouponVO(); userCouponVO.setId(optionId); @@ -738,6 +979,16 @@ public class CouponServiceImpl extends ServiceImpl imple return userCouponVO; } + /** + * Run business method `isCouponApplicable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @param now parameter `now` supplied by the caller + * @param orderAmount parameter `orderAmount` supplied by the caller + * @param productTags parameter `productTags` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ private boolean isCouponApplicable(CouponDO couponDO, LocalDateTime now, BigDecimal orderAmount, String productTags, Long shopId) { if (couponDO == null || Integer.valueOf(1).equals(couponDO.getIsDelete())) { return false; @@ -762,6 +1013,13 @@ public class CouponServiceImpl extends ServiceImpl imple return checkTagMatch(couponDO.getId(), productTags); } + /** + * Run business method `matchesShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ private boolean matchesShop(CouponDO couponDO, Long shopId) { if (shopId == null || couponDO.getShopId() == null) { return true; @@ -769,16 +1027,35 @@ public class CouponServiceImpl extends ServiceImpl imple return shopId.equals(couponDO.getShopId()); } + /** + * Run business method `isVipAutoCoupon`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ private boolean isVipAutoCoupon(CouponDO couponDO) { return couponDO != null && Integer.valueOf(1).equals(couponDO.getAutoMatch()) && COUPON_SCENE_VIP_AUTO.equals(couponDO.getCouponScene()); } + /** + * Run business method `hasRemainingDistributionStock`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @param requiredCount parameter `requiredCount` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ private boolean hasRemainingDistributionStock(CouponDO couponDO, int requiredCount) { return calculateRemainingDistributionCount(couponDO) >= requiredCount; } + /** + * Run business method `calculateRemainingDistributionCount`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @return private int result consumed by the caller or returned to the frontend + */ private int calculateRemainingDistributionCount(CouponDO couponDO) { if (couponDO == null || couponDO.getId() == null) { return 0; @@ -790,24 +1067,56 @@ public class CouponServiceImpl extends ServiceImpl imple return Math.max(0, totalCount - (int) issuedCount); } + /** + * Run business method `incrementCouponUsedCount`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponId parameter `couponId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void incrementCouponUsedCount(Long couponId) { CouponDO couponDO = getById(couponId); if (couponDO == null) { return; } couponDO.setUsedCount(normalizeCount(couponDO.getUsedCount()) + 1); + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ updateById(couponDO); } + /** + * Run business method `decrementCouponUsedCount`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponId parameter `couponId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void decrementCouponUsedCount(Long couponId) { CouponDO couponDO = getById(couponId); if (couponDO == null) { return; } couponDO.setUsedCount(Math.max(0, normalizeCount(couponDO.getUsedCount()) - 1)); + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ updateById(couponDO); } + /** + * Run business method `isUserEligibleForCouponDistribution`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param couponDO parameter `couponDO` supplied by the caller + * @param requestedShopId parameter `requestedShopId` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ private boolean isUserEligibleForCouponDistribution(Long userId, CouponDO couponDO, Long requestedShopId) { if (userId == null) { return false; @@ -827,6 +1136,12 @@ public class CouponServiceImpl extends ServiceImpl imple return true; } + /** + * Run business method `refreshCouponDistributionStatus`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponId parameter `couponId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void refreshCouponDistributionStatus(Long couponId) { CouponDO couponDO = getById(couponId); if (couponDO == null || Integer.valueOf(1).equals(couponDO.getIsDelete())) { @@ -840,14 +1155,33 @@ public class CouponServiceImpl extends ServiceImpl imple int targetStatus = remainingCount > 0 ? 1 : 3; if (!Objects.equals(couponDO.getStatus(), targetStatus)) { couponDO.setStatus(targetStatus); + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponDO parameter `couponDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ updateById(couponDO); } } + /** + * Run business method `normalizeCount`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param count parameter `count` supplied by the caller + * @return private int result consumed by the caller or returned to the frontend + */ private int normalizeCount(Integer count) { return count == null ? 0 : count; } + /** + * Run business method `calculateDiscountAmount`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponVO parameter `couponVO` supplied by the caller + * @param orderAmount parameter `orderAmount` supplied by the caller + * @return private BigDecimal result consumed by the caller or returned to the frontend + */ private BigDecimal calculateDiscountAmount(UserCouponVO couponVO, BigDecimal orderAmount) { if (couponVO == null || orderAmount == null || orderAmount.compareTo(BigDecimal.ZERO) <= 0) { return BigDecimal.ZERO; diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/EffectDiagramServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/EffectDiagramServiceImpl.java index 8f417460..50abec04 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/EffectDiagramServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/EffectDiagramServiceImpl.java @@ -23,10 +23,18 @@ import java.util.stream.Collectors; @Service @RequiredArgsConstructor public class EffectDiagramServiceImpl extends ServiceImpl implements EffectDiagramService { - + /** + * Variable `effectDiagramMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final EffectDiagramMapper effectDiagramMapper; @Override + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param effectDiagramDTO parameter `effectDiagramDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ public Long createEffectDiagram(EffectDiagramDTO effectDiagramDTO) { EffectDiagramDO effectDiagramDO = new EffectDiagramDO(); effectDiagramDO.setProductId(effectDiagramDTO.getProductId()); @@ -42,6 +50,13 @@ public class EffectDiagramServiceImpl extends ServiceImpl result consumed by the caller or returned to the frontend + */ public List listAllEffectDiagrams() { List effectDiagramDOs = effectDiagramMapper.selectList(null); return effectDiagramDOs.stream() @@ -85,6 +123,12 @@ public class EffectDiagramServiceImpl extends ServiceImpl result consumed by the caller or returned to the frontend + */ public List listEffectDiagramsByProductId(Long productId) { List effectDiagramDOs = effectDiagramMapper.selectList( Wrappers.lambdaQuery(EffectDiagramDO.class) @@ -96,6 +140,12 @@ public class EffectDiagramServiceImpl extends ServiceImpl result consumed by the caller or returned to the frontend + */ public List listEffectDiagramsByCategory(String category) { List effectDiagramDOs = effectDiagramMapper.selectList( Wrappers.lambdaQuery(EffectDiagramDO.class) diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/LegalAgreementServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/LegalAgreementServiceImpl.java new file mode 100644 index 00000000..01ff20ba --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/LegalAgreementServiceImpl.java @@ -0,0 +1,252 @@ +package com.xiaowang.yuminailcore.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; +import com.xiaowang.yuminailcore.dto.AgreementAwareRequest; +import com.xiaowang.yuminailcore.dto.LegalAgreementDTO; +import com.xiaowang.yuminailcore.entity.LegalAgreementDO; +import com.xiaowang.yuminailcore.entity.UserAgreementConsentDO; +import com.xiaowang.yuminailcore.entity.UserDO; +import com.xiaowang.yuminailcore.mapper.LegalAgreementMapper; +import com.xiaowang.yuminailcore.mapper.UserAgreementConsentMapper; +import com.xiaowang.yuminailcore.service.LegalAgreementService; +import com.xiaowang.yuminailcore.support.security.RequestThrottleService; +import com.xiaowang.yuminailcore.vo.LegalAgreementVO; +import com.xiaowang.yuminailcore.vo.UserAgreementConsentVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import javax.servlet.http.HttpServletRequest; +import java.time.LocalDateTime; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +public class LegalAgreementServiceImpl implements LegalAgreementService { + + public static final String USER_TERMS = "USER_TERMS"; + public static final String PRIVACY_POLICY = "PRIVACY_POLICY"; + + private final LegalAgreementMapper agreementMapper; + private final UserAgreementConsentMapper consentMapper; + + @Override + public List listAdminAgreements(UserDO currentUser) { + ensurePlatformAdmin(currentUser); + return agreementMapper.selectList(new LambdaQueryWrapper() + .eq(LegalAgreementDO::getIsDelete, 0) + .orderByDesc(LegalAgreementDO::getEffectiveTime) + .orderByDesc(LegalAgreementDO::getCreateTime)) + .stream() + .map(this::toVO) + .collect(Collectors.toList()); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public Long createAgreement(UserDO currentUser, LegalAgreementDTO dto) { + ensurePlatformAdmin(currentUser); + LegalAgreementDO agreement = new LegalAgreementDO(); + apply(agreement, dto); + agreement.setStatus(0); + agreement.setIsDelete(0); + agreementMapper.insert(agreement); + return agreement.getId(); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public Boolean updateAgreement(UserDO currentUser, Long id, LegalAgreementDTO dto) { + ensurePlatformAdmin(currentUser); + LegalAgreementDO agreement = requireAgreement(id); + apply(agreement, dto); + agreementMapper.updateById(agreement); + return true; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public Boolean publishAgreement(UserDO currentUser, Long id) { + ensurePlatformAdmin(currentUser); + LegalAgreementDO agreement = requireAgreement(id); + agreementMapper.update(null, new LambdaUpdateWrapper() + .eq(LegalAgreementDO::getAgreementType, agreement.getAgreementType()) + .eq(LegalAgreementDO::getIsDelete, 0) + .set(LegalAgreementDO::getStatus, 0)); + agreement.setStatus(1); + agreement.setEffectiveTime(LocalDateTime.now()); + agreementMapper.updateById(agreement); + return true; + } + + @Override + public Boolean disableAgreement(UserDO currentUser, Long id) { + ensurePlatformAdmin(currentUser); + LegalAgreementDO agreement = requireAgreement(id); + agreement.setStatus(0); + agreementMapper.updateById(agreement); + return true; + } + + @Override + public List listCurrentAgreements() { + return List.of(USER_TERMS, PRIVACY_POLICY).stream() + .map(this::getCurrentAgreement) + .collect(Collectors.toList()); + } + + @Override + public LegalAgreementVO getCurrentAgreement(String agreementType) { + LegalAgreementDO agreement = findCurrentAgreement(normalizeType(agreementType)); + if (agreement == null) { + throw new RuntimeException("当前协议未配置,请联系管理员"); + } + return toVO(agreement); + } + + @Override + public UserAgreementConsentVO getMyConsent(Long userId) { + Map versions = consentMapper.selectList(new LambdaQueryWrapper() + .eq(UserAgreementConsentDO::getUserId, userId)) + .stream() + .collect(Collectors.toMap(UserAgreementConsentDO::getAgreementType, UserAgreementConsentDO::getVersion, (left, right) -> right, LinkedHashMap::new)); + return new UserAgreementConsentVO(versions); + } + + @Override + public void requireAccepted(AgreementAwareRequest request) { + if (request == null || !Boolean.TRUE.equals(request.getAgreementAccepted())) { + throw new RuntimeException("请先阅读并同意用户协议和隐私政策"); + } + Map versions = request.getAgreementVersions(); + requireVersion(versions, USER_TERMS); + requireVersion(versions, PRIVACY_POLICY); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void recordConsent(Long userId, AgreementAwareRequest request, String entry, HttpServletRequest httpRequest) { + if (userId == null || request == null || request.getAgreementVersions() == null) { + return; + } + String clientType = StringUtils.hasText(request.getClientType()) ? request.getClientType().trim().toUpperCase() : "WEB"; + request.getAgreementVersions().forEach((type, version) -> upsertConsent( + userId, + normalizeType(type), + version, + entry, + clientType, + resolveClientIp(httpRequest), + httpRequest == null ? null : httpRequest.getHeader(RequestThrottleService.DEVICE_ID_HEADER) + )); + } + + private void requireVersion(Map versions, String type) { + LegalAgreementDO current = findCurrentAgreement(type); + if (current == null) { + throw new RuntimeException("当前协议未配置,请联系管理员"); + } + String submittedVersion = versions == null ? null : versions.get(type); + if (!StringUtils.hasText(submittedVersion) || !current.getVersion().equals(submittedVersion.trim())) { + throw new RuntimeException("协议版本已更新,请重新阅读并同意"); + } + } + + private void upsertConsent(Long userId, String type, String version, String entry, String clientType, String ip, String deviceId) { + if (!StringUtils.hasText(version)) { + return; + } + UserAgreementConsentDO existing = consentMapper.selectOne(new LambdaQueryWrapper() + .eq(UserAgreementConsentDO::getUserId, userId) + .eq(UserAgreementConsentDO::getAgreementType, type) + .last("limit 1")); + UserAgreementConsentDO consent = existing == null ? new UserAgreementConsentDO() : existing; + consent.setUserId(userId); + consent.setAgreementType(type); + consent.setVersion(version.trim()); + consent.setEntry(entry); + consent.setClientType(clientType); + consent.setIpAddress(ip); + consent.setDeviceId(deviceId); + consent.setConsentTime(LocalDateTime.now()); + if (existing == null) { + consentMapper.insert(consent); + } else { + consentMapper.updateById(consent); + } + } + + private LegalAgreementDO findCurrentAgreement(String type) { + return agreementMapper.selectOne(new LambdaQueryWrapper() + .eq(LegalAgreementDO::getAgreementType, normalizeType(type)) + .eq(LegalAgreementDO::getStatus, 1) + .eq(LegalAgreementDO::getIsDelete, 0) + .orderByDesc(LegalAgreementDO::getEffectiveTime) + .last("limit 1")); + } + + private LegalAgreementDO requireAgreement(Long id) { + LegalAgreementDO agreement = agreementMapper.selectById(id); + if (agreement == null || Integer.valueOf(1).equals(agreement.getIsDelete())) { + throw new RuntimeException("协议不存在"); + } + return agreement; + } + + private void apply(LegalAgreementDO agreement, LegalAgreementDTO dto) { + agreement.setAgreementType(normalizeType(dto.getAgreementType())); + agreement.setTitle(dto.getTitle().trim()); + agreement.setVersion(dto.getVersion().trim()); + agreement.setContent(dto.getContent().trim()); + } + + private String normalizeType(String type) { + if (!StringUtils.hasText(type)) { + throw new RuntimeException("协议类型不能为空"); + } + String normalized = type.trim().toUpperCase(); + if (!USER_TERMS.equals(normalized) && !PRIVACY_POLICY.equals(normalized)) { + throw new RuntimeException("协议类型不正确"); + } + return normalized; + } + + private void ensurePlatformAdmin(UserDO currentUser) { + if (currentUser == null || !Integer.valueOf(4).equals(currentUser.getType())) { + throw new RuntimeException("仅平台管理员可以管理协议"); + } + } + + private String resolveClientIp(HttpServletRequest request) { + if (request == null) { + return null; + } + String forwarded = request.getHeader("X-Forwarded-For"); + if (StringUtils.hasText(forwarded)) { + return forwarded.split(",")[0].trim(); + } + String realIp = request.getHeader("X-Real-IP"); + return StringUtils.hasText(realIp) ? realIp.trim() : request.getRemoteAddr(); + } + + private LegalAgreementVO toVO(LegalAgreementDO agreement) { + LegalAgreementVO vo = new LegalAgreementVO(); + vo.setId(agreement.getId()); + vo.setAgreementType(agreement.getAgreementType()); + vo.setAgreementTypeName(USER_TERMS.equals(agreement.getAgreementType()) ? "用户协议" : "隐私政策"); + vo.setTitle(agreement.getTitle()); + vo.setVersion(agreement.getVersion()); + vo.setContent(agreement.getContent()); + vo.setStatus(agreement.getStatus()); + vo.setStatusText(Integer.valueOf(1).equals(agreement.getStatus()) ? "已发布" : "草稿/停用"); + vo.setEffectiveTime(agreement.getEffectiveTime()); + vo.setCreateTime(agreement.getCreateTime()); + vo.setUpdateTime(agreement.getUpdateTime()); + return vo; + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/LoginIdentityServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/LoginIdentityServiceImpl.java index 8aaea782..adf2d040 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/LoginIdentityServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/LoginIdentityServiceImpl.java @@ -23,10 +23,18 @@ import java.util.stream.Collectors; @Service @RequiredArgsConstructor public class LoginIdentityServiceImpl extends ServiceImpl implements LoginIdentityService { - + /** + * Variable `loginIdentityMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final LoginIdentityMapper loginIdentityMapper; @Override + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param loginIdentityDTO parameter `loginIdentityDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ public Long createLoginIdentity(LoginIdentityDTO loginIdentityDTO) { LoginIdentityDO loginIdentityDO = new LoginIdentityDO(); loginIdentityDO.setUserId(loginIdentityDTO.getUserId()); @@ -39,6 +47,13 @@ public class LoginIdentityServiceImpl extends ServiceImpl 0; } @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return LoginIdentityVO result consumed by the caller or returned to the frontend + */ public LoginIdentityVO getLoginIdentityById(Long id) { LoginIdentityDO loginIdentityDO = loginIdentityMapper.selectById(id); if (loginIdentityDO == null) { return null; } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param loginIdentityDO parameter `loginIdentityDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ return convertToVO(loginIdentityDO); } @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ public List listAllLoginIdentities() { List loginIdentityDOs = loginIdentityMapper.selectList(null); return loginIdentityDOs.stream() @@ -75,6 +113,12 @@ public class LoginIdentityServiceImpl extends ServiceImpl result consumed by the caller or returned to the frontend + */ public List listLoginIdentitiesByUserId(Long userId) { List loginIdentityDOs = loginIdentityMapper.selectList( Wrappers.lambdaQuery(LoginIdentityDO.class) @@ -86,6 +130,12 @@ public class LoginIdentityServiceImpl extends ServiceImpl result consumed by the caller or returned to the frontend + */ public List listLoginIdentitiesByLoginMethod(String loginMethod) { List loginIdentityDOs = loginIdentityMapper.selectList( Wrappers.lambdaQuery(LoginIdentityDO.class) diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/MapServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/MapServiceImpl.java new file mode 100644 index 00000000..5e5748ac --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/MapServiceImpl.java @@ -0,0 +1,45 @@ +package com.xiaowang.yuminailcore.service.impl; + +import com.xiaowang.yuminailcore.service.MapService; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; +import org.springframework.web.util.UriUtils; + +import java.math.BigDecimal; +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashMap; +import java.util.Map; + +@Service +public class MapServiceImpl implements MapService { + + @Override + public String normalizeProvider(String provider) { + if (!StringUtils.hasText(provider)) { + return "TENCENT"; + } + String value = provider.trim().toUpperCase(); + return "AMAP".equals(value) || "TENCENT".equals(value) ? value : "TENCENT"; + } + + @Override + public Map buildNavigationUrls(String shopName, String address, BigDecimal longitude, BigDecimal latitude) { + Map urls = new LinkedHashMap<>(); + if (longitude == null || latitude == null) { + return urls; + } + String name = encode(StringUtils.hasText(shopName) ? shopName : "店铺位置"); + String addr = encode(StringUtils.hasText(address) ? address : ""); + String lon = longitude.stripTrailingZeros().toPlainString(); + String lat = latitude.stripTrailingZeros().toPlainString(); + + urls.put("AMAP", "https://uri.amap.com/navigation?to=" + lon + "," + lat + "," + name + "&mode=car&policy=1&src=yuminail&coordinate=gaode&callnative=1"); + urls.put("TENCENT", "https://apis.map.qq.com/uri/v1/routeplan?type=drive&tocoord=" + lat + "," + lon + "&to=" + name + "&referer=yuminail"); + urls.put("BROWSER", "https://apis.map.qq.com/uri/v1/marker?marker=coord:" + lat + "," + lon + ";title:" + name + ";addr:" + addr + "&referer=yuminail"); + return urls; + } + + private String encode(String value) { + return UriUtils.encode(value, StandardCharsets.UTF_8); + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/MessageHubClientServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/MessageHubClientServiceImpl.java index 186ab331..d14f88a7 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/MessageHubClientServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/MessageHubClientServiceImpl.java @@ -1,33 +1,51 @@ package com.xiaowang.yuminailcore.service.impl; import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.yuminailcore.entity.MessageHubPushConfigDO; import com.xiaowang.yuminailcore.service.MessageHubClientService; +import com.xiaowang.yuminailcore.service.MessageHubPushConfigService; import com.xiaowang.yuminailcore.support.id.TimeOrderedSnowflakeIdGenerator; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Value; import org.springframework.amqp.core.Message; import org.springframework.amqp.core.MessageBuilder; import org.springframework.amqp.rabbit.core.RabbitTemplate; +import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; + /** - * MessageHub 客户端服务实现。 - * 通过 RabbitMQ 发送消息到 MessageHub 服务。 + * YumiNail 到 MessageHub 的投递客户端。 + * + *

YumiNail 只决定某个业务场景使用哪组 MessageHub 对接参数,不直接连接 Spug、 + * 阿里云等短信供应商。真实通道选择和供应商密钥仍归 MessageHub 管理。

*/ @Slf4j @Service @RefreshScope @RequiredArgsConstructor public class MessageHubClientServiceImpl implements MessageHubClientService { - + /** + * Variable `rabbitTemplate`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final RabbitTemplate rabbitTemplate; + /** + * Variable `objectMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final ObjectMapper objectMapper; + /** + * Variable `snowflakeIdGenerator`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; + /** + * Variable `messageHubPushConfigService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final MessageHubPushConfigService messageHubPushConfigService; @Value("${messagehub.client.sms-queue:smsQueue}") private String smsQueue; @@ -38,25 +56,41 @@ public class MessageHubClientServiceImpl implements MessageHubClientService { @Value("${messagehub.client.verify-template-code:SPUG0001}") private String verifyTemplateCode; + @Value("${messagehub.client.send-method:SPUG}") + private String sendMethod; + @Override + /** + * Send or dispatch a message. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param code parameter `code` supplied by the caller + */ public void sendSmsVerificationCode(String phone, String code) { + /** + * Send or dispatch a message. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param USER_LOGIN_SMS_CODE parameter `USER_LOGIN_SMS_CODE` supplied by the caller + * @param phone parameter `phone` supplied by the caller + * @param code parameter `code` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + sendSmsVerificationCode("USER_LOGIN_SMS_CODE", phone, code); + } + + @Override + /** + * Send or dispatch a message. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sceneCode parameter `sceneCode` supplied by the caller + * @param phone parameter `phone` supplied by the caller + * @param code parameter `code` supplied by the caller + */ + public void sendSmsVerificationCode(String sceneCode, String phone, String code) { try { + MessageHubPushConfigDO config = messageHubPushConfigService.getEnabledConfig(sceneCode); String messageId = snowflakeIdGenerator.nextIdString(); - Map messageBody = new HashMap<>(); - messageBody.put("receiver", phone); - messageBody.put("channelType", "SMS"); - messageBody.put("msgType", "VERIFICATION"); - messageBody.put("templateCode", verifyTemplateCode); - messageBody.put("sourceSystem", sourceSystem); - messageBody.put("uniqueId", messageId); - messageBody.put("sendMethod", "SPUG"); - - Map templateParams = new HashMap<>(); - templateParams.put("name", "YumiNail"); - templateParams.put("code", code); - templateParams.put("number", "5"); - messageBody.put("templateParams", templateParams); - + Map messageBody = buildSmsMessageBody(config, sceneCode, phone, code, messageId); String jsonBody = objectMapper.writeValueAsString(messageBody); Message message = MessageBuilder .withBody(jsonBody.getBytes(StandardCharsets.UTF_8)) @@ -65,12 +99,49 @@ public class MessageHubClientServiceImpl implements MessageHubClientService { .setMessageId(messageId) .build(); - rabbitTemplate.convertAndSend(smsQueue, message); - log.info("短信验证码消息已发送到队列,手机号: {}, sourceSystem: {}, templateCode: {}", - phone, sourceSystem, verifyTemplateCode); + String queueName = config == null ? smsQueue : config.getQueueName(); + rabbitTemplate.convertAndSend(queueName, message); + log.info("短信验证码消息已投递到 MessageHub,sceneCode: {}, phone: {}, queue: {}, sourceSystem: {}, templateCode: {}", + sceneCode, phone, queueName, messageBody.get("sourceSystem"), messageBody.get("templateCode")); } catch (Exception exception) { log.error("发送短信验证码失败", exception); throw new RuntimeException("发送短信验证码失败: " + exception.getMessage(), exception); } } + + /** + * Run business method `buildSmsMessageBody`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param config parameter `config` supplied by the caller + * @param sceneCode parameter `sceneCode` supplied by the caller + * @param phone parameter `phone` supplied by the caller + * @param code parameter `code` supplied by the caller + * @param messageId parameter `messageId` supplied by the caller + * @return private Map result consumed by the caller or returned to the frontend + */ + private Map buildSmsMessageBody(MessageHubPushConfigDO config, String sceneCode, String phone, String code, String messageId) { + String platform = config == null ? "SMS" : config.getPlatform(); + String resolvedSendMethod = config == null ? sendMethod : config.getSendMethod(); + + Map messageBody = new HashMap<>(); + messageBody.put("receiver", phone); + messageBody.put("channelType", platform); + messageBody.put("platform", platform); + messageBody.put("msgType", config == null ? "VERIFICATION" : config.getMsgType()); + messageBody.put("templateCode", config == null ? verifyTemplateCode : config.getTemplateCode()); + messageBody.put("sourceSystem", config == null ? sourceSystem : config.getSourceSystem()); + messageBody.put("uniqueId", messageId); + messageBody.put("sendMethod", StringUtils.hasText(resolvedSendMethod) ? resolvedSendMethod : "OTHER"); + if (config != null && config.getChannelId() != null) { + messageBody.put("channelId", config.getChannelId()); + } + + Map templateParams = new HashMap<>(); + templateParams.put("name", "YumiNail"); + templateParams.put("code", code); + templateParams.put("number", "5"); + templateParams.put("sceneCode", sceneCode); + messageBody.put("templateParams", templateParams); + return messageBody; + } } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/MessageHubPushConfigServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/MessageHubPushConfigServiceImpl.java new file mode 100644 index 00000000..7dbea439 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/MessageHubPushConfigServiceImpl.java @@ -0,0 +1,328 @@ +package com.xiaowang.yuminailcore.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.xiaowang.yuminailcore.dto.MessageHubPushConfigDTO; +import com.xiaowang.yuminailcore.dto.MessageHubPushTestDTO; +import com.xiaowang.yuminailcore.entity.MessageHubPushConfigDO; +import com.xiaowang.yuminailcore.entity.UserDO; +import com.xiaowang.yuminailcore.mapper.MessageHubPushConfigMapper; +import com.xiaowang.yuminailcore.service.MessageHubClientService; +import com.xiaowang.yuminailcore.service.MessageHubPushConfigService; +import com.xiaowang.yuminailcore.vo.MessageHubPushConfigVO; +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.util.List; +import java.util.Locale; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +/** + * MessageHubPushConfigServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class MessageHubPushConfigServiceImpl implements MessageHubPushConfigService { + /** + * Variable `configMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final MessageHubPushConfigMapper configMapper; + @Lazy + /** + * Variable `messageHubClientService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final MessageHubClientService messageHubClientService; + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listConfigs(UserDO currentUser) { + /** + * Run business method `ensurePlatformAdmin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensurePlatformAdmin(currentUser); + return configMapper.selectList(new LambdaQueryWrapper() + .eq(MessageHubPushConfigDO::getIsDelete, 0) + .orderByAsc(MessageHubPushConfigDO::getSceneCode)) + .stream() + .map(this::toVO) + .collect(Collectors.toList()); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long createConfig(UserDO currentUser, MessageHubPushConfigDTO dto) { + /** + * Run business method `ensurePlatformAdmin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensurePlatformAdmin(currentUser); + String sceneCode = normalizeSceneCode(dto.getSceneCode()); + MessageHubPushConfigDO existing = configMapper.selectOne(new LambdaQueryWrapper() + .eq(MessageHubPushConfigDO::getSceneCode, sceneCode) + .eq(MessageHubPushConfigDO::getIsDelete, 0) + .last("LIMIT 1")); + if (existing != null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("该场景编码已存在"); + } + MessageHubPushConfigDO config = new MessageHubPushConfigDO(); + /** + * Run business method `apply`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param config parameter `config` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @param sceneCode parameter `sceneCode` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + apply(config, dto, sceneCode); + config.setIsDelete(0); + configMapper.insert(config); + return config.getId(); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean updateConfig(UserDO currentUser, Long id, MessageHubPushConfigDTO dto) { + /** + * Run business method `ensurePlatformAdmin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensurePlatformAdmin(currentUser); + MessageHubPushConfigDO config = requireConfig(id); + String sceneCode = normalizeSceneCode(dto.getSceneCode()); + MessageHubPushConfigDO existing = configMapper.selectOne(new LambdaQueryWrapper() + .eq(MessageHubPushConfigDO::getSceneCode, sceneCode) + .eq(MessageHubPushConfigDO::getIsDelete, 0) + .ne(MessageHubPushConfigDO::getId, id) + .last("LIMIT 1")); + if (existing != null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("该场景编码已存在"); + } + /** + * Run business method `apply`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param config parameter `config` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @param sceneCode parameter `sceneCode` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + apply(config, dto, sceneCode); + configMapper.updateById(config); + return true; + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Change the enabled/status flag of one record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param enabled parameter `enabled` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean updateStatus(UserDO currentUser, Long id, Integer enabled) { + /** + * Run business method `ensurePlatformAdmin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensurePlatformAdmin(currentUser); + MessageHubPushConfigDO config = requireConfig(id); + config.setEnabled(Integer.valueOf(1).equals(enabled) ? 1 : 0); + configMapper.updateById(config); + return true; + } + + @Override + /** + * Run a test call without changing normal business data. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean testConfig(UserDO currentUser, Long id, MessageHubPushTestDTO dto) { + /** + * Run business method `ensurePlatformAdmin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensurePlatformAdmin(currentUser); + MessageHubPushConfigDO config = requireConfig(id); + messageHubClientService.sendSmsVerificationCode(config.getSceneCode(), dto.getPhone(), "123456"); + return true; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sceneCode parameter `sceneCode` supplied by the caller + * @return MessageHubPushConfigDO result consumed by the caller or returned to the frontend + */ + public MessageHubPushConfigDO getEnabledConfig(String sceneCode) { + if (!StringUtils.hasText(sceneCode)) { + return null; + } + return configMapper.selectOne(new LambdaQueryWrapper() + .eq(MessageHubPushConfigDO::getSceneCode, normalizeSceneCode(sceneCode)) + .eq(MessageHubPushConfigDO::getEnabled, 1) + .eq(MessageHubPushConfigDO::getIsDelete, 0) + .last("LIMIT 1")); + } + + /** + * Run business method `apply`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param config parameter `config` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @param sceneCode parameter `sceneCode` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void apply(MessageHubPushConfigDO config, MessageHubPushConfigDTO dto, String sceneCode) { + config.setSceneCode(sceneCode); + config.setSceneName(dto.getSceneName().trim()); + config.setPlatform(normalizeUpper(dto.getPlatform(), "SMS")); + config.setMsgType(normalizeUpper(dto.getMsgType(), "VERIFICATION")); + config.setQueueName(dto.getQueueName().trim()); + config.setSourceSystem(dto.getSourceSystem().trim()); + config.setTemplateCode(dto.getTemplateCode().trim()); + config.setChannelId(dto.getChannelId()); + config.setSendMethod(StringUtils.hasText(dto.getSendMethod()) ? dto.getSendMethod().trim().toUpperCase(Locale.ROOT) : null); + config.setEnabled(Integer.valueOf(0).equals(dto.getEnabled()) ? 0 : 1); + config.setRemark(dto.getRemark()); + } + + /** + * Run business method `requireConfig`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return private MessageHubPushConfigDO result consumed by the caller or returned to the frontend + */ + private MessageHubPushConfigDO requireConfig(Long id) { + MessageHubPushConfigDO config = configMapper.selectById(id); + if (config == null || Integer.valueOf(1).equals(config.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("MessageHub 推送配置不存在"); + } + return config; + } + + /** + * Run business method `ensurePlatformAdmin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void ensurePlatformAdmin(UserDO currentUser) { + if (currentUser == null || !Integer.valueOf(4).equals(currentUser.getType())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("仅平台管理员可以管理消息推送配置"); + } + } + + /** + * Run business method `normalizeSceneCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sceneCode parameter `sceneCode` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String normalizeSceneCode(String sceneCode) { + if (!StringUtils.hasText(sceneCode)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("场景编码不能为空"); + } + return sceneCode.trim().toUpperCase(Locale.ROOT); + } + + /** + * Run business method `normalizeUpper`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param value parameter `value` supplied by the caller + * @param fallback parameter `fallback` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String normalizeUpper(String value, String fallback) { + return StringUtils.hasText(value) ? value.trim().toUpperCase(Locale.ROOT) : fallback; + } + + /** + * Run business method `toVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param config parameter `config` supplied by the caller + * @return private MessageHubPushConfigVO result consumed by the caller or returned to the frontend + */ + private MessageHubPushConfigVO toVO(MessageHubPushConfigDO config) { + MessageHubPushConfigVO vo = new MessageHubPushConfigVO(); + vo.setId(config.getId()); + vo.setSceneCode(config.getSceneCode()); + vo.setSceneName(config.getSceneName()); + vo.setPlatform(config.getPlatform()); + vo.setMsgType(config.getMsgType()); + vo.setQueueName(config.getQueueName()); + vo.setSourceSystem(config.getSourceSystem()); + vo.setTemplateCode(config.getTemplateCode()); + vo.setChannelId(config.getChannelId()); + vo.setSendMethod(config.getSendMethod()); + vo.setEnabled(config.getEnabled()); + vo.setRemark(config.getRemark()); + vo.setCreateTime(config.getCreateTime()); + vo.setUpdateTime(config.getUpdateTime()); + return vo; + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/MinioServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/MinioServiceImpl.java index 33a41c8c..f13d165d 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/MinioServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/MinioServiceImpl.java @@ -15,12 +15,28 @@ import java.util.concurrent.TimeUnit; @Slf4j @Service @RequiredArgsConstructor +/** + * MinioServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ public class MinioServiceImpl implements MinioService { - + /** + * Variable `minioClient`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final MinioClient minioClient; + /** + * Variable `minioConfig`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final MinioConfig minioConfig; @Override + /** + * Run business method `uploadFile`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param file parameter `file` supplied by the caller + * @param objectName parameter `objectName` supplied by the caller + * @return String result consumed by the caller or returned to the frontend + */ public String uploadFile(MultipartFile file, String objectName) throws Exception { try { try (InputStream inputStream = file.getInputStream()) { @@ -33,6 +49,15 @@ public class MinioServiceImpl implements MinioService { } @Override + /** + * Run business method `uploadStream`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param inputStream parameter `inputStream` supplied by the caller + * @param fileSize parameter `fileSize` supplied by the caller + * @param contentType parameter `contentType` supplied by the caller + * @param objectName parameter `objectName` supplied by the caller + * @return String result consumed by the caller or returned to the frontend + */ public String uploadStream(InputStream inputStream, long fileSize, String contentType, String objectName) throws Exception { try { minioClient.putObject( @@ -45,6 +70,12 @@ public class MinioServiceImpl implements MinioService { ); log.info("文件上传成功: {}", objectName); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param objectName parameter `objectName` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ return getFileUrl(objectName); } catch (Exception e) { log.error("文件上传失败: {}", objectName, e); @@ -53,6 +84,12 @@ public class MinioServiceImpl implements MinioService { } @Override + /** + * Run business method `downloadFile`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param objectName parameter `objectName` supplied by the caller + * @return InputStream result consumed by the caller or returned to the frontend + */ public InputStream downloadFile(String objectName) throws Exception { return minioClient.getObject( GetObjectArgs.builder() @@ -63,6 +100,11 @@ public class MinioServiceImpl implements MinioService { } @Override + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param objectName parameter `objectName` supplied by the caller + */ public void deleteFile(String objectName) throws Exception { minioClient.removeObject( RemoveObjectArgs.builder() @@ -74,11 +116,24 @@ public class MinioServiceImpl implements MinioService { } @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param objectName parameter `objectName` supplied by the caller + * @return String result consumed by the caller or returned to the frontend + */ public String getFileUrl(String objectName) { return minioConfig.getEndpoint() + "/" + minioConfig.getBucketName() + "/" + objectName; } @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param objectName parameter `objectName` supplied by the caller + * @param expiryTimeInMinutes parameter `expiryTimeInMinutes` supplied by the caller + * @return String result consumed by the caller or returned to the frontend + */ public String getPresignedUrl(String objectName, int expiryTimeInMinutes) throws Exception { String url = minioClient.getPresignedObjectUrl( GetPresignedObjectUrlArgs.builder() @@ -93,11 +148,22 @@ public class MinioServiceImpl implements MinioService { } @Override + /** + * Run business method `bucketExists`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param bucketName parameter `bucketName` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ public boolean bucketExists(String bucketName) throws Exception { return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build()); } @Override + /** + * Run business method `makeBucket`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param bucketName parameter `bucketName` supplied by the caller + */ public void makeBucket(String bucketName) throws Exception { if (!bucketExists(bucketName)) { minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build()); diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/NailArtistInfoServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/NailArtistInfoServiceImpl.java index 2eee14a7..4c37fc43 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/NailArtistInfoServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/NailArtistInfoServiceImpl.java @@ -4,11 +4,11 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.xiaowang.yuminailcore.dto.NailArtistInfoDTO; import com.xiaowang.yuminailcore.entity.NailArtistInfoDO; -import com.xiaowang.yuminailcore.entity.UserDO; import com.xiaowang.yuminailcore.entity.ShopDO; +import com.xiaowang.yuminailcore.entity.UserDO; import com.xiaowang.yuminailcore.mapper.NailArtistInfoMapper; -import com.xiaowang.yuminailcore.mapper.UserMapper; import com.xiaowang.yuminailcore.mapper.ShopMapper; +import com.xiaowang.yuminailcore.mapper.UserMapper; import com.xiaowang.yuminailcore.service.NailArtistInfoService; import com.xiaowang.yuminailcore.support.UserShopBindingSupport; import com.xiaowang.yuminailcore.vo.ShopSimpleVO; @@ -19,143 +19,221 @@ import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; -/** - * 美甲师信息服务实现 - */ @Service +/** + * NailArtistInfoServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ public class NailArtistInfoServiceImpl extends ServiceImpl implements NailArtistInfoService { - + @Autowired private UserMapper userMapper; - + @Autowired private ShopMapper shopMapper; @Autowired private UserShopBindingSupport userShopBindingSupport; - + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return NailArtistInfoDTO result consumed by the caller or returned to the frontend + */ public NailArtistInfoDTO getByUserId(Long userId) { - LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); - queryWrapper.eq(NailArtistInfoDO::getUserId, userId); - queryWrapper.eq(NailArtistInfoDO::getIsDelete, 0); - - NailArtistInfoDO nailArtistInfoDO = getOne(queryWrapper); - if (nailArtistInfoDO == null) { - return null; - } - - return convertToDTO(nailArtistInfoDO); + NailArtistInfoDO info = getOne(new LambdaQueryWrapper() + .eq(NailArtistInfoDO::getUserId, userId) + .eq(NailArtistInfoDO::getIsDelete, 0) + .last("LIMIT 1")); + return info == null ? null : convertToDTO(info); } - + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ public List getAllNailArtists() { - LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); - queryWrapper.eq(NailArtistInfoDO::getIsDelete, 0); - - List nailArtistInfoDOList = list(queryWrapper); - List nailArtistInfoDTOList = new ArrayList<>(); - - for (NailArtistInfoDO nailArtistInfoDO : nailArtistInfoDOList) { - nailArtistInfoDTOList.add(convertToDTO(nailArtistInfoDO)); + List result = new ArrayList<>(); + List records = list(new LambdaQueryWrapper() + .eq(NailArtistInfoDO::getIsDelete, 0)); + for (NailArtistInfoDO record : records) { + NailArtistInfoDTO dto = convertToDTO(record); + if (isVisibleServiceUser(dto)) { + result.add(dto); + } } - - return nailArtistInfoDTOList; + return result; } - + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ public List getByShopId(Long shopId) { - List artistUserIds = userShopBindingSupport.listUserIdsByShopId(shopId, true); - if (artistUserIds.isEmpty()) { + List serviceUserIds = userShopBindingSupport.listUserIdsByShopId(shopId, true); + if (serviceUserIds.isEmpty()) { return new ArrayList<>(); } - LambdaQueryWrapper userQueryWrapper = new LambdaQueryWrapper<>(); - userQueryWrapper.in(UserDO::getId, artistUserIds); - userQueryWrapper.eq(UserDO::getType, 3); - userQueryWrapper.eq(UserDO::getIsDelete, 0); - - List userDOList = userMapper.selectList(userQueryWrapper); - List nailArtistInfoDTOList = new ArrayList<>(); - ShopDO currentShop = shopMapper.selectById(shopId); - - for (UserDO userDO : userDOList) { - NailArtistInfoDTO nailArtistInfoDTO = getByUserId(userDO.getId()); - if (nailArtistInfoDTO != null) { - nailArtistInfoDTO.setShopId(shopId); - nailArtistInfoDTO.setShopName(currentShop == null ? null : currentShop.getShopName()); - nailArtistInfoDTOList.add(nailArtistInfoDTO); + List users = userMapper.selectList(new LambdaQueryWrapper() + .in(UserDO::getId, serviceUserIds) + .in(UserDO::getType, List.of(2, 3)) + .eq(UserDO::getIsDelete, 0)); + List result = new ArrayList<>(); + ShopDO shop = shopMapper.selectById(shopId); + for (UserDO user : users) { + NailArtistInfoDTO dto = getByUserId(user.getId()); + if (dto != null && isVisibleServiceUser(dto)) { + dto.setShopId(shopId); + dto.setShopName(shop == null ? null : shop.getShopName()); + result.add(dto); } } - - return nailArtistInfoDTOList; + return result; } - - @Override - public NailArtistInfoDTO saveOrUpdateNailArtistInfo(NailArtistInfoDTO nailArtistInfoDTO) { - NailArtistInfoDO nailArtistInfoDO = new NailArtistInfoDO(); - BeanUtils.copyProperties(nailArtistInfoDTO, nailArtistInfoDO); - - // 检查是否已存在 - LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); - queryWrapper.eq(NailArtistInfoDO::getUserId, nailArtistInfoDTO.getUserId()); - queryWrapper.eq(NailArtistInfoDO::getIsDelete, 0); - - NailArtistInfoDO existing = getOne(queryWrapper); - if (existing != null) { - nailArtistInfoDO.setId(existing.getId()); - } - - saveOrUpdate(nailArtistInfoDO); - return convertToDTO(nailArtistInfoDO); - } - - /** - * 将实体类转换为DTO - * @param nailArtistInfoDO 实体类 - * @return DTO - */ - private NailArtistInfoDTO convertToDTO(NailArtistInfoDO nailArtistInfoDO) { - NailArtistInfoDTO nailArtistInfoDTO = new NailArtistInfoDTO(); - BeanUtils.copyProperties(nailArtistInfoDO, nailArtistInfoDTO); - - // 获取用户信息 - UserDO userDO = userMapper.selectById(nailArtistInfoDO.getUserId()); - if (userDO != null) { - nailArtistInfoDTO.setNickname(userDO.getNickname()); - nailArtistInfoDTO.setSignature(userDO.getSignature()); // 添加用户签名 - List shopOptions = userShopBindingSupport.listShopOptionsByUserId(userDO.getId(), true, true); + @Override + /** + * Save submitted data. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param dto parameter `dto` supplied by the caller + * @return NailArtistInfoDTO result consumed by the caller or returned to the frontend + */ + public NailArtistInfoDTO saveOrUpdateNailArtistInfo(NailArtistInfoDTO dto) { + NailArtistInfoDO entity = new NailArtistInfoDO(); + BeanUtils.copyProperties(dto, entity); + + NailArtistInfoDO existing = getOne(new LambdaQueryWrapper() + .eq(NailArtistInfoDO::getUserId, dto.getUserId()) + .eq(NailArtistInfoDO::getIsDelete, 0) + .last("LIMIT 1")); + if (existing != null) { + entity.setId(existing.getId()); + } + if (entity.getStatus() == null) { + entity.setStatus(1); + } + if (entity.getParticipateProduction() == null) { + UserDO user = userMapper.selectById(dto.getUserId()); + entity.setParticipateProduction(user != null && Integer.valueOf(3).equals(user.getType()) ? 1 : 0); + } + + /** + * Save submitted data. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param entity parameter `entity` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + saveOrUpdate(entity); + /** + * Run business method `convertToDTO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param entity parameter `entity` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return convertToDTO(entity); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ + public List getAllAvailableNailArtists() { + List result = new ArrayList<>(); + List records = list(new LambdaQueryWrapper() + .eq(NailArtistInfoDO::getStatus, 1) + .eq(NailArtistInfoDO::getIsDelete, 0)); + for (NailArtistInfoDO record : records) { + NailArtistInfoDTO dto = convertToDTO(record); + if (isBookableServiceUser(dto)) { + result.add(dto); + } + } + return result; + } + + /** + * Run business method `convertToDTO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param entity parameter `entity` supplied by the caller + * @return private NailArtistInfoDTO result consumed by the caller or returned to the frontend + */ + private NailArtistInfoDTO convertToDTO(NailArtistInfoDO entity) { + NailArtistInfoDTO dto = new NailArtistInfoDTO(); + BeanUtils.copyProperties(entity, dto); + + UserDO user = userMapper.selectById(entity.getUserId()); + if (user != null) { + dto.setNickname(user.getNickname()); + dto.setSignature(user.getSignature()); + dto.setUserType(user.getType()); + dto.setUserTypeName(resolveUserTypeName(user.getType())); + if (dto.getParticipateProduction() == null) { + dto.setParticipateProduction(Integer.valueOf(3).equals(user.getType()) ? 1 : 0); + } + + List shopOptions = userShopBindingSupport.listShopOptionsByUserId(user.getId(), true, true); if (!shopOptions.isEmpty()) { ShopSimpleVO primaryShop = shopOptions.get(0); - nailArtistInfoDTO.setShopId(primaryShop.getId()); - nailArtistInfoDTO.setShopName(primaryShop.getShopName()); - } else if (userDO.getShopId() != null && userDO.getShopId() > 0) { - ShopDO shopDO = shopMapper.selectById(userDO.getShopId()); - if (shopDO != null) { - nailArtistInfoDTO.setShopId(shopDO.getId()); - nailArtistInfoDTO.setShopName(shopDO.getShopName()); + dto.setShopId(primaryShop.getId()); + dto.setShopName(primaryShop.getShopName()); + } else if (user.getShopId() != null && user.getShopId() > 0) { + ShopDO shop = shopMapper.selectById(user.getShopId()); + if (shop != null) { + dto.setShopId(shop.getId()); + dto.setShopName(shop.getShopName()); } } } - - return nailArtistInfoDTO; + return dto; } - - @Override - public List getAllAvailableNailArtists() { - // 先获取所有状态为营业中且未被删除的美甲师信息 - LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); - queryWrapper.eq(NailArtistInfoDO::getStatus, 1); // 1表示营业中 - queryWrapper.eq(NailArtistInfoDO::getIsDelete, 0); // 0表示未删除 - - List nailArtistInfoDOList = list(queryWrapper); - List nailArtistInfoDTOList = new ArrayList<>(); - - for (NailArtistInfoDO nailArtistInfoDO : nailArtistInfoDOList) { - nailArtistInfoDTOList.add(convertToDTO(nailArtistInfoDO)); + + /** + * Run business method `isVisibleServiceUser`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param dto parameter `dto` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean isVisibleServiceUser(NailArtistInfoDTO dto) { + if (dto == null || dto.getUserType() == null) { + return false; } - - return nailArtistInfoDTOList; + return Integer.valueOf(3).equals(dto.getUserType()) + || Integer.valueOf(2).equals(dto.getUserType()); + } + + /** + * Run business method `isBookableServiceUser`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param dto parameter `dto` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean isBookableServiceUser(NailArtistInfoDTO dto) { + return isVisibleServiceUser(dto) && Integer.valueOf(1).equals(dto.getStatus()); + } + + /** + * Run business method `resolveUserTypeName`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param type parameter `type` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String resolveUserTypeName(Integer type) { + if (Integer.valueOf(2).equals(type)) { + return "店长"; + } + if (Integer.valueOf(3).equals(type)) { + return "美甲师"; + } + return "用户"; } } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/ObjectStorageFileServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/ObjectStorageFileServiceImpl.java index a5c81237..e2c20ebe 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/ObjectStorageFileServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/ObjectStorageFileServiceImpl.java @@ -36,12 +36,26 @@ import java.util.stream.Collectors; public class ObjectStorageFileServiceImpl extends ServiceImpl implements ObjectStorageFileService { private static final String FILE_DETAIL_CACHE_PREFIX = "cache:file:detail:"; - + /** + * Variable `objectStorageFileMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final ObjectStorageFileMapper objectStorageFileMapper; + /** + * Variable `multiLevelCacheService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final MultiLevelCacheService multiLevelCacheService; + /** + * Variable `appCacheProperties`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final AppCacheProperties appCacheProperties; @Override + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param objectStorageFileDTO parameter `objectStorageFileDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ public Long createObjectStorageFile(ObjectStorageFileDTO objectStorageFileDTO) { ObjectStorageFileDO objectStorageFileDO = new ObjectStorageFileDO(); objectStorageFileDO.setFileName(objectStorageFileDTO.getFileName()); @@ -55,6 +69,13 @@ public class ObjectStorageFileServiceImpl extends ServiceImpl 0; if (updated) { + /** + * Run business method `evictFileCache`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ evictFileCache(id); } return updated; } @Override + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ public boolean deleteObjectStorageFile(Long id) { boolean deleted = objectStorageFileMapper.deleteById(id) > 0; if (deleted) { + /** + * Run business method `evictFileCache`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ evictFileCache(id); } return deleted; } @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return ObjectStorageFileVO result consumed by the caller or returned to the frontend + */ public ObjectStorageFileVO getObjectStorageFileById(Long id) { return getObjectStorageFileMapByIds(Collections.singleton(id)).get(id); } @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ids parameter `ids` supplied by the caller + * @return Map result consumed by the caller or returned to the frontend + */ public Map getObjectStorageFileMapByIds(Collection ids) { if (CollectionUtils.isEmpty(ids)) { return Collections.emptyMap(); @@ -133,6 +184,11 @@ public class ObjectStorageFileServiceImpl extends ServiceImpl result consumed by the caller or returned to the frontend + */ public List listAllObjectStorageFiles() { List objectStorageFileDOs = objectStorageFileMapper.selectList(null); return objectStorageFileDOs.stream() @@ -141,6 +197,12 @@ public class ObjectStorageFileServiceImpl extends ServiceImpl result consumed by the caller or returned to the frontend + */ public List listObjectStorageFilesByStatus(Integer status) { List objectStorageFileDOs = objectStorageFileMapper.selectList( Wrappers.lambdaQuery(ObjectStorageFileDO.class) @@ -169,12 +231,24 @@ public class ObjectStorageFileServiceImpl extends ServiceImpl 0) { multiLevelCacheService.evict(buildDetailCacheKey(id)); } } + /** + * Run business method `buildDetailCacheKey`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ private String buildDetailCacheKey(Long id) { return FILE_DETAIL_CACHE_PREFIX + id; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/OrderServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/OrderServiceImpl.java index 97e68399..4bc7f683 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/OrderServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/OrderServiceImpl.java @@ -1,10 +1,12 @@ package com.xiaowang.yuminailcore.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.xiaowang.yuminailcore.dto.OrderDTO; import com.xiaowang.yuminailcore.dto.OrderItemDTO; import com.xiaowang.yuminailcore.entity.CartDO; import com.xiaowang.yuminailcore.entity.CouponDO; +import com.xiaowang.yuminailcore.entity.NailArtistInfoDO; import com.xiaowang.yuminailcore.entity.OrderDO; import com.xiaowang.yuminailcore.entity.OrderItemDO; import com.xiaowang.yuminailcore.entity.ProductDO; @@ -13,6 +15,7 @@ import com.xiaowang.yuminailcore.entity.UserCouponDO; import com.xiaowang.yuminailcore.entity.UserDO; import com.xiaowang.yuminailcore.mapper.CartMapper; import com.xiaowang.yuminailcore.mapper.CouponMapper; +import com.xiaowang.yuminailcore.mapper.NailArtistInfoMapper; import com.xiaowang.yuminailcore.mapper.OrderItemMapper; import com.xiaowang.yuminailcore.mapper.OrderMapper; import com.xiaowang.yuminailcore.mapper.ProductMapper; @@ -22,9 +25,11 @@ import com.xiaowang.yuminailcore.mapper.UserMapper; import com.xiaowang.yuminailcore.service.CouponService; import com.xiaowang.yuminailcore.service.OrderService; import com.xiaowang.yuminailcore.service.TagService; +import com.xiaowang.yuminailcore.support.BookableArtistSupport; import com.xiaowang.yuminailcore.support.ObjectStorageUrlSupport; import com.xiaowang.yuminailcore.support.id.TimeOrderedSnowflakeIdGenerator; import com.xiaowang.yuminailcore.support.UserShopBindingSupport; +import com.xiaowang.yuminailcore.vo.ArtistCalendarAppointmentVO; import com.xiaowang.yuminailcore.vo.OrderItemVO; import com.xiaowang.yuminailcore.vo.OrderVO; import com.xiaowang.yuminailcore.vo.TagVO; @@ -40,6 +45,7 @@ import javax.annotation.Resource; import javax.annotation.PreDestroy; import java.math.BigDecimal; import java.time.Duration; +import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.format.DateTimeFormatter; @@ -49,6 +55,7 @@ import java.util.Arrays; import java.util.Comparator; import java.util.Collections; import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; @@ -63,6 +70,10 @@ import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; @Service +/** + * OrderServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ public class OrderServiceImpl implements OrderService { private static final DateTimeFormatter ORDER_NO_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmss"); @@ -121,6 +132,9 @@ public class OrderServiceImpl implements OrderService { @Resource private CouponMapper couponMapper; + @Resource + private NailArtistInfoMapper nailArtistInfoMapper; + @Resource private UserCouponMapper userCouponMapper; @@ -139,6 +153,9 @@ public class OrderServiceImpl implements OrderService { @Resource private UserShopBindingSupport userShopBindingSupport; + @Resource + private BookableArtistSupport bookableArtistSupport; + @Resource private TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; @@ -152,19 +169,40 @@ public class OrderServiceImpl implements OrderService { private TransactionTemplate transactionTemplate; @PreDestroy + /** + * Run business method `shutdownOrderLockRenewExecutor`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + */ public void shutdownOrderLockRenewExecutor() { LOCK_RENEW_EXECUTOR.shutdownNow(); } @Override + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param orderDTO parameter `orderDTO` supplied by the caller + * @return OrderVO result consumed by the caller or returned to the frontend + */ public OrderVO createOrder(Long userId, OrderDTO orderDTO) { if (orderDTO == null || orderDTO.getItems() == null || orderDTO.getItems().isEmpty()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("订单项不能为空"); } String userLockKey = ORDER_CREATE_USER_LOCK_PREFIX + userId; String userLockToken = UUID.randomUUID().toString(); if (!tryAcquireOrderLock(userLockKey, userLockToken)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("订单正在提交中,请勿重复点击"); } @@ -178,6 +216,11 @@ public class OrderServiceImpl implements OrderService { artistLockKey = ORDER_CREATE_ARTIST_LOCK_PREFIX + artistId; artistLockToken = UUID.randomUUID().toString(); if (!tryAcquireArtistOrderLock(artistLockKey, artistLockToken)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("当前美甲师预约繁忙,请稍后再试"); } @@ -185,19 +228,62 @@ public class OrderServiceImpl implements OrderService { OrderVO orderVO = transactionTemplate.execute(status -> createOrderInTransaction(userId, orderDTO)); if (orderVO == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("订单创建失败,请稍后重试"); } return orderVO; } finally { + /** + * Run business method `stopOrderLockRenewal`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param artistLockLease parameter `artistLockLease` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ stopOrderLockRenewal(artistLockLease); + /** + * Run business method `releaseOrderLock`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param artistLockKey parameter `artistLockKey` supplied by the caller + * @param artistLockToken parameter `artistLockToken` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ releaseOrderLock(artistLockKey, artistLockToken); + /** + * Run business method `stopOrderLockRenewal`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userLockLease parameter `userLockLease` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ stopOrderLockRenewal(userLockLease); + /** + * Run business method `releaseOrderLock`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userLockKey parameter `userLockKey` supplied by the caller + * @param userLockToken parameter `userLockToken` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ releaseOrderLock(userLockKey, userLockToken); } } + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param orderDTO parameter `orderDTO` supplied by the caller + * @return private OrderVO result consumed by the caller or returned to the frontend + */ private OrderVO createOrderInTransaction(Long userId, OrderDTO orderDTO) { if (orderDTO == null || orderDTO.getItems() == null || orderDTO.getItems().isEmpty()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("订单项不能为空"); } @@ -219,16 +305,31 @@ public class OrderServiceImpl implements OrderService { ProductDO product = productMapper.selectById(orderItemDTO.getProductId()); if (product == null || Integer.valueOf(1).equals(product.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("商品不存在或已下架"); } productCache.put(product.getId(), product); CartDO cartItem = lockedCartItemMap.get(orderItemDTO.getProductId()); if (cartItem == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("请先将商品加入购物车后再结算"); } Integer requestedQuantity = requestedQuantityByProductId.get(orderItemDTO.getProductId()); if (cartItem.getQuantity() == null || requestedQuantity == null || cartItem.getQuantity() < requestedQuantity) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("购物车中的商品数量已变化,请刷新后重试"); } @@ -236,14 +337,31 @@ public class OrderServiceImpl implements OrderService { if (shopId == null) { shopId = product.getShopId(); + /** + * Run business method `validateUserCanCreateOrderInShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ validateUserCanCreateOrderInShop(userId, shopId); } else if (!shopId.equals(product.getShopId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("跨店铺商品请分开下单"); } if (selectedArtistId == null) { selectedArtistId = artist.getId(); } else if (!selectedArtistId.equals(artist.getId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("不同美甲师的项目请分开下单"); } @@ -269,10 +387,29 @@ public class OrderServiceImpl implements OrderService { orderItems.add(orderItem); } + /** + * Run business method `validateRequestedSlotConflicts`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requestedSlots parameter `requestedSlots` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ validateRequestedSlotConflicts(requestedSlots); + /** + * Run business method `validateArtistScheduleConflicts`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param selectedArtistId parameter `selectedArtistId` supplied by the caller + * @param requestedSlots parameter `requestedSlots` supplied by the caller + * @param productCache parameter `productCache` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ validateArtistScheduleConflicts(selectedArtistId, requestedSlots, productCache); if (totalAmount.compareTo(BigDecimal.ZERO) == 0) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("订单金额无效"); } @@ -297,9 +434,19 @@ public class OrderServiceImpl implements OrderService { if (couponSelection != null) { CouponDO coupon = couponMapper.selectById(couponSelection.getCouponId()); if (coupon == null || Integer.valueOf(1).equals(coupon.getIsDelete()) || coupon.getStatus() != 1) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("优惠券不存在或已失效"); } if (shopId != null && coupon.getShopId() != null && !shopId.equals(coupon.getShopId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("该优惠券不适用于当前店铺"); } @@ -309,6 +456,13 @@ public class OrderServiceImpl implements OrderService { couponSourceType = couponSelection.getSourceType(); if (COUPON_SOURCE_USER.equals(couponSourceType)) { + /** + * Run business method `consumeUserCoupon`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userCouponId parameter `userCouponId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ consumeUserCoupon(userCouponId, userId); } } @@ -340,10 +494,22 @@ public class OrderServiceImpl implements OrderService { .in("product_id", requestedProductIds); cartMapper.delete(cartWrapper); + /** + * Run business method `buildOrderVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param order parameter `order` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ return buildOrderVO(order); } @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ public List getOrderList(Long userId) { List orderList = orderMapper.selectByUserId(userId); List orderVOList = new ArrayList<>(); @@ -356,47 +522,119 @@ public class OrderServiceImpl implements OrderService { } @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderId parameter `orderId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return OrderVO result consumed by the caller or returned to the frontend + */ public OrderVO getOrderDetail(Long orderId, Long userId) { OrderDO order = orderMapper.selectById(orderId); if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("订单不存在"); } if (!order.getUserId().equals(userId)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("无权查看此订单"); } + /** + * Run business method `buildOrderVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param order parameter `order` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ return buildOrderVO(order); } @Override @Transactional + /** + * Run business method `cancelOrder`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderId parameter `orderId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + */ public void cancelOrder(Long orderId, Long userId) { OrderDO order = orderMapper.selectById(orderId); if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("订单不存在"); } if (!order.getUserId().equals(userId)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("无权操作此订单"); } if (order.getStatus() != 1) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("订单状态不允许取消"); } order.setStatus(3); orderMapper.updateById(order); + /** + * Run business method `restoreUserCoupon`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param order parameter `order` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ restoreUserCoupon(order, userId); } @Override @Transactional + /** + * Run business method `processOrder`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderId parameter `orderId` supplied by the caller + * @param status parameter `status` supplied by the caller + */ public void processOrder(Long orderId, Integer status) { OrderDO order = orderMapper.selectById(orderId); if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("订单不存在"); } if (status != 2 && status != 3) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("无效的订单状态"); } if (order.getStatus() != 1) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("订单状态不允许处理"); } @@ -409,12 +647,28 @@ public class OrderServiceImpl implements OrderService { @Override @Transactional + /** + * Complete a business action. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderId parameter `orderId` supplied by the caller + * @param artistId parameter `artistId` supplied by the caller + */ public void completeArtistOrder(Long orderId, Long artistId) { OrderDO order = orderMapper.selectById(orderId); if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("订单不存在"); } if (order.getStatus() != 1) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("当前订单状态不允许完成"); } @@ -422,11 +676,21 @@ public class OrderServiceImpl implements OrderService { .filter(item -> !Integer.valueOf(1).equals(item.getIsDelete())) .toList(); if (activeItems.isEmpty()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("订单商品不存在"); } boolean allBelongToArtist = activeItems.stream().allMatch(item -> artistId.equals(item.getArtistId())); if (!allBelongToArtist) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("只能完成全部由自己承接的订单"); } @@ -435,6 +699,11 @@ public class OrderServiceImpl implements OrderService { } @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ public List getAllOrders() { List orderList = orderMapper.selectList(new QueryWrapper().eq("is_delete", 0)); List orderVOList = new ArrayList<>(); @@ -445,6 +714,12 @@ public class OrderServiceImpl implements OrderService { } @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param artistId parameter `artistId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ public List getOrdersByArtistId(Long artistId) { List orderList = orderMapper.selectByArtistId(artistId); List orderVOList = new ArrayList<>(); @@ -457,10 +732,232 @@ public class OrderServiceImpl implements OrderService { return orderVOList; } + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param artistId parameter `artistId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List getArtistWorkbenchOrders(Long artistId) { + Map orderMap = new LinkedHashMap<>(); + List serviceOrders = orderMapper.selectByArtistId(artistId); + for (OrderDO order : serviceOrders) { + OrderVO orderVO = buildOrderVO(order, artistId); + if (orderVO != null && orderVO.getItems() != null && !orderVO.getItems().isEmpty()) { + orderVO.setArtistOrderSource("SERVICE"); + orderVO.setArtistOrderSourceText("客户预约我的订单"); + orderMap.put(orderVO.getId(), orderVO); + } + } + + List selfOrders = orderMapper.selectByUserId(artistId); + for (OrderDO order : selfOrders) { + if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) { + continue; + } + OrderVO existing = orderMap.get(order.getId()); + if (existing != null) { + existing.setArtistOrderSource("BOTH"); + existing.setArtistOrderSourceText("我下的订单 / 客户预约我的订单"); + continue; + } + OrderVO orderVO = buildOrderVO(order); + orderVO.setArtistOrderSource("SELF"); + orderVO.setArtistOrderSourceText("我下的订单"); + orderMap.put(orderVO.getId(), orderVO); + } + + return orderMap.values().stream() + .sorted(Comparator.comparing(OrderVO::getCreateTime, Comparator.nullsLast(Comparator.reverseOrder()))) + .toList(); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userType parameter `userType` supplied by the caller + * @param days parameter `days` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List getArtistCalendarRecent(Long userId, Integer userType, Integer days) { + /** + * Run business method `ensureCalendarAccess`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userType parameter `userType` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensureCalendarAccess(userId, userType); + int normalizedDays = days == null ? 7 : Math.max(1, Math.min(days, 31)); + LocalDate startDate = LocalDate.now(); + return listArtistCalendarAppointments(userId, startDate.atStartOfDay(), startDate.plusDays(normalizedDays).atStartOfDay()); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userType parameter `userType` supplied by the caller + * @param date parameter `date` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List getArtistCalendarDay(Long userId, Integer userType, LocalDate date) { + /** + * Run business method `ensureCalendarAccess`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userType parameter `userType` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensureCalendarAccess(userId, userType); + LocalDate targetDate = date == null ? LocalDate.now() : date; + return listArtistCalendarAppointments(userId, targetDate.atStartOfDay(), targetDate.plusDays(1).atStartOfDay()); + } + + /** + * Run business method `buildOrderVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param order parameter `order` supplied by the caller + * @return private OrderVO result consumed by the caller or returned to the frontend + */ private OrderVO buildOrderVO(OrderDO order) { + /** + * Run business method `buildOrderVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param order parameter `order` supplied by the caller + * @param null parameter `null` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ return buildOrderVO(order, null); } + /** + * Run business method `ensureCalendarAccess`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userType parameter `userType` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void ensureCalendarAccess(Long userId, Integer userType) { + if (userId == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请先登录"); + } + if (Integer.valueOf(3).equals(userType)) { + return; + } + if (Integer.valueOf(2).equals(userType)) { + NailArtistInfoDO info = nailArtistInfoMapper.selectOne(new LambdaQueryWrapper() + .eq(NailArtistInfoDO::getUserId, userId) + .eq(NailArtistInfoDO::getIsDelete, 0) + .last("LIMIT 1")); + if (info != null && Integer.valueOf(1).equals(info.getParticipateProduction())) { + return; + } + } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("仅美甲师或参与制作的店长可查看预约日历"); + } + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param artistId parameter `artistId` supplied by the caller + * @param startTime parameter `startTime` supplied by the caller + * @param endTime parameter `endTime` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List listArtistCalendarAppointments(Long artistId, LocalDateTime startTime, LocalDateTime endTime) { + List items = orderItemMapper.selectArtistCalendarItems(artistId, startTime, endTime); + if (items == null || items.isEmpty()) { + return Collections.emptyList(); + } + + Map userCache = new HashMap<>(); + Map productCache = new HashMap<>(); + Map shopCache = new HashMap<>(); + UserDO artist = getUserFromCache(artistId, userCache); + List result = new ArrayList<>(); + + for (OrderItemDO item : items) { + OrderDO order = orderMapper.selectById(item.getOrderId()); + if (order == null || Integer.valueOf(1).equals(order.getIsDelete()) || Integer.valueOf(3).equals(order.getStatus())) { + continue; + } + ProductDO product = getProductFromCache(item.getProductId(), productCache); + if (product == null || item.getAppointmentTime() == null) { + continue; + } + ShopDO shop = getShopFromCache(order.getShopId() == null ? product.getShopId() : order.getShopId(), shopCache); + UserDO customer = getUserFromCache(order.getUserId(), userCache); + long singleDuration = resolveServiceDurationMinutes(product); + int quantity = Math.max(1, item.getQuantity() == null ? 1 : item.getQuantity()); + long durationMinutes = singleDuration * quantity; + + ArtistCalendarAppointmentVO vo = new ArtistCalendarAppointmentVO(); + vo.setOrderId(order.getId()); + vo.setOrderNo(order.getOrderNo()); + vo.setTotalAmount(order.getTotalAmount()); + vo.setActualAmount(order.getActualAmount()); + vo.setOrderStatus(order.getStatus()); + vo.setOrderStatusText(resolveOrderStatusText(order.getStatus())); + vo.setOrderItemId(item.getId()); + vo.setProductId(product.getId()); + vo.setProductTitle(product.getTitle()); + vo.setArtistId(artistId); + vo.setArtistName(artist == null ? null : artist.getNickname()); + vo.setCustomerNickname(resolveCustomerNickname(customer)); + vo.setCustomerPhoneMasked(maskPhone(customer == null ? null : customer.getPhone())); + vo.setShopId(order.getShopId() == null ? product.getShopId() : order.getShopId()); + vo.setShopName(shop == null ? null : shop.getShopName()); + vo.setAppointmentStartTime(item.getAppointmentTime()); + vo.setAppointmentEndTime(item.getAppointmentTime().plusMinutes(durationMinutes)); + vo.setQuantity(item.getQuantity()); + vo.setDurationMinutes(durationMinutes); + result.add(vo); + } + result.sort(Comparator.comparing(ArtistCalendarAppointmentVO::getAppointmentStartTime)); + return result; + } + + /** + * Run business method `resolveOrderStatusText`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param status parameter `status` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String resolveOrderStatusText(Integer status) { + if (Integer.valueOf(1).equals(status)) { + return "待服务"; + } + if (Integer.valueOf(2).equals(status)) { + return "已完成"; + } + if (Integer.valueOf(3).equals(status)) { + return "已取消"; + } + return "未知状态"; + } + + /** + * Run business method `buildOrderVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param order parameter `order` supplied by the caller + * @param artistIdFilter parameter `artistIdFilter` supplied by the caller + * @return private OrderVO result consumed by the caller or returned to the frontend + */ private OrderVO buildOrderVO(OrderDO order, Long artistIdFilter) { OrderVO orderVO = new OrderVO(); Map userCache = new HashMap<>(); @@ -468,6 +965,10 @@ public class OrderServiceImpl implements OrderService { orderVO.setOrderNo(order.getOrderNo()); orderVO.setUserId(order.getUserId()); orderVO.setShopId(order.getShopId()); + if (order.getShopId() != null) { + ShopDO shop = shopMapper.selectById(order.getShopId()); + orderVO.setShopName(shop == null ? null : shop.getShopName()); + } orderVO.setTotalAmount(order.getTotalAmount()); orderVO.setActualAmount(order.getActualAmount()); orderVO.setCouponId(order.getCouponId()); @@ -555,10 +1056,21 @@ public class OrderServiceImpl implements OrderService { return orderVO; } + /** + * Run business method `buildRequestedQuantityMap`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderItemDTOs parameter `orderItemDTOs` supplied by the caller + * @return private Map result consumed by the caller or returned to the frontend + */ private Map buildRequestedQuantityMap(List orderItemDTOs) { Map requestedQuantityByProductId = new HashMap<>(); for (OrderItemDTO orderItemDTO : orderItemDTOs) { if (orderItemDTO == null || orderItemDTO.getProductId() == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("订单商品信息不完整"); } requestedQuantityByProductId.merge( @@ -570,6 +1082,13 @@ public class OrderServiceImpl implements OrderService { return requestedQuantityByProductId; } + /** + * Run business method `loadLockedCartItems`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param requestedProductIds parameter `requestedProductIds` supplied by the caller + * @return private Map result consumed by the caller or returned to the frontend + */ private Map loadLockedCartItems(Long userId, List requestedProductIds) { if (requestedProductIds == null || requestedProductIds.isEmpty()) { return Collections.emptyMap(); @@ -585,16 +1104,39 @@ public class OrderServiceImpl implements OrderService { return lockedCartItemMap; } + /** + * Run business method `validateUserCanCreateOrderInShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void validateUserCanCreateOrderInShop(Long userId, Long shopId) { if (!userShopBindingSupport.canUserAccessShop(userId, shopId, false, null)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("当前账号已不可在该店铺下单,请切换门店后重试"); } } + /** + * Run business method `resolveRequestedArtistId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderItemDTOs parameter `orderItemDTOs` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ private Long resolveRequestedArtistId(List orderItemDTOs) { Long artistId = null; for (OrderItemDTO orderItemDTO : orderItemDTOs) { if (orderItemDTO == null || orderItemDTO.getArtistId() == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("请为每个商品选择美甲师"); } if (artistId == null) { @@ -602,21 +1144,45 @@ public class OrderServiceImpl implements OrderService { continue; } if (!artistId.equals(orderItemDTO.getArtistId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("不同美甲师的项目请分开下单"); } } if (artistId == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("请为每个商品选择美甲师"); } return artistId; } + /** + * Run business method `tryAcquireOrderLock`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param lockKey parameter `lockKey` supplied by the caller + * @param lockToken parameter `lockToken` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ private boolean tryAcquireOrderLock(String lockKey, String lockToken) { return Boolean.TRUE.equals( stringRedisTemplate.opsForValue().setIfAbsent(lockKey, lockToken, ORDER_CREATE_LOCK_TTL) ); } + /** + * Run business method `tryAcquireArtistOrderLock`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param lockKey parameter `lockKey` supplied by the caller + * @param lockToken parameter `lockToken` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ private boolean tryAcquireArtistOrderLock(String lockKey, String lockToken) { long deadline = System.currentTimeMillis() + ARTIST_LOCK_WAIT_TIMEOUT_MILLIS; while (System.currentTimeMillis() <= deadline) { @@ -634,6 +1200,13 @@ public class OrderServiceImpl implements OrderService { } // 慢事务期间持续续租,避免下单锁在事务未完成时提前过期。 + /** + * Run business method `startOrderLockRenewal`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param lockKey parameter `lockKey` supplied by the caller + * @param lockToken parameter `lockToken` supplied by the caller + * @return private LockLease result consumed by the caller or returned to the frontend + */ private LockLease startOrderLockRenewal(String lockKey, String lockToken) { if (!StringUtils.hasText(lockKey) || !StringUtils.hasText(lockToken)) { return null; @@ -650,6 +1223,12 @@ public class OrderServiceImpl implements OrderService { return lockLease; } + /** + * Run business method `renewOrderLock`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param lockLease parameter `lockLease` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void renewOrderLock(LockLease lockLease) { if (lockLease == null || !lockLease.isActive()) { return; @@ -668,6 +1247,12 @@ public class OrderServiceImpl implements OrderService { } } + /** + * Run business method `stopOrderLockRenewal`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param lockLease parameter `lockLease` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void stopOrderLockRenewal(LockLease lockLease) { if (lockLease == null) { return; @@ -675,6 +1260,13 @@ public class OrderServiceImpl implements OrderService { lockLease.cancel(); } + /** + * Run business method `releaseOrderLock`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param lockKey parameter `lockKey` supplied by the caller + * @param lockToken parameter `lockToken` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void releaseOrderLock(String lockKey, String lockToken) { if (!StringUtils.hasText(lockKey) || !StringUtils.hasText(lockToken)) { return; @@ -682,6 +1274,13 @@ public class OrderServiceImpl implements OrderService { stringRedisTemplate.execute(RELEASE_LOCK_SCRIPT, Collections.singletonList(lockKey), lockToken); } + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userCache parameter `userCache` supplied by the caller + * @return private UserDO result consumed by the caller or returned to the frontend + */ private UserDO getUserFromCache(Long userId, Map userCache) { if (userId == null) { return null; @@ -694,6 +1293,12 @@ public class OrderServiceImpl implements OrderService { return userDO; } + /** + * Run business method `resolveCustomerNickname`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param customer parameter `customer` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ private String resolveCustomerNickname(UserDO customer) { if (customer == null) { return "用户"; @@ -707,6 +1312,12 @@ public class OrderServiceImpl implements OrderService { return "用户"; } + /** + * Run business method `maskPhone`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ private String maskPhone(String phone) { if (!StringUtils.hasText(phone)) { return null; @@ -720,28 +1331,72 @@ public class OrderServiceImpl implements OrderService { + normalizedPhone.substring(normalizedPhone.length() - 4); } + /** + * Run business method `validateOrderQuantity`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param quantity parameter `quantity` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void validateOrderQuantity(Integer quantity) { if (quantity == null || quantity < 1) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param 0 parameter `0` supplied by the caller + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("订单商品数量必须大于 0"); } } + /** + * Run business method `validateArtistForProduct`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param product parameter `product` supplied by the caller + * @param artistId parameter `artistId` supplied by the caller + * @return private UserDO result consumed by the caller or returned to the frontend + */ private UserDO validateArtistForProduct(ProductDO product, Long artistId) { if (artistId == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("请为每个商品选择美甲师"); } UserDO artist = userMapper.selectById(artistId); if (artist == null || Integer.valueOf(1).equals(artist.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("美甲师不存在或已删除"); } - if (!Integer.valueOf(3).equals(artist.getType())) { - throw new RuntimeException("指定用户不是美甲师"); + if (!bookableArtistSupport.isBookableServiceUser(artist)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("指定用户不是可预约美甲服务人员"); } if (!Integer.valueOf(1).equals(artist.getStatus())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("美甲师当前不可预约"); } if (product.getShopId() != null && !userShopBindingSupport.isUserAccessibleInShop(artistId, product.getShopId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("该美甲师不属于当前商品店铺"); } @@ -755,6 +1410,11 @@ public class OrderServiceImpl implements OrderService { } } if (!isBookable) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("该美甲师无法预约此商品"); } } @@ -762,6 +1422,13 @@ public class OrderServiceImpl implements OrderService { return artist; } + /** + * Run business method `collectTagNames`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagNames parameter `tagNames` supplied by the caller + * @param tags parameter `tags` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void collectTagNames(Set tagNames, String tags) { if (tags == null || tags.isBlank()) { return; @@ -781,8 +1448,19 @@ public class OrderServiceImpl implements OrderService { } } + /** + * Run business method `parseAppointmentTime`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param appointmentTime parameter `appointmentTime` supplied by the caller + * @return private LocalDateTime result consumed by the caller or returned to the frontend + */ private LocalDateTime parseAppointmentTime(String appointmentTime) { if (appointmentTime == null || appointmentTime.isBlank()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("请为每个商品选择预约时间"); } @@ -793,15 +1471,41 @@ public class OrderServiceImpl implements OrderService { } catch (DateTimeParseException ignored) { } } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("预约时间格式不正确"); } + /** + * Run business method `validateAppointmentTime`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param appointmentTime parameter `appointmentTime` supplied by the caller + * @param productTitle parameter `productTitle` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void validateAppointmentTime(LocalDateTime appointmentTime, String productTitle) { if (!appointmentTime.isAfter(LocalDateTime.now())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("商品「" + productTitle + "」的预约时间必须晚于当前时间"); } } + /** + * Run business method `validateBusinessHours`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shop parameter `shop` supplied by the caller + * @param appointmentTime parameter `appointmentTime` supplied by the caller + * @param appointmentEndTime parameter `appointmentEndTime` supplied by the caller + * @param productTitle parameter `productTitle` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void validateBusinessHours(ShopDO shop, LocalDateTime appointmentTime, LocalDateTime appointmentEndTime, String productTitle) { if (shop == null || shop.getBusinessHours() == null || shop.getBusinessHours().isBlank()) { return; @@ -826,10 +1530,22 @@ public class OrderServiceImpl implements OrderService { if (!appointmentTime.toLocalDate().equals(appointmentEndTime.toLocalDate()) || appointmentTime.toLocalTime().isBefore(openTime) || appointmentEndTime.toLocalTime().isAfter(closeTime)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("商品「" + productTitle + "」的预约时间超出门店营业时间"); } } + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @param shopCache parameter `shopCache` supplied by the caller + * @return private ShopDO result consumed by the caller or returned to the frontend + */ private ShopDO getShopFromCache(Long shopId, Map shopCache) { if (shopId == null) { return null; @@ -846,6 +1562,12 @@ public class OrderServiceImpl implements OrderService { return shop; } + /** + * Run business method `validateRequestedSlotConflicts`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requestedSlots parameter `requestedSlots` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void validateRequestedSlotConflicts(List requestedSlots) { if (requestedSlots.size() <= 1) { return; @@ -861,6 +1583,14 @@ public class OrderServiceImpl implements OrderService { } } + /** + * Run business method `validateArtistScheduleConflicts`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param artistId parameter `artistId` supplied by the caller + * @param requestedSlots parameter `requestedSlots` supplied by the caller + * @param productCache parameter `productCache` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void validateArtistScheduleConflicts(Long artistId, List requestedSlots, Map productCache) { if (artistId == null || requestedSlots.isEmpty()) { return; @@ -892,6 +1622,13 @@ public class OrderServiceImpl implements OrderService { } } + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productId parameter `productId` supplied by the caller + * @param productCache parameter `productCache` supplied by the caller + * @return private ProductDO result consumed by the caller or returned to the frontend + */ private ProductDO getProductFromCache(Long productId, Map productCache) { if (productId == null) { return null; @@ -908,6 +1645,12 @@ public class OrderServiceImpl implements OrderService { return product; } + /** + * Run business method `resolveServiceDurationMinutes`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param product parameter `product` supplied by the caller + * @return private long result consumed by the caller or returned to the frontend + */ private long resolveServiceDurationMinutes(ProductDO product) { if (product == null || product.getApproximateDuration() == null || product.getApproximateDuration().isBlank()) { return DEFAULT_SERVICE_DURATION_MINUTES; @@ -923,10 +1666,25 @@ public class OrderServiceImpl implements OrderService { return DEFAULT_SERVICE_DURATION_MINUTES; } + /** + * Run business method `hasOverlap`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param startA parameter `startA` supplied by the caller + * @param endA parameter `endA` supplied by the caller + * @param startB parameter `startB` supplied by the caller + * @param endB parameter `endB` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ private boolean hasOverlap(LocalDateTime startA, LocalDateTime endA, LocalDateTime startB, LocalDateTime endB) { return startA.isBefore(endB) && startB.isBefore(endA); } + /** + * Run business method `formatAppointmentTime`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param appointmentTime parameter `appointmentTime` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ private String formatAppointmentTime(LocalDateTime appointmentTime) { if (appointmentTime == null) { return null; @@ -934,6 +1692,13 @@ public class OrderServiceImpl implements OrderService { return appointmentTime.format(APPOINTMENT_OUTPUT_FORMATTER); } + /** + * Run business method `resolveRequestedCoupon`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderDTO parameter `orderDTO` supplied by the caller + * @param availableCoupons parameter `availableCoupons` supplied by the caller + * @return private CouponSelection result consumed by the caller or returned to the frontend + */ private CouponSelection resolveRequestedCoupon(OrderDTO orderDTO, List availableCoupons) { if (orderDTO == null || orderDTO.getCouponId() == null || orderDTO.getCouponId() <= 0) { return null; @@ -946,6 +1711,11 @@ public class OrderServiceImpl implements OrderService { .toList(); if (matchedCoupons.isEmpty()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("当前订单不可使用所选优惠券"); } @@ -961,6 +1731,13 @@ public class OrderServiceImpl implements OrderService { ); } + /** + * Run business method `selectBestAvailableCoupon`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param availableCoupons parameter `availableCoupons` supplied by the caller + * @param totalAmount parameter `totalAmount` supplied by the caller + * @return private CouponSelection result consumed by the caller or returned to the frontend + */ private CouponSelection selectBestAvailableCoupon(List availableCoupons, BigDecimal totalAmount) { return availableCoupons.stream() .filter(coupon -> coupon.getCouponId() != null) @@ -973,6 +1750,12 @@ public class OrderServiceImpl implements OrderService { .orElse(null); } + /** + * Run business method `normalizeCouponSourceType`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponSourceType parameter `couponSourceType` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ private String normalizeCouponSourceType(String couponSourceType) { if (couponSourceType == null || couponSourceType.isBlank()) { return null; @@ -980,12 +1763,25 @@ public class OrderServiceImpl implements OrderService { return couponSourceType.trim().toUpperCase(); } + /** + * Run business method `isExplicitNoCoupon`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param orderDTO parameter `orderDTO` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ private boolean isExplicitNoCoupon(OrderDTO orderDTO) { return orderDTO != null && orderDTO.getCouponId() == null && COUPON_SOURCE_NONE.equalsIgnoreCase(orderDTO.getCouponSourceType()); } + /** + * Run business method `calculateCouponDiscountAmount`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param coupon parameter `coupon` supplied by the caller + * @param totalAmount parameter `totalAmount` supplied by the caller + * @return private BigDecimal result consumed by the caller or returned to the frontend + */ private BigDecimal calculateCouponDiscountAmount(UserCouponVO coupon, BigDecimal totalAmount) { if (coupon == null || totalAmount == null || totalAmount.compareTo(BigDecimal.ZERO) <= 0) { return BigDecimal.ZERO; @@ -1005,6 +1801,13 @@ public class OrderServiceImpl implements OrderService { return BigDecimal.ZERO; } + /** + * Run business method `applyCouponDiscount`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param totalAmount parameter `totalAmount` supplied by the caller + * @param coupon parameter `coupon` supplied by the caller + * @return private BigDecimal result consumed by the caller or returned to the frontend + */ private BigDecimal applyCouponDiscount(BigDecimal totalAmount, CouponDO coupon) { if (coupon.getCouponType() == 1 && coupon.getDiscountValue() != null) { return totalAmount.multiply(coupon.getDiscountValue()) @@ -1017,19 +1820,46 @@ public class OrderServiceImpl implements OrderService { return totalAmount; } + /** + * Run business method `consumeUserCoupon`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userCouponId parameter `userCouponId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void consumeUserCoupon(Long userCouponId, Long userId) { if (userCouponId == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("用户优惠券信息缺失"); } UserCouponDO userCoupon = userCouponMapper.selectById(userCouponId); if (userCoupon == null || Integer.valueOf(1).equals(userCoupon.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("优惠券不存在或已失效"); } if (!userId.equals(userCoupon.getUserId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("优惠券不属于当前用户"); } if (userCoupon.getStatus() == null || userCoupon.getStatus() != 1) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("优惠券已被使用或不可用"); } @@ -1039,6 +1869,13 @@ public class OrderServiceImpl implements OrderService { updateCouponUsedCount(userCoupon.getCouponId(), 1); } + /** + * Run business method `restoreUserCoupon`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param order parameter `order` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void restoreUserCoupon(OrderDO order, Long userId) { if (order == null || !COUPON_SOURCE_USER.equals(order.getCouponSourceType()) @@ -1058,6 +1895,13 @@ public class OrderServiceImpl implements OrderService { updateCouponUsedCount(userCoupon.getCouponId(), -1); } + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param couponId parameter `couponId` supplied by the caller + * @param delta parameter `delta` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void updateCouponUsedCount(Long couponId, int delta) { if (couponId == null || delta == 0) { return; @@ -1074,28 +1918,62 @@ public class OrderServiceImpl implements OrderService { } private static final class LockLease { + /** + * Variable `lockKey`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final String lockKey; + /** + * Variable `lockToken`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final String lockToken; private volatile ScheduledFuture future; private volatile boolean active = true; + /** + * Run business method `LockLease`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param lockKey parameter `lockKey` supplied by the caller + * @param lockToken parameter `lockToken` supplied by the caller + * @return private result consumed by the caller or returned to the frontend + */ private LockLease(String lockKey, String lockToken) { this.lockKey = lockKey; this.lockToken = lockToken; } + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private String result consumed by the caller or returned to the frontend + */ private String getLockKey() { return lockKey; } + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private String result consumed by the caller or returned to the frontend + */ private String getLockToken() { return lockToken; } + /** + * Run business method `isActive`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private boolean result consumed by the caller or returned to the frontend + */ private boolean isActive() { return active; } + /** + * Run business method `attachFuture`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param future parameter `future` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void attachFuture(ScheduledFuture future) { this.future = future; if (!active && future != null) { @@ -1103,6 +1981,11 @@ public class OrderServiceImpl implements OrderService { } } + /** + * Run business method `cancel`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private void result consumed by the caller or returned to the frontend + */ private void cancel() { active = false; ScheduledFuture currentFuture = future; @@ -1114,6 +1997,12 @@ public class OrderServiceImpl implements OrderService { private static final class LockRenewThreadFactory implements ThreadFactory { @Override + /** + * Run business method `newThread`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param runnable parameter `runnable` supplied by the caller + * @return Thread result consumed by the caller or returned to the frontend + */ public Thread newThread(Runnable runnable) { Thread thread = new Thread(runnable, "order-lock-renew"); thread.setDaemon(true); @@ -1122,48 +2011,112 @@ public class OrderServiceImpl implements OrderService { } private static final class CouponSelection { + /** + * Variable `sourceType`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final String sourceType; + /** + * Variable `couponId`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final Long couponId; + /** + * Variable `userCouponId`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final Long userCouponId; + /** + * Run business method `CouponSelection`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sourceType parameter `sourceType` supplied by the caller + * @param couponId parameter `couponId` supplied by the caller + * @param userCouponId parameter `userCouponId` supplied by the caller + * @return private result consumed by the caller or returned to the frontend + */ private CouponSelection(String sourceType, Long couponId, Long userCouponId) { this.sourceType = sourceType; this.couponId = couponId; this.userCouponId = userCouponId; } + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private String result consumed by the caller or returned to the frontend + */ private String getSourceType() { return sourceType; } + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private Long result consumed by the caller or returned to the frontend + */ private Long getCouponId() { return couponId; } + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private Long result consumed by the caller or returned to the frontend + */ private Long getUserCouponId() { return userCouponId; } } private static final class AppointmentSlot { + /** + * Variable `productTitle`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final String productTitle; + /** + * Variable `startTime`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final LocalDateTime startTime; + /** + * Variable `endTime`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final LocalDateTime endTime; + /** + * Run business method `AppointmentSlot`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productTitle parameter `productTitle` supplied by the caller + * @param startTime parameter `startTime` supplied by the caller + * @param endTime parameter `endTime` supplied by the caller + * @return private result consumed by the caller or returned to the frontend + */ private AppointmentSlot(String productTitle, LocalDateTime startTime, LocalDateTime endTime) { this.productTitle = productTitle; this.startTime = startTime; this.endTime = endTime; } + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private String result consumed by the caller or returned to the frontend + */ private String getProductTitle() { return productTitle; } + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private LocalDateTime result consumed by the caller or returned to the frontend + */ private LocalDateTime getStartTime() { return startTime; } + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private LocalDateTime result consumed by the caller or returned to the frontend + */ private LocalDateTime getEndTime() { return endTime; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/PermissionServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/PermissionServiceImpl.java index 2c7623b8..22dba1ad 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/PermissionServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/PermissionServiceImpl.java @@ -7,9 +7,13 @@ import com.xiaowang.yuminailcore.dto.UserPermissionDTO; import com.xiaowang.yuminailcore.entity.PermissionDO; import com.xiaowang.yuminailcore.entity.UserDO; import com.xiaowang.yuminailcore.entity.UserPermissionDO; +import com.xiaowang.yuminailcore.entity.ShopRolePermissionDO; +import com.xiaowang.yuminailcore.entity.UserShopRoleDO; import com.xiaowang.yuminailcore.mapper.PermissionMapper; import com.xiaowang.yuminailcore.mapper.UserMapper; import com.xiaowang.yuminailcore.mapper.UserPermissionMapper; +import com.xiaowang.yuminailcore.mapper.ShopRolePermissionMapper; +import com.xiaowang.yuminailcore.mapper.UserShopRoleMapper; import com.xiaowang.yuminailcore.service.PermissionService; import com.xiaowang.yuminailcore.support.PermissionPolicy; import com.xiaowang.yuminailcore.support.RequestShopContext; @@ -28,19 +32,48 @@ import java.util.stream.Collectors; @Service @RequiredArgsConstructor +/** + * PermissionServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ public class PermissionServiceImpl extends ServiceImpl implements PermissionService { private static final Set SHOP_BOOTSTRAP_PERMISSION_CODES = Set.of( "shop:view", "shop:create" ); - + /** + * Variable `permissionMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final PermissionMapper permissionMapper; + /** + * Variable `userPermissionMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final UserPermissionMapper userPermissionMapper; + /** + * Variable `shopRolePermissionMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopRolePermissionMapper shopRolePermissionMapper; + /** + * Variable `userShopRoleMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserShopRoleMapper userShopRoleMapper; + /** + * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final UserMapper userMapper; + /** + * Variable `userShopBindingSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final UserShopBindingSupport userShopBindingSupport; @Override + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param permissionDTO parameter `permissionDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ public Long createPermission(PermissionDTO permissionDTO) { PermissionDO permissionDO = new PermissionDO(); permissionDO.setPermissionCode(permissionDTO.getPermissionCode()); @@ -53,6 +86,13 @@ public class PermissionServiceImpl extends ServiceImpl result consumed by the caller or returned to the frontend + */ public List listAllPermissions() { return permissionMapper.selectList( Wrappers.lambdaQuery(PermissionDO.class) @@ -105,6 +168,12 @@ public class PermissionServiceImpl extends ServiceImpl result consumed by the caller or returned to the frontend + */ public List listPermissionsByGroup(String permissionGroup) { return permissionMapper.selectList( Wrappers.lambdaQuery(PermissionDO.class) @@ -116,6 +185,12 @@ public class PermissionServiceImpl extends ServiceImpl result consumed by the caller or returned to the frontend + */ public List listUserPermissions(Long userId) { UserDO userDO = userMapper.selectById(userId); List userPermissions = userPermissionMapper.selectList( @@ -153,32 +228,69 @@ public class PermissionServiceImpl extends ServiceImpl result consumed by the caller or returned to the frontend + */ public List listAssignablePermissionIds(Long targetUserId, Long currentUserId) { UserDO currentUser = userMapper.selectById(currentUserId); if (currentUser == null || Integer.valueOf(1).equals(currentUser.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("当前用户不存在"); } UserDO targetUser = userMapper.selectById(targetUserId); if (targetUser == null || Integer.valueOf(1).equals(targetUser.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("目标用户不存在"); } if (!hasPermission(currentUserId, "permission:assign")) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("权限不足,无法分配权限"); } boolean platformAdmin = Integer.valueOf(4).equals(currentUser.getType()); Long currentShopId = RequestShopContext.getCurrentShopId(); if (!PermissionPolicy.canManageUserType(currentUser.getType(), targetUser.getType())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("当前角色不能维护该用户的权限"); } if (!platformAdmin) { if (currentUserId.equals(targetUserId)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("不允许给自己调整权限"); } if (currentShopId == null || !userShopBindingSupport.isUserAccessibleInShop(targetUserId, currentShopId)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("只能给本店铺用户分配权限"); } } @@ -204,6 +316,13 @@ public class PermissionServiceImpl extends ServiceImpl permissionIds = userPermissionDTO.getPermissionIds() == null @@ -215,29 +334,59 @@ public class PermissionServiceImpl extends ServiceImpl requestedPermissionCodes = resolvePermissionCodes(permissionIds); Set allowedPermissionCodes = PermissionPolicy.getDefaultPermissionCodeSet(targetUser.getType()); if (!allowedPermissionCodes.containsAll(requestedPermissionCodes)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("目标角色的权限配置超出允许范围"); } if (!platformAdmin) { Set operatorPermissionCodes = listPermissionCodesByUserId(currentUserId); if (!operatorPermissionCodes.containsAll(requestedPermissionCodes)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("不能分配超出自己已有的权限"); } } @@ -272,6 +431,13 @@ public class PermissionServiceImpl extends ServiceImpl userPermissions = userPermissionMapper.selectList( @@ -297,7 +463,14 @@ public class PermissionServiceImpl extends ServiceImpl roles = userShopRoleMapper.selectList(Wrappers.lambdaQuery(UserShopRoleDO.class) + .eq(UserShopRoleDO::getUserId, userId) + .eq(UserShopRoleDO::getIsDelete, 0) + .eq(UserShopRoleDO::getStatus, 1)); + if (roles.isEmpty()) { + return false; + } + List roleIds = roles.stream().map(UserShopRoleDO::getRoleId).filter(Objects::nonNull).distinct().collect(Collectors.toList()); + if (roleIds.isEmpty()) { + return false; + } + List permissionIds = shopRolePermissionMapper.selectList(Wrappers.lambdaQuery(ShopRolePermissionDO.class) + .in(ShopRolePermissionDO::getRoleId, roleIds) + .eq(ShopRolePermissionDO::getIsDelete, 0)) + .stream() + .map(ShopRolePermissionDO::getPermissionId) + .filter(Objects::nonNull) + .distinct() + .collect(Collectors.toList()); + if (permissionIds.isEmpty()) { + return false; + } + PermissionDO permissionDO = permissionMapper.selectOne( + Wrappers.lambdaQuery(PermissionDO.class) + .eq(PermissionDO::getPermissionCode, permissionCode) + .eq(PermissionDO::getIsDelete, 0) + .last("limit 1")); + return permissionDO != null && permissionIds.contains(permissionDO.getId()); + } + + /** + * Run business method `resolvePermissionCodes`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param permissionIds parameter `permissionIds` supplied by the caller + * @return private Set result consumed by the caller or returned to the frontend + */ private Set resolvePermissionCodes(List permissionIds) { if (permissionIds == null || permissionIds.isEmpty()) { return Collections.emptySet(); @@ -318,6 +535,11 @@ public class PermissionServiceImpl extends ServiceImpl result consumed by the caller or returned to the frontend + */ private Set listPermissionCodesByUserId(Long userId) { List userPermissions = userPermissionMapper.selectList( Wrappers.lambdaQuery(UserPermissionDO.class) @@ -353,12 +581,24 @@ public class PermissionServiceImpl extends ServiceImpl wrapper = new LambdaQueryWrapper<>(); wrapper.eq(ProductLikeDO::getUserId, userId); wrapper.eq(ProductLikeDO::getProductId, productId); + /** + * Remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param wrapper parameter `wrapper` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ remove(wrapper); // 减少商品点赞数 @@ -60,6 +84,13 @@ public class ProductLikeServiceImpl extends ServiceImpl wrapper = new LambdaQueryWrapper<>(); wrapper.eq(ProductLikeDO::getUserId, userId); diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/ProductServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/ProductServiceImpl.java index 8ab424a6..2865f434 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/ProductServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/ProductServiceImpl.java @@ -41,23 +41,56 @@ import java.util.stream.Collectors; @Service @RequiredArgsConstructor +/** + * ProductServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ public class ProductServiceImpl extends ServiceImpl implements ProductService { private static final String PRODUCT_DETAIL_CACHE_PREFIX = "cache:product:detail:"; private static final String PRODUCT_LIST_CACHE_PREFIX = "cache:product:list:"; private static final String PRODUCT_SEARCH_CACHE_PREFIX = "cache:product:search:"; private static final int DEFAULT_PUBLIC_PAGE_SIZE = 10; private static final int MAX_PUBLIC_PAGE_SIZE = 30; - + /** + * Variable `productMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final ProductMapper productMapper; + /** + * Variable `objectStorageFileService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final ObjectStorageFileService objectStorageFileService; + /** + * Variable `couponMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final CouponMapper couponMapper; + /** + * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final ShopMapper shopMapper; + /** + * Variable `tagMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final TagMapper tagMapper; + /** + * Variable `bookableArtistSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final BookableArtistSupport bookableArtistSupport; + /** + * Variable `multiLevelCacheService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final MultiLevelCacheService multiLevelCacheService; + /** + * Variable `appCacheProperties`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final AppCacheProperties appCacheProperties; @Override + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productDTO parameter `productDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ public Long createProduct(ProductDTO productDTO) { validateBookableArtists(productDTO.getShopId(), productDTO.getBookableArtists()); validateAvailableCoupons(productDTO.getShopId(), productDTO.getAvailableCoupons()); @@ -80,6 +113,13 @@ public class ProductServiceImpl extends ServiceImpl im } @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param productDTO parameter `productDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ public boolean updateProduct(Long id, ProductDTO productDTO) { ProductDO productDO = productMapper.selectById(id); if (productDO == null) { @@ -104,12 +144,24 @@ public class ProductServiceImpl extends ServiceImpl im productDO.setAvailableCoupons(productDTO.getAvailableCoupons()); boolean updated = productMapper.updateById(productDO) > 0; if (updated) { + /** + * Run business method `evictPublicProductCaches`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ evictPublicProductCaches(id); } return updated; } @Override + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ public boolean deleteProduct(Long id) { ProductDO productDO = productMapper.selectById(id); if (productDO == null || Integer.valueOf(1).equals(productDO.getIsDelete())) { @@ -118,30 +170,66 @@ public class ProductServiceImpl extends ServiceImpl im productDO.setIsDelete(1); boolean deleted = productMapper.updateById(productDO) > 0; if (deleted) { + /** + * Run business method `evictPublicProductCaches`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ evictPublicProductCaches(id); } return deleted; } @Override + /** + * Run business method `incrementLikeCount`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productId parameter `productId` supplied by the caller + * @return int result consumed by the caller or returned to the frontend + */ public int incrementLikeCount(Long productId) { int updated = productMapper.incrementLikeCount(productId); if (updated > 0) { + /** + * Run business method `evictPublicProductCaches`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productId parameter `productId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ evictPublicProductCaches(productId); } return updated; } @Override + /** + * Run business method `decrementLikeCount`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productId parameter `productId` supplied by the caller + * @return int result consumed by the caller or returned to the frontend + */ public int decrementLikeCount(Long productId) { int updated = productMapper.decrementLikeCount(productId); if (updated > 0) { + /** + * Run business method `evictPublicProductCaches`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productId parameter `productId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ evictPublicProductCaches(productId); } return updated; } @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return ProductVO result consumed by the caller or returned to the frontend + */ public ProductVO getProductById(Long id) { AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getProductDetail(); return multiLevelCacheService.getOrLoad( @@ -155,12 +243,23 @@ public class ProductServiceImpl extends ServiceImpl im if (productDO == null || Integer.valueOf(1).equals(productDO.getIsDelete())) { return null; } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productDO parameter `productDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ return convertToVO(productDO); } ); } @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ public List listAllProducts() { AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getProductList(); return multiLevelCacheService.getOrLoad( @@ -178,6 +277,12 @@ public class ProductServiceImpl extends ServiceImpl im } @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ public List listProductsByShopId(Long shopId) { AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getProductList(); return multiLevelCacheService.getOrLoad( @@ -193,12 +298,24 @@ public class ProductServiceImpl extends ServiceImpl im .eq(ProductDO::getShopId, shopId) .orderByDesc(ProductDO::getCreateTime) ); + /** + * Run business method `toProductVOList`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productDOs parameter `productDOs` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ return toProductVOList(productDOs); } ); } @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tag parameter `tag` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ public List listProductsByTag(String tag) { AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getProductList(); String normalizedTag = normalizeOptionalKeyword(tag); @@ -213,6 +330,12 @@ public class ProductServiceImpl extends ServiceImpl im } @Override + /** + * Run business method `searchProducts`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param keyword parameter `keyword` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ public List searchProducts(String keyword) { if (!StringUtils.hasText(keyword)) { return new ArrayList<>(); @@ -229,6 +352,12 @@ public class ProductServiceImpl extends ServiceImpl im ); } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productDO parameter `productDO` supplied by the caller + * @return private ProductVO result consumed by the caller or returned to the frontend + */ private ProductVO convertToVO(ProductDO productDO) { if (productDO == null) { return null; @@ -238,6 +367,12 @@ public class ProductServiceImpl extends ServiceImpl im .orElse(null); } + /** + * Run business method `toProductVOList`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productDOs parameter `productDOs` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ private List toProductVOList(List productDOs) { if (productDOs == null || productDOs.isEmpty()) { return new ArrayList<>(); @@ -248,6 +383,13 @@ public class ProductServiceImpl extends ServiceImpl im .collect(Collectors.toList()); } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productDO parameter `productDO` supplied by the caller + * @param context parameter `context` supplied by the caller + * @return private ProductVO result consumed by the caller or returned to the frontend + */ private ProductVO convertToVO(ProductDO productDO, ProductEnrichmentContext context) { ProductVO productVO = new ProductVO(); productVO.setId(productDO.getId()); @@ -299,6 +441,12 @@ public class ProductServiceImpl extends ServiceImpl im return productVO; } + /** + * Run business method `buildEnrichmentContext`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productDOs parameter `productDOs` supplied by the caller + * @return private ProductEnrichmentContext result consumed by the caller or returned to the frontend + */ private ProductEnrichmentContext buildEnrichmentContext(List productDOs) { Set shopIds = new LinkedHashSet<>(); Set tagIds = new LinkedHashSet<>(); @@ -321,6 +469,15 @@ public class ProductServiceImpl extends ServiceImpl im } @Override + /** + * Query paged records. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @param size parameter `size` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return PageResultVO result consumed by the caller or returned to the frontend + */ public PageResultVO pageProducts(Integer page, Integer size, String keyword, Long shopId) { Page pageParam = new Page<>(page, size); @@ -347,6 +504,15 @@ public class ProductServiceImpl extends ServiceImpl im } @Override + /** + * Query paged records. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @param size parameter `size` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @param tag parameter `tag` supplied by the caller + * @return PageResultVO result consumed by the caller or returned to the frontend + */ public PageResultVO pagePublicProducts(Integer page, Integer size, String keyword, String tag) { int normalizedPage = normalizePage(page); int normalizedSize = normalizePageSize(size); @@ -369,12 +535,24 @@ public class ProductServiceImpl extends ServiceImpl im ); } + /** + * Run business method `validateBookableArtists`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @param bookableArtists parameter `bookableArtists` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void validateBookableArtists(Long shopId, String bookableArtists) { if (!StringUtils.hasText(bookableArtists)) { return; } if (shopId == null || shopId <= 0) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("閰嶇疆鍙绾︾編鐢插笀鍓嶅繀椤诲厛閫夋嫨搴楅摵"); } @@ -387,21 +565,43 @@ public class ProductServiceImpl extends ServiceImpl im try { artistId = Long.parseLong(artistIdStr.trim()); } catch (NumberFormatException ex) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("鍙绾︾編鐢插笀閰嶇疆鏍煎紡涓嶆纭?"); } if (!bookableArtistSupport.isValidBookableArtist(shopId, artistId)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("瀛樺湪鏃犳晥銆佸凡鍋滅敤鎴栦笉灞炰簬褰撳墠搴楅摵鐨勭編鐢插笀閰嶇疆"); } } } + /** + * Run business method `validateAvailableCoupons`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @param availableCoupons parameter `availableCoupons` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void validateAvailableCoupons(Long shopId, String availableCoupons) { if (!StringUtils.hasText(availableCoupons)) { return; } if (shopId == null || shopId <= 0) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("閰嶇疆鍙敤浼樻儬鍒稿墠蹇呴』鍏堥€夋嫨搴楅摵"); } @@ -414,22 +614,48 @@ public class ProductServiceImpl extends ServiceImpl im try { couponId = Long.parseLong(couponIdStr.trim()); } catch (NumberFormatException exception) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("鍙敤浼樻儬鍒搁厤缃牸寮忎笉姝g‘"); } CouponDO couponDO = couponMapper.selectById(couponId); if (couponDO == null || Integer.valueOf(1).equals(couponDO.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("瀛樺湪鏃犳晥鐨勪紭鎯犲埜閰嶇疆"); } if (!Integer.valueOf(1).equals(couponDO.getStatus())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("瀛樺湪宸插け鏁堢殑浼樻儬鍒搁厤缃?"); } if (couponDO.getShopId() == null || !shopId.equals(couponDO.getShopId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("涓嶅彲璺ㄥ簵閾洪厤缃彲鐢ㄤ紭鎯犲埜"); } } } + /** + * Run business method `countBookableArtists`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param bookableArtists parameter `bookableArtists` supplied by the caller + * @return private int result consumed by the caller or returned to the frontend + */ private int countBookableArtists(String bookableArtists) { if (!StringUtils.hasText(bookableArtists)) { return 0; @@ -440,6 +666,12 @@ public class ProductServiceImpl extends ServiceImpl im .count(); } + /** + * Run business method `normalizeInteractionCount`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param count parameter `count` supplied by the caller + * @return private Integer result consumed by the caller or returned to the frontend + */ private Integer normalizeInteractionCount(Integer count) { if (count == null || count < 0) { return 0; @@ -447,6 +679,12 @@ public class ProductServiceImpl extends ServiceImpl im return count; } + /** + * Run business method `loadProductsByTag`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tag parameter `tag` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ private List loadProductsByTag(String tag) { if (!StringUtils.hasText(tag)) { return new ArrayList<>(); @@ -458,20 +696,49 @@ public class ProductServiceImpl extends ServiceImpl im LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(ProductDO.class) .eq(ProductDO::getIsDelete, 0) .orderByDesc(ProductDO::getCreateTime); + /** + * Run business method `applyTagIdConditions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param wrapper parameter `wrapper` supplied by the caller + * @param matchedTagIds parameter `matchedTagIds` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ applyTagIdConditions(wrapper, matchedTagIds); return toProductVOList(productMapper.selectList(wrapper)); } + /** + * Run business method `searchFrontProducts`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param keyword parameter `keyword` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ private List searchFrontProducts(String keyword) { LambdaQueryWrapper wrapper = buildFrontQuery(keyword, null, null); return toProductVOList(productMapper.selectList(wrapper)); } + /** + * Run business method `buildPublicProductPage`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @param size parameter `size` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @param tag parameter `tag` supplied by the caller + * @return private PageResultVO result consumed by the caller or returned to the frontend + */ private PageResultVO buildPublicProductPage(int page, int size, String keyword, String tag) { Set exactTagIds = null; if (StringUtils.hasText(tag)) { exactTagIds = findExactTagIds(tag); if (exactTagIds.isEmpty()) { + /** + * Run business method `buildEmptyPageResult`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @param size parameter `size` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ return buildEmptyPageResult(page, size); } } @@ -486,9 +753,24 @@ public class ProductServiceImpl extends ServiceImpl im return result; } + /** + * Run business method `buildFrontQuery`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param keyword parameter `keyword` supplied by the caller + * @param tag parameter `tag` supplied by the caller + * @param exactTagIds parameter `exactTagIds` supplied by the caller + * @return private LambdaQueryWrapper result consumed by the caller or returned to the frontend + */ private LambdaQueryWrapper buildFrontQuery(String keyword, String tag, Set exactTagIds) { LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(ProductDO.class) .eq(ProductDO::getIsDelete, 0); + /** + * Run business method `applyKeywordFilter`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param wrapper parameter `wrapper` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ applyKeywordFilter(wrapper, keyword); if (StringUtils.hasText(tag)) { applyTagIdConditions(wrapper, exactTagIds == null ? findExactTagIds(tag) : exactTagIds); @@ -497,6 +779,13 @@ public class ProductServiceImpl extends ServiceImpl im return wrapper; } + /** + * Run business method `applyKeywordFilter`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param wrapper parameter `wrapper` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void applyKeywordFilter(LambdaQueryWrapper wrapper, String keyword) { if (!StringUtils.hasText(keyword)) { return; @@ -506,10 +795,24 @@ public class ProductServiceImpl extends ServiceImpl im w.like(ProductDO::getTitle, keyword) .or() .like(ProductDO::getDescription, keyword); + /** + * Run business method `appendOrTagIdConditions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param w parameter `w` supplied by the caller + * @param matchedTagIds parameter `matchedTagIds` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ appendOrTagIdConditions(w, matchedTagIds); }); } + /** + * Run business method `applyTagIdConditions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param wrapper parameter `wrapper` supplied by the caller + * @param tagIds parameter `tagIds` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void applyTagIdConditions(LambdaQueryWrapper wrapper, Set tagIds) { wrapper.and(w -> { boolean appended = false; @@ -531,6 +834,13 @@ public class ProductServiceImpl extends ServiceImpl im }); } + /** + * Run business method `appendOrTagIdConditions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param wrapper parameter `wrapper` supplied by the caller + * @param tagIds parameter `tagIds` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void appendOrTagIdConditions(LambdaQueryWrapper wrapper, Set tagIds) { if (tagIds == null || tagIds.isEmpty()) { return; @@ -543,6 +853,12 @@ public class ProductServiceImpl extends ServiceImpl im } } + /** + * Run business method `loadShopNameMap`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopIds parameter `shopIds` supplied by the caller + * @return private Map result consumed by the caller or returned to the frontend + */ private Map loadShopNameMap(Set shopIds) { if (shopIds == null || shopIds.isEmpty()) { return Collections.emptyMap(); @@ -552,6 +868,12 @@ public class ProductServiceImpl extends ServiceImpl im .collect(Collectors.toMap(ShopDO::getId, ShopDO::getShopName, (left, right) -> left, LinkedHashMap::new)); } + /** + * Run business method `loadTagMap`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagIds parameter `tagIds` supplied by the caller + * @return private Map result consumed by the caller or returned to the frontend + */ private Map loadTagMap(Set tagIds) { if (tagIds == null || tagIds.isEmpty()) { return Collections.emptyMap(); @@ -561,6 +883,13 @@ public class ProductServiceImpl extends ServiceImpl im .collect(Collectors.toMap(TagDO::getId, tagDO -> tagDO, (left, right) -> left, LinkedHashMap::new)); } + /** + * Run business method `parseDelimitedLongIds`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param rawValue parameter `rawValue` supplied by the caller + * @param delimiter parameter `delimiter` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ private List parseDelimitedLongIds(String rawValue, String delimiter) { if (!StringUtils.hasText(rawValue)) { return Collections.emptyList(); @@ -579,6 +908,12 @@ public class ProductServiceImpl extends ServiceImpl im return ids; } + /** + * Run business method `findExactTagIds`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tag parameter `tag` supplied by the caller + * @return private Set result consumed by the caller or returned to the frontend + */ private Set findExactTagIds(String tag) { if (!StringUtils.hasText(tag)) { return Set.of(); @@ -593,6 +928,12 @@ public class ProductServiceImpl extends ServiceImpl im .collect(Collectors.toCollection(HashSet::new)); } + /** + * Run business method `findLikeTagIds`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param keyword parameter `keyword` supplied by the caller + * @return private Set result consumed by the caller or returned to the frontend + */ private Set findLikeTagIds(String keyword) { if (!StringUtils.hasText(keyword)) { return Set.of(); @@ -607,6 +948,13 @@ public class ProductServiceImpl extends ServiceImpl im .collect(Collectors.toCollection(HashSet::new)); } + /** + * Run business method `buildEmptyPageResult`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @param size parameter `size` supplied by the caller + * @return private PageResultVO result consumed by the caller or returned to the frontend + */ private PageResultVO buildEmptyPageResult(int page, int size) { PageResultVO result = new PageResultVO<>(); result.setList(List.of()); @@ -616,10 +964,22 @@ public class ProductServiceImpl extends ServiceImpl im return result; } + /** + * Run business method `normalizePage`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @return private int result consumed by the caller or returned to the frontend + */ private int normalizePage(Integer page) { return page == null || page < 1 ? 1 : page; } + /** + * Run business method `normalizePageSize`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param size parameter `size` supplied by the caller + * @return private int result consumed by the caller or returned to the frontend + */ private int normalizePageSize(Integer size) { if (size == null || size < 1) { return DEFAULT_PUBLIC_PAGE_SIZE; @@ -627,10 +987,22 @@ public class ProductServiceImpl extends ServiceImpl im return Math.min(size, MAX_PUBLIC_PAGE_SIZE); } + /** + * Run business method `normalizeOptionalKeyword`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param value parameter `value` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ private String normalizeOptionalKeyword(String value) { return StringUtils.hasText(value) ? value.trim() : ""; } + /** + * Run business method `evictPublicProductCaches`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productId parameter `productId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void evictPublicProductCaches(Long productId) { if (productId != null) { multiLevelCacheService.evict(PRODUCT_DETAIL_CACHE_PREFIX + productId); diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/SecurityAuditLogServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/SecurityAuditLogServiceImpl.java new file mode 100644 index 00000000..64bbeb42 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/SecurityAuditLogServiceImpl.java @@ -0,0 +1,56 @@ +package com.xiaowang.yuminailcore.service.impl; + +import com.xiaowang.yuminailcore.entity.SecurityAuditLogDO; +import com.xiaowang.yuminailcore.mapper.SecurityAuditLogMapper; +import com.xiaowang.yuminailcore.service.SecurityAuditLogService; +import com.xiaowang.yuminailcore.support.security.RequestThrottleService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import javax.servlet.http.HttpServletRequest; +import java.time.LocalDateTime; + +@Service +@RequiredArgsConstructor +public class SecurityAuditLogServiceImpl implements SecurityAuditLogService { + + private final SecurityAuditLogMapper auditLogMapper; + + @Override + public void record(Long userId, String account, String action, String result, String reason, HttpServletRequest request) { + try { + SecurityAuditLogDO log = new SecurityAuditLogDO(); + log.setUserId(userId); + log.setAccount(limit(account, 80)); + log.setAction(limit(action, 80)); + log.setResult(limit(result, 20)); + log.setReason(limit(reason, 500)); + log.setIpAddress(limit(resolveClientIp(request), 80)); + log.setDeviceId(limit(request == null ? null : request.getHeader(RequestThrottleService.DEVICE_ID_HEADER), 120)); + log.setOperateTime(LocalDateTime.now()); + auditLogMapper.insert(log); + } catch (Exception ignored) { + // Audit failure must never block the main user flow. + } + } + + private String resolveClientIp(HttpServletRequest request) { + if (request == null) { + return null; + } + String forwarded = request.getHeader("X-Forwarded-For"); + if (StringUtils.hasText(forwarded)) { + return forwarded.split(",")[0].trim(); + } + String realIp = request.getHeader("X-Real-IP"); + return StringUtils.hasText(realIp) ? realIp.trim() : request.getRemoteAddr(); + } + + private String limit(String value, int max) { + if (value == null || value.length() <= max) { + return value; + } + return value.substring(0, max); + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/ShopRoleServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/ShopRoleServiceImpl.java new file mode 100644 index 00000000..16a03781 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/ShopRoleServiceImpl.java @@ -0,0 +1,547 @@ +package com.xiaowang.yuminailcore.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.xiaowang.yuminailcore.dto.InviteCodeDTO; +import com.xiaowang.yuminailcore.dto.ShopRoleDTO; +import com.xiaowang.yuminailcore.dto.UserRelationUpdateDTO; +import com.xiaowang.yuminailcore.entity.PermissionDO; +import com.xiaowang.yuminailcore.entity.ShopDO; +import com.xiaowang.yuminailcore.entity.ShopRoleDO; +import com.xiaowang.yuminailcore.entity.ShopRolePermissionDO; +import com.xiaowang.yuminailcore.entity.UserDO; +import com.xiaowang.yuminailcore.entity.UserInviteCodeDO; +import com.xiaowang.yuminailcore.entity.UserRelationDO; +import com.xiaowang.yuminailcore.entity.UserShopRoleDO; +import com.xiaowang.yuminailcore.mapper.PermissionMapper; +import com.xiaowang.yuminailcore.mapper.ShopMapper; +import com.xiaowang.yuminailcore.mapper.ShopRoleMapper; +import com.xiaowang.yuminailcore.mapper.ShopRolePermissionMapper; +import com.xiaowang.yuminailcore.mapper.UserInviteCodeMapper; +import com.xiaowang.yuminailcore.mapper.UserMapper; +import com.xiaowang.yuminailcore.mapper.UserRelationMapper; +import com.xiaowang.yuminailcore.mapper.UserShopBindingMapper; +import com.xiaowang.yuminailcore.mapper.UserShopRoleMapper; +import com.xiaowang.yuminailcore.service.ShopRoleService; +import com.xiaowang.yuminailcore.support.AdminScopeHelper; +import com.xiaowang.yuminailcore.support.PermissionPolicy; +import com.xiaowang.yuminailcore.vo.InviteCodeVO; +import com.xiaowang.yuminailcore.vo.ShopRoleVO; +import com.xiaowang.yuminailcore.vo.ShopSimpleVO; +import com.xiaowang.yuminailcore.vo.UserRelationVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.time.LocalDateTime; +import java.util.*; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +/** + * ShopRoleServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class ShopRoleServiceImpl extends ServiceImpl implements ShopRoleService { + /** + * Variable `shopRoleMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopRoleMapper shopRoleMapper; + /** + * Variable `shopRolePermissionMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopRolePermissionMapper shopRolePermissionMapper; + /** + * Variable `userShopRoleMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserShopRoleMapper userShopRoleMapper; + /** + * Variable `userRelationMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserRelationMapper userRelationMapper; + /** + * Variable `userInviteCodeMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserInviteCodeMapper userInviteCodeMapper; + /** + * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserMapper userMapper; + /** + * Variable `permissionMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final PermissionMapper permissionMapper; + /** + * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopMapper shopMapper; + /** + * Variable `userShopBindingMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserShopBindingMapper userShopBindingMapper; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listRoles(UserDO currentUser, Long shopId) { + Long scopedShopId = adminScopeHelper.resolveShopScope(currentUser, shopId); + return shopRoleMapper.selectList(new LambdaQueryWrapper() + .eq(ShopRoleDO::getIsDelete, 0) + .eq(scopedShopId != null, ShopRoleDO::getShopId, scopedShopId) + .orderByAsc(ShopRoleDO::getSortOrder) + .orderByDesc(ShopRoleDO::getCreateTime)) + .stream().map(this::toVO).collect(Collectors.toList()); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long createRole(UserDO currentUser, ShopRoleDTO dto) { + Long shopId = adminScopeHelper.resolveShopScope(currentUser, dto.getShopId()); + if (shopId == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请选择店铺"); + } + adminScopeHelper.ensureShopAccessible(currentUser, shopId, "无权创建其他店铺角色"); + ShopRoleDO role = new ShopRoleDO(); + role.setShopId(shopId); + role.setRoleName(dto.getRoleName().trim()); + role.setCreatorId(currentUser.getId()); + role.setStatus(dto.getStatus() == null || dto.getStatus() != 0 ? 1 : 0); + role.setRemark(dto.getRemark()); + role.setSortOrder(dto.getSortOrder() == null ? 0 : dto.getSortOrder()); + role.setIsDelete(0); + shopRoleMapper.insert(role); + syncPermissions(role.getId(), dto.getPermissionIds()); + syncUsers(role.getId(), dto.getUserIds(), shopId); + return role.getId(); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean updateRole(UserDO currentUser, Long id, ShopRoleDTO dto) { + ShopRoleDO role = requireRole(id); + adminScopeHelper.ensureShopAccessible(currentUser, role.getShopId(), "无权修改其他店铺角色"); + if (StringUtils.hasText(dto.getRoleName())) { + role.setRoleName(dto.getRoleName().trim()); + } + if (dto.getStatus() != null) { + role.setStatus(dto.getStatus() == 0 ? 0 : 1); + } + if (dto.getRemark() != null) { + role.setRemark(dto.getRemark()); + } + if (dto.getSortOrder() != null) { + role.setSortOrder(dto.getSortOrder()); + } + role.setUpdateTime(LocalDateTime.now()); + shopRoleMapper.updateById(role); + if (dto.getPermissionIds() != null) { + syncPermissions(role.getId(), dto.getPermissionIds()); + } + if (dto.getUserIds() != null) { + syncUsers(role.getId(), dto.getUserIds(), role.getShopId()); + } + return true; + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean deleteRole(UserDO currentUser, Long id) { + ShopRoleDO role = requireRole(id); + adminScopeHelper.ensureShopAccessible(currentUser, role.getShopId(), "无权删除其他店铺角色"); + role.setIsDelete(1); + role.setUpdateTime(LocalDateTime.now()); + shopRoleMapper.updateById(role); + return true; + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Run business method `assignPermissions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param permissionIds parameter `permissionIds` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean assignPermissions(UserDO currentUser, Long id, List permissionIds) { + ShopRoleDO role = requireRole(id); + adminScopeHelper.ensureShopAccessible(currentUser, role.getShopId(), "无权分配其他店铺角色"); + /** + * Run business method `syncPermissions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param permissionIds parameter `permissionIds` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + syncPermissions(id, permissionIds); + return true; + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Run business method `assignUsers`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param userIds parameter `userIds` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean assignUsers(UserDO currentUser, Long id, List userIds) { + ShopRoleDO role = requireRole(id); + adminScopeHelper.ensureShopAccessible(currentUser, role.getShopId(), "无权绑定其他店铺员工"); + syncUsers(id, userIds, role.getShopId()); + return true; + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listRelationOptions(UserDO currentUser, Long shopId) { + Long scopedShopId = adminScopeHelper.resolveShopScope(currentUser, shopId); + List users = userMapper.selectList(new LambdaQueryWrapper().eq(UserDO::getIsDelete, 0)); + if (scopedShopId != null) { + Set userIds = userShopBindingMapper.selectList(new LambdaQueryWrapper<>()) + .stream().filter(b -> Objects.equals(scopedShopId, b.getShopId()) && Integer.valueOf(1).equals(b.getStatus())) + .map(b -> b.getUserId()).collect(Collectors.toSet()); + users = users.stream().filter(u -> userIds.contains(u.getId())).collect(Collectors.toList()); + } + return users.stream().map(u -> { + UserRelationVO vo = new UserRelationVO(); + vo.setUserId(u.getId()); + vo.setShopId(scopedShopId); + vo.setParentUserId(null); + vo.setParentUserName(u.getNickname()); + vo.setParentRoleType(u.getType()); + vo.setParentRoleTypeName(typeName(u.getType())); + vo.setSourceType("MANUAL"); + vo.setSourceTypeName("手动维护"); + return vo; + }).collect(Collectors.toList()); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean updateUserRelation(UserDO currentUser, Long userId, UserRelationUpdateDTO dto) { + UserDO user = userMapper.selectById(userId); + if (user == null || Integer.valueOf(1).equals(user.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("用户不存在"); + } + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权修改所属关系"); + UserRelationDO relation = userRelationMapper.selectOne(new LambdaQueryWrapper() + .eq(UserRelationDO::getUserId, userId) + .eq(UserRelationDO::getIsDelete, 0) + .last("limit 1")); + if (relation == null) { + relation = new UserRelationDO(); + relation.setUserId(userId); + relation.setIsDelete(0); + userRelationMapper.insert(relation); + } + relation.setShopId(dto.getShopId() == null ? user.getShopId() : dto.getShopId()); + relation.setParentUserId(dto.getParentUserId()); + relation.setParentRoleType(dto.getParentRoleType()); + relation.setSourceType(dto.getSourceType()); + relation.setCreatorId(currentUser.getId()); + relation.setUpdateTime(LocalDateTime.now()); + userRelationMapper.updateById(relation); + return true; + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listInviteCodes(UserDO currentUser, Long shopId) { + Long scopedShopId = adminScopeHelper.resolveShopScope(currentUser, shopId); + return userInviteCodeMapper.selectList(new LambdaQueryWrapper() + .eq(UserInviteCodeDO::getIsDelete, 0) + .eq(scopedShopId != null, UserInviteCodeDO::getShopId, scopedShopId) + .orderByDesc(UserInviteCodeDO::getCreateTime)) + .stream().map(this::toInviteVO).collect(Collectors.toList()); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long createInviteCode(UserDO currentUser, InviteCodeDTO dto) { + Long shopId = adminScopeHelper.resolveShopScope(currentUser, dto.getShopId()); + if (shopId == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请选择店铺"); + } + UserInviteCodeDO code = new UserInviteCodeDO(); + code.setInviteCode(dto.getInviteCode().trim()); + code.setOwnerUserId(dto.getOwnerUserId()); + code.setShopId(shopId); + code.setStatus(dto.getStatus() == null || dto.getStatus() != 0 ? 1 : 0); + code.setUseCount(dto.getUseCount() == null ? 0 : dto.getUseCount()); + code.setExpireTime(dto.getExpireTime()); + code.setIsDelete(0); + userInviteCodeMapper.insert(code); + return code.getId(); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param status parameter `status` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean updateInviteCodeStatus(UserDO currentUser, Long id, Integer status) { + UserInviteCodeDO code = userInviteCodeMapper.selectById(id); + if (code == null || Integer.valueOf(1).equals(code.getIsDelete())) { + return false; + } + adminScopeHelper.ensureShopAccessible(currentUser, code.getShopId(), "无权修改其他店铺邀请码"); + code.setStatus(status == null || status == 0 ? 0 : 1); + code.setUpdateTime(LocalDateTime.now()); + userInviteCodeMapper.updateById(code); + return true; + } + + @Override + /** + * Run business method `resolveInviteCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param code parameter `code` supplied by the caller + * @return InviteCodeVO result consumed by the caller or returned to the frontend + */ + public InviteCodeVO resolveInviteCode(String code) { + if (!StringUtils.hasText(code)) { + return null; + } + UserInviteCodeDO entity = userInviteCodeMapper.selectOne(new LambdaQueryWrapper() + .eq(UserInviteCodeDO::getInviteCode, code.trim()) + .eq(UserInviteCodeDO::getIsDelete, 0) + .last("limit 1")); + return entity == null ? null : toInviteVO(entity); + } + + /** + * Run business method `syncPermissions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param roleId parameter `roleId` supplied by the caller + * @param permissionIds parameter `permissionIds` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void syncPermissions(Long roleId, List permissionIds) { + // 保存角色权限时采用“先清空再重建”的方式: + // 表单里传来的 permissionIds 就是最终状态,避免残留上一次勾选的权限。 + shopRolePermissionMapper.delete(new LambdaQueryWrapper().eq(ShopRolePermissionDO::getRoleId, roleId)); + if (permissionIds == null) { + return; + } + for (Long permissionId : permissionIds.stream().filter(Objects::nonNull).distinct().toList()) { + ShopRolePermissionDO item = new ShopRolePermissionDO(); + item.setRoleId(roleId); + item.setPermissionId(permissionId); + item.setIsDelete(0); + shopRolePermissionMapper.insert(item); + } + } + + /** + * Run business method `syncUsers`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param roleId parameter `roleId` supplied by the caller + * @param userIds parameter `userIds` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void syncUsers(Long roleId, List userIds, Long shopId) { + userShopRoleMapper.delete(new LambdaQueryWrapper().eq(UserShopRoleDO::getRoleId, roleId)); + if (userIds == null) { + return; + } + for (Long userId : userIds.stream().filter(Objects::nonNull).distinct().toList()) { + UserDO user = userMapper.selectById(userId); + if (user == null || Integer.valueOf(1).equals(user.getIsDelete())) { + continue; + } + long bindingCount = userShopBindingMapper.selectCount(new LambdaQueryWrapper() + .eq(com.xiaowang.yuminailcore.entity.UserShopBindingDO::getUserId, userId) + .eq(com.xiaowang.yuminailcore.entity.UserShopBindingDO::getShopId, shopId) + .eq(com.xiaowang.yuminailcore.entity.UserShopBindingDO::getIsDelete, 0)); + if (!Objects.equals(shopId, user.getShopId()) && bindingCount <= 0) { + continue; + } + UserShopRoleDO item = new UserShopRoleDO(); + item.setRoleId(roleId); + item.setUserId(userId); + item.setShopId(shopId); + item.setStatus(1); + item.setIsDelete(0); + userShopRoleMapper.insert(item); + } + } + + /** + * Run business method `toVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param role parameter `role` supplied by the caller + * @return private ShopRoleVO result consumed by the caller or returned to the frontend + */ + private ShopRoleVO toVO(ShopRoleDO role) { + ShopRoleVO vo = new ShopRoleVO(); + vo.setId(role.getId()); + vo.setShopId(role.getShopId()); + ShopDO shop = shopMapper.selectById(role.getShopId()); + vo.setShopName(shop == null ? null : shop.getShopName()); + vo.setRoleName(role.getRoleName()); + vo.setCreatorId(role.getCreatorId()); + UserDO creator = role.getCreatorId() == null ? null : userMapper.selectById(role.getCreatorId()); + vo.setCreatorName(creator == null ? null : creator.getNickname()); + vo.setStatus(role.getStatus()); + vo.setRemark(role.getRemark()); + vo.setSortOrder(role.getSortOrder()); + vo.setCreateTime(role.getCreateTime()); + vo.setUpdateTime(role.getUpdateTime()); + List permissions = shopRolePermissionMapper.selectList(new LambdaQueryWrapper() + .eq(ShopRolePermissionDO::getRoleId, role.getId()) + .eq(ShopRolePermissionDO::getIsDelete, 0)); + vo.setPermissionIds(permissions.stream().map(ShopRolePermissionDO::getPermissionId).collect(Collectors.toList())); + Set permissionIds = vo.getPermissionIds().stream().collect(Collectors.toSet()); + if (!permissionIds.isEmpty()) { + vo.setPermissionCodes(permissionMapper.selectBatchIds(permissionIds).stream().map(PermissionDO::getPermissionCode).collect(Collectors.toList())); + } else { + vo.setPermissionCodes(List.of()); + } + vo.setUserIds(userShopRoleMapper.selectList(new LambdaQueryWrapper() + .eq(UserShopRoleDO::getRoleId, role.getId()) + .eq(UserShopRoleDO::getIsDelete, 0)) + .stream().map(UserShopRoleDO::getUserId).collect(Collectors.toList())); + return vo; + } + + /** + * Run business method `toInviteVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param code parameter `code` supplied by the caller + * @return private InviteCodeVO result consumed by the caller or returned to the frontend + */ + private InviteCodeVO toInviteVO(UserInviteCodeDO code) { + InviteCodeVO vo = new InviteCodeVO(); + vo.setId(code.getId()); + vo.setInviteCode(code.getInviteCode()); + vo.setOwnerUserId(code.getOwnerUserId()); + vo.setOwnerUserName(code.getOwnerUserId() == null ? null : Optional.ofNullable(userMapper.selectById(code.getOwnerUserId())).map(UserDO::getNickname).orElse(null)); + vo.setShopId(code.getShopId()); + vo.setShopName(code.getShopId() == null ? null : Optional.ofNullable(shopMapper.selectById(code.getShopId())).map(ShopDO::getShopName).orElse(null)); + vo.setStatus(code.getStatus()); + vo.setUseCount(code.getUseCount()); + vo.setExpireTime(code.getExpireTime()); + vo.setCreateTime(code.getCreateTime()); + return vo; + } + + /** + * Run business method `requireRole`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return private ShopRoleDO result consumed by the caller or returned to the frontend + */ + private ShopRoleDO requireRole(Long id) { + ShopRoleDO role = shopRoleMapper.selectById(id); + if (role == null || Integer.valueOf(1).equals(role.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("角色不存在"); + } + return role; + } + + /** + * Run business method `typeName`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param type parameter `type` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String typeName(Integer type) { + return switch (type == null ? -1 : type) { + case 0 -> "普通用户"; + case 2 -> "店长"; + case 3 -> "美甲师"; + case 4 -> "管理员"; + default -> "未知"; + }; + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/ShopServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/ShopServiceImpl.java index 50362e93..74e36707 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/ShopServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/ShopServiceImpl.java @@ -20,6 +20,7 @@ import com.xiaowang.yuminailcore.mapper.ShopMapper; import com.xiaowang.yuminailcore.mapper.TagMapper; import com.xiaowang.yuminailcore.mapper.UserCouponMapper; import com.xiaowang.yuminailcore.service.CouponService; +import com.xiaowang.yuminailcore.service.MapService; import com.xiaowang.yuminailcore.service.ShopService; import com.xiaowang.yuminailcore.support.UserShopBindingSupport; import com.xiaowang.yuminailcore.support.cache.MultiLevelCacheService; @@ -31,6 +32,7 @@ import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; import java.time.Duration; +import java.time.LocalDateTime; import java.util.List; import java.util.stream.Collectors; @@ -46,28 +48,68 @@ import java.util.stream.Collectors; public class ShopServiceImpl extends ServiceImpl implements ShopService { private static final String SHOP_DETAIL_CACHE_PREFIX = "cache:shop:detail:"; private static final String SHOP_LIST_CACHE_PREFIX = "cache:shop:list:"; - + /** + * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final ShopMapper shopMapper; + /** + * Variable `couponService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final CouponService couponService; + /** + * Variable `couponMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final CouponMapper couponMapper; + /** + * Variable `productMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final ProductMapper productMapper; + /** + * Variable `tagMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final TagMapper tagMapper; + /** + * Variable `commentMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final CommentMapper commentMapper; + /** + * Variable `userCouponMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final UserCouponMapper userCouponMapper; + /** + * Variable `userShopBindingSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final UserShopBindingSupport userShopBindingSupport; + /** + * Variable `multiLevelCacheService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final MultiLevelCacheService multiLevelCacheService; + /** + * Variable `appCacheProperties`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final AppCacheProperties appCacheProperties; + private final MapService mapService; @Override @Transactional(rollbackFor = Exception.class) + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopDTO parameter `shopDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ public Long createShop(ShopDTO shopDTO) { ShopDO shopDO = new ShopDO(); shopDO.setShopName(shopDTO.getShopName()); shopDO.setDescription(shopDTO.getDescription()); shopDO.setAddress(shopDTO.getAddress()); + shopDO.setMapProvider(mapService.normalizeProvider(shopDTO.getMapProvider())); + shopDO.setLongitude(shopDTO.getLongitude()); + shopDO.setLatitude(shopDTO.getLatitude()); shopDO.setBusinessHours(shopDTO.getBusinessHours()); shopDO.setCoverImageFileId(shopDTO.getCoverImageFileId()); shopDO.setImageFileIds(shopDTO.getImageFileIds()); + shopDO.setAuthorizationExpireTime(shopDTO.getAuthorizationExpireTime()); shopDO.setStatus(normalizeStatus(shopDTO.getStatus())); shopDO.setIsDelete(0); shopMapper.insert(shopDO); @@ -77,6 +119,13 @@ public class ShopServiceImpl extends ServiceImpl implements } @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param shopDTO parameter `shopDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ public boolean updateShop(Long id, ShopDTO shopDTO) { ShopDO shopDO = shopMapper.selectById(id); if (shopDO == null) { @@ -85,14 +134,24 @@ public class ShopServiceImpl extends ServiceImpl implements shopDO.setShopName(shopDTO.getShopName()); shopDO.setDescription(shopDTO.getDescription()); shopDO.setAddress(shopDTO.getAddress()); + shopDO.setMapProvider(mapService.normalizeProvider(shopDTO.getMapProvider())); + shopDO.setLongitude(shopDTO.getLongitude()); + shopDO.setLatitude(shopDTO.getLatitude()); shopDO.setBusinessHours(shopDTO.getBusinessHours()); shopDO.setCoverImageFileId(shopDTO.getCoverImageFileId()); shopDO.setImageFileIds(shopDTO.getImageFileIds()); + shopDO.setAuthorizationExpireTime(shopDTO.getAuthorizationExpireTime()); if (shopDTO.getStatus() != null) { shopDO.setStatus(normalizeStatus(shopDTO.getStatus())); } boolean updated = shopMapper.updateById(shopDO) > 0; if (updated) { + /** + * Run business method `evictShopCaches`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ evictShopCaches(id); } return updated; @@ -100,6 +159,12 @@ public class ShopServiceImpl extends ServiceImpl implements @Override @Transactional(rollbackFor = Exception.class) + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ public boolean deleteShop(Long id) { ShopDO shopDO = shopMapper.selectById(id); if (shopDO == null || Integer.valueOf(1).equals(shopDO.getIsDelete())) { @@ -139,12 +204,25 @@ public class ShopServiceImpl extends ServiceImpl implements shopDO.setIsDelete(1); boolean deleted = shopMapper.updateById(shopDO) > 0; if (deleted) { + /** + * Run business method `evictShopCaches`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ evictShopCaches(id); } return deleted; } @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param status parameter `status` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ public boolean updateShopStatus(Long id, Integer status) { ShopDO shopDO = shopMapper.selectById(id); if (shopDO == null || Integer.valueOf(1).equals(shopDO.getIsDelete())) { @@ -153,12 +231,24 @@ public class ShopServiceImpl extends ServiceImpl implements shopDO.setStatus(normalizeStatus(status)); boolean updated = shopMapper.updateById(shopDO) > 0; if (updated) { + /** + * Run business method `evictShopCaches`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ evictShopCaches(id); } return updated; } @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return ShopVO result consumed by the caller or returned to the frontend + */ public ShopVO getShopById(Long id) { AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getShop(); return multiLevelCacheService.getOrLoad( @@ -172,12 +262,23 @@ public class ShopServiceImpl extends ServiceImpl implements if (shopDO == null || Integer.valueOf(1).equals(shopDO.getIsDelete())) { return null; } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopDO parameter `shopDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ return convertToVO(shopDO); } ); } @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ public List listAllShops() { AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getShop(); return multiLevelCacheService.getOrLoad( @@ -192,12 +293,18 @@ public class ShopServiceImpl extends ServiceImpl implements .eq(ShopDO::getStatus, 1) .orderByDesc(ShopDO::getCreateTime) ).stream() + .filter(this::isAuthorizationValid) .map(this::convertToVO) .collect(Collectors.toList()) ); } @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ public List listAllShopsForAdmin() { List shopDOs = shopMapper.selectList( Wrappers.lambdaQuery(ShopDO.class) @@ -210,6 +317,12 @@ public class ShopServiceImpl extends ServiceImpl implements } @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopName parameter `shopName` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ public List listShopsByShopName(String shopName) { AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getShop(); String normalizedShopName = StringUtils.hasText(shopName) ? shopName.trim() : ""; @@ -225,7 +338,7 @@ public class ShopServiceImpl extends ServiceImpl implements .eq(ShopDO::getIsDelete, 0) .eq(ShopDO::getStatus, 1) .like(ShopDO::getShopName, normalizedShopName) - ); + ).stream().filter(this::isAuthorizationValid).collect(Collectors.toList()); return shopDOs.stream() .map(this::convertToVO) .collect(Collectors.toList()); @@ -234,6 +347,15 @@ public class ShopServiceImpl extends ServiceImpl implements } @Override + /** + * Query paged records. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @param size parameter `size` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return PageResultVO result consumed by the caller or returned to the frontend + */ public PageResultVO pageShops(Integer page, Integer size, String keyword, Long shopId) { Page pageParam = new Page<>(page, size); @@ -272,21 +394,95 @@ public class ShopServiceImpl extends ServiceImpl implements shopVO.setShopName(shopDO.getShopName()); shopVO.setDescription(shopDO.getDescription()); shopVO.setAddress(shopDO.getAddress()); + shopVO.setMapProvider(mapService.normalizeProvider(shopDO.getMapProvider())); + shopVO.setLongitude(shopDO.getLongitude()); + shopVO.setLatitude(shopDO.getLatitude()); + shopVO.setNavigationUrls(mapService.buildNavigationUrls(shopDO.getShopName(), shopDO.getAddress(), shopDO.getLongitude(), shopDO.getLatitude())); shopVO.setBusinessHours(shopDO.getBusinessHours()); shopVO.setCoverImageFileId(shopDO.getCoverImageFileId()); shopVO.setCoverImageUrls(new java.util.ArrayList<>()); shopVO.setImageFileIds(shopDO.getImageFileIds()); shopVO.setImageUrls(new java.util.ArrayList<>()); shopVO.setStatus(normalizeStatus(shopDO.getStatus())); + shopVO.setAuthorizationExpireTime(shopDO.getAuthorizationExpireTime()); + boolean expired = isAuthorizationExpired(shopDO); + shopVO.setAuthorizationExpired(expired); + shopVO.setAuthorizationStatusText(expired ? "已到期" : "有效"); shopVO.setCreateTime(shopDO.getCreateTime()); shopVO.setUpdateTime(shopDO.getUpdateTime()); return shopVO; } + @Override + /** + * Run business method `isAuthorizationExpired`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean isAuthorizationExpired(Long shopId) { + if (shopId == null || shopId <= 0) { + return false; + } + return isAuthorizationExpired(shopMapper.selectById(shopId)); + } + + @Override + /** + * Run business method `isFrontendAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ + public boolean isFrontendAvailable(Long shopId) { + if (shopId == null || shopId <= 0) { + return false; + } + ShopDO shopDO = shopMapper.selectById(shopId); + return shopDO != null + && !Integer.valueOf(1).equals(shopDO.getIsDelete()) + && Integer.valueOf(1).equals(normalizeStatus(shopDO.getStatus())) + && isAuthorizationValid(shopDO); + } + + /** + * Run business method `isAuthorizationValid`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopDO parameter `shopDO` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean isAuthorizationValid(ShopDO shopDO) { + return !isAuthorizationExpired(shopDO); + } + + /** + * Run business method `isAuthorizationExpired`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopDO parameter `shopDO` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean isAuthorizationExpired(ShopDO shopDO) { + return shopDO != null + && shopDO.getAuthorizationExpireTime() != null + && shopDO.getAuthorizationExpireTime().isBefore(LocalDateTime.now()); + } + + /** + * Run business method `normalizeStatus`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param status parameter `status` supplied by the caller + * @return private Integer result consumed by the caller or returned to the frontend + */ private Integer normalizeStatus(Integer status) { return Integer.valueOf(0).equals(status) ? 0 : 1; } + /** + * Run business method `evictShopCaches`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void evictShopCaches(Long shopId) { if (shopId != null) { multiLevelCacheService.evict(SHOP_DETAIL_CACHE_PREFIX + shopId); diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/SystemMessageServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/SystemMessageServiceImpl.java new file mode 100644 index 00000000..7c2d781e --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/SystemMessageServiceImpl.java @@ -0,0 +1,850 @@ +package com.xiaowang.yuminailcore.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.xiaowang.yuminailcore.dto.SystemMessageCreateDTO; +import com.xiaowang.yuminailcore.entity.ShopDO; +import com.xiaowang.yuminailcore.entity.SystemMessageDO; +import com.xiaowang.yuminailcore.entity.SystemMessageUserStateDO; +import com.xiaowang.yuminailcore.entity.UserDO; +import com.xiaowang.yuminailcore.entity.UserShopBindingDO; +import com.xiaowang.yuminailcore.mapper.ShopMapper; +import com.xiaowang.yuminailcore.mapper.SystemMessageMapper; +import com.xiaowang.yuminailcore.mapper.SystemMessageUserStateMapper; +import com.xiaowang.yuminailcore.mapper.UserMapper; +import com.xiaowang.yuminailcore.mapper.UserShopBindingMapper; +import com.xiaowang.yuminailcore.service.ObjectStorageFileService; +import com.xiaowang.yuminailcore.service.SystemMessageService; +import com.xiaowang.yuminailcore.support.AdminScopeHelper; +import com.xiaowang.yuminailcore.support.ObjectStorageUrlSupport; +import com.xiaowang.yuminailcore.vo.MessageTargetOptionsVO; +import com.xiaowang.yuminailcore.vo.ObjectStorageFileVO; +import com.xiaowang.yuminailcore.vo.SystemMessageVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.CollectionUtils; +import org.springframework.util.StringUtils; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.function.Function; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +/** + * SystemMessageServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class SystemMessageServiceImpl extends ServiceImpl implements SystemMessageService { + + public static final String TARGET_PLATFORM_ALL = "PLATFORM_ALL"; + public static final String TARGET_CURRENT_SHOP_ALL = "CURRENT_SHOP_ALL"; + public static final String TARGET_SHOP_ALL = "SHOP_ALL"; + public static final String TARGET_SELECTED_SHOPS = "SELECTED_SHOPS"; + public static final String TARGET_SELECTED_USERS = "SELECTED_USERS"; + /** + * Variable `systemMessageMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final SystemMessageMapper systemMessageMapper; + /** + * Variable `stateMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final SystemMessageUserStateMapper stateMapper; + /** + * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserMapper userMapper; + /** + * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopMapper shopMapper; + /** + * Variable `userShopBindingMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserShopBindingMapper userShopBindingMapper; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + /** + * Variable `objectStorageFileService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ObjectStorageFileService objectStorageFileService; + /** + * Variable `objectStorageUrlSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ObjectStorageUrlSupport objectStorageUrlSupport; + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Run business method `publishMessage`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long publishMessage(UserDO currentUser, SystemMessageCreateDTO dto) { + String targetType = normalizeTargetType(dto.getTargetType()); + List targetIds = resolveAndValidateTargets(currentUser, targetType, dto); + String title = dto.getTitle() == null ? "" : dto.getTitle().trim(); + String content = dto.getContent() == null ? "" : dto.getContent().trim(); + if (!StringUtils.hasText(title)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("消息标题不能为空"); + } + if (!StringUtils.hasText(content) && dto.getImageFileId() == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请填写消息内容或上传消息图片"); + } + if (dto.getImageFileId() != null) { + ObjectStorageFileVO imageFile = objectStorageFileService.getObjectStorageFileById(dto.getImageFileId()); + if (imageFile == null || !Integer.valueOf(1).equals(imageFile.getStatus())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("消息图片不存在或不可用"); + } + } + + SystemMessageDO message = new SystemMessageDO(); + message.setTitle(title); + message.setContent(content); + message.setImageFileId(dto.getImageFileId()); + message.setPublisherId(currentUser.getId()); + message.setPublisherName(resolvePublisherName(currentUser)); + message.setPublisherType(currentUser.getType()); + message.setTargetType(targetType); + message.setTargetIds(joinIds(targetIds)); + message.setPopupEnabled(Integer.valueOf(0).equals(dto.getPopupEnabled()) ? 0 : 1); + message.setStatus(1); + message.setPublishTime(LocalDateTime.now()); + message.setIsDelete(0); + systemMessageMapper.insert(message); + return message.getId(); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listAdminMessages(UserDO currentUser) { + List messages = systemMessageMapper.selectList(new LambdaQueryWrapper() + .eq(SystemMessageDO::getIsDelete, 0) + .orderByDesc(SystemMessageDO::getPublishTime)); + return messages.stream() + .filter(message -> canAdminSeeMessage(currentUser, message)) + .map(message -> toVO(message, null)) + .collect(Collectors.toList()); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param messageId parameter `messageId` supplied by the caller + * @return SystemMessageVO result consumed by the caller or returned to the frontend + */ + public SystemMessageVO getAdminMessage(UserDO currentUser, Long messageId) { + SystemMessageDO message = requireMessage(messageId); + if (!canAdminSeeMessage(currentUser, message)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("无权查看该消息"); + } + /** + * Run business method `toVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param message parameter `message` supplied by the caller + * @param null parameter `null` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return toVO(message, null); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Run business method `revokeMessage`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param messageId parameter `messageId` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean revokeMessage(UserDO currentUser, Long messageId) { + SystemMessageDO message = requireMessage(messageId); + if (!canAdminSeeMessage(currentUser, message)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("无权撤回该消息"); + } + message.setStatus(0); + systemMessageMapper.updateById(message); + return true; + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return MessageTargetOptionsVO result consumed by the caller or returned to the frontend + */ + public MessageTargetOptionsVO listTargetOptions(UserDO currentUser) { + MessageTargetOptionsVO options = new MessageTargetOptionsVO(); + List shops = adminScopeHelper.isPlatformAdmin(currentUser) + ? shopMapper.selectList(new LambdaQueryWrapper().eq(ShopDO::getIsDelete, 0).eq(ShopDO::getStatus, 1)) + : shopMapper.selectList(new LambdaQueryWrapper().eq(ShopDO::getId, adminScopeHelper.getManagedShopId(currentUser)).eq(ShopDO::getIsDelete, 0)); + Map shopNameMap = shops.stream().collect(Collectors.toMap(ShopDO::getId, ShopDO::getShopName, (a, b) -> a)); + + List shopIds = shops.stream().map(ShopDO::getId).collect(Collectors.toList()); + List users = shopIds.isEmpty() + ? List.of() + : userMapper.selectList(new LambdaQueryWrapper() + .eq(UserDO::getIsDelete, 0) + .eq(UserDO::getStatus, 1) + .in(UserDO::getShopId, shopIds) + .orderByAsc(UserDO::getType) + .orderByAsc(UserDO::getNickname)); + + options.setShops(shops.stream().map(shop -> { + MessageTargetOptionsVO.ShopOptionVO vo = new MessageTargetOptionsVO.ShopOptionVO(); + vo.setId(shop.getId()); + vo.setShopName(shop.getShopName()); + return vo; + }).collect(Collectors.toList())); + options.setUsers(users.stream().map(user -> { + MessageTargetOptionsVO.UserOptionVO vo = new MessageTargetOptionsVO.UserOptionVO(); + vo.setId(user.getId()); + vo.setNickname(user.getNickname()); + vo.setAccount(user.getAccount()); + vo.setShopId(user.getShopId()); + vo.setShopName(shopNameMap.get(user.getShopId())); + vo.setType(user.getType()); + return vo; + }).collect(Collectors.toList())); + return options; + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listMyMessages(Long userId) { + UserDO user = requireUser(userId); + Map stateMap = loadStateMap(userId); + return listVisibleMessages(user).stream() + .map(message -> toVO(message, stateMap.get(message.getId()))) + .collect(Collectors.toList()); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listMyPopupMessages(Long userId) { + UserDO user = requireUser(userId); + Map stateMap = loadStateMap(userId); + return listVisibleMessages(user).stream() + .filter(message -> Integer.valueOf(1).equals(message.getPopupEnabled())) + .filter(message -> { + SystemMessageUserStateDO state = stateMap.get(message.getId()); + return state == null || !Integer.valueOf(1).equals(state.getPopupShown()); + }) + .map(message -> toVO(message, stateMap.get(message.getId()))) + .collect(Collectors.toList()); + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param messageId parameter `messageId` supplied by the caller + * @return SystemMessageVO result consumed by the caller or returned to the frontend + */ + public SystemMessageVO getMyMessage(Long userId, Long messageId) { + UserDO user = requireUser(userId); + SystemMessageDO message = requireMessage(messageId); + if (!isMessageVisibleToUser(message, user)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("消息不存在或无权查看"); + } + SystemMessageUserStateDO state = findState(userId, messageId); + /** + * Run business method `toVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param message parameter `message` supplied by the caller + * @param state parameter `state` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return toVO(message, state); + } + + @Override + /** + * Run business method `countMyUnreadMessages`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long countMyUnreadMessages(Long userId) { + UserDO user = requireUser(userId); + Map stateMap = loadStateMap(userId); + return listVisibleMessages(user).stream() + .filter(message -> { + SystemMessageUserStateDO state = stateMap.get(message.getId()); + return state == null || !Integer.valueOf(1).equals(state.getReadStatus()); + }) + .count(); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Mark user state such as read or popup shown. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param messageId parameter `messageId` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean markPopupShown(Long userId, Long messageId) { + UserDO user = requireUser(userId); + SystemMessageDO message = requireMessage(messageId); + if (!isMessageVisibleToUser(message, user)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("消息不存在或无权查看"); + } + SystemMessageUserStateDO state = getOrCreateState(userId, messageId); + if (!Integer.valueOf(1).equals(state.getPopupShown())) { + state.setPopupShown(1); + state.setPopupTime(LocalDateTime.now()); + stateMapper.updateById(state); + } + return true; + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Mark user state such as read or popup shown. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param messageId parameter `messageId` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean markRead(Long userId, Long messageId) { + UserDO user = requireUser(userId); + SystemMessageDO message = requireMessage(messageId); + if (!isMessageVisibleToUser(message, user)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("消息不存在或无权查看"); + } + SystemMessageUserStateDO state = getOrCreateState(userId, messageId); + if (!Integer.valueOf(1).equals(state.getReadStatus())) { + state.setReadStatus(1); + state.setReadTime(LocalDateTime.now()); + stateMapper.updateById(state); + } + return true; + } + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param user parameter `user` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List listVisibleMessages(UserDO user) { + return systemMessageMapper.selectList(new LambdaQueryWrapper() + .eq(SystemMessageDO::getIsDelete, 0) + .eq(SystemMessageDO::getStatus, 1) + .orderByDesc(SystemMessageDO::getPublishTime)) + .stream() + .filter(message -> isMessageVisibleToUser(message, user)) + .collect(Collectors.toList()); + } + + /** + * Run business method `isMessageVisibleToUser`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param message parameter `message` supplied by the caller + * @param user parameter `user` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean isMessageVisibleToUser(SystemMessageDO message, UserDO user) { + String targetType = message.getTargetType(); + Set targetIds = parseIds(message.getTargetIds()); + if (TARGET_PLATFORM_ALL.equals(targetType)) { + return true; + } + if (TARGET_SELECTED_USERS.equals(targetType)) { + return targetIds.contains(user.getId()); + } + Set userShopIds = getUserShopIds(user); + if (TARGET_CURRENT_SHOP_ALL.equals(targetType) || TARGET_SHOP_ALL.equals(targetType) || TARGET_SELECTED_SHOPS.equals(targetType)) { + return userShopIds.stream().anyMatch(targetIds::contains); + } + return false; + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param user parameter `user` supplied by the caller + * @return private Set result consumed by the caller or returned to the frontend + */ + private Set getUserShopIds(UserDO user) { + LinkedHashSet ids = new LinkedHashSet<>(); + if (user.getShopId() != null && user.getShopId() > 0) { + ids.add(user.getShopId()); + } + List bindings = userShopBindingMapper.selectList(new LambdaQueryWrapper() + .eq(UserShopBindingDO::getUserId, user.getId()) + .eq(UserShopBindingDO::getIsDelete, 0) + .eq(UserShopBindingDO::getStatus, 1)); + bindings.forEach(binding -> { + if (binding.getShopId() != null && binding.getShopId() > 0) { + ids.add(binding.getShopId()); + } + }); + return ids; + } + + /** + * Run business method `resolveAndValidateTargets`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param targetType parameter `targetType` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List resolveAndValidateTargets(UserDO currentUser, String targetType, SystemMessageCreateDTO dto) { + if (adminScopeHelper.isPlatformAdmin(currentUser)) { + /** + * Run business method `resolveAdminTargets`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetType parameter `targetType` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return resolveAdminTargets(targetType, dto); + } + if (!Integer.valueOf(2).equals(currentUser.getType())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("只有管理员或店长可以发布消息"); + } + Long managedShopId = adminScopeHelper.getManagedShopId(currentUser); + if (TARGET_CURRENT_SHOP_ALL.equals(targetType) || TARGET_SHOP_ALL.equals(targetType)) { + return List.of(managedShopId); + } + if (TARGET_SELECTED_USERS.equals(targetType)) { + List userIds = normalizeIds(dto.getUserIds()); + if (userIds.isEmpty()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请选择接收用户"); + } + userIds.forEach(userId -> adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权选择其他店铺用户")); + return userIds; + } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("店长只能发布本店全员或本店部分用户消息"); + } + + /** + * Run business method `resolveAdminTargets`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetType parameter `targetType` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List resolveAdminTargets(String targetType, SystemMessageCreateDTO dto) { + if (TARGET_PLATFORM_ALL.equals(targetType)) { + return List.of(); + } + if (TARGET_SHOP_ALL.equals(targetType) || TARGET_SELECTED_SHOPS.equals(targetType)) { + List shopIds = normalizeIds(dto.getShopIds()); + if (shopIds.isEmpty()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请选择接收店铺"); + } + /** + * Run business method `assertShopsExist`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopIds parameter `shopIds` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertShopsExist(shopIds); + return shopIds; + } + if (TARGET_SELECTED_USERS.equals(targetType)) { + List userIds = normalizeIds(dto.getUserIds()); + if (userIds.isEmpty()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请选择接收用户"); + } + /** + * Run business method `assertUsersExist`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userIds parameter `userIds` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + assertUsersExist(userIds); + return userIds; + } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("管理员消息范围不正确"); + } + + /** + * Run business method `assertShopsExist`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopIds parameter `shopIds` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void assertShopsExist(List shopIds) { + Long count = shopMapper.selectCount(new LambdaQueryWrapper().in(ShopDO::getId, shopIds).eq(ShopDO::getIsDelete, 0)); + if (count == null || count < shopIds.size()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("存在无效店铺"); + } + } + + /** + * Run business method `assertUsersExist`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userIds parameter `userIds` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void assertUsersExist(List userIds) { + Long count = userMapper.selectCount(new LambdaQueryWrapper().in(UserDO::getId, userIds).eq(UserDO::getIsDelete, 0)); + if (count == null || count < userIds.size()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("存在无效用户"); + } + } + + /** + * Run business method `canAdminSeeMessage`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param message parameter `message` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ + private boolean canAdminSeeMessage(UserDO currentUser, SystemMessageDO message) { + if (adminScopeHelper.isPlatformAdmin(currentUser)) { + return true; + } + Long managedShopId = adminScopeHelper.getManagedShopId(currentUser); + if (TARGET_CURRENT_SHOP_ALL.equals(message.getTargetType()) || TARGET_SHOP_ALL.equals(message.getTargetType()) || TARGET_SELECTED_SHOPS.equals(message.getTargetType())) { + return parseIds(message.getTargetIds()).contains(managedShopId); + } + return Objects.equals(message.getPublisherId(), currentUser.getId()); + } + + /** + * Run business method `toVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param message parameter `message` supplied by the caller + * @param state parameter `state` supplied by the caller + * @return private SystemMessageVO result consumed by the caller or returned to the frontend + */ + private SystemMessageVO toVO(SystemMessageDO message, SystemMessageUserStateDO state) { + SystemMessageVO vo = new SystemMessageVO(); + vo.setId(message.getId()); + vo.setTitle(message.getTitle()); + vo.setContent(message.getContent()); + vo.setImageFileId(message.getImageFileId()); + vo.setImageUrl(resolveImageUrl(message.getImageFileId())); + vo.setPublisherId(message.getPublisherId()); + vo.setPublisherName(message.getPublisherName()); + vo.setPublisherType(message.getPublisherType()); + vo.setTargetType(message.getTargetType()); + vo.setTargetTypeName(targetTypeName(message.getTargetType())); + vo.setTargetIds(new ArrayList<>(parseIds(message.getTargetIds()))); + vo.setPopupEnabled(message.getPopupEnabled()); + vo.setStatus(message.getStatus()); + vo.setPublishTime(message.getPublishTime()); + vo.setCreateTime(message.getCreateTime()); + vo.setPopupShown(state == null ? 0 : state.getPopupShown()); + vo.setReadStatus(state == null ? 0 : state.getReadStatus()); + vo.setPopupTime(state == null ? null : state.getPopupTime()); + vo.setReadTime(state == null ? null : state.getReadTime()); + return vo; + } + + /** + * Run business method `resolveImageUrl`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param imageFileId parameter `imageFileId` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String resolveImageUrl(Long imageFileId) { + if (imageFileId == null || imageFileId <= 0) { + return null; + } + ObjectStorageFileVO imageFile = objectStorageFileService.getObjectStorageFileById(imageFileId); + if (imageFile == null || !StringUtils.hasText(imageFile.getFileUrl())) { + return null; + } + return objectStorageUrlSupport.toAccessibleUrl(imageFile.getFileUrl()); + } + + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param messageId parameter `messageId` supplied by the caller + * @return private SystemMessageUserStateDO result consumed by the caller or returned to the frontend + */ + private SystemMessageUserStateDO getOrCreateState(Long userId, Long messageId) { + SystemMessageUserStateDO state = findState(userId, messageId); + if (state != null) { + return state; + } + state = new SystemMessageUserStateDO(); + state.setMessageId(messageId); + state.setUserId(userId); + state.setPopupShown(0); + state.setReadStatus(0); + state.setIsDelete(0); + stateMapper.insert(state); + return state; + } + + /** + * Run business method `findState`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param messageId parameter `messageId` supplied by the caller + * @return private SystemMessageUserStateDO result consumed by the caller or returned to the frontend + */ + private SystemMessageUserStateDO findState(Long userId, Long messageId) { + return stateMapper.selectOne(new LambdaQueryWrapper() + .eq(SystemMessageUserStateDO::getUserId, userId) + .eq(SystemMessageUserStateDO::getMessageId, messageId) + .eq(SystemMessageUserStateDO::getIsDelete, 0) + .last("LIMIT 1")); + } + + /** + * Run business method `loadStateMap`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return private Map result consumed by the caller or returned to the frontend + */ + private Map loadStateMap(Long userId) { + return stateMapper.selectList(new LambdaQueryWrapper() + .eq(SystemMessageUserStateDO::getUserId, userId) + .eq(SystemMessageUserStateDO::getIsDelete, 0)) + .stream() + .collect(Collectors.toMap(SystemMessageUserStateDO::getMessageId, Function.identity(), (a, b) -> a)); + } + + /** + * Run business method `requireMessage`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param messageId parameter `messageId` supplied by the caller + * @return private SystemMessageDO result consumed by the caller or returned to the frontend + */ + private SystemMessageDO requireMessage(Long messageId) { + SystemMessageDO message = systemMessageMapper.selectById(messageId); + if (message == null || Integer.valueOf(1).equals(message.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("消息不存在"); + } + return message; + } + + /** + * Run business method `requireUser`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return private UserDO result consumed by the caller or returned to the frontend + */ + private UserDO requireUser(Long userId) { + UserDO user = userMapper.selectById(userId); + if (user == null || Integer.valueOf(1).equals(user.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("用户不存在"); + } + return user; + } + + /** + * Run business method `normalizeTargetType`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetType parameter `targetType` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String normalizeTargetType(String targetType) { + if (!StringUtils.hasText(targetType)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("接收范围不能为空"); + } + return targetType.trim().toUpperCase(); + } + + /** + * Run business method `normalizeIds`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ids parameter `ids` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List normalizeIds(List ids) { + if (CollectionUtils.isEmpty(ids)) { + return List.of(); + } + return ids.stream() + .filter(Objects::nonNull) + .filter(id -> id > 0) + .distinct() + .collect(Collectors.toList()); + } + + /** + * Run business method `parseIds`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ids parameter `ids` supplied by the caller + * @return private Set result consumed by the caller or returned to the frontend + */ + private Set parseIds(String ids) { + if (!StringUtils.hasText(ids)) { + return Set.of(); + } + return java.util.Arrays.stream(ids.split(",")) + .map(String::trim) + .filter(StringUtils::hasText) + .map(Long::valueOf) + .collect(Collectors.toCollection(LinkedHashSet::new)); + } + + /** + * Run business method `joinIds`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ids parameter `ids` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String joinIds(List ids) { + return ids.stream().map(String::valueOf).collect(Collectors.joining(",")); + } + + /** + * Run business method `targetTypeName`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetType parameter `targetType` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String targetTypeName(String targetType) { + return switch (targetType) { + case TARGET_PLATFORM_ALL -> "全平台"; + case TARGET_CURRENT_SHOP_ALL, TARGET_SHOP_ALL -> "指定店铺全员"; + case TARGET_SELECTED_SHOPS -> "多个店铺"; + case TARGET_SELECTED_USERS -> "指定用户"; + default -> targetType; + }; + } + + /** + * Run business method `resolvePublisherName`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String resolvePublisherName(UserDO currentUser) { + if (StringUtils.hasText(currentUser.getNickname())) { + return currentUser.getNickname(); + } + return currentUser.getAccount(); + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/SystemParameterConfigServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/SystemParameterConfigServiceImpl.java new file mode 100644 index 00000000..8001e504 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/SystemParameterConfigServiceImpl.java @@ -0,0 +1,104 @@ +package com.xiaowang.yuminailcore.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.xiaowang.yuminailcore.dto.SystemParameterConfigDTO; +import com.xiaowang.yuminailcore.entity.SystemParameterConfigDO; +import com.xiaowang.yuminailcore.entity.UserDO; +import com.xiaowang.yuminailcore.mapper.SystemParameterConfigMapper; +import com.xiaowang.yuminailcore.service.SystemParameterConfigService; +import com.xiaowang.yuminailcore.vo.SystemParameterConfigVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.util.List; +import java.util.Locale; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +public class SystemParameterConfigServiceImpl implements SystemParameterConfigService { + + private final SystemParameterConfigMapper configMapper; + + @Override + public List listConfigs(UserDO currentUser, String configGroup) { + ensurePlatformAdmin(currentUser); + LambdaQueryWrapper wrapper = new LambdaQueryWrapper() + .eq(SystemParameterConfigDO::getIsDelete, 0) + .orderByAsc(SystemParameterConfigDO::getConfigGroup) + .orderByAsc(SystemParameterConfigDO::getConfigKey); + if (StringUtils.hasText(configGroup)) { + wrapper.eq(SystemParameterConfigDO::getConfigGroup, normalize(configGroup)); + } + return configMapper.selectList(wrapper).stream().map(this::toVO).collect(Collectors.toList()); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public Boolean saveConfig(UserDO currentUser, SystemParameterConfigDTO dto) { + ensurePlatformAdmin(currentUser); + String group = normalize(dto.getConfigGroup()); + String key = normalize(dto.getConfigKey()); + SystemParameterConfigDO config = configMapper.selectOne(new LambdaQueryWrapper() + .eq(SystemParameterConfigDO::getConfigGroup, group) + .eq(SystemParameterConfigDO::getConfigKey, key) + .eq(SystemParameterConfigDO::getIsDelete, 0) + .last("LIMIT 1")); + if (config == null) { + config = new SystemParameterConfigDO(); + config.setConfigGroup(group); + config.setConfigKey(key); + config.setIsDelete(0); + } + config.setConfigName(dto.getConfigName().trim()); + config.setConfigValue(StringUtils.hasText(dto.getConfigValue()) ? dto.getConfigValue().trim() : ""); + config.setEnabled(Integer.valueOf(0).equals(dto.getEnabled()) ? 0 : 1); + config.setRemark(dto.getRemark()); + if (config.getId() == null) { + configMapper.insert(config); + } else { + configMapper.updateById(config); + } + return true; + } + + @Override + public String getEnabledValue(String configGroup, String configKey) { + if (!StringUtils.hasText(configGroup) || !StringUtils.hasText(configKey)) { + return ""; + } + SystemParameterConfigDO config = configMapper.selectOne(new LambdaQueryWrapper() + .eq(SystemParameterConfigDO::getConfigGroup, normalize(configGroup)) + .eq(SystemParameterConfigDO::getConfigKey, normalize(configKey)) + .eq(SystemParameterConfigDO::getEnabled, 1) + .eq(SystemParameterConfigDO::getIsDelete, 0) + .last("LIMIT 1")); + return config == null ? "" : config.getConfigValue(); + } + + private void ensurePlatformAdmin(UserDO currentUser) { + if (currentUser == null || !Integer.valueOf(4).equals(currentUser.getType())) { + throw new RuntimeException("仅平台管理员可以管理系统参数"); + } + } + + private String normalize(String value) { + return value.trim().toUpperCase(Locale.ROOT); + } + + private SystemParameterConfigVO toVO(SystemParameterConfigDO config) { + SystemParameterConfigVO vo = new SystemParameterConfigVO(); + vo.setId(config.getId()); + vo.setConfigGroup(config.getConfigGroup()); + vo.setConfigKey(config.getConfigKey()); + vo.setConfigName(config.getConfigName()); + vo.setConfigValue(config.getConfigValue()); + vo.setEnabled(config.getEnabled()); + vo.setRemark(config.getRemark()); + vo.setCreateTime(config.getCreateTime()); + vo.setUpdateTime(config.getUpdateTime()); + return vo; + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/TagServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/TagServiceImpl.java index 40b79a27..99bb20d8 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/TagServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/TagServiceImpl.java @@ -33,16 +33,41 @@ import java.util.stream.Collectors; public class TagServiceImpl extends ServiceImpl implements TagService { private static final String TAG_DETAIL_CACHE_PREFIX = "cache:tag:detail:"; private static final String TAG_LIST_CACHE_PREFIX = "cache:tag:list:"; - + /** + * Variable `tagMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final TagMapper tagMapper; + /** + * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final ShopMapper shopMapper; + /** + * Variable `multiLevelCacheService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final MultiLevelCacheService multiLevelCacheService; + /** + * Variable `appCacheProperties`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final AppCacheProperties appCacheProperties; @Override + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagDTO parameter `tagDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ public Long createTag(TagDTO tagDTO) { String tagName = normalizeTagName(tagDTO.getTagName()); Long shopId = requireShopId(tagDTO.getShopId()); + /** + * Run business method `ensureTagNameUniqueInShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagName parameter `tagName` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param null parameter `null` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ ensureTagNameUniqueInShop(tagName, shopId, null); TagDO tagDO = new TagDO(); @@ -55,6 +80,14 @@ public class TagServiceImpl extends ServiceImpl implements Tag try { tagMapper.insert(tagDO); } catch (DuplicateKeyException exception) { + /** + * Run business method `buildDuplicateTagException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagName parameter `tagName` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param null parameter `null` supplied by the caller + * @return throw result consumed by the caller or returned to the frontend + */ throw buildDuplicateTagException(tagName, shopId, null); } evictTagCaches(tagDO.getId(), shopId); @@ -62,6 +95,13 @@ public class TagServiceImpl extends ServiceImpl implements Tag } @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param tagDTO parameter `tagDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ public boolean updateTag(Long id, TagDTO tagDTO) { TagDO tagDO = tagMapper.selectById(id); if (tagDO == null) { @@ -69,6 +109,14 @@ public class TagServiceImpl extends ServiceImpl implements Tag } String tagName = normalizeTagName(tagDTO.getTagName()); Long shopId = requireShopId(tagDTO.getShopId()); + /** + * Run business method `ensureTagNameUniqueInShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagName parameter `tagName` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ ensureTagNameUniqueInShop(tagName, shopId, id); tagDO.setTagName(tagName); @@ -79,15 +127,36 @@ public class TagServiceImpl extends ServiceImpl implements Tag try { boolean updated = tagMapper.updateById(tagDO) > 0; if (updated) { + /** + * Run business method `evictTagCaches`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ evictTagCaches(id, shopId); } return updated; } catch (DuplicateKeyException exception) { + /** + * Run business method `buildDuplicateTagException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagName parameter `tagName` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param id parameter `id` supplied by the caller + * @return throw result consumed by the caller or returned to the frontend + */ throw buildDuplicateTagException(tagName, shopId, id); } } @Override + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ public boolean deleteTag(Long id) { TagDO tagDO = tagMapper.selectById(id); if (tagDO == null) { @@ -102,6 +171,12 @@ public class TagServiceImpl extends ServiceImpl implements Tag } @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return TagVO result consumed by the caller or returned to the frontend + */ public TagVO getTagById(Long id) { AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getTag(); return multiLevelCacheService.getOrLoad( @@ -115,12 +190,23 @@ public class TagServiceImpl extends ServiceImpl implements Tag if (tagDO == null || Integer.valueOf(1).equals(tagDO.getIsDelete())) { return null; } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagDO parameter `tagDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ return convertToVO(tagDO); } ); } @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ public List listAllTags() { AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getTag(); return multiLevelCacheService.getOrLoad( @@ -140,6 +226,12 @@ public class TagServiceImpl extends ServiceImpl implements Tag } @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ public List listTagsByShopId(Long shopId) { AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getTag(); return multiLevelCacheService.getOrLoad( @@ -160,6 +252,12 @@ public class TagServiceImpl extends ServiceImpl implements Tag } @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagName parameter `tagName` supplied by the caller + * @return TagVO result consumed by the caller or returned to the frontend + */ public TagVO getTagByTagName(String tagName) { TagDO tagDO = tagMapper.selectOne( Wrappers.lambdaQuery(TagDO.class) @@ -169,6 +267,12 @@ public class TagServiceImpl extends ServiceImpl implements Tag if (tagDO == null) { return null; } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagDO parameter `tagDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ return convertToVO(tagDO); } @@ -192,26 +296,69 @@ public class TagServiceImpl extends ServiceImpl implements Tag return tagVO; } + /** + * Run business method `normalizeTagName`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagName parameter `tagName` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ private String normalizeTagName(String tagName) { if (!StringUtils.hasText(tagName)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("标签名称不能为空"); } return tagName.trim(); } + /** + * Run business method `requireShopId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ private Long requireShopId(Long shopId) { if (shopId == null || shopId <= 0) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("请选择所属店铺"); } return shopId; } + /** + * Run business method `ensureTagNameUniqueInShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagName parameter `tagName` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param excludeId parameter `excludeId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void ensureTagNameUniqueInShop(String tagName, Long shopId, Long excludeId) { if (findActiveTagByNameAndShopId(tagName, shopId, excludeId) != null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("当前店铺已存在同名标签"); } } + /** + * Run business method `findActiveTagByNameAndShopId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagName parameter `tagName` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param excludeId parameter `excludeId` supplied by the caller + * @return private TagDO result consumed by the caller or returned to the frontend + */ private TagDO findActiveTagByNameAndShopId(String tagName, Long shopId, Long excludeId) { return tagMapper.selectOne( Wrappers.lambdaQuery(TagDO.class) @@ -223,13 +370,37 @@ public class TagServiceImpl extends ServiceImpl implements Tag ); } + /** + * Run business method `buildDuplicateTagException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagName parameter `tagName` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param excludeId parameter `excludeId` supplied by the caller + * @return private RuntimeException result consumed by the caller or returned to the frontend + */ private RuntimeException buildDuplicateTagException(String tagName, Long shopId, Long excludeId) { if (findActiveTagByNameAndShopId(tagName, shopId, excludeId) != null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return return new result consumed by the caller or returned to the frontend + */ return new RuntimeException("当前店铺已存在同名标签"); } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return return new result consumed by the caller or returned to the frontend + */ return new RuntimeException("数据库仍使用旧的标签全局唯一约束,请先执行本次提供的 SQL 补丁"); } + /** + * Run business method `resolveShopName`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ private String resolveShopName(Long shopId) { if (shopId == null || shopId <= 0) { return null; @@ -238,6 +409,13 @@ public class TagServiceImpl extends ServiceImpl implements Tag return shopDO == null ? null : shopDO.getShopName(); } + /** + * Run business method `evictTagCaches`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param tagId parameter `tagId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void evictTagCaches(Long tagId, Long shopId) { if (tagId != null) { multiLevelCacheService.evict(TAG_DETAIL_CACHE_PREFIX + tagId); diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/UserAssetServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/UserAssetServiceImpl.java index 10959c11..9a303572 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/UserAssetServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/UserAssetServiceImpl.java @@ -31,6 +31,10 @@ import java.util.stream.Collectors; @Service @RequiredArgsConstructor +/** + * UserAssetServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ public class UserAssetServiceImpl implements UserAssetService { private static final String VIP_LEVEL_NORMAL = "普通"; @@ -39,15 +43,38 @@ public class UserAssetServiceImpl implements UserAssetService { private static final String SCENE_MANUAL_DEDUCT = "MANUAL_DEDUCT"; private static final String SCENE_ORDER_CONSUME = "ORDER_CONSUME"; private static final String SCENE_ORDER_REFUND = "ORDER_REFUND"; - + /** + * Variable `balanceMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final BalanceMapper balanceMapper; + /** + * Variable `balanceChangeDetailMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final BalanceChangeDetailMapper balanceChangeDetailMapper; + /** + * Variable `vipInfoMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final VipInfoMapper vipInfoMapper; + /** + * Variable `vipBenefitMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final VipBenefitMapper vipBenefitMapper; + /** + * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final UserMapper userMapper; + /** + * Variable `orderMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final OrderMapper orderMapper; @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return UserAssetVO result consumed by the caller or returned to the frontend + */ public UserAssetVO getUserAsset(Long userId) { UserDO user = getAvailableUser(userId); BalanceDO balance = ensureBalance(userId); @@ -55,10 +82,25 @@ public class UserAssetServiceImpl implements UserAssetService { VipBenefitDO benefit = vipInfo != null && vipInfo.getBenefitId() != null ? vipBenefitMapper.selectById(vipInfo.getBenefitId()) : null; + /** + * Run business method `toAssetVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param user parameter `user` supplied by the caller + * @param balance parameter `balance` supplied by the caller + * @param vipInfo parameter `vipInfo` supplied by the caller + * @param benefit parameter `benefit` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ return toAssetVO(user, balance, vipInfo, benefit); } @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ public List listBalanceHistory(Long userId) { UserDO user = getAvailableUser(userId); return balanceChangeDetailMapper.selectList( @@ -73,11 +115,30 @@ public class UserAssetServiceImpl implements UserAssetService { @Override @Transactional(rollbackFor = Exception.class) + /** + * Run business method `changeBalance`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param operatorId parameter `operatorId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return UserAssetVO result consumed by the caller or returned to the frontend + */ public UserAssetVO changeBalance(Long operatorId, Long userId, AdminUserBalanceChangeDTO request) { if (request == null || request.getAmount() == null || request.getAmount().compareTo(BigDecimal.ZERO) <= 0) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param 0 parameter `0` supplied by the caller + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("变动金额必须大于 0"); } if (!StringUtils.hasText(request.getChangeScene())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("变动场景不能为空"); } @@ -89,6 +150,11 @@ public class UserAssetServiceImpl implements UserAssetService { BigDecimal delta = normalizeDelta(request.getAmount(), request.getChangeScene()); BigDecimal afterBalance = beforeBalance.add(delta); if (afterBalance.compareTo(BigDecimal.ZERO) < 0) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("余额不足,无法执行扣减"); } @@ -97,9 +163,19 @@ public class UserAssetServiceImpl implements UserAssetService { if (request.getRelatedOrderId() != null) { relatedOrder = orderMapper.selectById(request.getRelatedOrderId()); if (relatedOrder == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("关联系统订单不存在"); } if (!userId.equals(relatedOrder.getUserId())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("所选订单不属于当前用户"); } relatedOrderNo = relatedOrder.getOrderNo(); @@ -108,6 +184,11 @@ public class UserAssetServiceImpl implements UserAssetService { if (isDeductScene(request.getChangeScene()) && relatedOrder == null && !StringUtils.hasText(request.getExternalOrderNo())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("扣减余额时必须关联系统订单或填写外部订单号"); } @@ -136,16 +217,42 @@ public class UserAssetServiceImpl implements UserAssetService { balanceChangeDetailMapper.insert(detail); if (SCENE_RECHARGE.equals(request.getChangeScene())) { + /** + * Run business method `recalculateVipInternal`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param user parameter `user` supplied by the caller + * @param false parameter `false` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ recalculateVipInternal(user, false); } + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ return getUserAsset(userId); } @Override @Transactional(rollbackFor = Exception.class) + /** + * Run business method `overrideVip`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param operatorId parameter `operatorId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @param request parameter `request` supplied by the caller + * @return UserAssetVO result consumed by the caller or returned to the frontend + */ public UserAssetVO overrideVip(Long operatorId, Long userId, AdminUserVipOverrideDTO request) { if (request == null || !StringUtils.hasText(request.getVipLevel())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("VIP 等级不能为空"); } @@ -164,6 +271,11 @@ public class UserAssetServiceImpl implements UserAssetService { .eq(VipBenefitDO::getStatus, 1) .last("limit 1")); if (benefit == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("目标 VIP 等级未配置有效规则"); } vipInfo.setBenefitId(benefit.getId()); @@ -173,18 +285,53 @@ public class UserAssetServiceImpl implements UserAssetService { vipInfo.setVipLevel(targetLevel); vipInfoMapper.updateById(vipInfo); + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param user parameter `user` supplied by the caller + * @param vipInfo parameter `vipInfo` supplied by the caller + * @param targetLevel parameter `targetLevel` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ updateUserVipFields(user, vipInfo, targetLevel); return toAssetVO(userMapper.selectById(userId), ensureBalance(userId), vipInfo, benefit); } @Override @Transactional(rollbackFor = Exception.class) + /** + * Run business method `recalculateVip`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param operatorId parameter `operatorId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return UserAssetVO result consumed by the caller or returned to the frontend + */ public UserAssetVO recalculateVip(Long operatorId, Long userId) { UserDO user = getAvailableUser(userId); + /** + * Run business method `recalculateVipInternal`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param user parameter `user` supplied by the caller + * @param true parameter `true` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ recalculateVipInternal(user, true); + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ return getUserAsset(userId); } + /** + * Run business method `recalculateVipInternal`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param user parameter `user` supplied by the caller + * @param clearManualOverride parameter `clearManualOverride` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void recalculateVipInternal(UserDO user, boolean clearManualOverride) { BalanceDO balance = ensureBalance(user.getId()); VipBenefitDO matchedBenefit = vipBenefitMapper.selectList( @@ -204,6 +351,14 @@ public class UserAssetServiceImpl implements UserAssetService { return; } if (vipInfo == null && matchedBenefit == null) { + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param user parameter `user` supplied by the caller + * @param null parameter `null` supplied by the caller + * @param VIP_LEVEL_NORMAL parameter `VIP_LEVEL_NORMAL` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ updateUserVipFields(user, null, VIP_LEVEL_NORMAL); return; } @@ -218,9 +373,25 @@ public class UserAssetServiceImpl implements UserAssetService { vipInfo.setBenefitId(matchedBenefit != null ? matchedBenefit.getId() : null); vipInfoMapper.updateById(vipInfo); + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param user parameter `user` supplied by the caller + * @param vipInfo parameter `vipInfo` supplied by the caller + * @param targetLevel parameter `targetLevel` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ updateUserVipFields(user, vipInfo, targetLevel); } + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param user parameter `user` supplied by the caller + * @param vipInfo parameter `vipInfo` supplied by the caller + * @param vipLevel parameter `vipLevel` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void updateUserVipFields(UserDO user, VipInfoDO vipInfo, String vipLevel) { user.setLevel(StringUtils.hasText(vipLevel) ? vipLevel : VIP_LEVEL_NORMAL); user.setVipId(VIP_LEVEL_NORMAL.equals(user.getLevel()) || vipInfo == null ? 0L : vipInfo.getId()); @@ -228,6 +399,13 @@ public class UserAssetServiceImpl implements UserAssetService { userMapper.updateById(user); } + /** + * Run business method `normalizeDelta`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param amount parameter `amount` supplied by the caller + * @param changeScene parameter `changeScene` supplied by the caller + * @return private BigDecimal result consumed by the caller or returned to the frontend + */ private BigDecimal normalizeDelta(BigDecimal amount, String changeScene) { if (isDeductScene(changeScene)) { return amount.negate(); @@ -235,13 +413,30 @@ public class UserAssetServiceImpl implements UserAssetService { if (SCENE_RECHARGE.equals(changeScene) || SCENE_MANUAL_ADD.equals(changeScene) || SCENE_ORDER_REFUND.equals(changeScene)) { return amount; } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("不支持的余额变动场景"); } + /** + * Run business method `isDeductScene`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param changeScene parameter `changeScene` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ private boolean isDeductScene(String changeScene) { return SCENE_MANUAL_DEDUCT.equals(changeScene) || SCENE_ORDER_CONSUME.equals(changeScene); } + /** + * Run business method `ensureBalance`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return private BalanceDO result consumed by the caller or returned to the frontend + */ private BalanceDO ensureBalance(Long userId) { BalanceDO balance = balanceMapper.selectOne( Wrappers.lambdaQuery(BalanceDO.class) @@ -266,6 +461,12 @@ public class UserAssetServiceImpl implements UserAssetService { return balance; } + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return private VipInfoDO result consumed by the caller or returned to the frontend + */ private VipInfoDO getVipInfo(Long userId) { return vipInfoMapper.selectOne( Wrappers.lambdaQuery(VipInfoDO.class) @@ -273,6 +474,12 @@ public class UserAssetServiceImpl implements UserAssetService { .last("limit 1")); } + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return private VipInfoDO result consumed by the caller or returned to the frontend + */ private VipInfoDO getOrCreateVipInfo(Long userId) { VipInfoDO vipInfo = getVipInfo(userId); if (vipInfo != null) { @@ -288,18 +495,44 @@ public class UserAssetServiceImpl implements UserAssetService { return vipInfo; } + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return private UserDO result consumed by the caller or returned to the frontend + */ private UserDO getAvailableUser(Long userId) { UserDO user = userMapper.selectById(userId); if (user == null || Integer.valueOf(1).equals(user.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("用户不存在"); } return user; } + /** + * Run business method `defaultDecimal`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param value parameter `value` supplied by the caller + * @return private BigDecimal result consumed by the caller or returned to the frontend + */ private BigDecimal defaultDecimal(BigDecimal value) { return value == null ? BigDecimal.ZERO : value; } + /** + * Run business method `toAssetVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param user parameter `user` supplied by the caller + * @param balance parameter `balance` supplied by the caller + * @param vipInfo parameter `vipInfo` supplied by the caller + * @param benefit parameter `benefit` supplied by the caller + * @return private UserAssetVO result consumed by the caller or returned to the frontend + */ private UserAssetVO toAssetVO(UserDO user, BalanceDO balance, VipInfoDO vipInfo, VipBenefitDO benefit) { UserAssetVO vo = new UserAssetVO(); vo.setUserId(user.getId()); @@ -317,6 +550,13 @@ public class UserAssetServiceImpl implements UserAssetService { return vo; } + /** + * Run business method `toBalanceHistoryVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param detail parameter `detail` supplied by the caller + * @param nickname parameter `nickname` supplied by the caller + * @return private BalanceChangeDetailVO result consumed by the caller or returned to the frontend + */ private BalanceChangeDetailVO toBalanceHistoryVO(BalanceChangeDetailDO detail, String nickname) { BalanceChangeDetailVO vo = new BalanceChangeDetailVO(); vo.setId(detail.getId()); diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/UserServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/UserServiceImpl.java index 3f47a6cb..0b406cc9 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/UserServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/UserServiceImpl.java @@ -10,10 +10,16 @@ import com.xiaowang.yuminailcore.dto.NailArtistInfoDTO; import com.xiaowang.yuminailcore.entity.UserDO; import com.xiaowang.yuminailcore.entity.UserPermissionDO; import com.xiaowang.yuminailcore.entity.PermissionDO; +import com.xiaowang.yuminailcore.entity.UserRelationDO; +import com.xiaowang.yuminailcore.entity.UserInviteCodeDO; +import com.xiaowang.yuminailcore.entity.UserShopRoleDO; import com.xiaowang.yuminailcore.entity.WechatMiniBindingDO; import com.xiaowang.yuminailcore.mapper.UserMapper; import com.xiaowang.yuminailcore.mapper.UserPermissionMapper; import com.xiaowang.yuminailcore.mapper.PermissionMapper; +import com.xiaowang.yuminailcore.mapper.UserRelationMapper; +import com.xiaowang.yuminailcore.mapper.UserInviteCodeMapper; +import com.xiaowang.yuminailcore.mapper.UserShopRoleMapper; import com.xiaowang.yuminailcore.mapper.WechatMiniBindingMapper; import com.xiaowang.yuminailcore.service.NailArtistInfoService; import com.xiaowang.yuminailcore.service.ShopService; @@ -33,6 +39,8 @@ import com.xiaowang.yuminailcore.vo.PageResultVO; import com.xiaowang.yuminailcore.vo.ShopSimpleVO; import com.xiaowang.yuminailcore.vo.UserVO; import com.xiaowang.yuminailcore.vo.ShopVO; +import com.xiaowang.yuminailcore.vo.UserRelationVO; +import com.xiaowang.yuminailcore.vo.UserStatisticsVO; import lombok.RequiredArgsConstructor; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; @@ -49,6 +57,7 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; @@ -72,22 +81,77 @@ public class UserServiceImpl extends ServiceImpl implements private static final Long SYSTEM_PERMISSION_ASSIGNER_ID = 0L; private static final Set MANAGED_DEFAULT_PERMISSION_CODES = PermissionPolicy.getManagedDefaultPermissionCodes(); private static final Map DEFAULT_PERMISSION_SEEDS = buildDefaultPermissionSeeds(); - + /** + * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final UserMapper userMapper; + /** + * Variable `jwtUtil`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final JwtUtil jwtUtil; + /** + * Variable `shopService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final ShopService shopService; + /** + * Variable `userPermissionMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final UserPermissionMapper userPermissionMapper; + /** + * Variable `permissionMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final PermissionMapper permissionMapper; + /** + * Variable `userRelationMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserRelationMapper userRelationMapper; + /** + * Variable `userInviteCodeMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserInviteCodeMapper userInviteCodeMapper; + /** + * Variable `userShopRoleMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserShopRoleMapper userShopRoleMapper; + /** + * Variable `nailArtistInfoService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final NailArtistInfoService nailArtistInfoService; private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); + /** + * Variable `verificationCodeService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final VerificationCodeService verificationCodeService; + /** + * Variable `userShopBindingSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final UserShopBindingSupport userShopBindingSupport; + /** + * Variable `objectStorageUrlSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final ObjectStorageUrlSupport objectStorageUrlSupport; + /** + * Variable `redisTemplate`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final StringRedisTemplate redisTemplate; + /** + * Variable `snowflakeIdGenerator`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; + /** + * Variable `wechatMiniBindingMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final WechatMiniBindingMapper wechatMiniBindingMapper; + /** + * Variable `userSessionService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final UserSessionService userSessionService; + /** + * Run business method `buildDefaultPermissionSeeds`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private static Map result consumed by the caller or returned to the frontend + */ private static Map buildDefaultPermissionSeeds() { Map seeds = new HashMap<>(); seeds.put("home:view", new PermissionSeed("查看首页", "首页", "查看系统首页入口与概览")); @@ -102,6 +166,12 @@ public class UserServiceImpl extends ServiceImpl implements seeds.put("user:balance:view", new PermissionSeed("查看余额资产", "用户资产", "查看用户余额、累计充值与流水")); seeds.put("user:balance:manage", new PermissionSeed("调整余额", "用户资产", "充值、手工加减余额与关联订单")); seeds.put("user:vip:manage", new PermissionSeed("管理VIP", "用户资产", "手工设置VIP等级或恢复自动判级")); + seeds.put("role:view", new PermissionSeed("查看店铺角色", "角色管理", "查看店铺自定义角色")); + seeds.put("role:create", new PermissionSeed("新增店铺角色", "角色管理", "创建店铺自定义角色")); + seeds.put("role:edit", new PermissionSeed("编辑店铺角色", "角色管理", "编辑角色权限和绑定员工")); + seeds.put("role:delete", new PermissionSeed("删除店铺角色", "角色管理", "删除店铺自定义角色")); + seeds.put("user:relation:view", new PermissionSeed("查看用户所属", "用户管理", "查看用户归属关系")); + seeds.put("user:relation:edit", new PermissionSeed("编辑用户所属", "用户管理", "调整用户店铺和直属上级")); seeds.put("product:view", new PermissionSeed("查看商品", "商品管理", "查看商品列表与详情")); seeds.put("product:create", new PermissionSeed("新增商品", "商品管理", "创建商品")); seeds.put("product:edit", new PermissionSeed("编辑商品", "商品管理", "编辑商品信息")); @@ -138,6 +208,13 @@ public class UserServiceImpl extends ServiceImpl implements return Map.copyOf(seeds); } + /** + * Run business method `synchronizeManagedDefaultPermissions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userType parameter `userType` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void synchronizeManagedDefaultPermissions(Long userId, Integer userType) { List desiredPermissionCodes = getDefaultPermissionCodes(userType); List managedPermissions = permissionMapper.selectList( @@ -195,6 +272,11 @@ public class UserServiceImpl extends ServiceImpl implements } } + /** + * Run business method `ensurePermissionDefinitions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private void result consumed by the caller or returned to the frontend + */ private void ensurePermissionDefinitions() { List existingPermissions = permissionMapper.selectList( Wrappers.lambdaQuery(PermissionDO.class) @@ -225,11 +307,31 @@ public class UserServiceImpl extends ServiceImpl implements } } + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userType parameter `userType` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ private List getDefaultPermissionCodes(Integer userType) { return PermissionPolicy.getDefaultPermissionCodes(userType); } + /** + * Run business method `assignDefaultPermissions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userType parameter `userType` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void assignDefaultPermissions(Long userId, Integer userType) { + /** + * Run business method `syncDefaultPermissions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userType parameter `userType` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ syncDefaultPermissions(userId, userType); } @@ -249,6 +351,11 @@ public class UserServiceImpl extends ServiceImpl implements .eq(UserDO::getIsDelete, 0) ); if (existingUser != null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("账号已存在"); } @@ -257,6 +364,13 @@ public class UserServiceImpl extends ServiceImpl implements String validatedPhone = validateUserPhone(userDTO.getPhone(), null, true); Integer userType = userDTO.getType(); + /** + * Run business method `ensureShopBindingRequirement`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userType parameter `userType` supplied by the caller + * @param validatedShopIds parameter `validatedShopIds` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ ensureShopBindingRequirement(userType, validatedShopIds); // 创建用户实体并设置属性 @@ -264,6 +378,7 @@ public class UserServiceImpl extends ServiceImpl implements userDO.setShopId(validatedShopId); userDO.setNickname(userDTO.getNickname()); userDO.setAccount(validatedAccount); + validatePasswordStrength(userDTO.getPassword()); userDO.setPassword(passwordEncoder.encode(userDTO.getPassword())); userDO.setPhone(validatedPhone); userDO.setSignature(userDTO.getSignature()); @@ -290,6 +405,11 @@ public class UserServiceImpl extends ServiceImpl implements } catch (Exception e) { // 捕获重复账号异常 if (e.getMessage() != null && e.getMessage().contains("Duplicate entry")) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("账号已被使用"); } throw e; @@ -325,12 +445,29 @@ public class UserServiceImpl extends ServiceImpl implements return; } + /** + * Run business method `ensurePermissionDefinitions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return result consumed by the caller or returned to the frontend + */ ensurePermissionDefinitions(); + /** + * Run business method `synchronizeManagedDefaultPermissions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userType parameter `userType` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ synchronizeManagedDefaultPermissions(userId, userType); } @Override @Transactional(rollbackFor = Exception.class) + /** + * Run business method `syncManagedPermissions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + */ public void syncManagedPermissions(Long userId) { if (userId == null) { return; @@ -366,6 +503,11 @@ public class UserServiceImpl extends ServiceImpl implements .eq(UserDO::getIsDelete, 0) ); if (existingUser != null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("账号已存在"); } userDO.setAccount(normalizedAccount); @@ -379,6 +521,7 @@ public class UserServiceImpl extends ServiceImpl implements userDO.setNickname(userDTO.getNickname()); } if (userDTO.getPassword() != null) { + validatePasswordStrength(userDTO.getPassword()); userDO.setPassword(passwordEncoder.encode(userDTO.getPassword())); } if (userDTO.getPhone() != null) { @@ -408,6 +551,13 @@ public class UserServiceImpl extends ServiceImpl implements boolean shopBindingChanged = userDTO.getShopIds() != null || userDTO.getShopId() != null; if (shopBindingChanged) { validatedShopIds = resolveValidatedShopIds(userDTO.getShopIds(), userDTO.getShopId()); + /** + * Run business method `ensureShopBindingRequirement`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetUserType parameter `targetUserType` supplied by the caller + * @param validatedShopIds parameter `validatedShopIds` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ ensureShopBindingRequirement(targetUserType, validatedShopIds); userDO.setShopId(pickPrimaryShopId(validatedShopIds)); } @@ -420,6 +570,13 @@ public class UserServiceImpl extends ServiceImpl implements if (userDTO.getPassword() != null) { userSessionService.revokeAllUserSessions(id); } + /** + * Run business method `syncDefaultPermissions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param targetUserType parameter `targetUserType` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ syncDefaultPermissions(id, targetUserType); } return updated; @@ -472,6 +629,12 @@ public class UserServiceImpl extends ServiceImpl implements if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { return null; } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ return convertToVO(userDO); } @@ -544,6 +707,12 @@ public class UserServiceImpl extends ServiceImpl implements if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { return null; } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ return convertToVO(userDO); } @@ -580,13 +749,24 @@ public class UserServiceImpl extends ServiceImpl implements userVO.setSignature(userDO.getSignature()); userVO.setLevel(userDO.getLevel()); userVO.setType(userDO.getType()); + userVO.setTypeName(resolveUserTypeName(userDO.getType())); userVO.setVipId(userDO.getVipId()); userVO.setCreateTime(userDO.getCreateTime()); userVO.setUpdateTime(userDO.getUpdateTime()); userVO.setStatus(userDO.getStatus() != null ? userDO.getStatus() : 1); + userVO.setEmail(userDO.getEmail()); + userVO.setMaskedPhone(maskPhone(userDO.getPhone())); + userVO.setMaskedEmail(maskEmail(userDO.getEmail())); + applyRelationInfo(userVO, userDO.getId()); return userVO; } + /** + * Run business method `resolveAccessibleAvatar`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param avatarUrl parameter `avatarUrl` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ private String resolveAccessibleAvatar(String avatarUrl) { if (!StringUtils.hasText(avatarUrl)) { return DEFAULT_AVATAR_URL; @@ -594,6 +774,12 @@ public class UserServiceImpl extends ServiceImpl implements return objectStorageUrlSupport.toAccessibleUrl(avatarUrl); } + /** + * Run business method `normalizeStoredAvatar`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param avatarUrl parameter `avatarUrl` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ private String normalizeStoredAvatar(String avatarUrl) { if (!StringUtils.hasText(avatarUrl)) { return avatarUrl; @@ -602,6 +788,12 @@ public class UserServiceImpl extends ServiceImpl implements } @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param account parameter `account` supplied by the caller + * @return LoginShopSelectionVO result consumed by the caller or returned to the frontend + */ public LoginShopSelectionVO getLoginShopSelectionByAccount(String account) { String normalizedAccount = account == null ? "" : account.trim(); if (!StringUtils.hasText(normalizedAccount)) { @@ -639,6 +831,12 @@ public class UserServiceImpl extends ServiceImpl implements } @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @return LoginShopSelectionVO result consumed by the caller or returned to the frontend + */ public LoginShopSelectionVO getLoginShopSelectionByPhone(String phone) { String normalizedPhone = phone == null ? "" : phone.trim(); if (!StringUtils.hasText(normalizedPhone)) { @@ -679,6 +877,12 @@ public class UserServiceImpl extends ServiceImpl implements } @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param account parameter `account` supplied by the caller + * @return LoginShopSelectionVO result consumed by the caller or returned to the frontend + */ public LoginShopSelectionVO getAdminLoginShopSelection(String account) { String normalizedAccount = account == null ? "" : account.trim(); if (!StringUtils.hasText(normalizedAccount)) { @@ -703,15 +907,23 @@ public class UserServiceImpl extends ServiceImpl implements } if (Integer.valueOf(4).equals(userDO.getType())) { - List shops = userShopBindingSupport.listAllActiveShopOptions(); + List shops = listEnabledShopOptionsForAdmin(); boolean allowShoplessLogin = shops.isEmpty(); String message = allowShoplessLogin ? "当前暂无启用店铺,可直接登录后台创建店铺" : buildAdminLoginShopMessage(shops); + /** + * Run business method `buildLoginShopSelection`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shops parameter `shops` supplied by the caller + * @param allowShoplessLogin parameter `allowShoplessLogin` supplied by the caller + * @param message parameter `message` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ return buildLoginShopSelection(shops, allowShoplessLogin, message); } - List shops = userShopBindingSupport.listActiveShopOptionsByUserId(userDO.getId()); + List shops = listEnabledShopOptionsForUser(userDO.getId()); if (!shops.isEmpty()) { return buildLoginShopSelection(shops, false, buildLoginShopMessage(shops)); } @@ -719,6 +931,12 @@ public class UserServiceImpl extends ServiceImpl implements } @Override + /** + * Run the login flow. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param loginRequestDTO parameter `loginRequestDTO` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ public LoginResponseVO login(LoginRequestDTO loginRequestDTO) { String normalizedAccount = AccountValidationUtils.requireValidAccount(loginRequestDTO.getAccount()); UserDO userDO = userMapper.selectOne( @@ -726,25 +944,61 @@ public class UserServiceImpl extends ServiceImpl implements .eq(UserDO::getAccount, normalizedAccount) ); + /** + * Run business method `assertLoginAccountAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ assertLoginAccountAvailable(userDO); // 检查是否为未设置密码的账号 if (ENCODED_UNSET_PASSWORD.equals(userDO.getPassword())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("请使用手机号验证码登录,并在个人中心设置密码"); } if (!passwordEncoder.matches(loginRequestDTO.getPassword(), userDO.getPassword())) { + /** + * Run business method `handleLoginPasswordFailure`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ handleLoginPasswordFailure(userDO); } Long resolvedShopId = resolveUserLoginShopId(userDO, loginRequestDTO.getShopId()); clearLoginFailureCount(userDO.getAccount()); + /** + * Run business method `buildLoginResponse`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @param resolvedShopId parameter `resolvedShopId` supplied by the caller + * @param false parameter `false` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ return buildLoginResponse(userDO, resolvedShopId, false); } @Override + /** + * Run business method `phoneLogin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phoneLoginRequestDTO parameter `phoneLoginRequestDTO` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ public LoginResponseVO phoneLogin(PhoneLoginRequestDTO phoneLoginRequestDTO) { if (!verificationCodeService.verifyCode(phoneLoginRequestDTO.getPhone(), phoneLoginRequestDTO.getVerificationCode())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("验证码错误或已过期"); } @@ -756,10 +1010,21 @@ public class UserServiceImpl extends ServiceImpl implements if (userDO == null) { if (phoneLoginRequestDTO.getShopId() == null || phoneLoginRequestDTO.getShopId() == 0) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("首次登录需要选择店铺"); } userDO = registerByPhone(phoneLoginRequestDTO.getPhone(), phoneLoginRequestDTO.getShopId()); } else { + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ assertUserAvailable(userDO); clearLoginFailureCount(userDO.getAccount()); } @@ -770,6 +1035,13 @@ public class UserServiceImpl extends ServiceImpl implements // 未设置密码的特殊标识 @Override + /** + * Run the login flow. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ public LoginResponseVO loginByVerifiedPhone(String phone, Long shopId) { UserDO userDO = userMapper.selectOne( Wrappers.lambdaQuery(UserDO.class) @@ -780,10 +1052,21 @@ public class UserServiceImpl extends ServiceImpl implements if (userDO == null) { if (shopId == null || shopId == 0) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("首次登录需要选择店铺"); } userDO = registerByPhone(phone, shopId); } else { + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ assertUserAvailable(userDO); clearLoginFailureCount(userDO.getAccount()); } @@ -793,8 +1076,21 @@ public class UserServiceImpl extends ServiceImpl implements } @Override + /** + * Run the login flow. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ public LoginResponseVO loginByUserId(Long userId, Long shopId) { UserDO userDO = userMapper.selectById(userId); + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ assertUserAvailable(userDO); clearLoginFailureCount(userDO.getAccount()); Long resolvedShopId = resolveUserLoginShopId(userDO, shopId); @@ -804,9 +1100,21 @@ public class UserServiceImpl extends ServiceImpl implements private static final String UNSET_PASSWORD_MARKER = "__UNSET_PASSWORD__"; private static final String ENCODED_UNSET_PASSWORD = "$2a$10$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"; // 加密后的特殊标识 + /** + * Run the registration flow. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return private UserDO result consumed by the caller or returned to the frontend + */ private UserDO registerByPhone(String phone, Long shopId) { Long validatedShopId = validateAndNormalizeShopId(shopId); if (validatedShopId == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("首次登录需要选择店铺"); } UserDO userDO = new UserDO(); @@ -832,6 +1140,12 @@ public class UserServiceImpl extends ServiceImpl implements @Override @Transactional(rollbackFor = Exception.class) + /** + * Run business method `adminLogin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param loginRequestDTO parameter `loginRequestDTO` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ public LoginResponseVO adminLogin(LoginRequestDTO loginRequestDTO) { String normalizedAccount = AccountValidationUtils.requireValidAccount(loginRequestDTO.getAccount()); UserDO userDO = userMapper.selectOne( @@ -839,14 +1153,31 @@ public class UserServiceImpl extends ServiceImpl implements .eq(UserDO::getAccount, normalizedAccount) ); + /** + * Run business method `assertLoginAccountAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ assertLoginAccountAvailable(userDO); if (!passwordEncoder.matches(loginRequestDTO.getPassword(), userDO.getPassword())) { + /** + * Run business method `handleLoginPasswordFailure`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ handleLoginPasswordFailure(userDO); } Integer userType = userDO.getType(); if (userType == null || userType < 2) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("该账号不是后台管理账号"); } @@ -854,14 +1185,41 @@ public class UserServiceImpl extends ServiceImpl implements Long resolvedShopId = resolveAdminLoginShopId(userDO, loginRequestDTO.getShopId()); clearLoginFailureCount(userDO.getAccount()); + /** + * Run business method `buildLoginResponse`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @param resolvedShopId parameter `resolvedShopId` supplied by the caller + * @param false parameter `false` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ return buildLoginResponse(userDO, resolvedShopId, false); } @Override + /** + * Run business method `switchShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param previousSessionId parameter `previousSessionId` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ public LoginResponseVO switchShop(Long userId, Long shopId, String previousSessionId) { UserDO userDO = userMapper.selectById(userId); + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ assertUserAvailable(userDO); if (userDO.getType() != null && userDO.getType() >= 2) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("当前账号请使用后台切换店铺"); } Long resolvedShopId = resolveUserLoginShopId(userDO, shopId); @@ -869,17 +1227,52 @@ public class UserServiceImpl extends ServiceImpl implements } @Override + /** + * Run business method `switchAdminShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param previousSessionId parameter `previousSessionId` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ public LoginResponseVO switchAdminShop(Long userId, Long shopId, String previousSessionId) { UserDO userDO = userMapper.selectById(userId); + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ assertUserAvailable(userDO); Integer userType = userDO.getType(); if (userType == null || userType < 2) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("您没有后台管理权限"); } Long resolvedShopId = resolveAdminLoginShopId(userDO, shopId); + /** + * Run business method `buildLoginResponse`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @param resolvedShopId parameter `resolvedShopId` supplied by the caller + * @param false parameter `false` supplied by the caller + * @param previousSessionId parameter `previousSessionId` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ return buildLoginResponse(userDO, resolvedShopId, false, previousSessionId); } + /** + * Run business method `resolveAdminLoginShopId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @param requestedShopId parameter `requestedShopId` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ private Long resolveAdminLoginShopId(UserDO userDO, Long requestedShopId) { if (Integer.valueOf(4).equals(userDO.getType()) && !hasAnyShop()) { return null; @@ -888,21 +1281,43 @@ public class UserServiceImpl extends ServiceImpl implements if (Integer.valueOf(4).equals(userDO.getType())) { Long normalizedRequestedShopId = normalizeShopId(requestedShopId); if (normalizedRequestedShopId == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("请选择登录店铺"); } - if (!userShopBindingSupport.isShopActive(normalizedRequestedShopId)) { + if (!userShopBindingSupport.isShopEnabledIgnoringAuthorization(normalizedRequestedShopId)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("所选店铺不存在或已停用"); } return normalizedRequestedShopId; } - List activeShopIds = userShopBindingSupport.listActiveShopIdsByUserId(userDO.getId()); + List activeShopIds = listEnabledShopOptionsForUser(userDO.getId()).stream() + .map(ShopSimpleVO::getId) + .collect(Collectors.toList()); if (activeShopIds.isEmpty()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("当前账号没有可登录的店铺,请联系平台管理员"); } Long normalizedRequestedShopId = normalizeShopId(requestedShopId); if (normalizedRequestedShopId != null) { if (!activeShopIds.contains(normalizedRequestedShopId)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("当前账号无权登录所选店铺"); } return normalizedRequestedShopId; @@ -910,21 +1325,48 @@ public class UserServiceImpl extends ServiceImpl implements if (activeShopIds.size() == 1) { return activeShopIds.get(0); } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("请选择登录店铺"); } + /** + * Run business method `hasAnyShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private boolean result consumed by the caller or returned to the frontend + */ private boolean hasAnyShop() { - return !userShopBindingSupport.listAllActiveShopOptions().isEmpty(); + return !listEnabledShopOptionsForAdmin().isEmpty(); } + /** + * Run business method `normalizeShopId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ private Long normalizeShopId(Long shopId) { return shopId != null && shopId > 0 ? shopId : null; } @Override + /** + * Run the registration flow. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param registerRequestDTO parameter `registerRequestDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ public boolean register(RegisterRequestDTO registerRequestDTO) { String validatedAccount = AccountValidationUtils.requireValidAccount(registerRequestDTO.getAccount()); if (!verificationCodeService.verifyCode(registerRequestDTO.getPhone(), registerRequestDTO.getVerificationCode())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("验证码错误或已过期"); } @@ -935,8 +1377,18 @@ public class UserServiceImpl extends ServiceImpl implements if (existingUser != null) { if (existingUser.getIsDelete() == 0) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("账号已存在"); } else { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("该账号已被注销,请使用手机号验证码登录"); } } @@ -948,17 +1400,28 @@ public class UserServiceImpl extends ServiceImpl implements ); if (existingPhoneUser != null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("该手机号已被注册"); } - Long validatedShopId = validateAndNormalizeShopId(registerRequestDTO.getShopId()); + Long validatedShopId = resolveRegisterShopId(registerRequestDTO.getShopId(), registerRequestDTO.getInviteCode()); if (validatedShopId == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("请选择店铺"); } UserDO userDO = new UserDO(); userDO.setShopId(validatedShopId); userDO.setAccount(validatedAccount); + validatePasswordStrength(registerRequestDTO.getPassword()); userDO.setPassword(passwordEncoder.encode(registerRequestDTO.getPassword())); userDO.setNickname(registerRequestDTO.getNickname()); userDO.setPhone(registerRequestDTO.getPhone()); @@ -973,16 +1436,35 @@ public class UserServiceImpl extends ServiceImpl implements userMapper.insert(userDO); assignDefaultPermissions(userDO.getId(), userDO.getType()); userShopBindingSupport.syncUserShopBindings(userDO.getId(), List.of(validatedShopId)); + createRelationForRegister(userDO.getId(), validatedShopId, registerRequestDTO.getInviteCode()); return true; } @Override + /** + * Run business method `refreshToken`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param refreshToken parameter `refreshToken` supplied by the caller + * @return LoginResponseVO result consumed by the caller or returned to the frontend + */ public LoginResponseVO refreshToken(String refreshToken) { if (!jwtUtil.validateToken(refreshToken)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param Token parameter `Token` supplied by the caller + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("刷新Token无效或已过期"); } if (!jwtUtil.isRefreshToken(refreshToken)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param Token parameter `Token` supplied by the caller + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("Token类型错误"); } @@ -992,13 +1474,29 @@ public class UserServiceImpl extends ServiceImpl implements String sessionId = jwtUtil.getSessionIdFromToken(refreshToken); String refreshJti = jwtUtil.getJtiFromToken(refreshToken); if (!userSessionService.isRefreshSessionActive(userId, sessionId, refreshJti)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("登录态已失效,请重新登录"); } UserDO userDO = userMapper.selectById(userId); + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ assertUserAvailable(userDO); boolean adminLogin = userDO.getType() != null && userDO.getType() >= 2; if (!userShopBindingSupport.canUserAccessShop(userId, currentShopId, adminLogin, userDO.getType())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("当前登录店铺已失效,请重新登录"); } @@ -1006,19 +1504,46 @@ public class UserServiceImpl extends ServiceImpl implements } @Override + /** + * Run business method `logout`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sessionId parameter `sessionId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ public boolean logout(String sessionId) { userSessionService.revokeSession(sessionId); return true; } @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return UserVO result consumed by the caller or returned to the frontend + */ public UserVO getCurrentUserInfo() { - return null; + org.springframework.web.context.request.ServletRequestAttributes attributes = + (org.springframework.web.context.request.ServletRequestAttributes) org.springframework.web.context.request.RequestContextHolder.getRequestAttributes(); + Long userId = attributes == null ? null : (Long) attributes.getRequest().getAttribute("userId"); + return userId == null ? null : getUserById(userId); } @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param userDTO parameter `userDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ public boolean updateCurrentUserInfo(Long userId, UserDTO userDTO) { UserDO userDO = userMapper.selectById(userId); + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ assertUserAvailable(userDO); if (userDTO.getNickname() != null) { @@ -1044,8 +1569,21 @@ public class UserServiceImpl extends ServiceImpl implements } @Override + /** + * Run business method `bindPhone`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param bindPhoneRequestDTO parameter `bindPhoneRequestDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ public boolean bindPhone(Long userId, BindPhoneRequestDTO bindPhoneRequestDTO) { UserDO userDO = userMapper.selectById(userId); + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ assertUserAvailable(userDO); validateVerificationCode(bindPhoneRequestDTO.getPhone(), bindPhoneRequestDTO.getVerificationCode()); ensurePhoneNotUsed(bindPhoneRequestDTO.getPhone(), userId); @@ -1058,9 +1596,21 @@ public class UserServiceImpl extends ServiceImpl implements } @Override + /** + * Run business method `bindEmail`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param bindEmailRequestDTO parameter `bindEmailRequestDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ public boolean bindEmail(Long userId, BindEmailRequestDTO bindEmailRequestDTO) { UserDO userDO = userMapper.selectById(userId); if (userDO == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("用户不存在"); } @@ -1072,14 +1622,31 @@ public class UserServiceImpl extends ServiceImpl implements } @Override + /** + * Run business method `resetPassword`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param targetUserId parameter `targetUserId` supplied by the caller + * @param currentUserId parameter `currentUserId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ public boolean resetPassword(Long targetUserId, Long currentUserId) { UserDO targetUser = userMapper.selectById(targetUserId); if (targetUser == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("目标用户不存在"); } UserDO currentUser = userMapper.selectById(currentUserId); if (currentUser == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("当前用户不存在"); } @@ -1087,10 +1654,20 @@ public class UserServiceImpl extends ServiceImpl implements Integer targetUserType = targetUser.getType(); if (currentUserType == null || targetUserType == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("用户类型错误"); } if (currentUserType <= targetUserType) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("权限不足,只能重置比自己级别低的用户密码"); } @@ -1104,7 +1681,60 @@ public class UserServiceImpl extends ServiceImpl implements } @Override + /** + * Query paged records. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @param size parameter `size` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param type parameter `type` supplied by the caller + * @return PageResultVO result consumed by the caller or returned to the frontend + */ public PageResultVO pageUsers(Integer page, Integer size, String keyword, Long shopId, Integer type) { + /** + * Query paged records. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @param size parameter `size` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param type parameter `type` supplied by the caller + * @param null parameter `null` supplied by the caller + * @param null parameter `null` supplied by the caller + * @param null parameter `null` supplied by the caller + * @param null parameter `null` supplied by the caller + * @param null parameter `null` supplied by the caller + * @param null parameter `null` supplied by the caller + * @param null parameter `null` supplied by the caller + * @param null parameter `null` supplied by the caller + * @param null parameter `null` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return pageUsers(page, size, keyword, shopId, type, null, null, null, null, null, null, null, null, null); + } + + @Override + /** + * Query paged records. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param page parameter `page` supplied by the caller + * @param size parameter `size` supplied by the caller + * @param keyword parameter `keyword` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param type parameter `type` supplied by the caller + * @param roleId parameter `roleId` supplied by the caller + * @param parentUserId parameter `parentUserId` supplied by the caller + * @param sourceType parameter `sourceType` supplied by the caller + * @param status parameter `status` supplied by the caller + * @param vipLevel parameter `vipLevel` supplied by the caller + * @param createdFrom parameter `createdFrom` supplied by the caller + * @param createdTo parameter `createdTo` supplied by the caller + * @param hasPhone parameter `hasPhone` supplied by the caller + * @param hasOrder parameter `hasOrder` supplied by the caller + * @return PageResultVO result consumed by the caller or returned to the frontend + */ + public PageResultVO pageUsers(Integer page, Integer size, String keyword, Long shopId, Integer type, Long roleId, Long parentUserId, String sourceType, Integer status, String vipLevel, String createdFrom, String createdTo, Boolean hasPhone, Boolean hasOrder) { Page pageParam = new Page<>(page, size); LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(UserDO.class); @@ -1127,9 +1757,39 @@ public class UserServiceImpl extends ServiceImpl implements } wrapper.in(UserDO::getId, userIds); } + Set relationFilteredIds = resolveRelationFilteredUserIds(roleId, parentUserId, sourceType); + if (relationFilteredIds != null) { + if (relationFilteredIds.isEmpty()) { + PageResultVO emptyResult = new PageResultVO<>(); + emptyResult.setList(List.of()); + emptyResult.setTotal(0L); + emptyResult.setPage(page); + emptyResult.setSize(size); + return emptyResult; + } + wrapper.in(UserDO::getId, relationFilteredIds); + } if (type != null) { wrapper.eq(UserDO::getType, type); } + if (status != null) { + wrapper.eq(UserDO::getStatus, status); + } + if (StringUtils.hasText(vipLevel)) { + wrapper.eq(UserDO::getLevel, vipLevel); + } + if (StringUtils.hasText(createdFrom)) { + wrapper.ge(UserDO::getCreateTime, LocalDateTime.parse(createdFrom)); + } + if (StringUtils.hasText(createdTo)) { + wrapper.le(UserDO::getCreateTime, LocalDateTime.parse(createdTo)); + } + if (Boolean.TRUE.equals(hasPhone)) { + wrapper.isNotNull(UserDO::getPhone); + } + if (Boolean.FALSE.equals(hasPhone)) { + wrapper.isNull(UserDO::getPhone); + } wrapper.orderByDesc(UserDO::getCreateTime); Page userPage = userMapper.selectPage(pageParam, wrapper); @@ -1144,6 +1804,13 @@ public class UserServiceImpl extends ServiceImpl implements } @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param status parameter `status` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ public boolean updateUserStatus(Long id, Integer status) { UserDO userDO = userMapper.selectById(id); if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { @@ -1170,27 +1837,135 @@ public class UserServiceImpl extends ServiceImpl implements } @Override + /** + * Run business method `statisticsUsers`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param keyword parameter `keyword` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param type parameter `type` supplied by the caller + * @param roleId parameter `roleId` supplied by the caller + * @param parentUserId parameter `parentUserId` supplied by the caller + * @param sourceType parameter `sourceType` supplied by the caller + * @param status parameter `status` supplied by the caller + * @param vipLevel parameter `vipLevel` supplied by the caller + * @param createdFrom parameter `createdFrom` supplied by the caller + * @param createdTo parameter `createdTo` supplied by the caller + * @param hasPhone parameter `hasPhone` supplied by the caller + * @param hasOrder parameter `hasOrder` supplied by the caller + * @return UserStatisticsVO result consumed by the caller or returned to the frontend + */ + public UserStatisticsVO statisticsUsers(String keyword, Long shopId, Integer type, Long roleId, Long parentUserId, String sourceType, Integer status, String vipLevel, String createdFrom, String createdTo, Boolean hasPhone, Boolean hasOrder) { + List users = pageUsers(1, Integer.MAX_VALUE, keyword, shopId, type, roleId, parentUserId, sourceType, status, vipLevel, createdFrom, createdTo, hasPhone, hasOrder).getList(); + UserStatisticsVO vo = new UserStatisticsVO(); + vo.setTotalUserCount(users.size()); + vo.setNormalUserCount(users.stream().filter(u -> Integer.valueOf(0).equals(u.getType())).count()); + vo.setEmployeeCount(users.stream().filter(u -> Integer.valueOf(2).equals(u.getType()) || Integer.valueOf(3).equals(u.getType())).count()); + vo.setManagerCount(users.stream().filter(u -> Integer.valueOf(2).equals(u.getType())).count()); + vo.setArtistCount(users.stream().filter(u -> Integer.valueOf(3).equals(u.getType())).count()); + vo.setVipUserCount(users.stream().filter(u -> StringUtils.hasText(u.getLevel()) && !"普通".equals(u.getLevel())).count()); + vo.setNewUserCount(users.stream().filter(u -> u.getCreateTime() != null && u.getCreateTime().isAfter(LocalDateTime.now().minusDays(7))).count()); + vo.setByShop(users.stream().collect(Collectors.groupingBy(u -> String.valueOf(u.getShopId()), Collectors.counting()))); + vo.setByRole(users.stream().collect(Collectors.groupingBy(u -> String.valueOf(u.getShopRoleName()), Collectors.counting()))); + vo.setByParent(users.stream().collect(Collectors.groupingBy(u -> String.valueOf(u.getParentUserName()), Collectors.counting()))); + return vo; + } + + @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return UserRelationVO result consumed by the caller or returned to the frontend + */ + public UserRelationVO getCurrentUserRelation(Long userId) { + /** + * Run business method `buildRelationVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ + return buildRelationVO(userId); + } + + @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param status parameter `status` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ public boolean updateUserStatusInShop(Long id, Integer status, Long shopId) { + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param status parameter `status` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ return updateUserStatus(id, status); } @Override @Transactional(rollbackFor = Exception.class) + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ public boolean deleteUserInShop(Long id, Long shopId) { + /** + * Run business method `unbindUserInShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ return unbindUserInShop(id, shopId); } @Override @Transactional(rollbackFor = Exception.class) + /** + * Run business method `unbindUserInShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ public boolean unbindUserInShop(Long id, Long shopId) { + /** + * Run business method `unbindUserInShopWithOperator`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param null parameter `null` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ return unbindUserInShopWithOperator(id, shopId, null); } @Override @Transactional(rollbackFor = Exception.class) + /** + * Run business method `unbindUserInShopWithOperator`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param operatorType parameter `operatorType` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ public boolean unbindUserInShopWithOperator(Long id, Long shopId, Integer operatorType) { Long normalizedShopId = normalizeShopId(shopId); if (normalizedShopId == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("当前操作缺少店铺上下文"); } UserDO userDO = userMapper.selectById(id); @@ -1213,8 +1988,21 @@ public class UserServiceImpl extends ServiceImpl implements } @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param avatarUrl parameter `avatarUrl` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ public boolean updateUserAvatar(Long userId, String avatarUrl) { UserDO userDO = userMapper.selectById(userId); + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ assertUserAvailable(userDO); userDO.setAvatar(avatarUrl); userDO.setUpdateTime(LocalDateTime.now()); @@ -1222,13 +2010,33 @@ public class UserServiceImpl extends ServiceImpl implements } @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param password parameter `password` supplied by the caller + * @param verificationCode parameter `verificationCode` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ public boolean updatePassword(Long userId, String password, String verificationCode) { UserDO userDO = userMapper.selectById(userId); + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ assertUserAvailable(userDO); if (!StringUtils.hasText(userDO.getPhone())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("请先绑定手机号"); } validateVerificationCode(userDO.getPhone(), verificationCode); + validatePasswordStrength(password); userDO.setPassword(passwordEncoder.encode(password)); userDO.setUpdateTime(LocalDateTime.now()); boolean updated = userMapper.updateById(userDO) > 0; @@ -1239,21 +2047,58 @@ public class UserServiceImpl extends ServiceImpl implements } @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param updatePhoneDTO parameter `updatePhoneDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ public boolean updatePhone(Long userId, UpdatePhoneRequestDTO updatePhoneDTO) { String oldPhone = updatePhoneDTO.getOldPhone(); String newPhone = updatePhoneDTO.getNewPhone(); String verificationCode = updatePhoneDTO.getVerificationCode(); UserDO userDO = userMapper.selectById(userId); + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ assertUserAvailable(userDO); if (!StringUtils.hasText(userDO.getPhone())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("当前账号未绑定手机号"); } if (!userDO.getPhone().equals(oldPhone)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("原手机号不匹配"); } + /** + * Run business method `validateVerificationCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param newPhone parameter `newPhone` supplied by the caller + * @param verificationCode parameter `verificationCode` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ validateVerificationCode(newPhone, verificationCode); + /** + * Run business method `ensurePhoneNotUsed`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param newPhone parameter `newPhone` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ ensurePhoneNotUsed(newPhone, userId); userDO.setPhone(newPhone); @@ -1263,11 +2108,24 @@ public class UserServiceImpl extends ServiceImpl implements } @Override + /** + * Run business method `resetPasswordByPhone`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param resetPasswordRequestDTO parameter `resetPasswordRequestDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ public boolean resetPasswordByPhone(ResetPasswordRequestDTO resetPasswordRequestDTO) { String phone = resetPasswordRequestDTO.getPhone(); String verificationCode = resetPasswordRequestDTO.getVerificationCode(); String newPassword = resetPasswordRequestDTO.getNewPassword(); + /** + * Run business method `validateVerificationCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param verificationCode parameter `verificationCode` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ validateVerificationCode(phone, verificationCode); // 根据手机号查找用户 @@ -1277,13 +2135,24 @@ public class UserServiceImpl extends ServiceImpl implements UserDO userDO = userMapper.selectOne(wrapper); if (userDO == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("未绑定手机号,请联系店员"); } if (userDO.getStatus() != null && !Integer.valueOf(1).equals(userDO.getStatus())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("账号已被禁用"); } // 更新密码 + validatePasswordStrength(newPassword); userDO.setPassword(passwordEncoder.encode(newPassword)); userDO.setUpdateTime(LocalDateTime.now()); boolean updated = userMapper.updateById(userDO) > 0; @@ -1293,18 +2162,51 @@ public class UserServiceImpl extends ServiceImpl implements return updated; } + /** + * Run business method `buildDeletedAccount`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ private String buildDeletedAccount(UserDO userDO) { String suffix = userDO.getId() + "_" + snowflakeIdGenerator.nextIdString(); String base = StringUtils.hasText(userDO.getAccount()) ? userDO.getAccount() : "deleted"; + /** + * Run business method `trimDeletedPlaceholder`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param suffix parameter `suffix` supplied by the caller + * @param 50 parameter `50` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ return trimDeletedPlaceholder(base + DELETED_PHONE_MARKER + suffix, 50); } + /** + * Run business method `buildDeletedPhone`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ private String buildDeletedPhone(UserDO userDO) { String suffix = userDO.getId() + "_" + snowflakeIdGenerator.nextIdString(); String base = StringUtils.hasText(userDO.getPhone()) ? userDO.getPhone() : "deleted_phone"; + /** + * Run business method `trimDeletedPlaceholder`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param suffix parameter `suffix` supplied by the caller + * @param 50 parameter `50` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ return trimDeletedPlaceholder(base + DELETED_PHONE_MARKER + suffix, 50); } + /** + * Run business method `trimDeletedPlaceholder`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param value parameter `value` supplied by the caller + * @param maxLength parameter `maxLength` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ private String trimDeletedPlaceholder(String value, int maxLength) { if (!StringUtils.hasText(value) || value.length() <= maxLength) { return value; @@ -1312,26 +2214,69 @@ public class UserServiceImpl extends ServiceImpl implements return value.substring(value.length() - maxLength); } + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void assertUserAvailable(UserDO userDO) { if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("用户不存在"); } if (userDO.getStatus() != null && !Integer.valueOf(1).equals(userDO.getStatus())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("账号已被禁用"); } } + /** + * Run business method `assertLoginAccountAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void assertLoginAccountAvailable(UserDO userDO) { if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("该账号不存在"); } if (userDO.getStatus() != null && !Integer.valueOf(1).equals(userDO.getStatus())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("该账号已被禁用"); } } + /** + * Run business method `handleLoginPasswordFailure`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void handleLoginPasswordFailure(UserDO userDO) { if (userDO == null || !StringUtils.hasText(userDO.getAccount())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("密码错误"); } String failKey = buildLoginFailKey(userDO.getAccount()); @@ -1341,12 +2286,28 @@ public class UserServiceImpl extends ServiceImpl implements if (safeFailCount >= MAX_LOGIN_FAILURES) { disableUserByFailedPassword(userDO.getId()); redisTemplate.delete(failKey); + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("密码错误次数过多,账号已被禁用"); } long remainingAttempts = MAX_LOGIN_FAILURES - safeFailCount; + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("密码错误,还可尝试" + remainingAttempts + "次"); } + /** + * Run business method `disableUserByFailedPassword`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void disableUserByFailedPassword(Long userId) { if (userId == null) { return; @@ -1362,6 +2323,12 @@ public class UserServiceImpl extends ServiceImpl implements userSessionService.revokeAllUserSessions(userId); } + /** + * Run business method `clearLoginFailureCount`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param account parameter `account` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void clearLoginFailureCount(String account) { if (!StringUtils.hasText(account)) { return; @@ -1369,19 +2336,71 @@ public class UserServiceImpl extends ServiceImpl implements redisTemplate.delete(buildLoginFailKey(account)); } + /** + * Run business method `buildLoginFailKey`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param account parameter `account` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ private String buildLoginFailKey(String account) { return LOGIN_FAIL_KEY_PREFIX + account.trim(); } + /** + * Run business method `validateVerificationCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param verificationCode parameter `verificationCode` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void validateVerificationCode(String phone, String verificationCode) { if (!StringUtils.hasText(phone) || !StringUtils.hasText(verificationCode)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("验证码不能为空"); } if (!verificationCodeService.verifyCode(phone, verificationCode)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("验证码错误或已过期"); } } + private void validatePasswordStrength(String password) { + if (!StringUtils.hasText(password) || password.length() < 8 || password.length() > 32) { + throw new RuntimeException("密码长度需为 8-32 位"); + } + int count = 0; + if (password.matches(".*\\d.*")) { + count++; + } + if (password.matches(".*[a-z].*")) { + count++; + } + if (password.matches(".*[A-Z].*")) { + count++; + } + if (password.matches(".*[!@#$%^&*()_+\\-=\\[\\]{};':\"\\\\|,.<>/?].*")) { + count++; + } + if (count < 3) { + throw new RuntimeException("密码需至少包含数字、小写字母、大写字母、特殊符号中的 3 类"); + } + } + + /** + * Run business method `resolveValidatedShopIds`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopIds parameter `shopIds` supplied by the caller + * @param fallbackShopId parameter `fallbackShopId` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ private List resolveValidatedShopIds(List shopIds, Long fallbackShopId) { LinkedHashSet resolvedShopIds = new LinkedHashSet<>(); if (shopIds != null) { @@ -1399,19 +2418,45 @@ public class UserServiceImpl extends ServiceImpl implements return new ArrayList<>(resolvedShopIds); } + /** + * Run business method `pickPrimaryShopId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopIds parameter `shopIds` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ private Long pickPrimaryShopId(List shopIds) { return shopIds == null || shopIds.isEmpty() ? null : shopIds.get(0); } + /** + * Run business method `ensureShopBindingRequirement`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userType parameter `userType` supplied by the caller + * @param shopIds parameter `shopIds` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void ensureShopBindingRequirement(Integer userType, List shopIds) { if (Integer.valueOf(4).equals(userType)) { return; } if (shopIds == null || shopIds.isEmpty()) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("请至少选择一个所属店铺"); } } + /** + * Run business method `buildLoginShopSelection`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shops parameter `shops` supplied by the caller + * @param allowShoplessLogin parameter `allowShoplessLogin` supplied by the caller + * @param message parameter `message` supplied by the caller + * @return private LoginShopSelectionVO result consumed by the caller or returned to the frontend + */ private LoginShopSelectionVO buildLoginShopSelection(List shops, boolean allowShoplessLogin, String message) { LoginShopSelectionVO selectionVO = new LoginShopSelectionVO(); selectionVO.setAllowShoplessLogin(allowShoplessLogin); @@ -1420,6 +2465,12 @@ public class UserServiceImpl extends ServiceImpl implements return selectionVO; } + /** + * Run business method `buildLoginShopMessage`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shops parameter `shops` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ private String buildLoginShopMessage(List shops) { if (shops == null || shops.isEmpty()) { return "当前暂无可登录店铺"; @@ -1430,6 +2481,12 @@ public class UserServiceImpl extends ServiceImpl implements return "该账号已绑定多家店铺,请选择本次登录店铺"; } + /** + * Run business method `buildAdminLoginShopMessage`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shops parameter `shops` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ private String buildAdminLoginShopMessage(List shops) { if (shops == null || shops.isEmpty()) { return "当前暂无启用店铺,可直接登录后台创建店铺"; @@ -1440,12 +2497,24 @@ public class UserServiceImpl extends ServiceImpl implements return "当前已有 " + shops.size() + " 家启用店铺,请选择本次登录店铺"; } + /** + * Run business method `resolveUserLoginShopId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @param requestedShopId parameter `requestedShopId` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ private Long resolveUserLoginShopId(UserDO userDO, Long requestedShopId) { Long normalizedRequestedShopId = validateAndNormalizeShopId(requestedShopId); List activeShopIds = userShopBindingSupport.listActiveShopIdsByUserId(userDO.getId()); if (!activeShopIds.isEmpty()) { if (normalizedRequestedShopId != null) { if (!activeShopIds.contains(normalizedRequestedShopId)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("当前账号无权登录所选店铺"); } return normalizedRequestedShopId; @@ -1453,6 +2522,11 @@ public class UserServiceImpl extends ServiceImpl implements if (activeShopIds.size() == 1) { return activeShopIds.get(0); } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("请选择登录店铺"); } @@ -1468,16 +2542,52 @@ public class UserServiceImpl extends ServiceImpl implements return legacyShopId; } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("请选择店铺"); } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("当前账号没有可登录的店铺,请联系门店处理"); } + /** + * Run business method `buildLoginResponse`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @param currentShopId parameter `currentShopId` supplied by the caller + * @param needSetPassword parameter `needSetPassword` supplied by the caller + * @return private LoginResponseVO result consumed by the caller or returned to the frontend + */ private LoginResponseVO buildLoginResponse(UserDO userDO, Long currentShopId, boolean needSetPassword) { + /** + * Run business method `buildLoginResponse`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @param currentShopId parameter `currentShopId` supplied by the caller + * @param needSetPassword parameter `needSetPassword` supplied by the caller + * @param null parameter `null` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ return buildLoginResponse(userDO, currentShopId, needSetPassword, null); } + /** + * Run business method `buildLoginResponse`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @param currentShopId parameter `currentShopId` supplied by the caller + * @param needSetPassword parameter `needSetPassword` supplied by the caller + * @param previousSessionId parameter `previousSessionId` supplied by the caller + * @return private LoginResponseVO result consumed by the caller or returned to the frontend + */ private LoginResponseVO buildLoginResponse(UserDO userDO, Long currentShopId, boolean needSetPassword, String previousSessionId) { UserSessionService.SessionIssueResult sessionIssueResult = StringUtils.hasText(previousSessionId) ? userSessionService.rotateSession(previousSessionId, userDO.getId(), userDO.getAccount(), currentShopId, userDO.getType()) @@ -1505,8 +2615,16 @@ public class UserServiceImpl extends ServiceImpl implements return responseVO; } + /** + * Run business method `buildLoginUserInfo`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @param currentShopId parameter `currentShopId` supplied by the caller + * @return private LoginResponseVO.UserInfo result consumed by the caller or returned to the frontend + */ private LoginResponseVO.UserInfo buildLoginUserInfo(UserDO userDO, Long currentShopId) { - List activeShopOptions = resolveShopOptions(userDO, true, true); + boolean adminLogin = userDO.getType() != null && userDO.getType() >= 2; + List activeShopOptions = resolveShopOptions(userDO, true, !adminLogin); Long normalizedCurrentShopId = normalizeShopId(currentShopId); String currentShopName = activeShopOptions.stream() .filter(shop -> Objects.equals(shop.getId(), normalizedCurrentShopId)) @@ -1528,12 +2646,23 @@ public class UserServiceImpl extends ServiceImpl implements userInfo.setType(userDO.getType()); userInfo.setShopId(normalizedCurrentShopId); userInfo.setShopName(currentShopName); + ShopVO currentShop = normalizedCurrentShopId == null ? null : shopService.getShopById(normalizedCurrentShopId); + userInfo.setShopAuthorizationExpireTime(currentShop == null ? null : currentShop.getAuthorizationExpireTime()); + userInfo.setShopAuthorizationExpired(currentShop != null && Boolean.TRUE.equals(currentShop.getAuthorizationExpired())); userInfo.setShopIds(activeShopOptions.stream().map(ShopSimpleVO::getId).collect(Collectors.toList())); userInfo.setShopNames(activeShopOptions.stream().map(ShopSimpleVO::getShopName).collect(Collectors.toList())); userInfo.setCreateTime(userDO.getCreateTime()); return userInfo; } + /** + * Run business method `resolveShopOptions`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @param onlyActiveBindings parameter `onlyActiveBindings` supplied by the caller + * @param onlyActiveShops parameter `onlyActiveShops` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ private List resolveShopOptions(UserDO userDO, boolean onlyActiveBindings, boolean onlyActiveShops) { if (userDO == null) { return new ArrayList<>(); @@ -1541,7 +2670,9 @@ public class UserServiceImpl extends ServiceImpl implements List shopOptions; if (Integer.valueOf(4).equals(userDO.getType())) { - shopOptions = new ArrayList<>(userShopBindingSupport.listAllActiveShopOptions()); + shopOptions = new ArrayList<>(onlyActiveShops + ? userShopBindingSupport.listAllActiveShopOptions() + : listEnabledShopOptionsForAdmin()); } else { shopOptions = new ArrayList<>(userShopBindingSupport.listShopOptionsByUserId( userDO.getId(), @@ -1568,21 +2699,78 @@ public class UserServiceImpl extends ServiceImpl implements return shopOptions; } + /** + * Run business method `validateAndNormalizeShopId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ private Long validateAndNormalizeShopId(Long shopId) { Long normalizedShopId = normalizeShopId(shopId); if (normalizedShopId == null) { return null; } if (!userShopBindingSupport.isShopActive(normalizedShopId)) { + if (userShopBindingSupport.isShopEnabledIgnoringAuthorization(normalizedShopId) + && userShopBindingSupport.isShopAuthorizationExpired(normalizedShopId)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("店铺已被冻结"); + } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("所属店铺不存在或已失效"); } return normalizedShopId; } + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private List result consumed by the caller or returned to the frontend + */ + private List listEnabledShopOptionsForAdmin() { + return shopService.listAllShopsForAdmin().stream() + .filter(shop -> Integer.valueOf(1).equals(shop.getStatus())) + .map(shop -> new ShopSimpleVO(shop.getId(), shop.getShopName())) + .collect(Collectors.toList()); + } + + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List listEnabledShopOptionsForUser(Long userId) { + return userShopBindingSupport.listShopOptionsByUserId(userId, true, false).stream() + .filter(shop -> userShopBindingSupport.isShopEnabledIgnoringAuthorization(shop.getId())) + .collect(Collectors.toList()); + } + + /** + * Run business method `validateUserPhone`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param currentUserId parameter `currentUserId` supplied by the caller + * @param required parameter `required` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ private String validateUserPhone(String phone, Long currentUserId, boolean required) { String normalizedPhone = phone == null ? null : phone.trim(); if (!StringUtils.hasText(normalizedPhone)) { if (required) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("手机号不能为空"); } return null; @@ -1591,16 +2779,41 @@ public class UserServiceImpl extends ServiceImpl implements return normalizedPhone; } if (!normalizedPhone.matches(PHONE_REGEX)) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("手机号格式不正确"); } + /** + * Run business method `ensurePhoneNotUsed`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param normalizedPhone parameter `normalizedPhone` supplied by the caller + * @param currentUserId parameter `currentUserId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ ensurePhoneNotUsed(normalizedPhone, currentUserId); return normalizedPhone; } + /** + * Run business method `isDeletedPlaceholderPhone`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @return private boolean result consumed by the caller or returned to the frontend + */ private boolean isDeletedPlaceholderPhone(String phone) { return StringUtils.hasText(phone) && phone.contains(DELETED_PHONE_MARKER); } + /** + * Run business method `ensurePhoneNotUsed`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param currentUserId parameter `currentUserId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void ensurePhoneNotUsed(String phone, Long currentUserId) { LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(UserDO.class) .eq(UserDO::getPhone, phone) @@ -1609,9 +2822,253 @@ public class UserServiceImpl extends ServiceImpl implements wrapper.ne(UserDO::getId, currentUserId); } if (userMapper.selectOne(wrapper) != null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("手机号已被使用"); } } + /** + * Run business method `buildRelationVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return private UserRelationVO result consumed by the caller or returned to the frontend + */ + private UserRelationVO buildRelationVO(Long userId) { + if (userId == null) { + return null; + } + UserRelationDO relation = userRelationMapper.selectOne(new LambdaQueryWrapper() + .eq(UserRelationDO::getUserId, userId) + .eq(UserRelationDO::getIsDelete, 0) + .last("limit 1")); + if (relation == null) { + return null; + } + UserRelationVO vo = new UserRelationVO(); + vo.setUserId(userId); + vo.setShopId(relation.getShopId()); + vo.setShopName(relation.getShopId() == null ? null : Optional.ofNullable(shopService.getShopById(relation.getShopId())).map(ShopVO::getShopName).orElse(null)); + vo.setParentUserId(relation.getParentUserId()); + vo.setParentUserName(relation.getParentUserId() == null ? null : Optional.ofNullable(userMapper.selectById(relation.getParentUserId())).map(UserDO::getNickname).orElse(null)); + vo.setParentRoleType(relation.getParentRoleType()); + vo.setParentRoleTypeName(resolveUserTypeName(relation.getParentRoleType())); + vo.setSourceType(relation.getSourceType()); + vo.setSourceTypeName(resolveSourceTypeName(relation.getSourceType())); + return vo; + } + + /** + * Run business method `applyRelationInfo`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userVO parameter `userVO` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void applyRelationInfo(UserVO userVO, Long userId) { + UserRelationVO relation = buildRelationVO(userId); + if (relation != null) { + userVO.setParentUserId(relation.getParentUserId()); + userVO.setParentUserName(relation.getParentUserName()); + userVO.setParentUserTypeName(relation.getParentRoleTypeName()); + userVO.setRelationSourceType(relation.getSourceTypeName()); + } + UserShopRoleDO roleBinding = userShopRoleMapper.selectOne(new LambdaQueryWrapper() + .eq(UserShopRoleDO::getUserId, userId) + .eq(UserShopRoleDO::getIsDelete, 0) + .eq(UserShopRoleDO::getStatus, 1) + .last("limit 1")); + if (roleBinding != null) { + userVO.setShopRoleId(roleBinding.getRoleId()); + } + } + + /** + * Run business method `resolveUserTypeName`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param type parameter `type` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String resolveUserTypeName(Integer type) { + return switch (type == null ? -1 : type) { + case 0 -> "普通用户"; + case 2 -> "店长"; + case 3 -> "美甲师"; + case 4 -> "管理员"; + default -> "未知"; + }; + } + + /** + * Run business method `resolveSourceTypeName`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param sourceType parameter `sourceType` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String resolveSourceTypeName(String sourceType) { + if (!StringUtils.hasText(sourceType)) { + return "-"; + } + return switch (sourceType) { + case "INVITE" -> "邀请码"; + case "DEFAULT_MANAGER" -> "默认店长"; + case "MANUAL" -> "手动"; + default -> sourceType; + }; + } + + /** + * Run business method `maskPhone`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String maskPhone(String phone) { + if (!StringUtils.hasText(phone) || phone.length() < 7) { + return phone; + } + return phone.substring(0, 3) + "****" + phone.substring(phone.length() - 4); + } + + /** + * Run business method `maskEmail`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param email parameter `email` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ + private String maskEmail(String email) { + if (!StringUtils.hasText(email) || !email.contains("@")) { + return email; + } + int at = email.indexOf('@'); + return (at <= 1 ? "***" : email.substring(0, 1) + "***") + email.substring(at); + } + + /** + * Run business method `resolveRegisterShopId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requestedShopId parameter `requestedShopId` supplied by the caller + * @param inviteCode parameter `inviteCode` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ + private Long resolveRegisterShopId(Long requestedShopId, String inviteCode) { + if (StringUtils.hasText(inviteCode)) { + UserInviteCodeDO code = userInviteCodeMapper.selectOne(new LambdaQueryWrapper() + .eq(UserInviteCodeDO::getInviteCode, inviteCode.trim()) + .eq(UserInviteCodeDO::getIsDelete, 0) + .eq(UserInviteCodeDO::getStatus, 1) + .last("limit 1")); + if (code != null) { + return code.getShopId(); + } + } + Long normalized = validateAndNormalizeShopId(requestedShopId); + if (normalized != null) { + return normalized; + } + Long currentShopId = RequestShopContext.getCurrentShopId(); + if (currentShopId != null) { + return currentShopId; + } + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请选择店铺"); + } + + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @param inviteCode parameter `inviteCode` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void createRelationForRegister(Long userId, Long shopId, String inviteCode) { + UserRelationDO relation = new UserRelationDO(); + relation.setUserId(userId); + relation.setShopId(shopId); + relation.setCreatorId(userId); + relation.setSourceType(StringUtils.hasText(inviteCode) ? "INVITE" : "DEFAULT_MANAGER"); + relation.setIsDelete(0); + if (StringUtils.hasText(inviteCode)) { + UserInviteCodeDO code = userInviteCodeMapper.selectOne(new LambdaQueryWrapper() + .eq(UserInviteCodeDO::getInviteCode, inviteCode.trim()) + .eq(UserInviteCodeDO::getIsDelete, 0) + .last("limit 1")); + if (code != null) { + relation.setParentUserId(code.getOwnerUserId()); + UserDO parent = userMapper.selectById(code.getOwnerUserId()); + relation.setParentRoleType(parent == null ? null : parent.getType()); + code.setUseCount((code.getUseCount() == null ? 0 : code.getUseCount()) + 1); + code.setUpdateTime(LocalDateTime.now()); + userInviteCodeMapper.updateById(code); + } + } else if (shopId != null) { + UserDO manager = userMapper.selectOne(new LambdaQueryWrapper() + .eq(UserDO::getShopId, shopId) + .eq(UserDO::getType, 2) + .eq(UserDO::getIsDelete, 0) + .eq(UserDO::getStatus, 1) + .last("limit 1")); + relation.setParentUserId(manager == null ? null : manager.getId()); + relation.setParentRoleType(manager == null ? null : manager.getType()); + } + userRelationMapper.insert(relation); + } + + /** + * Run business method `resolveRelationFilteredUserIds`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param roleId parameter `roleId` supplied by the caller + * @param parentUserId parameter `parentUserId` supplied by the caller + * @param sourceType parameter `sourceType` supplied by the caller + * @return private Set result consumed by the caller or returned to the frontend + */ + private Set resolveRelationFilteredUserIds(Long roleId, Long parentUserId, String sourceType) { + if (roleId == null && parentUserId == null && !StringUtils.hasText(sourceType)) { + return null; + } + List relations = userRelationMapper.selectList(new LambdaQueryWrapper() + .eq(UserRelationDO::getIsDelete, 0)); + if (roleId != null) { + Set roleUserIds = userShopRoleMapper.selectList(new LambdaQueryWrapper() + .eq(UserShopRoleDO::getRoleId, roleId) + .eq(UserShopRoleDO::getIsDelete, 0) + .eq(UserShopRoleDO::getStatus, 1)) + .stream().map(UserShopRoleDO::getUserId).filter(Objects::nonNull).collect(Collectors.toSet()); + relations = relations.stream() + .filter(r -> roleUserIds.contains(r.getParentUserId())) + .collect(Collectors.toList()); + } + if (parentUserId != null) { + relations = relations.stream() + .filter(r -> Objects.equals(parentUserId, r.getParentUserId())) + .collect(Collectors.toList()); + } + if (StringUtils.hasText(sourceType)) { + relations = relations.stream() + .filter(r -> sourceType.equals(r.getSourceType())) + .collect(Collectors.toList()); + } + return relations.stream() + .map(UserRelationDO::getUserId) + .filter(Objects::nonNull) + .collect(Collectors.toCollection(LinkedHashSet::new)); + } + + /** + * Run business method `PermissionSeed`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param permissionName parameter `permissionName` supplied by the caller + * @param permissionGroup parameter `permissionGroup` supplied by the caller + * @param description parameter `description` supplied by the caller + * @return private record result consumed by the caller or returned to the frontend + */ private record PermissionSeed(String permissionName, String permissionGroup, String description) { } } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/VerificationCodeServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/VerificationCodeServiceImpl.java index f092a885..7be43f93 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/VerificationCodeServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/VerificationCodeServiceImpl.java @@ -23,11 +23,21 @@ public class VerificationCodeServiceImpl implements VerificationCodeService { private static final int CODE_LENGTH = 6; private static final int CODE_EXPIRE_MINUTES = 5; private static final int RESEND_INTERVAL_SECONDS = 60; - + /** + * Variable `redisTemplate`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final StringRedisTemplate redisTemplate; + /** + * Variable `messageHubClientService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final MessageHubClientService messageHubClientService; @Override + /** + * Run business method `generateVerificationCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return String result consumed by the caller or returned to the frontend + */ public String generateVerificationCode() { SecureRandom random = new SecureRandom(); StringBuilder code = new StringBuilder(); @@ -38,7 +48,30 @@ public class VerificationCodeServiceImpl implements VerificationCodeService { } @Override + /** + * Send or dispatch a message. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + */ public void sendVerificationCode(String phone) { + /** + * Send or dispatch a message. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param USER_LOGIN_SMS_CODE parameter `USER_LOGIN_SMS_CODE` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + sendVerificationCode(phone, "USER_LOGIN_SMS_CODE"); + } + + @Override + /** + * Send or dispatch a message. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param sceneCode parameter `sceneCode` supplied by the caller + */ + public void sendVerificationCode(String phone, String sceneCode) { String code = generateVerificationCode(); String codeKey = CODE_PREFIX + phone; @@ -48,11 +81,18 @@ public class VerificationCodeServiceImpl implements VerificationCodeService { redisTemplate.opsForValue().set(sendTimeKey, String.valueOf(System.currentTimeMillis()), Duration.ofSeconds(RESEND_INTERVAL_SECONDS)); - messageHubClientService.sendSmsVerificationCode(phone, code); - log.info("验证码已发送,手机号: {}", phone); + messageHubClientService.sendSmsVerificationCode(sceneCode, phone, code); + log.info("验证码已发送,手机号: {}, sceneCode: {}", phone, sceneCode); } @Override + /** + * Run business method `verifyCode`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @param code parameter `code` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ public boolean verifyCode(String phone, String code) { String codeKey = CODE_PREFIX + phone; String storedCode = redisTemplate.opsForValue().get(codeKey); @@ -73,6 +113,12 @@ public class VerificationCodeServiceImpl implements VerificationCodeService { } @Override + /** + * Run business method `canResend`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ public boolean canResend(String phone) { String sendTimeKey = SEND_TIME_PREFIX + phone; String sendTime = redisTemplate.opsForValue().get(sendTimeKey); diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/VipBenefitServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/VipBenefitServiceImpl.java index 72833b31..ca39cafc 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/VipBenefitServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/VipBenefitServiceImpl.java @@ -23,10 +23,18 @@ import java.util.stream.Collectors; @Service @RequiredArgsConstructor public class VipBenefitServiceImpl extends ServiceImpl implements VipBenefitService { - + /** + * Variable `vipBenefitMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final VipBenefitMapper vipBenefitMapper; @Override + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param vipBenefitDTO parameter `vipBenefitDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ public Long createVipBenefit(VipBenefitDTO vipBenefitDTO) { VipBenefitDO vipBenefitDO = new VipBenefitDO(); vipBenefitDO.setBenefitInfo(vipBenefitDTO.getBenefitInfo()); @@ -36,6 +44,13 @@ public class VipBenefitServiceImpl extends ServiceImpl 0; } @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return VipBenefitVO result consumed by the caller or returned to the frontend + */ public VipBenefitVO getVipBenefitById(Long id) { VipBenefitDO vipBenefitDO = vipBenefitMapper.selectById(id); if (vipBenefitDO == null) { return null; } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param vipBenefitDO parameter `vipBenefitDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ return convertToVO(vipBenefitDO); } @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ public List listAllVipBenefits() { List vipBenefitDOs = vipBenefitMapper.selectList(null); return vipBenefitDOs.stream() @@ -69,6 +107,12 @@ public class VipBenefitServiceImpl extends ServiceImpl result consumed by the caller or returned to the frontend + */ public List listVipBenefitsByRequiredVipLevel(String requiredVipLevel) { List vipBenefitDOs = vipBenefitMapper.selectList( Wrappers.lambdaQuery(VipBenefitDO.class) diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/VipInfoServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/VipInfoServiceImpl.java index 2c973876..4977863a 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/VipInfoServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/VipInfoServiceImpl.java @@ -23,10 +23,18 @@ import java.util.stream.Collectors; @Service @RequiredArgsConstructor public class VipInfoServiceImpl extends ServiceImpl implements VipInfoService { - + /** + * Variable `vipInfoMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final VipInfoMapper vipInfoMapper; @Override + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param vipInfoDTO parameter `vipInfoDTO` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ public Long createVipInfo(VipInfoDTO vipInfoDTO) { VipInfoDO vipInfoDO = new VipInfoDO(); vipInfoDO.setUserId(vipInfoDTO.getUserId()); @@ -41,6 +49,13 @@ public class VipInfoServiceImpl extends ServiceImpl im } @Override + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @param vipInfoDTO parameter `vipInfoDTO` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ public boolean updateVipInfo(Long id, VipInfoDTO vipInfoDTO) { VipInfoDO vipInfoDO = vipInfoMapper.selectById(id); if (vipInfoDO == null) { @@ -57,20 +72,43 @@ public class VipInfoServiceImpl extends ServiceImpl im } @Override + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ public boolean deleteVipInfo(Long id) { return vipInfoMapper.deleteById(id) > 0; } @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return VipInfoVO result consumed by the caller or returned to the frontend + */ public VipInfoVO getVipInfoById(Long id) { VipInfoDO vipInfoDO = vipInfoMapper.selectById(id); if (vipInfoDO == null) { return null; } + /** + * Run business method `convertToVO`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param vipInfoDO parameter `vipInfoDO` supplied by the caller + * @return return result consumed by the caller or returned to the frontend + */ return convertToVO(vipInfoDO); } @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return List result consumed by the caller or returned to the frontend + */ public List listAllVipInfos() { List vipInfoDOs = vipInfoMapper.selectList(null); return vipInfoDOs.stream() @@ -79,6 +117,12 @@ public class VipInfoServiceImpl extends ServiceImpl im } @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param vipLevel parameter `vipLevel` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ public List listVipInfosByVipLevel(String vipLevel) { List vipInfoDOs = vipInfoMapper.selectList( Wrappers.lambdaQuery(VipInfoDO.class) diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/VipRechargePlanServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/VipRechargePlanServiceImpl.java new file mode 100644 index 00000000..1bdcd584 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/VipRechargePlanServiceImpl.java @@ -0,0 +1,325 @@ +package com.xiaowang.yuminailcore.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.xiaowang.yuminailcore.dto.VipRechargePlanDTO; +import com.xiaowang.yuminailcore.entity.ShopDO; +import com.xiaowang.yuminailcore.entity.UserDO; +import com.xiaowang.yuminailcore.entity.UserShopBindingDO; +import com.xiaowang.yuminailcore.entity.VipRechargePlanDO; +import com.xiaowang.yuminailcore.mapper.ShopMapper; +import com.xiaowang.yuminailcore.mapper.UserMapper; +import com.xiaowang.yuminailcore.mapper.UserShopBindingMapper; +import com.xiaowang.yuminailcore.mapper.VipRechargePlanMapper; +import com.xiaowang.yuminailcore.service.VipRechargePlanService; +import com.xiaowang.yuminailcore.support.AdminScopeHelper; +import com.xiaowang.yuminailcore.vo.VipRechargePlanVO; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +/** + * VipRechargePlanServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ +public class VipRechargePlanServiceImpl extends ServiceImpl implements VipRechargePlanService { + /** + * Variable `planMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final VipRechargePlanMapper planMapper; + /** + * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final ShopMapper shopMapper; + /** + * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserMapper userMapper; + /** + * Variable `userShopBindingMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final UserShopBindingMapper userShopBindingMapper; + /** + * Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ + private final AdminScopeHelper adminScopeHelper; + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Create a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Long result consumed by the caller or returned to the frontend + */ + public Long createPlan(UserDO currentUser, VipRechargePlanDTO dto) { + Long shopId = resolveManagedShopId(currentUser, dto.getShopId()); + VipRechargePlanDO plan = new VipRechargePlanDO(); + /** + * Run business method `apply`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param plan parameter `plan` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + apply(plan, dto, shopId); + plan.setIsDelete(0); + planMapper.insert(plan); + return plan.getId(); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Update an existing record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean updatePlan(UserDO currentUser, Long id, VipRechargePlanDTO dto) { + VipRechargePlanDO plan = requirePlan(id); + /** + * Run business method `ensurePlanAccessible`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param plan parameter `plan` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensurePlanAccessible(currentUser, plan); + Long shopId = resolveManagedShopId(currentUser, dto.getShopId() == null ? plan.getShopId() : dto.getShopId()); + /** + * Run business method `apply`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param plan parameter `plan` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + apply(plan, dto, shopId); + planMapper.updateById(plan); + return true; + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Change the enabled/status flag of one record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param id parameter `id` supplied by the caller + * @param status parameter `status` supplied by the caller + * @return Boolean result consumed by the caller or returned to the frontend + */ + public Boolean updateStatus(UserDO currentUser, Long id, Integer status) { + VipRechargePlanDO plan = requirePlan(id); + /** + * Run business method `ensurePlanAccessible`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param plan parameter `plan` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensurePlanAccessible(currentUser, plan); + plan.setStatus(Integer.valueOf(1).equals(status) ? 1 : 0); + planMapper.updateById(plan); + return true; + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listAdminPlans(UserDO currentUser, Long shopId) { + Long scopedShopId = adminScopeHelper.resolveShopScope(currentUser, shopId); + LambdaQueryWrapper wrapper = new LambdaQueryWrapper() + .eq(VipRechargePlanDO::getIsDelete, 0) + .orderByAsc(VipRechargePlanDO::getSortOrder) + .orderByDesc(VipRechargePlanDO::getCreateTime); + if (scopedShopId != null && scopedShopId > 0) { + wrapper.eq(VipRechargePlanDO::getShopId, scopedShopId); + } + return toVOList(planMapper.selectList(wrapper)); + } + + @Override + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ + public List listMyPlans(Long userId) { + UserDO user = userMapper.selectById(userId); + if (user == null || Integer.valueOf(1).equals(user.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("用户不存在"); + } + Set shopIds = new LinkedHashSet<>(); + if (user.getShopId() != null && user.getShopId() > 0) { + shopIds.add(user.getShopId()); + } + userShopBindingMapper.selectList(new LambdaQueryWrapper() + .eq(UserShopBindingDO::getUserId, userId) + .eq(UserShopBindingDO::getIsDelete, 0) + .eq(UserShopBindingDO::getStatus, 1)) + .forEach(binding -> { + if (binding.getShopId() != null && binding.getShopId() > 0) shopIds.add(binding.getShopId()); + }); + if (shopIds.isEmpty()) { + return List.of(); + } + return toVOList(planMapper.selectList(new LambdaQueryWrapper() + .eq(VipRechargePlanDO::getIsDelete, 0) + .eq(VipRechargePlanDO::getStatus, 1) + .in(VipRechargePlanDO::getShopId, shopIds) + .orderByAsc(VipRechargePlanDO::getSortOrder) + .orderByAsc(VipRechargePlanDO::getRechargeAmount))); + } + + /** + * Run business method `apply`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param plan parameter `plan` supplied by the caller + * @param dto parameter `dto` supplied by the caller + * @param shopId parameter `shopId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void apply(VipRechargePlanDO plan, VipRechargePlanDTO dto, Long shopId) { + /** + * Run business method `ensureShopExists`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ + ensureShopExists(shopId); + plan.setShopId(shopId); + plan.setTitle(dto.getTitle().trim()); + plan.setRechargeAmount(dto.getRechargeAmount()); + plan.setGiftAmount(dto.getGiftAmount()); + plan.setVipLevel(dto.getVipLevel().trim()); + plan.setDescription(dto.getDescription()); + plan.setSortOrder(dto.getSortOrder() == null ? 0 : dto.getSortOrder()); + plan.setStatus(Integer.valueOf(0).equals(dto.getStatus()) ? 0 : 1); + } + + /** + * Run business method `resolveManagedShopId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param requestedShopId parameter `requestedShopId` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ + private Long resolveManagedShopId(UserDO currentUser, Long requestedShopId) { + Long shopId = adminScopeHelper.resolveShopScope(currentUser, requestedShopId); + if (shopId == null || shopId <= 0) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("请选择店铺"); + } + adminScopeHelper.ensureShopAccessible(currentUser, shopId, "无权维护其他店铺充值档位"); + return shopId; + } + + /** + * Run business method `ensurePlanAccessible`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param currentUser parameter `currentUser` supplied by the caller + * @param plan parameter `plan` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void ensurePlanAccessible(UserDO currentUser, VipRechargePlanDO plan) { + adminScopeHelper.ensureShopAccessible(currentUser, plan.getShopId(), "无权维护其他店铺充值档位"); + } + + /** + * Run business method `requirePlan`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param id parameter `id` supplied by the caller + * @return private VipRechargePlanDO result consumed by the caller or returned to the frontend + */ + private VipRechargePlanDO requirePlan(Long id) { + VipRechargePlanDO plan = planMapper.selectById(id); + if (plan == null || Integer.valueOf(1).equals(plan.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("充值档位不存在"); + } + return plan; + } + + /** + * Run business method `ensureShopExists`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ + private void ensureShopExists(Long shopId) { + ShopDO shop = shopMapper.selectById(shopId); + if (shop == null || Integer.valueOf(1).equals(shop.getIsDelete())) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ + throw new RuntimeException("店铺不存在"); + } + } + + /** + * Run business method `toVOList`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param plans parameter `plans` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ + private List toVOList(List plans) { + Set shopIds = plans.stream().map(VipRechargePlanDO::getShopId).filter(Objects::nonNull).collect(Collectors.toSet()); + Map shopNameMap = shopIds.isEmpty() + ? Map.of() + : shopMapper.selectList(new LambdaQueryWrapper().in(ShopDO::getId, shopIds)) + .stream() + .collect(Collectors.toMap(ShopDO::getId, ShopDO::getShopName, (a, b) -> a)); + return plans.stream().map(plan -> { + VipRechargePlanVO vo = new VipRechargePlanVO(); + vo.setId(plan.getId()); + vo.setShopId(plan.getShopId()); + vo.setShopName(shopNameMap.get(plan.getShopId())); + vo.setTitle(plan.getTitle()); + vo.setRechargeAmount(plan.getRechargeAmount()); + vo.setGiftAmount(plan.getGiftAmount()); + vo.setVipLevel(plan.getVipLevel()); + vo.setDescription(plan.getDescription()); + vo.setSortOrder(plan.getSortOrder()); + vo.setStatus(plan.getStatus()); + vo.setCreateTime(plan.getCreateTime()); + vo.setUpdateTime(plan.getUpdateTime()); + return vo; + }).collect(Collectors.toList()); + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/WechatMiniAuthServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/WechatMiniAuthServiceImpl.java index 1014f10e..3cdbcd9c 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/WechatMiniAuthServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/WechatMiniAuthServiceImpl.java @@ -46,17 +46,46 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { private static final String PHONE_REGEX = "^1[3-9]\\d{9}$"; private static final String TICKET_KEY_PREFIX = "user:wechat-mini:login-ticket:"; private static final Duration TICKET_TTL = Duration.ofMinutes(5); - + /** + * Variable `wechatMiniClientService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final WechatMiniClientService wechatMiniClientService; + /** + * Variable `wechatMiniBindingMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final WechatMiniBindingMapper wechatMiniBindingMapper; + /** + * Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final UserMapper userMapper; + /** + * Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final UserService userService; + /** + * Variable `userShopBindingSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final UserShopBindingSupport userShopBindingSupport; + /** + * Variable `redisTemplate`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final StringRedisTemplate redisTemplate; + /** + * Variable `objectMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final ObjectMapper objectMapper; + /** + * Variable `snowflakeIdGenerator`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; @Override + /** + * Run business method `autoLogin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return WechatMiniLoginResultVO result consumed by the caller or returned to the frontend + */ public WechatMiniLoginResultVO autoLogin(WechatMiniAutoLoginRequestDTO requestDTO) { WechatMiniClientService.SessionInfo sessionInfo; try { @@ -80,10 +109,21 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { } @Override + /** + * Run business method `phoneLogin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return WechatMiniLoginResultVO result consumed by the caller or returned to the frontend + */ public WechatMiniLoginResultVO phoneLogin(WechatMiniPhoneLoginRequestDTO requestDTO) { WechatMiniClientService.SessionInfo sessionInfo = wechatMiniClientService.code2Session(requestDTO.getWxCode()); String phone = normalizePhone(wechatMiniClientService.getPhoneNumber(requestDTO.getPhoneCode())); if (!StringUtils.hasText(phone) || !phone.matches(PHONE_REGEX)) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new BusinessException("获取到的微信手机号格式不正确"); } @@ -93,6 +133,11 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { if (boundUser != null) { UserDO phoneUser = findActiveUserByPhone(phone); if (phoneUser != null && !Objects.equals(phoneUser.getId(), boundUser.getId())) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new BusinessException("当前微信已绑定其他账号,无法关联该手机号"); } return loginOrSelectShop(boundUser, normalizeShopId(requestDTO.getPreferredShopId()), sessionInfo, false); @@ -101,6 +146,12 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { UserDO phoneUser = findActiveUserByPhone(phone); if (phoneUser != null) { + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phoneUser parameter `phoneUser` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ assertUserAvailable(phoneUser); return loginOrSelectShop(phoneUser, normalizeShopId(requestDTO.getPreferredShopId()), sessionInfo, false); } @@ -118,9 +169,20 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { @Override @Transactional(rollbackFor = Exception.class) + /** + * Run business method `confirmLogin`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param requestDTO parameter `requestDTO` supplied by the caller + * @return WechatMiniLoginResultVO result consumed by the caller or returned to the frontend + */ public WechatMiniLoginResultVO confirmLogin(WechatMiniConfirmLoginRequestDTO requestDTO) { Long shopId = normalizeShopId(requestDTO.getShopId()); if (shopId == null) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new BusinessException("请选择登录门店"); } @@ -131,6 +193,11 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { } else if (StringUtils.hasText(ticketPayload.getPhone())) { loginResponse = userService.loginByVerifiedPhone(ticketPayload.getPhone(), shopId); } else { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new BusinessException("登录票据数据不完整,请重新发起微信一键登录"); } @@ -144,6 +211,11 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { } @Override + /** + * Run business method `invalidateBindingsByUserId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + */ public void invalidateBindingsByUserId(Long userId) { if (userId == null) { return; @@ -182,25 +254,59 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { ); } + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param bindingDO parameter `bindingDO` supplied by the caller + * @return private UserDO result consumed by the caller or returned to the frontend + */ private UserDO getAvailableBoundUser(WechatMiniBindingDO bindingDO) { UserDO userDO = userMapper.selectById(bindingDO.getUserId()); if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { deactivateBinding(bindingDO.getId()); return null; } + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ assertUserAvailable(userDO); return userDO; } + /** + * Run business method `assertUserAvailable`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userDO parameter `userDO` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void assertUserAvailable(UserDO userDO) { if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new BusinessException("账号不存在"); } if (userDO.getStatus() != null && !Integer.valueOf(1).equals(userDO.getStatus())) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new BusinessException("账号已停用"); } } + /** + * Run business method `findActiveUserByPhone`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @return private UserDO result consumed by the caller or returned to the frontend + */ private UserDO findActiveUserByPhone(String phone) { if (!StringUtils.hasText(phone)) { return null; @@ -213,6 +319,12 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { ); } + /** + * Run business method `findBindingByOpenId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param openId parameter `openId` supplied by the caller + * @return private WechatMiniBindingDO result consumed by the caller or returned to the frontend + */ private WechatMiniBindingDO findBindingByOpenId(String openId) { return wechatMiniBindingMapper.selectOne( new LambdaQueryWrapper() @@ -223,6 +335,13 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { ); } + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param appId parameter `appId` supplied by the caller + * @param openId parameter `openId` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ private List listBindingsByOpenId(String appId, String openId) { if (!StringUtils.hasText(openId)) { return List.of(); @@ -238,6 +357,13 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { ); } + /** + * List records for the current query or current user scope. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param appId parameter `appId` supplied by the caller + * @param userId parameter `userId` supplied by the caller + * @return private List result consumed by the caller or returned to the frontend + */ private List listBindingsByUserId(String appId, Long userId) { if (userId == null) { return List.of(); @@ -254,8 +380,20 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { } @Transactional(rollbackFor = Exception.class) + /** + * Run business method `ensureBinding`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param openId parameter `openId` supplied by the caller + * @param unionId parameter `unionId` supplied by the caller + */ protected void ensureBinding(Long userId, String openId, String unionId) { if (userId == null || !StringUtils.hasText(openId)) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new BusinessException("微信绑定信息不完整"); } @@ -263,6 +401,15 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { List openIdBindings = listBindingsByOpenId(appId, openId); List userBindings = listBindingsByUserId(appId, userId); + /** + * Run business method `validateExclusiveActiveBinding`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param openId parameter `openId` supplied by the caller + * @param openIdBindings parameter `openIdBindings` supplied by the caller + * @param userBindings parameter `userBindings` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ validateExclusiveActiveBinding(userId, openId, openIdBindings, userBindings); WechatMiniBindingDO targetBinding = pickTargetBinding(userId, openId, openIdBindings, userBindings); @@ -288,6 +435,12 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { deactivateDuplicateBindings(targetBinding.getId(), mergeBindings(openIdBindings, userBindings)); } + /** + * Run business method `deactivateBinding`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param bindingId parameter `bindingId` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void deactivateBinding(Long bindingId) { if (bindingId == null) { return; @@ -311,6 +464,11 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { .filter(binding -> Integer.valueOf(1).equals(binding.getStatus())) .anyMatch(binding -> !Objects.equals(binding.getUserId(), userId)); if (openIdBoundToOtherUser) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new BusinessException("当前微信已绑定其他账号,无法完成登录"); } @@ -318,6 +476,11 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { .filter(binding -> Integer.valueOf(1).equals(binding.getStatus())) .anyMatch(binding -> !Objects.equals(binding.getOpenId(), openId)); if (userBoundToOtherWechat) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new BusinessException("当前账号已绑定其他微信,请联系管理员处理"); } } @@ -356,6 +519,13 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { return merged; } + /** + * Run business method `appendUniqueBinding`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param merged parameter `merged` supplied by the caller + * @param candidate parameter `candidate` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void appendUniqueBinding(List merged, WechatMiniBindingDO candidate) { if (candidate == null) { return; @@ -366,12 +536,26 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { } } + /** + * Run business method `deactivateDuplicateBindings`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param keepBindingId parameter `keepBindingId` supplied by the caller + * @param bindings parameter `bindings` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void deactivateDuplicateBindings(Long keepBindingId, List bindings) { bindings.stream() .filter(binding -> binding.getId() != null && !Objects.equals(binding.getId(), keepBindingId)) .forEach(binding -> deactivateBinding(binding.getId())); } + /** + * Run business method `resolvePreferredOrOnlyShop`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shops parameter `shops` supplied by the caller + * @param preferredShopId parameter `preferredShopId` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ private Long resolvePreferredOrOnlyShop(List shops, Long preferredShopId) { Long normalizedPreferredShopId = normalizeShopId(preferredShopId); if (normalizedPreferredShopId != null) { @@ -395,6 +579,12 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { return WechatMiniLoginResultVO.selectShop(message, ticket, Boolean.TRUE.equals(ticketPayload.getNewUser()), shops); } + /** + * Run business method `storeTicketPayload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ticketPayload parameter `ticketPayload` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ private String storeTicketPayload(TicketPayload ticketPayload) { String ticket = "wxmini_" + snowflakeIdGenerator.nextIdString(); try { @@ -405,30 +595,71 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { ); return ticket; } catch (JsonProcessingException exception) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param exception parameter `exception` supplied by the caller + * @return throw new result consumed by the caller or returned to the frontend + */ throw new BusinessException("生成微信登录票据失败", exception); } } + /** + * Run business method `readTicketPayload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ticket parameter `ticket` supplied by the caller + * @return private TicketPayload result consumed by the caller or returned to the frontend + */ private TicketPayload readTicketPayload(String ticket) { String payloadJson = redisTemplate.opsForValue().get(TICKET_KEY_PREFIX + ticket); if (!StringUtils.hasText(payloadJson)) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new BusinessException("登录票据已失效,请重新发起微信一键登录"); } try { return objectMapper.readValue(payloadJson, TicketPayload.class); } catch (JsonProcessingException exception) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param exception parameter `exception` supplied by the caller + * @return throw new result consumed by the caller or returned to the frontend + */ throw new BusinessException("解析微信登录票据失败", exception); } } + /** + * Delete, revoke, or logically remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param ticket parameter `ticket` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void deleteTicketPayload(String ticket) { redisTemplate.delete(TICKET_KEY_PREFIX + ticket); } + /** + * Run business method `normalizeShopId`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param shopId parameter `shopId` supplied by the caller + * @return private Long result consumed by the caller or returned to the frontend + */ private Long normalizeShopId(Long shopId) { return shopId != null && shopId > 0 ? shopId : null; } + /** + * Run business method `normalizePhone`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phone parameter `phone` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ private String normalizePhone(String phone) { return phone == null ? "" : phone.trim(); } @@ -441,9 +672,24 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { private String unionId; private Boolean newUser; + /** + * Run business method `TicketPayload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return public result consumed by the caller or returned to the frontend + */ public TicketPayload() { } + /** + * Run business method `TicketPayload`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param phone parameter `phone` supplied by the caller + * @param openId parameter `openId` supplied by the caller + * @param unionId parameter `unionId` supplied by the caller + * @param newUser parameter `newUser` supplied by the caller + * @return public result consumed by the caller or returned to the frontend + */ public TicketPayload(Long userId, String phone, String openId, String unionId, Boolean newUser) { this.userId = userId; this.phone = phone; diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/WechatMiniClientServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/WechatMiniClientServiceImpl.java index 59b4af28..d6817a3b 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/WechatMiniClientServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/WechatMiniClientServiceImpl.java @@ -30,17 +30,44 @@ public class WechatMiniClientServiceImpl implements WechatMiniClientService { private static final String ACCESS_TOKEN_CACHE_KEY_PREFIX = "wechat:mini:access-token:"; private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token"; - + /** + * Variable `restTemplate`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final RestTemplate restTemplate; + /** + * Variable `redisTemplate`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final StringRedisTemplate redisTemplate; + /** + * Variable `objectMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final ObjectMapper objectMapper; + /** + * Variable `properties`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. + */ private final WechatMiniProperties properties; @Override + /** + * Run business method `code2Session`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param wxCode parameter `wxCode` supplied by the caller + * @return SessionInfo result consumed by the caller or returned to the frontend + */ public SessionInfo code2Session(String wxCode) { if (!StringUtils.hasText(wxCode)) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new BusinessException("微信登录凭证不能为空"); } + /** + * Run business method `requireConfiguredCredentials`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return result consumed by the caller or returned to the frontend + */ requireConfiguredCredentials(); Map response = readJsonResponse( doGetForString( @@ -55,17 +82,40 @@ public class WechatMiniClientServiceImpl implements WechatMiniClientService { ), "获取微信登录身份失败" ); + /** + * Run business method `assertWechatResponseOk`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param response parameter `response` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ assertWechatResponseOk(response, "获取微信登录身份失败"); String openId = asText(response.get("openid")); if (!StringUtils.hasText(openId)) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param openid parameter `openid` supplied by the caller + * @return throw new result consumed by the caller or returned to the frontend + */ throw new BusinessException("获取微信登录身份失败:缺少 openid"); } return new SessionInfo(openId, asText(response.get("unionid")), asText(response.get("session_key"))); } @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param phoneCode parameter `phoneCode` supplied by the caller + * @return String result consumed by the caller or returned to the frontend + */ public String getPhoneNumber(String phoneCode) { if (!StringUtils.hasText(phoneCode)) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new BusinessException("微信手机号凭证不能为空"); } @@ -84,15 +134,31 @@ public class WechatMiniClientServiceImpl implements WechatMiniClientService { ), "获取微信手机号失败" ); + /** + * Run business method `assertWechatResponseOk`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param response parameter `response` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ assertWechatResponseOk(response, "获取微信手机号失败"); Object phoneInfoRaw = response.get("phone_info"); if (phoneInfoRaw == null) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new BusinessException("获取微信手机号失败:未返回手机号信息"); } Map phoneInfo = objectMapper.convertValue(phoneInfoRaw, new TypeReference>() { }); if (phoneInfo == null || phoneInfo.isEmpty()) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new BusinessException("获取微信手机号失败:未返回手机号信息"); } @@ -101,18 +167,43 @@ public class WechatMiniClientServiceImpl implements WechatMiniClientService { phoneNumber = asText(phoneInfo.get("purePhoneNumber")); } if (!StringUtils.hasText(phoneNumber)) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new BusinessException("获取微信手机号失败:未返回手机号信息"); } return phoneNumber; } @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return String result consumed by the caller or returned to the frontend + */ public String getConfiguredAppId() { + /** + * Run business method `requireConfiguredCredentials`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return result consumed by the caller or returned to the frontend + */ requireConfiguredCredentials(); return properties.getAppId(); } + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private String result consumed by the caller or returned to the frontend + */ private String getAccessToken() { + /** + * Run business method `requireConfiguredCredentials`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return result consumed by the caller or returned to the frontend + */ requireConfiguredCredentials(); String cacheKey = ACCESS_TOKEN_CACHE_KEY_PREFIX + properties.getAppId(); String cachedToken = redisTemplate.opsForValue().get(cacheKey); @@ -132,10 +223,22 @@ public class WechatMiniClientServiceImpl implements WechatMiniClientService { ), "获取微信 access_token 失败" ); + /** + * Run business method `assertWechatResponseOk`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param response parameter `response` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ assertWechatResponseOk(response, "获取微信 access_token 失败"); String accessToken = asText(response.get("access_token")); if (!StringUtils.hasText(accessToken)) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param access_token parameter `access_token` supplied by the caller + * @return throw new result consumed by the caller or returned to the frontend + */ throw new BusinessException("获取微信 access_token 失败:未返回 access_token"); } @@ -146,40 +249,103 @@ public class WechatMiniClientServiceImpl implements WechatMiniClientService { return accessToken; } + /** + * Run business method `requireConfiguredCredentials`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return private void result consumed by the caller or returned to the frontend + */ private void requireConfiguredCredentials() { if (!StringUtils.hasText(properties.getAppId()) || !StringUtils.hasText(properties.getAppSecret())) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param appIdappSecret parameter `appIdappSecret` supplied by the caller + * @return throw new result consumed by the caller or returned to the frontend + */ throw new BusinessException("微信小程序登录未配置 appId/appSecret"); } } + /** + * Run business method `doGetForString`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param url parameter `url` supplied by the caller + * @param defaultMessage parameter `defaultMessage` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ private String doGetForString(String url, String defaultMessage) { try { return restTemplate.getForObject(url, String.class); } catch (RestClientException exception) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param exception parameter `exception` supplied by the caller + * @return throw new result consumed by the caller or returned to the frontend + */ throw new BusinessException(defaultMessage + ":微信服务调用失败", exception); } } + /** + * Run business method `doPostForString`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param url parameter `url` supplied by the caller + * @param requestEntity parameter `requestEntity` supplied by the caller + * @param defaultMessage parameter `defaultMessage` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ private String doPostForString(String url, HttpEntity requestEntity, String defaultMessage) { try { return restTemplate.postForObject(url, requestEntity, String.class); } catch (RestClientException exception) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param exception parameter `exception` supplied by the caller + * @return throw new result consumed by the caller or returned to the frontend + */ throw new BusinessException(defaultMessage + ":微信服务调用失败", exception); } } + /** + * Run business method `readJsonResponse`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param responseBody parameter `responseBody` supplied by the caller + * @param defaultMessage parameter `defaultMessage` supplied by the caller + * @return private Map result consumed by the caller or returned to the frontend + */ private Map readJsonResponse(String responseBody, String defaultMessage) { if (!StringUtils.hasText(responseBody)) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new BusinessException(defaultMessage + ":微信服务未返回数据"); } try { return objectMapper.readValue(responseBody, new TypeReference>() { }); } catch (JsonProcessingException exception) { + /** + * Run business method `BusinessException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param exception parameter `exception` supplied by the caller + * @return throw new result consumed by the caller or returned to the frontend + */ throw new BusinessException(defaultMessage + ":微信服务返回了无法解析的响应", exception); } } + /** + * Run business method `assertWechatResponseOk`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param response parameter `response` supplied by the caller + * @param defaultMessage parameter `defaultMessage` supplied by the caller + * @return private void result consumed by the caller or returned to the frontend + */ private void assertWechatResponseOk(Map response, String defaultMessage) { long errCode = parseLong(response.get("errcode"), 0L); if (errCode == 0L) { @@ -189,6 +355,13 @@ public class WechatMiniClientServiceImpl implements WechatMiniClientService { throw new BusinessException(defaultMessage + ":" + (StringUtils.hasText(errMsg) ? errMsg : ("错误码 " + errCode))); } + /** + * Run business method `parseLong`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param value parameter `value` supplied by the caller + * @param defaultValue parameter `defaultValue` supplied by the caller + * @return private long result consumed by the caller or returned to the frontend + */ private long parseLong(Object value, long defaultValue) { if (value == null) { return defaultValue; @@ -206,6 +379,12 @@ public class WechatMiniClientServiceImpl implements WechatMiniClientService { return defaultValue; } + /** + * Run business method `asText`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param value parameter `value` supplied by the caller + * @return private String result consumed by the caller or returned to the frontend + */ private String asText(Object value) { return value == null ? "" : String.valueOf(value).trim(); } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/WishlistServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/WishlistServiceImpl.java index ff649e78..9cc22d45 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/WishlistServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/WishlistServiceImpl.java @@ -19,6 +19,10 @@ import java.util.List; import java.util.stream.Collectors; @Service +/** + * WishlistServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects. + * Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class. + */ public class WishlistServiceImpl extends ServiceImpl implements WishlistService { @Autowired @@ -29,9 +33,20 @@ public class WishlistServiceImpl extends ServiceImpl @Override @Transactional + /** + * Add a new record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param productId parameter `productId` supplied by the caller + */ public void addToWishlist(Long userId, Long productId) { ProductDO product = getValidProduct(productId); if (product == null) { + /** + * Run business method `RuntimeException`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @return throw new result consumed by the caller or returned to the frontend + */ throw new RuntimeException("商品不存在或已下架"); } @@ -42,6 +57,12 @@ public class WishlistServiceImpl extends ServiceImpl WishlistDO wishlistDO = new WishlistDO(); wishlistDO.setUserId(userId); wishlistDO.setProductId(productId); + /** + * Save submitted data. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param wishlistDO parameter `wishlistDO` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ save(wishlistDO); // 增加商品收藏数 productMapper.incrementCollectCount(productId); @@ -50,11 +71,23 @@ public class WishlistServiceImpl extends ServiceImpl @Override @Transactional + /** + * Remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param productId parameter `productId` supplied by the caller + */ public void removeFromWishlist(Long userId, Long productId) { LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); wrapper.eq(WishlistDO::getUserId, userId); wrapper.eq(WishlistDO::getProductId, productId); if (count(wrapper) > 0) { + /** + * Remove a record. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param wrapper parameter `wrapper` supplied by the caller + * @return result consumed by the caller or returned to the frontend + */ remove(wrapper); // 减少商品收藏数 if (getValidProduct(productId) != null) { @@ -64,6 +97,13 @@ public class WishlistServiceImpl extends ServiceImpl } @Override + /** + * Run business method `isInWishlist`. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @param productId parameter `productId` supplied by the caller + * @return boolean result consumed by the caller or returned to the frontend + */ public boolean isInWishlist(Long userId, Long productId) { if (getValidProduct(productId) == null) { return false; @@ -75,6 +115,12 @@ public class WishlistServiceImpl extends ServiceImpl } @Override + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param userId parameter `userId` supplied by the caller + * @return List result consumed by the caller or returned to the frontend + */ public List getWishlistByUserId(Long userId) { LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); wrapper.eq(WishlistDO::getUserId, userId); @@ -88,6 +134,12 @@ public class WishlistServiceImpl extends ServiceImpl }).filter(wishlistDTO -> wishlistDTO.getProduct() != null).collect(Collectors.toList()); } + /** + * Load data by the supplied parameter. + * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param productId parameter `productId` supplied by the caller + * @return private ProductDO result consumed by the caller or returned to the frontend + */ private ProductDO getValidProduct(Long productId) { if (productId == null) { return null; diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/BookableArtistSupport.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/BookableArtistSupport.java index f99cd99c..9c18c210 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/BookableArtistSupport.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/BookableArtistSupport.java @@ -1,10 +1,13 @@ package com.xiaowang.yuminailcore.support; import com.xiaowang.yuminailcore.entity.UserDO; +import com.xiaowang.yuminailcore.entity.NailArtistInfoDO; +import com.xiaowang.yuminailcore.mapper.NailArtistInfoMapper; import com.xiaowang.yuminailcore.mapper.UserMapper; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import java.util.LinkedHashSet; import java.util.Set; @@ -15,6 +18,7 @@ import java.util.stream.Collectors; public class BookableArtistSupport { private final UserMapper userMapper; + private final NailArtistInfoMapper nailArtistInfoMapper; private final UserShopBindingSupport userShopBindingSupport; public boolean isValidBookableArtist(Long shopId, Long artistId) { @@ -26,7 +30,7 @@ public class BookableArtistSupport { if (artist == null || Integer.valueOf(1).equals(artist.getIsDelete())) { return false; } - if (!Integer.valueOf(3).equals(artist.getType())) { + if (!isBookableServiceUser(artist)) { return false; } if (!Integer.valueOf(1).equals(artist.getStatus())) { @@ -35,6 +39,27 @@ public class BookableArtistSupport { return shopId == null || shopId <= 0 || userShopBindingSupport.isUserAccessibleInShop(artistId, shopId); } + public boolean isBookableServiceUser(UserDO user) { + if (user == null || Integer.valueOf(1).equals(user.getIsDelete()) || !Integer.valueOf(1).equals(user.getStatus())) { + return false; + } + if (Integer.valueOf(3).equals(user.getType())) { + return true; + } + if (!Integer.valueOf(2).equals(user.getType())) { + return false; + } + NailArtistInfoDO info = nailArtistInfoMapper.selectOne( + new LambdaQueryWrapper() + .eq(NailArtistInfoDO::getUserId, user.getId()) + .eq(NailArtistInfoDO::getIsDelete, 0) + .last("LIMIT 1") + ); + return info != null + && Integer.valueOf(1).equals(info.getStatus()) + && Integer.valueOf(1).equals(info.getParticipateProduction()); + } + public String filterValidBookableArtists(Long shopId, String rawBookableArtists) { if (!StringUtils.hasText(rawBookableArtists)) { return ""; diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/PermissionPolicy.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/PermissionPolicy.java index 21de839c..7d1ac166 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/PermissionPolicy.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/PermissionPolicy.java @@ -14,6 +14,7 @@ public final class PermissionPolicy { "dashboard:view", "user:view", "user:create", "user:edit", "user:disable", "user:unbind", "user:reset_password", "user:delete", "user:balance:view", "user:balance:manage", "user:vip:manage", + "role:view", "role:create", "role:edit", "role:delete", "user:relation:view", "user:relation:edit", "product:view", "product:create", "product:edit", "product:delete", "product:category:manage", "shop:view", "shop:create", "shop:edit", "shop:delete", "shop:staff:manage", "permission:view", "permission:create", "permission:edit", "permission:delete", "permission:assign", @@ -21,7 +22,10 @@ public final class PermissionPolicy { "coupon:view", "coupon:create", "coupon:edit", "coupon:delete", "coupon:assign", "comment:view", "comment:delete", "order:view", "order:process", "order:edit", "order:delete", - "nail_artist:view", "nail_artist:edit" + "nail_artist:view", "nail_artist:edit", + "message:view", "message:create", "message:delete", + "announcement:view", "announcement:create", "announcement:delete", + "messagehub:config:manage" ); private static final List SHOP_MANAGER_DEFAULT_PERMISSION_CODES = List.of( @@ -29,6 +33,7 @@ public final class PermissionPolicy { "dashboard:view", "user:view", "user:create", "user:edit", "user:unbind", "user:reset_password", "user:balance:view", "user:balance:manage", "user:vip:manage", + "role:view", "role:create", "role:edit", "role:delete", "user:relation:view", "user:relation:edit", "product:view", "product:create", "product:edit", "product:delete", "product:category:manage", "shop:view", "shop:edit", "shop:staff:manage", "permission:view", "permission:assign", @@ -36,7 +41,9 @@ public final class PermissionPolicy { "coupon:view", "coupon:create", "coupon:edit", "coupon:delete", "coupon:assign", "comment:view", "comment:delete", "order:view", "order:process", "order:edit", "order:delete", - "nail_artist:view", "nail_artist:edit" + "nail_artist:view", "nail_artist:edit", + "message:view", "message:create", + "announcement:view", "announcement:create" ); private static final List NAIL_ARTIST_DEFAULT_PERMISSION_CODES = List.of( diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/UserShopBindingSupport.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/UserShopBindingSupport.java index b7c76e3a..bab84912 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/UserShopBindingSupport.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/UserShopBindingSupport.java @@ -110,6 +110,10 @@ public class UserShopBindingSupport { } public boolean isShopActive(Long shopId) { + return isShopEnabledIgnoringAuthorization(shopId) && !isShopAuthorizationExpired(shopId); + } + + public boolean isShopEnabledIgnoringAuthorization(Long shopId) { if (shopId == null || shopId <= 0) { return false; } @@ -119,6 +123,16 @@ public class UserShopBindingSupport { && Integer.valueOf(1).equals(normalizeShopStatus(shopDO.getStatus())); } + public boolean isShopAuthorizationExpired(Long shopId) { + if (shopId == null || shopId <= 0) { + return false; + } + ShopDO shopDO = shopMapper.selectById(shopId); + return shopDO != null + && shopDO.getAuthorizationExpireTime() != null + && shopDO.getAuthorizationExpireTime().isBefore(LocalDateTime.now()); + } + public Long pickPrimaryShopId(Long userId) { return listActiveBindingsByUserId(userId).stream() .map(UserShopBindingDO::getShopId) @@ -355,7 +369,11 @@ public class UserShopBindingSupport { && Integer.valueOf(4).equals(userType) && listAllActiveShopOptions().isEmpty(); } - if (!isShopActive(shopId)) { + if (Boolean.TRUE.equals(adminLogin)) { + if (!isShopEnabledIgnoringAuthorization(shopId)) { + return false; + } + } else if (!isShopActive(shopId)) { return false; } if (Boolean.TRUE.equals(adminLogin) && Integer.valueOf(4).equals(userType)) { @@ -431,6 +449,7 @@ public class UserShopBindingSupport { wrapper.eq(ShopDO::getStatus, 1); } return shopMapper.selectList(wrapper).stream() + .filter(shop -> !onlyActiveShops || !isShopAuthorizationExpired(shop.getId())) .collect(Collectors.toMap(ShopDO::getId, shop -> shop, (left, right) -> left, LinkedHashMap::new)); } @@ -446,6 +465,7 @@ public class UserShopBindingSupport { } return shopMapper.selectList(wrapper) .stream() + .filter(shop -> !onlyActiveShops || !isShopAuthorizationExpired(shop.getId())) .collect(Collectors.toMap(ShopDO::getId, shop -> shop, (left, right) -> left, LinkedHashMap::new)); } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/security/RequestThrottleService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/security/RequestThrottleService.java index 8836e70a..3f36e07f 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/security/RequestThrottleService.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/security/RequestThrottleService.java @@ -1,5 +1,6 @@ package com.xiaowang.yuminailcore.support.security; +import com.xiaowang.yuminailcore.config.LoginLockProperties; import com.xiaowang.yuminailcore.config.RateLimitProperties; import lombok.RequiredArgsConstructor; import org.springframework.data.redis.core.StringRedisTemplate; @@ -11,9 +12,6 @@ import javax.servlet.http.HttpServletRequest; import java.nio.charset.StandardCharsets; import java.util.concurrent.TimeUnit; -/** - * 请求限流服务。 - */ @Component @RequiredArgsConstructor public class RequestThrottleService { @@ -22,20 +20,31 @@ public class RequestThrottleService { private final StringRedisTemplate stringRedisTemplate; private final RateLimitProperties rateLimitProperties; + private final LoginLockProperties loginLockProperties; public void checkLogin(HttpServletRequest request, String account) { - RateLimitProperties.LimitRule rule = rateLimitProperties.getLogin(); - assertAllowed("login", request, sanitize(account), rule, "登录过于频繁,请稍后再试"); + assertLoginNotLocked(request, account); + assertAllowed("login", request, sanitize(account), rateLimitProperties.getLogin(), "登录过于频繁,请稍后再试"); + } + + public void checkRegister(HttpServletRequest request, String account) { + assertAllowed("register", request, sanitize(account), rateLimitProperties.getRegister(), "注册过于频繁,请稍后再试"); } public void checkSendCode(HttpServletRequest request, String phone) { - RateLimitProperties.LimitRule rule = rateLimitProperties.getSendCode(); - assertAllowed("send-code", request, sanitize(phone), rule, "验证码发送过于频繁,请稍后再试"); + assertAllowed("send-code", request, sanitize(phone), rateLimitProperties.getSendCode(), "验证码发送过于频繁,请稍后再试"); } public void checkResetPassword(HttpServletRequest request, String phone) { - RateLimitProperties.LimitRule rule = rateLimitProperties.getResetPassword(); - assertAllowed("reset-password", request, sanitize(phone), rule, "密码重置请求过于频繁,请稍后再试"); + assertAllowed("reset-password", request, sanitize(phone), rateLimitProperties.getResetPassword(), "密码重置请求过于频繁,请稍后再试"); + } + + public void checkWechatMiniLogin(HttpServletRequest request, String subject) { + assertAllowed("wechat-mini-login", request, sanitize(subject), rateLimitProperties.getWechatMiniLogin(), "微信登录过于频繁,请稍后再试"); + } + + public void checkAgreementRead(HttpServletRequest request, String agreementType) { + assertAllowed("agreement-read", request, sanitize(agreementType), rateLimitProperties.getAgreementRead(), "协议读取过于频繁,请稍后再试"); } public void checkAuthenticatedWrite(HttpServletRequest request, Long userId) { @@ -50,6 +59,25 @@ public class RequestThrottleService { assertAllowed(category, request, userId == null ? "" : String.valueOf(userId), rule, message); } + public void recordLoginFailure(HttpServletRequest request, String account) { + if (loginLockProperties.getMaxFailures() <= 0 || loginLockProperties.getWindowSeconds() <= 0) { + return; + } + String key = buildLoginFailureKey(request, account); + Long count = stringRedisTemplate.opsForValue().increment(key); + if (count != null && count == 1L) { + stringRedisTemplate.expire(key, loginLockProperties.getWindowSeconds(), TimeUnit.SECONDS); + } + if (count != null && count >= loginLockProperties.getMaxFailures()) { + stringRedisTemplate.opsForValue().set(buildLoginLockKey(request, account), "1", loginLockProperties.getLockSeconds(), TimeUnit.SECONDS); + } + } + + public void clearLoginFailure(HttpServletRequest request, String account) { + stringRedisTemplate.delete(buildLoginFailureKey(request, account)); + stringRedisTemplate.delete(buildLoginLockKey(request, account)); + } + private void assertAllowed(String category, HttpServletRequest request, String subject, @@ -74,7 +102,29 @@ public class RequestThrottleService { } } + private void assertLoginNotLocked(HttpServletRequest request, String account) { + Boolean locked = stringRedisTemplate.hasKey(buildLoginLockKey(request, account)); + if (Boolean.TRUE.equals(locked)) { + throw new RuntimeException("登录失败次数过多,请稍后再试"); + } + } + + private String buildLoginFailureKey(HttpServletRequest request, String account) { + return "login:fail:" + DigestUtils.md5DigestAsHex(buildLoginLockRaw(request, account).getBytes(StandardCharsets.UTF_8)); + } + + private String buildLoginLockKey(HttpServletRequest request, String account) { + return "login:lock:" + DigestUtils.md5DigestAsHex(buildLoginLockRaw(request, account).getBytes(StandardCharsets.UTF_8)); + } + + private String buildLoginLockRaw(HttpServletRequest request, String account) { + return String.join("|", sanitize(resolveClientIp(request)), sanitize(resolveDeviceId(request)), sanitize(account)); + } + private String resolveClientIp(HttpServletRequest request) { + if (request == null) { + return "-"; + } String forwarded = request.getHeader("X-Forwarded-For"); if (StringUtils.hasText(forwarded)) { return forwarded.split(",")[0].trim(); @@ -87,7 +137,7 @@ public class RequestThrottleService { } private String resolveDeviceId(HttpServletRequest request) { - return request.getHeader(DEVICE_ID_HEADER); + return request == null ? null : request.getHeader(DEVICE_ID_HEADER); } private String sanitize(String value) { diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/security/UploadSecurityValidator.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/security/UploadSecurityValidator.java new file mode 100644 index 00000000..de2a117a --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/security/UploadSecurityValidator.java @@ -0,0 +1,65 @@ +package com.xiaowang.yuminailcore.support.security; + +import com.xiaowang.yuminailcore.config.UploadSecurityProperties; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; +import org.springframework.web.multipart.MultipartFile; + +import java.util.Locale; +import java.util.Set; + +@Component +@RequiredArgsConstructor +public class UploadSecurityValidator { + + private static final Set BLOCKED_EXTENSIONS = Set.of( + ".jsp", ".jspx", ".php", ".asp", ".aspx", ".js", ".html", ".htm", ".exe", ".bat", ".cmd", ".sh", ".jar" + ); + + private static final Set IMAGE_EXTENSIONS = Set.of(".jpg", ".jpeg", ".png", ".webp", ".gif"); + + private final UploadSecurityProperties properties; + + public void validate(MultipartFile file) { + if (file == null || file.isEmpty()) { + throw new RuntimeException("上传文件不能为空"); + } + if (file.getSize() > properties.getMaxSize()) { + throw new RuntimeException("上传文件过大"); + } + String filename = file.getOriginalFilename(); + String extension = resolveExtension(filename); + if (!StringUtils.hasText(extension) || BLOCKED_EXTENSIONS.contains(extension)) { + throw new RuntimeException("不支持的文件类型"); + } + String contentType = StringUtils.hasText(file.getContentType()) ? file.getContentType().toLowerCase(Locale.ROOT) : ""; + if (!properties.getAllowedMimeTypes().contains(contentType)) { + throw new RuntimeException("文件 MIME 类型不允许"); + } + if (contentType.startsWith("image/") && !IMAGE_EXTENSIONS.contains(extension)) { + throw new RuntimeException("图片文件扩展名不匹配"); + } + } + + public void validateMetadata(String filename, String contentType, Long fileSize) { + if (fileSize == null || fileSize <= 0 || fileSize > properties.getMaxSize()) { + throw new RuntimeException("上传文件大小不合法"); + } + String extension = resolveExtension(filename); + if (!StringUtils.hasText(extension) || BLOCKED_EXTENSIONS.contains(extension)) { + throw new RuntimeException("不支持的文件类型"); + } + String normalizedContentType = StringUtils.hasText(contentType) ? contentType.toLowerCase(Locale.ROOT) : ""; + if (!properties.getAllowedMimeTypes().contains(normalizedContentType)) { + throw new RuntimeException("文件 MIME 类型不允许"); + } + } + + private String resolveExtension(String filename) { + if (!StringUtils.hasText(filename) || !filename.contains(".")) { + return ""; + } + return filename.substring(filename.lastIndexOf(".")).toLowerCase(Locale.ROOT); + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/AnnouncementVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/AnnouncementVO.java new file mode 100644 index 00000000..265aafc4 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/AnnouncementVO.java @@ -0,0 +1,66 @@ +package com.xiaowang.yuminailcore.vo; + +import lombok.Data; + +import java.time.LocalDateTime; +import java.util.List; + +@Data +/** + * AnnouncementVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class AnnouncementVO { + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + /** + * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String title; + /** + * Field `content` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String content; + /** + * Field `publisherId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long publisherId; + /** + * Field `publisherName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String publisherName; + /** + * Field `publisherType` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer publisherType; + /** + * Field `targetType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String targetType; + /** + * Field `targetTypeName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String targetTypeName; + /** + * Field `targetIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List targetIds; + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + /** + * Field `sortOrder` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer sortOrder; + /** + * Field `publishTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime publishTime; + /** + * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime createTime; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/ArtistCalendarAppointmentVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/ArtistCalendarAppointmentVO.java new file mode 100644 index 00000000..2112437c --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/ArtistCalendarAppointmentVO.java @@ -0,0 +1,90 @@ +package com.xiaowang.yuminailcore.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +@Data +/** + * ArtistCalendarAppointmentVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class ArtistCalendarAppointmentVO { + /** + * Field `orderId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long orderId; + /** + * Field `orderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String orderNo; + /** + * Field `totalAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal totalAmount; + /** + * Field `actualAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal actualAmount; + /** + * Field `orderStatus` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer orderStatus; + /** + * Field `orderStatusText` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String orderStatusText; + /** + * Field `orderItemId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long orderItemId; + /** + * Field `productId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long productId; + /** + * Field `productTitle` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String productTitle; + /** + * Field `artistId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long artistId; + /** + * Field `artistName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String artistName; + /** + * Field `customerNickname` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String customerNickname; + /** + * Field `customerPhoneMasked` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String customerPhoneMasked; + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + /** + * Field `shopName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String shopName; + /** + * Field `appointmentStartTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime appointmentStartTime; + /** + * Field `appointmentEndTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime appointmentEndTime; + /** + * Field `quantity` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer quantity; + /** + * Field `durationMinutes` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long durationMinutes; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/BalanceChangeDetailVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/BalanceChangeDetailVO.java index c32ce9db..2b1e7209 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/BalanceChangeDetailVO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/BalanceChangeDetailVO.java @@ -44,13 +44,37 @@ public class BalanceChangeDetailVO { * 变动后的当前余额 */ private BigDecimal currentBalance; + /** + * Field `beforeBalance` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private BigDecimal beforeBalance; + /** + * Field `afterBalance` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private BigDecimal afterBalance; + /** + * Field `changeScene` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String changeScene; + /** + * Field `relatedOrderId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long relatedOrderId; + /** + * Field `relatedOrderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String relatedOrderNo; + /** + * Field `externalOrderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String externalOrderNo; + /** + * Field `operatorId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long operatorId; + /** + * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String remark; /** diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/BalanceVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/BalanceVO.java index 75c79ca3..f9c8f173 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/BalanceVO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/BalanceVO.java @@ -34,7 +34,13 @@ public class BalanceVO { * 当前余额 */ private BigDecimal amount; + /** + * Field `totalRechargeAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private BigDecimal totalRechargeAmount; + /** + * Field `lastRechargeTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private LocalDateTime lastRechargeTime; /** diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/CartArtistVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/CartArtistVO.java index 379ccd63..99e5b3d3 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/CartArtistVO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/CartArtistVO.java @@ -3,8 +3,33 @@ package com.xiaowang.yuminailcore.vo; import lombok.Data; @Data +/** + * CartArtistVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ public class CartArtistVO { + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long id; + /** + * Field `name` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String name; + /** + * Field `avatar` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String avatar; + /** + * Field `userType` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer userType; + /** + * Field `roleLabel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String roleLabel; + /** + * Field `participateProduction` (Boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Boolean participateProduction; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/CartVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/CartVO.java index 150725a7..62bcfa49 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/CartVO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/CartVO.java @@ -6,20 +6,69 @@ import java.math.BigDecimal; import java.util.List; @Data +/** + * CartVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ public class CartVO { + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long id; + /** + * Field `productId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long productId; + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long shopId; + /** + * Field `productTitle` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String productTitle; + /** + * Field `productImage` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String productImage; + /** + * Field `price` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private BigDecimal price; + /** + * Field `quantity` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Integer quantity; + /** + * Field `totalPrice` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private BigDecimal totalPrice; + /** + * Field `tags` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String tags; + /** + * Field `tagNames` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String tagNames; + /** + * Field `approximateDuration` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String approximateDuration; + /** + * Field `bookableArtists` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String bookableArtists; + /** + * Field `availableBookableArtistCount` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Integer availableBookableArtistCount; + /** + * Field `bookableArtistRestricted` (Boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Boolean bookableArtistRestricted; + /** + * Field `availableArtists` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private List availableArtists; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/ChunkUploadSessionVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/ChunkUploadSessionVO.java index 31318d83..83482293 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/ChunkUploadSessionVO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/ChunkUploadSessionVO.java @@ -10,11 +10,23 @@ import java.util.List; @Data public class ChunkUploadSessionVO { + /** + * Field `uploadId` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String uploadId; + /** + * Field `chunkSize` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Integer chunkSize; + /** + * Field `totalChunks` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Integer totalChunks; + /** + * Field `uploadedChunks` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private List uploadedChunks; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/ContactInfoVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/ContactInfoVO.java new file mode 100644 index 00000000..71a31824 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/ContactInfoVO.java @@ -0,0 +1,39 @@ +package com.xiaowang.yuminailcore.vo; + +import lombok.Data; + +@Data +/** + * ContactInfoVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class ContactInfoVO { + /** + * Field `contactUserId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long contactUserId; + /** + * Field `contactName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String contactName; + /** + * Field `roleLabel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String roleLabel; + /** + * Field `phone` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String phone; + /** + * Field `phoneAvailable` (Boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Boolean phoneAvailable; + /** + * Field `platformContactAvailable` (Boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Boolean platformContactAvailable; + /** + * Field `platformContactText` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String platformContactText; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/CouponVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/CouponVO.java index faa8edcc..5506d65f 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/CouponVO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/CouponVO.java @@ -96,8 +96,17 @@ public class CouponVO { * 所属店铺名称 */ private String shopName; + /** + * Field `couponScene` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String couponScene; + /** + * Field `requiredVipLevel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String requiredVipLevel; + /** + * Field `autoMatch` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Integer autoMatch; /** diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/DashboardStatsVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/DashboardStatsVO.java index e1001ada..f2171cfc 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/DashboardStatsVO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/DashboardStatsVO.java @@ -5,11 +5,33 @@ import lombok.Data; import java.util.List; @Data +/** + * DashboardStatsVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ public class DashboardStatsVO { + /** + * Field `totalUsers` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long totalUsers; + /** + * Field `totalProducts` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long totalProducts; + /** + * Field `totalShops` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long totalShops; + /** + * Field `todayOrders` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long todayOrders; + /** + * Field `hotProducts` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private List hotProducts; + /** + * Field `recentActivities` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private List recentActivities; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/HotProductVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/HotProductVO.java index 2a688a1b..5a44925d 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/HotProductVO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/HotProductVO.java @@ -5,10 +5,29 @@ import lombok.Data; import java.math.BigDecimal; @Data +/** + * HotProductVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ public class HotProductVO { + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long id; + /** + * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String title; + /** + * Field `price` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private BigDecimal price; + /** + * Field `likeCount` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Integer likeCount; + /** + * Field `collectCount` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Integer collectCount; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/InviteCodeVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/InviteCodeVO.java new file mode 100644 index 00000000..36e0ab9a --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/InviteCodeVO.java @@ -0,0 +1,58 @@ +package com.xiaowang.yuminailcore.vo; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +/** + * InviteCodeVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class InviteCodeVO { + @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + /** + * Field `inviteCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String inviteCode; + @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `ownerUserId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long ownerUserId; + /** + * Field `ownerUserName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String ownerUserName; + @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + /** + * Field `shopName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String shopName; + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + /** + * Field `useCount` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer useCount; + /** + * Field `expireTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime expireTime; + /** + * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime createTime; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/LegalAgreementVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/LegalAgreementVO.java new file mode 100644 index 00000000..187f4ff1 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/LegalAgreementVO.java @@ -0,0 +1,31 @@ +package com.xiaowang.yuminailcore.vo; + +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +public class LegalAgreementVO { + + private Long id; + + private String agreementType; + + private String agreementTypeName; + + private String title; + + private String version; + + private String content; + + private Integer status; + + private String statusText; + + private LocalDateTime effectiveTime; + + private LocalDateTime createTime; + + private LocalDateTime updateTime; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/LoginResponseVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/LoginResponseVO.java index 2587881f..ea9cf24d 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/LoginResponseVO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/LoginResponseVO.java @@ -16,28 +16,78 @@ import java.util.List; @Data public class LoginResponseVO { + /** + * Field `accessToken` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String accessToken; + /** + * Field `refreshToken` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String refreshToken; + /** + * Field `userInfo` (UserInfo): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private UserInfo userInfo; + /** + * Field `needSetPassword` (boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private boolean needSetPassword; // 是否需要设置密码 @Data public static class UserInfo { @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long id; + /** + * Field `account` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String account; + /** + * Field `nickname` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String nickname; + /** + * Field `avatar` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String avatar; + /** + * Field `type` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Integer type; @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long shopId; + /** + * Field `shopName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String shopName; + /** + * Field `shopAuthorizationExpireTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime shopAuthorizationExpireTime; + /** + * Field `shopAuthorizationExpired` (Boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Boolean shopAuthorizationExpired; @JsonSerialize(contentUsing = ToStringSerializer.class) + /** + * Field `shopIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private List shopIds; + /** + * Field `shopNames` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private List shopNames; + /** + * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private LocalDateTime createTime; } } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/LoginShopSelectionVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/LoginShopSelectionVO.java index 592d3f50..9d263f27 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/LoginShopSelectionVO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/LoginShopSelectionVO.java @@ -11,9 +11,18 @@ import java.util.List; @Data public class LoginShopSelectionVO { + /** + * Field `allowShoplessLogin` (boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private boolean allowShoplessLogin; + /** + * Field `message` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String message; + /** + * Field `shops` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private List shops = new ArrayList<>(); } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/MessageHubPushConfigVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/MessageHubPushConfigVO.java new file mode 100644 index 00000000..ec819799 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/MessageHubPushConfigVO.java @@ -0,0 +1,69 @@ +package com.xiaowang.yuminailcore.vo; + +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +/** + * MessageHubPushConfigVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class MessageHubPushConfigVO { + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + /** + * Field `sceneCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sceneCode; + /** + * Field `sceneName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sceneName; + /** + * Field `platform` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String platform; + /** + * Field `msgType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String msgType; + /** + * Field `queueName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String queueName; + /** + * Field `sourceSystem` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sourceSystem; + /** + * Field `templateCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String templateCode; + /** + * Field `channelId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long channelId; + /** + * Field `sendMethod` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sendMethod; + /** + * Field `enabled` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer enabled; + /** + * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String remark; + /** + * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime createTime; + /** + * Field `updateTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime updateTime; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/MessageTargetOptionsVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/MessageTargetOptionsVO.java new file mode 100644 index 00000000..2d4e9188 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/MessageTargetOptionsVO.java @@ -0,0 +1,61 @@ +package com.xiaowang.yuminailcore.vo; + +import lombok.Data; + +import java.util.List; + +@Data +/** + * MessageTargetOptionsVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class MessageTargetOptionsVO { + /** + * Field `shops` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List shops; + /** + * Field `users` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List users; + + @Data + public static class ShopOptionVO { + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + /** + * Field `shopName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String shopName; + } + + @Data + public static class UserOptionVO { + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + /** + * Field `nickname` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String nickname; + /** + * Field `account` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String account; + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + /** + * Field `shopName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String shopName; + /** + * Field `type` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer type; + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/MessageUnreadCountVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/MessageUnreadCountVO.java new file mode 100644 index 00000000..52395c15 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/MessageUnreadCountVO.java @@ -0,0 +1,17 @@ +package com.xiaowang.yuminailcore.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +/** + * MessageUnreadCountVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class MessageUnreadCountVO { + /** + * Field `unreadCount` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long unreadCount; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/OrderItemVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/OrderItemVO.java index 57794b42..25550e7f 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/OrderItemVO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/OrderItemVO.java @@ -5,16 +5,53 @@ import lombok.Data; import java.math.BigDecimal; @Data +/** + * OrderItemVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ public class OrderItemVO { + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long id; + /** + * Field `productId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long productId; + /** + * Field `productTitle` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String productTitle; + /** + * Field `productImage` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String productImage; + /** + * Field `quantity` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Integer quantity; + /** + * Field `price` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private BigDecimal price; + /** + * Field `totalPrice` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private BigDecimal totalPrice; + /** + * Field `artistId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long artistId; + /** + * Field `artistName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String artistName; + /** + * Field `artistAvatar` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String artistAvatar; + /** + * Field `appointmentTime` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String appointmentTime; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/OrderVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/OrderVO.java index bcb1ac18..dfef0ab1 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/OrderVO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/OrderVO.java @@ -7,21 +7,82 @@ import java.time.LocalDateTime; import java.util.List; @Data +/** + * OrderVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ public class OrderVO { + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long id; + /** + * Field `orderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String orderNo; + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long userId; + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long shopId; + private String shopName; + /** + * Field `totalAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private BigDecimal totalAmount; + /** + * Field `actualAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private BigDecimal actualAmount; + /** + * Field `couponId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long couponId; + /** + * Field `userCouponId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long userCouponId; + /** + * Field `couponSourceType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String couponSourceType; + /** + * Field `couponName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String couponName; + /** + * Field `customerNickname` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String customerNickname; + /** + * Field `customerPhoneMasked` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String customerPhoneMasked; + /** + * Field `artistOrderSource` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String artistOrderSource; + /** + * Field `artistOrderSourceText` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String artistOrderSourceText; + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Integer status; + /** + * Field `statusText` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String statusText; + /** + * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private LocalDateTime createTime; + /** + * Field `items` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private List items; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/PageResultVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/PageResultVO.java index 350b9a8e..8a676ffb 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/PageResultVO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/PageResultVO.java @@ -5,9 +5,25 @@ import lombok.Data; import java.util.List; @Data +/** + * PageResultVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ public class PageResultVO { + /** + * Field `list` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private List list; + /** + * Field `total` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long total; + /** + * Field `page` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Integer page; + /** + * Field `size` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Integer size; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/RecentActivityVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/RecentActivityVO.java index 4a471bdd..f374442a 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/RecentActivityVO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/RecentActivityVO.java @@ -5,11 +5,33 @@ import lombok.Data; import java.time.LocalDateTime; @Data +/** + * RecentActivityVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ public class RecentActivityVO { + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long id; + /** + * Field `type` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String type; + /** + * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String title; + /** + * Field `description` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String description; + /** + * Field `time` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private LocalDateTime time; + /** + * Field `color` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String color; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/ShopRoleVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/ShopRoleVO.java new file mode 100644 index 00000000..11ac0d23 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/ShopRoleVO.java @@ -0,0 +1,75 @@ +package com.xiaowang.yuminailcore.vo; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import lombok.Data; + +import java.time.LocalDateTime; +import java.util.List; + +@Data +/** + * ShopRoleVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class ShopRoleVO { + @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + /** + * Field `shopName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String shopName; + /** + * Field `roleName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String roleName; + @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `creatorId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long creatorId; + /** + * Field `creatorName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String creatorName; + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + /** + * Field `remark` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String remark; + /** + * Field `sortOrder` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer sortOrder; + /** + * Field `permissionIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List permissionIds; + /** + * Field `permissionCodes` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List permissionCodes; + /** + * Field `userIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List userIds; + /** + * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime createTime; + /** + * Field `updateTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime updateTime; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/ShopSimpleVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/ShopSimpleVO.java index 9c288fd4..e786864f 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/ShopSimpleVO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/ShopSimpleVO.java @@ -9,9 +9,19 @@ import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor +/** + * ShopSimpleVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ public class ShopSimpleVO { @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long id; + /** + * Field `shopName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String shopName; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/ShopVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/ShopVO.java index f6b68db7..3be6d18c 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/ShopVO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/ShopVO.java @@ -4,8 +4,10 @@ import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import lombok.Data; +import java.math.BigDecimal; import java.time.LocalDateTime; import java.util.List; +import java.util.Map; /** * 店铺信息表 VO @@ -38,6 +40,14 @@ public class ShopVO { */ private String address; + private String mapProvider; + + private BigDecimal longitude; + + private BigDecimal latitude; + + private Map navigationUrls; + /** * 店铺营业时间 */ @@ -68,6 +78,21 @@ public class ShopVO { */ private Integer status; + /** + * 店铺授权有效期;为空表示长期有效。 + */ + private LocalDateTime authorizationExpireTime; + + /** + * 当前时间是否已超过授权有效期。 + */ + private Boolean authorizationExpired; + + /** + * 给前端直接展示的授权状态文案。 + */ + private String authorizationStatusText; + /** * 创建时间 */ diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/SystemMessageVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/SystemMessageVO.java new file mode 100644 index 00000000..3d55b60a --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/SystemMessageVO.java @@ -0,0 +1,90 @@ +package com.xiaowang.yuminailcore.vo; + +import lombok.Data; + +import java.time.LocalDateTime; +import java.util.List; + +@Data +/** + * SystemMessageVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class SystemMessageVO { + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + /** + * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String title; + /** + * Field `content` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String content; + /** + * Field `imageFileId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long imageFileId; + /** + * Field `imageUrl` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String imageUrl; + /** + * Field `publisherId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long publisherId; + /** + * Field `publisherName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String publisherName; + /** + * Field `publisherType` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer publisherType; + /** + * Field `targetType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String targetType; + /** + * Field `targetTypeName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String targetTypeName; + /** + * Field `targetIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private List targetIds; + /** + * Field `popupEnabled` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer popupEnabled; + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + /** + * Field `publishTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime publishTime; + /** + * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime createTime; + /** + * Field `popupShown` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer popupShown; + /** + * Field `readStatus` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer readStatus; + /** + * Field `popupTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime popupTime; + /** + * Field `readTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime readTime; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/SystemParameterConfigVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/SystemParameterConfigVO.java new file mode 100644 index 00000000..3013171d --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/SystemParameterConfigVO.java @@ -0,0 +1,19 @@ +package com.xiaowang.yuminailcore.vo; + +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +public class SystemParameterConfigVO { + + private Long id; + private String configGroup; + private String configKey; + private String configName; + private String configValue; + private Integer enabled; + private String remark; + private LocalDateTime createTime; + private LocalDateTime updateTime; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/UserAgreementConsentVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/UserAgreementConsentVO.java new file mode 100644 index 00000000..e86559f1 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/UserAgreementConsentVO.java @@ -0,0 +1,15 @@ +package com.xiaowang.yuminailcore.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.Map; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class UserAgreementConsentVO { + + private Map consentVersions; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/UserAssetVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/UserAssetVO.java index 4e6d8b87..c499e7c2 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/UserAssetVO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/UserAssetVO.java @@ -6,29 +6,69 @@ import java.math.BigDecimal; import java.time.LocalDateTime; @Data +/** + * UserAssetVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ public class UserAssetVO { + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long userId; + /** + * Field `nickname` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String nickname; + /** + * Field `balance` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private BigDecimal balance; + /** + * Field `totalRechargeAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private BigDecimal totalRechargeAmount; + /** + * Field `lastRechargeTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private LocalDateTime lastRechargeTime; + /** + * Field `vipInfoId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long vipInfoId; + /** + * Field `vipLevel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String vipLevel; + /** + * Field `benefitId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long benefitId; + /** + * Field `benefitInfo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String benefitInfo; + /** + * Field `manualOverride` (Boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Boolean manualOverride; + /** + * Field `vipStartTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private LocalDateTime vipStartTime; + /** + * Field `vipExpireTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private LocalDateTime vipExpireTime; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/UserCouponVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/UserCouponVO.java index 3b5930bf..5c896377 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/UserCouponVO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/UserCouponVO.java @@ -79,7 +79,16 @@ public class UserCouponVO { * 使用时间 */ private LocalDateTime useTime; + /** + * Field `sourceType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String sourceType; + /** + * Field `requiredVipLevel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String requiredVipLevel; + /** + * Field `autoMatched` (Boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Boolean autoMatched; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/UserRelationVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/UserRelationVO.java new file mode 100644 index 00000000..c086d2af --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/UserRelationVO.java @@ -0,0 +1,52 @@ +package com.xiaowang.yuminailcore.vo; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import lombok.Data; + +@Data +/** + * UserRelationVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class UserRelationVO { + @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long userId; + @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + /** + * Field `shopName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String shopName; + @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `parentUserId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long parentUserId; + /** + * Field `parentUserName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String parentUserName; + /** + * Field `parentRoleType` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer parentRoleType; + /** + * Field `parentRoleTypeName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String parentRoleTypeName; + /** + * Field `sourceType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sourceType; + /** + * Field `sourceTypeName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String sourceTypeName; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/UserStatisticsVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/UserStatisticsVO.java new file mode 100644 index 00000000..0c021fb7 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/UserStatisticsVO.java @@ -0,0 +1,53 @@ +package com.xiaowang.yuminailcore.vo; + +import lombok.Data; + +import java.util.Map; + +@Data +/** + * UserStatisticsVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class UserStatisticsVO { + /** + * Field `totalUserCount` (long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private long totalUserCount; + /** + * Field `normalUserCount` (long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private long normalUserCount; + /** + * Field `employeeCount` (long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private long employeeCount; + /** + * Field `managerCount` (long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private long managerCount; + /** + * Field `artistCount` (long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private long artistCount; + /** + * Field `vipUserCount` (long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private long vipUserCount; + /** + * Field `newUserCount` (long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private long newUserCount; + /** + * Field `byShop` (Map): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Map byShop; + /** + * Field `byRole` (Map): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Map byRole; + /** + * Field `byParent` (Map): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Map byParent; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/UserVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/UserVO.java index 17c2bda0..67b0a108 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/UserVO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/UserVO.java @@ -110,4 +110,42 @@ public class UserVO { * 手机号 */ private String phone; + /** + * Field `email` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String email; + /** + * Field `maskedPhone` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String maskedPhone; + /** + * Field `maskedEmail` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String maskedEmail; + @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `shopRoleId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopRoleId; + /** + * Field `shopRoleName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String shopRoleName; + @JsonSerialize(using = ToStringSerializer.class) + /** + * Field `parentUserId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long parentUserId; + /** + * Field `parentUserName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String parentUserName; + /** + * Field `parentUserTypeName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String parentUserTypeName; + /** + * Field `relationSourceType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String relationSourceType; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/VipBenefitVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/VipBenefitVO.java index c4030c1c..2ce8b84c 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/VipBenefitVO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/VipBenefitVO.java @@ -29,8 +29,17 @@ public class VipBenefitVO { * 所需VIP等级 */ private String requiredVipLevel; + /** + * Field `levelRank` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Integer levelRank; + /** + * Field `rechargeThreshold` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private BigDecimal rechargeThreshold; + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Integer status; /** diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/VipInfoVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/VipInfoVO.java index 177c1b87..9026e4c4 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/VipInfoVO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/VipInfoVO.java @@ -14,6 +14,9 @@ import java.time.LocalDateTime; @Data public class VipInfoVO { + /** + * Field `userId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Long userId; /** @@ -50,6 +53,9 @@ public class VipInfoVO { * 权益详情 */ private String benefitInfo; + /** + * Field `manualOverride` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Integer manualOverride; /** diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/VipRechargePlanVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/VipRechargePlanVO.java new file mode 100644 index 00000000..9a0673b4 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/VipRechargePlanVO.java @@ -0,0 +1,62 @@ +package com.xiaowang.yuminailcore.vo; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDateTime; + +@Data +/** + * VipRechargePlanVO is a response VO. Services build it and controllers return it to the frontend. + * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. + */ +public class VipRechargePlanVO { + /** + * Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long id; + /** + * Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Long shopId; + /** + * Field `shopName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String shopName; + /** + * Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String title; + /** + * Field `rechargeAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal rechargeAmount; + /** + * Field `giftAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private BigDecimal giftAmount; + /** + * Field `vipLevel` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String vipLevel; + /** + * Field `description` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private String description; + /** + * Field `sortOrder` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer sortOrder; + /** + * Field `status` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private Integer status; + /** + * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime createTime; + /** + * Field `updateTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ + private LocalDateTime updateTime; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/WechatMiniLoginResultVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/WechatMiniLoginResultVO.java index b77beb3f..d20910b5 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/WechatMiniLoginResultVO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/WechatMiniLoginResultVO.java @@ -14,14 +14,41 @@ public class WechatMiniLoginResultVO { public static final String STATUS_SELECT_SHOP = "SELECT_SHOP"; public static final String STATUS_NEED_MANUAL_LOGIN = "NEED_MANUAL_LOGIN"; + /** + * Field `status` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String status; + /** + * Field `message` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String message; + /** + * Field `ticket` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String ticket; + /** + * Field `newUser` (Boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Boolean newUser; + /** + * Field `shops` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private List shops; + /** + * Field `accessToken` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String accessToken; + /** + * Field `refreshToken` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private String refreshToken; + /** + * Field `userInfo` (LoginResponseVO.UserInfo): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private LoginResponseVO.UserInfo userInfo; + /** + * Field `needSetPassword` (Boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. + */ private Boolean needSetPassword; public static WechatMiniLoginResultVO success(String message, LoginResponseVO loginResponse, boolean newUser) { diff --git a/YumiNail-Core/src/main/resources/files/2026-03-20_init_admin_permission_template.sql b/YumiNail-Core/src/main/resources/files/2026-03-20_init_admin_permission_template.sql deleted file mode 100644 index 33e48465..00000000 --- a/YumiNail-Core/src/main/resources/files/2026-03-20_init_admin_permission_template.sql +++ /dev/null @@ -1,228 +0,0 @@ --- 2026-03-20 空库初始化模板:admin01 / 权限种子 / 最终权限分配 --- 执行前置: --- 1. 已执行 YumiNail.sql --- 2. 已执行 2026-03-20_user_asset_vip_coupon_permission_patch.sql --- 说明: --- 1. 本文件负责空库初始化模板,不覆盖原始 YumiNail.sql --- 2. admin01 会显式写入后台默认权限,不再依赖 type=4 的运行时全权限兜底 --- 3. 本文件的 t_user_permission 只负责“按用户类型初始化默认权限”,不会删除已有的自定义分配;如果要严格重置已有数据库,请先手工清理旧的 t_user_permission 数据 -use nailart; -SET NAMES utf8mb4; - -INSERT INTO t_permission (permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) -VALUES - ('home:view', '查看首页', '首页', '查看系统首页入口与概览', NOW(), NOW(), 0), - ('dashboard:view', '查看仪表盘', '仪表盘', '查看后台仪表盘统计', NOW(), NOW(), 0), - ('user:view', '查看用户', '用户管理', '查看用户列表与详情', NOW(), NOW(), 0), - ('user:create', '新增用户', '用户管理', '创建用户账号', NOW(), NOW(), 0), - ('user:edit', '编辑用户', '用户管理', '修改用户基础信息', NOW(), NOW(), 0), - ('user:disable', '启停用户', '用户管理', '启用或禁用用户账号', NOW(), NOW(), 0), - ('user:unbind', '解绑用户', '用户管理', '解绑用户与当前店铺的关系', NOW(), NOW(), 0), - ('user:reset_password', '重置密码', '用户管理', '重置用户密码', NOW(), NOW(), 0), - ('user:delete', '删除用户', '用户管理', '删除用户账号', NOW(), NOW(), 0), - ('user:balance:view', '查看余额资产', '用户资产', '查看用户余额、累计充值与流水', NOW(), NOW(), 0), - ('user:balance:manage', '调整余额', '用户资产', '充值、手工加减余额与关联订单', NOW(), NOW(), 0), - ('user:vip:manage', '管理VIP', '用户资产', '手工设置VIP等级或恢复自动判级', NOW(), NOW(), 0), - ('product:view', '查看商品', '商品管理', '查看商品列表与详情', NOW(), NOW(), 0), - ('product:create', '新增商品', '商品管理', '创建商品', NOW(), NOW(), 0), - ('product:edit', '编辑商品', '商品管理', '编辑商品信息', NOW(), NOW(), 0), - ('product:delete', '删除商品', '商品管理', '删除商品', NOW(), NOW(), 0), - ('product:category:manage', '管理商品分类', '商品管理', '维护商品分类与归类信息', NOW(), NOW(), 0), - ('shop:view', '查看店铺', '店铺管理', '查看店铺列表与详情', NOW(), NOW(), 0), - ('shop:create', '新增店铺', '店铺管理', '创建店铺', NOW(), NOW(), 0), - ('shop:edit', '编辑店铺', '店铺管理', '编辑店铺信息', NOW(), NOW(), 0), - ('shop:delete', '删除店铺', '店铺管理', '删除店铺', NOW(), NOW(), 0), - ('shop:staff:manage', '管理员工', '店铺管理', '管理店铺员工与归属', NOW(), NOW(), 0), - ('permission:view', '查看权限', '权限管理', '查看权限清单', NOW(), NOW(), 0), - ('permission:create', '新增权限', '权限管理', '新增系统权限定义', NOW(), NOW(), 0), - ('permission:edit', '编辑权限', '权限管理', '编辑系统权限定义', NOW(), NOW(), 0), - ('permission:delete', '删除权限', '权限管理', '删除系统权限定义', NOW(), NOW(), 0), - ('permission:assign', '分配权限', '权限管理', '给用户分配后台权限', NOW(), NOW(), 0), - ('tag:view', '查看标签', '标签管理', '查看标签列表与详情', NOW(), NOW(), 0), - ('tag:create', '新增标签', '标签管理', '创建标签', NOW(), NOW(), 0), - ('tag:edit', '编辑标签', '标签管理', '编辑标签', NOW(), NOW(), 0), - ('tag:delete', '删除标签', '标签管理', '删除标签', NOW(), NOW(), 0), - ('tag:assign', '分配标签', '标签管理', '给商品或优惠券分配标签', NOW(), NOW(), 0), - ('coupon:view', '查看优惠券', '优惠券管理', '查看优惠券与发放情况', NOW(), NOW(), 0), - ('coupon:create', '新增优惠券', '优惠券管理', '创建优惠券模板', NOW(), NOW(), 0), - ('coupon:edit', '编辑优惠券', '优惠券管理', '编辑优惠券模板', NOW(), NOW(), 0), - ('coupon:delete', '删除优惠券', '优惠券管理', '删除优惠券模板', NOW(), NOW(), 0), - ('coupon:assign', '发放优惠券', '优惠券管理', '向用户发放普通优惠券', NOW(), NOW(), 0), - ('order:view', '查看订单', '订单管理', '查看订单列表与详情', NOW(), NOW(), 0), - ('order:process', '处理订单', '订单管理', '处理订单状态或由美甲师完结订单', NOW(), NOW(), 0), - ('order:edit', '编辑订单', '订单管理', '编辑订单信息的预留权限', NOW(), NOW(), 0), - ('order:delete', '删除订单', '订单管理', '删除订单的预留权限', NOW(), NOW(), 0), - ('nail_artist:view', '查看美甲师', '美甲师管理', '查看美甲师信息与排班入口', NOW(), NOW(), 0), - ('nail_artist:edit', '编辑美甲师', '美甲师管理', '编辑美甲师信息', NOW(), NOW(), 0) -ON DUPLICATE KEY UPDATE - permission_name = VALUES(permission_name), - permission_group = VALUES(permission_group), - description = VALUES(description), - update_time = NOW(), - is_delete = 0; - -INSERT INTO t_user ( - shop_id, - nickname, - account, - phone_verified, - email_verified, - password, - signature, - level, - type, - vip_id, - create_time, - update_time, - is_delete, - status -) -SELECT - 0, - '系统管理员', - 'admin01', - 0, - 0, - '$2a$10$9v.6PztWy3.vmJiVMaOyKuWeVqAnpuHB3hQ3Dgiuz6L8IwBe7Cn9W', - '', - '管理员', - 4, - 0, - NOW(), - NOW(), - 0, - 1 -WHERE NOT EXISTS ( - SELECT 1 - FROM t_user - WHERE account = 'admin01' -); - --- 如需严格按当前默认矩阵重置已有后台用户的权限,请先手工执行类似清理 SQL: --- DELETE up --- FROM t_user_permission up --- INNER JOIN t_user u ON u.id = up.user_id --- WHERE u.type IN (2, 3, 4); - -INSERT INTO t_user_permission (user_id, permission_id, create_time, update_time, create_by, update_by, is_delete) -SELECT u.id, p.id, NOW(), NOW(), u.id, u.id, 0 -FROM t_user u -INNER JOIN t_permission p - ON p.is_delete = 0 - AND p.permission_code IN ( - 'home:view', - 'dashboard:view', - 'user:view', - 'user:create', - 'user:edit', - 'user:disable', - 'user:unbind', - 'user:reset_password', - 'user:delete', - 'user:balance:view', - 'product:view', - 'shop:view', - 'shop:create', - 'shop:edit', - 'shop:delete', - 'shop:staff:manage', - 'permission:view', - 'permission:create', - 'permission:edit', - 'permission:delete', - 'permission:assign', - 'tag:view', - 'coupon:view', - 'order:view', - 'nail_artist:view' - ) -WHERE u.is_delete = 0 - AND u.type = 4 - AND NOT EXISTS ( - SELECT 1 - FROM t_user_permission up - WHERE up.user_id = u.id - AND up.permission_id = p.id - ); - -INSERT INTO t_user_permission (user_id, permission_id, create_time, update_time, create_by, update_by, is_delete) -SELECT u.id, p.id, NOW(), NOW(), u.id, u.id, 0 -FROM t_user u -INNER JOIN t_permission p - ON p.is_delete = 0 - AND p.permission_code IN ( - 'home:view', - 'dashboard:view', - 'user:view', - 'user:create', - 'user:edit', - 'user:unbind', - 'user:reset_password', - 'user:balance:view', - 'user:balance:manage', - 'user:vip:manage', - 'product:view', - 'product:create', - 'product:edit', - 'product:delete', - 'product:category:manage', - 'shop:view', - 'shop:edit', - 'shop:staff:manage', - 'permission:view', - 'permission:assign', - 'tag:view', - 'tag:create', - 'tag:edit', - 'tag:delete', - 'tag:assign', - 'coupon:view', - 'coupon:create', - 'coupon:edit', - 'coupon:delete', - 'coupon:assign', - 'order:view', - 'order:process', - 'order:edit', - 'order:delete', - 'nail_artist:view', - 'nail_artist:edit' - ) -WHERE u.is_delete = 0 - AND u.type = 2 - AND NOT EXISTS ( - SELECT 1 - FROM t_user_permission up - WHERE up.user_id = u.id - AND up.permission_id = p.id - ); - -INSERT INTO t_user_permission (user_id, permission_id, create_time, update_time, create_by, update_by, is_delete) -SELECT u.id, p.id, NOW(), NOW(), u.id, u.id, 0 -FROM t_user u -INNER JOIN t_permission p - ON p.is_delete = 0 - AND p.permission_code IN ( - 'home:view', - 'user:view', - 'user:create', - 'user:balance:view', - 'product:view', - 'product:create', - 'shop:view', - 'tag:view', - 'tag:create', - 'coupon:view', - 'order:view', - 'order:process' - ) -WHERE u.is_delete = 0 - AND u.type = 3 - AND NOT EXISTS ( - SELECT 1 - FROM t_user_permission up - WHERE up.user_id = u.id - AND up.permission_id = p.id - ); - --- 普通用户不初始化后台权限;当前仅允许前台登录和前台业务访问。 diff --git a/YumiNail-Core/src/main/resources/files/2026-03-20_user_asset_vip_coupon_permission_patch.sql b/YumiNail-Core/src/main/resources/files/2026-03-20_user_asset_vip_coupon_permission_patch.sql deleted file mode 100644 index 5c800f41..00000000 --- a/YumiNail-Core/src/main/resources/files/2026-03-20_user_asset_vip_coupon_permission_patch.sql +++ /dev/null @@ -1,329 +0,0 @@ --- 2026-03-20 用户资产 / VIP / 优惠券增量补丁 --- 适用前提:已先执行 YumiNail.sql 完成基础建表 --- 执行说明: --- 1. 本文件只做增量修正,不覆盖原始 YumiNail.sql --- 2. 当前推荐执行链路:YumiNail.sql -> 本补丁 -> 2026-03-20_init_admin_permission_template.sql --- 3. 本补丁仅负责结构补列、索引补齐、VIP 规则与 VIP 自动券模板;权限种子、admin01 初始化与 t_user_permission 模板已迁移到独立初始化模板 SQL --- 4. 历史累计充值金额无法从旧表精确反推,本补丁仅把缺失值归零;如需保留历史累计充值,请按业务数据手工回填 total_recharge_amount -use nailart; -SET NAMES utf8mb4; - -DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists; -DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists; -DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists; - -DELIMITER $$ - -CREATE PROCEDURE sp_add_column_if_not_exists( - IN p_table_name VARCHAR(64), - IN p_column_name VARCHAR(64), - IN p_definition TEXT -) -BEGIN - IF NOT EXISTS ( - SELECT 1 - FROM information_schema.COLUMNS - WHERE TABLE_SCHEMA = DATABASE() - AND TABLE_NAME = p_table_name - AND COLUMN_NAME = p_column_name - ) THEN - SET @sql = CONCAT( - 'ALTER TABLE `', p_table_name, '` ADD COLUMN `', p_column_name, '` ', - p_definition - ); - PREPARE stmt FROM @sql; - EXECUTE stmt; - DEALLOCATE PREPARE stmt; - END IF; -END$$ - -CREATE PROCEDURE sp_add_index_if_not_exists( - IN p_table_name VARCHAR(64), - IN p_index_name VARCHAR(64), - IN p_columns TEXT -) -BEGIN - IF NOT EXISTS ( - SELECT 1 - FROM information_schema.STATISTICS - WHERE TABLE_SCHEMA = DATABASE() - AND TABLE_NAME = p_table_name - AND INDEX_NAME = p_index_name - ) THEN - SET @sql = CONCAT( - 'ALTER TABLE `', p_table_name, '` ADD INDEX `', p_index_name, '` ', - p_columns - ); - PREPARE stmt FROM @sql; - EXECUTE stmt; - DEALLOCATE PREPARE stmt; - END IF; -END$$ - -CREATE PROCEDURE sp_add_unique_index_if_not_exists( - IN p_table_name VARCHAR(64), - IN p_index_name VARCHAR(64), - IN p_columns TEXT -) -BEGIN - IF NOT EXISTS ( - SELECT 1 - FROM information_schema.STATISTICS - WHERE TABLE_SCHEMA = DATABASE() - AND TABLE_NAME = p_table_name - AND INDEX_NAME = p_index_name - ) THEN - SET @sql = CONCAT( - 'ALTER TABLE `', p_table_name, '` ADD UNIQUE INDEX `', p_index_name, '` ', - p_columns - ); - PREPARE stmt FROM @sql; - EXECUTE stmt; - DEALLOCATE PREPARE stmt; - END IF; -END$$ - -DELIMITER ; - -CALL sp_add_column_if_not_exists('t_balance', 'total_recharge_amount', 'decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT ''累计充值金额'''); -CALL sp_add_column_if_not_exists('t_balance', 'last_recharge_time', 'datetime NULL COMMENT ''最近一次充值时间'''); - -UPDATE t_balance -SET total_recharge_amount = COALESCE(total_recharge_amount, 0.00) -WHERE total_recharge_amount IS NULL; - -CALL sp_add_column_if_not_exists('t_balance_change_detail', 'before_balance', 'decimal(10,2) NULL COMMENT ''变动前余额'''); -CALL sp_add_column_if_not_exists('t_balance_change_detail', 'after_balance', 'decimal(10,2) NULL COMMENT ''变动后余额'''); -CALL sp_add_column_if_not_exists('t_balance_change_detail', 'change_scene', 'varchar(32) NULL COMMENT ''余额变动场景'''); -CALL sp_add_column_if_not_exists('t_balance_change_detail', 'related_order_id', 'bigint unsigned NULL COMMENT ''关联系统订单ID'''); -CALL sp_add_column_if_not_exists('t_balance_change_detail', 'related_order_no', 'varchar(64) NULL COMMENT ''关联系统订单号'''); -CALL sp_add_column_if_not_exists('t_balance_change_detail', 'external_order_no', 'varchar(64) NULL COMMENT ''手工录入的外部订单号'''); -CALL sp_add_column_if_not_exists('t_balance_change_detail', 'operator_id', 'bigint unsigned NULL COMMENT ''操作人ID'''); -CALL sp_add_column_if_not_exists('t_balance_change_detail', 'remark', 'varchar(255) NULL COMMENT ''备注'''); - -UPDATE t_balance_change_detail -SET before_balance = COALESCE(before_balance, current_balance - amount), - after_balance = COALESCE(after_balance, current_balance), - change_scene = COALESCE(NULLIF(change_scene, ''), type) -WHERE before_balance IS NULL - OR after_balance IS NULL - OR change_scene IS NULL - OR change_scene = ''; - -CALL sp_add_index_if_not_exists('t_balance_change_detail', 'idx_balance_detail_related_order_id', '(`related_order_id`)'); -CALL sp_add_index_if_not_exists('t_balance_change_detail', 'idx_balance_detail_operator_id', '(`operator_id`)'); - -CALL sp_add_column_if_not_exists('t_order', 'shop_id', 'bigint unsigned NULL COMMENT ''所属店铺ID'''); -CALL sp_add_column_if_not_exists('t_order', 'user_coupon_id', 'bigint unsigned NULL COMMENT ''用户券ID'''); -CALL sp_add_column_if_not_exists('t_order', 'coupon_source_type', 'varchar(32) NULL COMMENT ''优惠来源类型'''); - -UPDATE t_order -SET coupon_id = NULL -WHERE coupon_id = 0; - -UPDATE t_order o -INNER JOIN ( - SELECT oi.order_id, MIN(p.shop_id) AS resolved_shop_id - FROM t_order_item oi - INNER JOIN t_product p ON p.id = oi.product_id - GROUP BY oi.order_id -) detail_shop ON detail_shop.order_id = o.id -SET o.shop_id = detail_shop.resolved_shop_id -WHERE o.shop_id IS NULL; - -UPDATE t_order -SET coupon_source_type = 'USER_COUPON' -WHERE coupon_source_type IS NULL - AND coupon_id IS NOT NULL; - -CALL sp_add_index_if_not_exists('t_order', 'idx_t_order_shop_id', '(`shop_id`)'); -CALL sp_add_index_if_not_exists('t_order', 'idx_t_order_coupon_source_type', '(`coupon_source_type`)'); - -CALL sp_add_column_if_not_exists('t_order_item', 'appointment_time', 'datetime NULL COMMENT ''预约开始时间'''); -CALL sp_add_index_if_not_exists('t_order_item', 'idx_t_order_item_artist_appointment_time', '(`artist_id`, `appointment_time`)'); - -CALL sp_add_column_if_not_exists('t_coupon', 'coupon_scene', 'varchar(32) NOT NULL DEFAULT ''NORMAL'' COMMENT ''优惠券场景'''); -CALL sp_add_column_if_not_exists('t_coupon', 'required_vip_level', 'varchar(20) NULL COMMENT ''要求的VIP等级'''); -CALL sp_add_column_if_not_exists('t_coupon', 'auto_match', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''是否自动匹配'''); - -UPDATE t_coupon -SET coupon_scene = COALESCE(NULLIF(coupon_scene, ''), 'NORMAL'), - auto_match = COALESCE(auto_match, 0) -WHERE coupon_scene IS NULL - OR coupon_scene = '' - OR auto_match IS NULL; - -CALL sp_add_index_if_not_exists('t_coupon', 'idx_t_coupon_scene_auto_match', '(`coupon_scene`, `auto_match`)'); -CALL sp_add_index_if_not_exists('t_coupon', 'idx_t_coupon_required_vip_level', '(`required_vip_level`)'); - -CALL sp_add_column_if_not_exists('t_vip_benefit', 'level_rank', 'int NOT NULL DEFAULT 0 COMMENT ''等级序号'''); -CALL sp_add_column_if_not_exists('t_vip_benefit', 'recharge_threshold', 'decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT ''累计充值门槛'''); -CALL sp_add_column_if_not_exists('t_vip_benefit', 'status', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''状态'''); - -UPDATE t_vip_benefit -SET level_rank = CASE required_vip_level - WHEN '普通' THEN 0 - WHEN '青铜' THEN 1 - WHEN '白银' THEN 2 - WHEN '黄金' THEN 3 - ELSE level_rank - END, - recharge_threshold = CASE required_vip_level - WHEN '普通' THEN 0.00 - WHEN '青铜' THEN 500.00 - WHEN '白银' THEN 1000.00 - WHEN '黄金' THEN 2000.00 - ELSE recharge_threshold - END, - status = COALESCE(status, 1) -WHERE required_vip_level IN ('普通', '青铜', '白银', '黄金'); - -CALL sp_add_index_if_not_exists('t_vip_benefit', 'idx_t_vip_benefit_status_rank', '(`status`, `level_rank`)'); - -CALL sp_add_column_if_not_exists('t_vip_info', 'user_id', 'bigint unsigned NULL COMMENT ''所属用户ID'''); -CALL sp_add_column_if_not_exists('t_vip_info', 'manual_override', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''是否手工覆盖VIP等级'''); - -ALTER TABLE t_vip_info - MODIFY COLUMN expire_time datetime NULL COMMENT 'VIP到期时间', - MODIFY COLUMN benefit_id bigint unsigned NULL COMMENT '关联VIP权益信息表主键'; - -UPDATE t_vip_info vi -INNER JOIN t_user u ON u.vip_id = vi.id -SET vi.user_id = u.id -WHERE (vi.user_id IS NULL OR vi.user_id = 0) - AND u.vip_id IS NOT NULL - AND u.vip_id <> 0; - -UPDATE t_vip_info -SET start_time = COALESCE(start_time, create_time, NOW()), - activation_method = COALESCE(NULLIF(activation_method, ''), 'INIT'), - manual_override = COALESCE(manual_override, 0); - -CALL sp_add_unique_index_if_not_exists('t_vip_info', 'uk_t_vip_info_user_id', '(`user_id`)'); -CALL sp_add_index_if_not_exists('t_vip_info', 'idx_t_vip_info_manual_override', '(`manual_override`)'); - -UPDATE t_user u -LEFT JOIN t_vip_info vi ON vi.id = u.vip_id -SET u.level = CASE - WHEN u.type = 0 AND u.vip_id IS NOT NULL AND u.vip_id <> 0 AND vi.vip_level IS NOT NULL THEN vi.vip_level - WHEN u.type = 0 THEN '普通' - ELSE u.level - END, - u.vip_id = CASE - WHEN u.type = 0 AND u.vip_id IS NULL THEN 0 - ELSE u.vip_id - END, - u.update_time = NOW() -WHERE u.is_delete = 0 - AND u.type = 0 - AND (u.level IS NULL OR u.level = '' OR u.vip_id IS NULL); - --- 权限种子、admin01 初始化与最终的 t_user_permission 分配规则, --- 已迁移到 2026-03-20_init_admin_permission_template.sql 统一维护。 - -UPDATE t_vip_benefit -SET benefit_info = '普通用户,无额外VIP折扣', - level_rank = 0, - recharge_threshold = 0.00, - status = 1, - update_time = NOW() -WHERE required_vip_level = '普通'; - -INSERT INTO t_vip_benefit (benefit_info, required_vip_level, level_rank, recharge_threshold, status, create_time, update_time) -SELECT '普通用户,无额外VIP折扣', '普通', 0, 0.00, 1, NOW(), NOW() -WHERE NOT EXISTS ( - SELECT 1 - FROM t_vip_benefit - WHERE required_vip_level = '普通' -); - -UPDATE t_vip_benefit -SET benefit_info = '青铜VIP,系统自动匹配9.5折券', - level_rank = 1, - recharge_threshold = 500.00, - status = 1, - update_time = NOW() -WHERE required_vip_level = '青铜'; - -INSERT INTO t_vip_benefit (benefit_info, required_vip_level, level_rank, recharge_threshold, status, create_time, update_time) -SELECT '青铜VIP,系统自动匹配9.5折券', '青铜', 1, 500.00, 1, NOW(), NOW() -WHERE NOT EXISTS ( - SELECT 1 - FROM t_vip_benefit - WHERE required_vip_level = '青铜' -); - -UPDATE t_vip_benefit -SET benefit_info = '白银VIP,系统自动匹配9.2折券', - level_rank = 2, - recharge_threshold = 1000.00, - status = 1, - update_time = NOW() -WHERE required_vip_level = '白银'; - -INSERT INTO t_vip_benefit (benefit_info, required_vip_level, level_rank, recharge_threshold, status, create_time, update_time) -SELECT '白银VIP,系统自动匹配9.2折券', '白银', 2, 1000.00, 1, NOW(), NOW() -WHERE NOT EXISTS ( - SELECT 1 - FROM t_vip_benefit - WHERE required_vip_level = '白银' -); - -UPDATE t_vip_benefit -SET benefit_info = '黄金VIP,系统自动匹配9.0折券', - level_rank = 3, - recharge_threshold = 2000.00, - status = 1, - update_time = NOW() -WHERE required_vip_level = '黄金'; - -INSERT INTO t_vip_benefit (benefit_info, required_vip_level, level_rank, recharge_threshold, status, create_time, update_time) -SELECT '黄金VIP,系统自动匹配9.0折券', '黄金', 3, 2000.00, 1, NOW(), NOW() -WHERE NOT EXISTS ( - SELECT 1 - FROM t_vip_benefit - WHERE required_vip_level = '黄金' -); - -INSERT INTO t_coupon ( - coupon_code, - coupon_name, - coupon_type, - discount_value, - min_amount, - reduce_amount, - total_count, - used_count, - start_time, - end_time, - status, - create_time, - update_time, - is_delete, - shop_id, - coupon_scene, - required_vip_level, - auto_match -) -VALUES - ('VIP_AUTO_BRONZE_95', '青铜VIP自动95折券', 1, 9.50, 0.00, 0.00, 999999, 0, NOW(), '2099-12-31 23:59:59', 1, NOW(), NOW(), 0, NULL, 'VIP_AUTO', '青铜', 1), - ('VIP_AUTO_SILVER_92', '白银VIP自动92折券', 1, 9.20, 0.00, 0.00, 999999, 0, NOW(), '2099-12-31 23:59:59', 1, NOW(), NOW(), 0, NULL, 'VIP_AUTO', '白银', 1), - ('VIP_AUTO_GOLD_90', '黄金VIP自动90折券', 1, 9.00, 0.00, 0.00, 999999, 0, NOW(), '2099-12-31 23:59:59', 1, NOW(), NOW(), 0, NULL, 'VIP_AUTO', '黄金', 1) -ON DUPLICATE KEY UPDATE - coupon_name = VALUES(coupon_name), - coupon_type = VALUES(coupon_type), - discount_value = VALUES(discount_value), - min_amount = VALUES(min_amount), - reduce_amount = VALUES(reduce_amount), - total_count = VALUES(total_count), - status = VALUES(status), - is_delete = VALUES(is_delete), - shop_id = VALUES(shop_id), - coupon_scene = VALUES(coupon_scene), - required_vip_level = VALUES(required_vip_level), - auto_match = VALUES(auto_match), - update_time = NOW(); - -DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists; -DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists; -DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists; diff --git a/YumiNail-Core/src/main/resources/files/2026-03-25_user_shop_binding_and_shop_status_patch.sql b/YumiNail-Core/src/main/resources/files/2026-03-25_user_shop_binding_and_shop_status_patch.sql deleted file mode 100644 index ff7f6141..00000000 --- a/YumiNail-Core/src/main/resources/files/2026-03-25_user_shop_binding_and_shop_status_patch.sql +++ /dev/null @@ -1,165 +0,0 @@ --- 2026-03-25 多店铺登录 / 店铺状态 / 用户店铺绑定补丁 --- 推荐执行顺序: --- 1. YumiNail.sql --- 2. 2026-03-20_user_asset_vip_coupon_permission_patch.sql --- 3. 2026-03-25_user_shop_binding_and_shop_status_patch.sql --- 4. 2026-03-20_init_admin_permission_template.sql --- --- 说明: --- 1. 本文件不覆盖主建表 SQL,只补结构与历史数据回填。 --- 2. 本补丁会新增 t_user_shop_binding,并把现有 t_user.shop_id 回填为默认绑定关系。 --- 3. t_shop.status 用于店铺启停;停用后不删除绑定,只禁止该店铺登录。 - -use nailart; -SET NAMES utf8mb4; - -DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists; -DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists; -DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists; - -DELIMITER $$ - -CREATE PROCEDURE sp_add_column_if_not_exists( - IN p_table_name VARCHAR(64), - IN p_column_name VARCHAR(64), - IN p_definition TEXT -) -BEGIN - IF NOT EXISTS ( - SELECT 1 - FROM information_schema.COLUMNS - WHERE TABLE_SCHEMA = DATABASE() - AND TABLE_NAME = p_table_name - AND COLUMN_NAME = p_column_name - ) THEN - SET @sql = CONCAT( - 'ALTER TABLE `', p_table_name, '` ADD COLUMN `', p_column_name, '` ', - p_definition - ); - PREPARE stmt FROM @sql; - EXECUTE stmt; - DEALLOCATE PREPARE stmt; - END IF; -END$$ - -CREATE PROCEDURE sp_add_index_if_not_exists( - IN p_table_name VARCHAR(64), - IN p_index_name VARCHAR(64), - IN p_columns TEXT -) -BEGIN - IF NOT EXISTS ( - SELECT 1 - FROM information_schema.STATISTICS - WHERE TABLE_SCHEMA = DATABASE() - AND TABLE_NAME = p_table_name - AND INDEX_NAME = p_index_name - ) THEN - SET @sql = CONCAT( - 'ALTER TABLE `', p_table_name, '` ADD INDEX `', p_index_name, '` ', - p_columns - ); - PREPARE stmt FROM @sql; - EXECUTE stmt; - DEALLOCATE PREPARE stmt; - END IF; -END$$ - -CREATE PROCEDURE sp_add_unique_index_if_not_exists( - IN p_table_name VARCHAR(64), - IN p_index_name VARCHAR(64), - IN p_columns TEXT -) -BEGIN - IF NOT EXISTS ( - SELECT 1 - FROM information_schema.STATISTICS - WHERE TABLE_SCHEMA = DATABASE() - AND TABLE_NAME = p_table_name - AND INDEX_NAME = p_index_name - ) THEN - SET @sql = CONCAT( - 'ALTER TABLE `', p_table_name, '` ADD UNIQUE INDEX `', p_index_name, '` ', - p_columns - ); - PREPARE stmt FROM @sql; - EXECUTE stmt; - DEALLOCATE PREPARE stmt; - END IF; -END$$ - -DELIMITER ; - -CALL sp_add_column_if_not_exists('t_shop', 'status', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''店铺状态:1-启用,0-停用'''); - -UPDATE t_shop -SET status = 1 -WHERE status IS NULL; - -CALL sp_add_index_if_not_exists('t_shop', 'idx_t_shop_status', '(`status`)'); - -CREATE TABLE IF NOT EXISTS `t_user_shop_binding` ( - `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT '用户店铺绑定主键ID', - `user_id` bigint unsigned NOT NULL COMMENT '用户ID', - `shop_id` bigint unsigned NOT NULL COMMENT '店铺ID', - `status` tinyint unsigned NOT NULL DEFAULT 1 COMMENT '绑定状态:1-正常,0-禁用', - `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', - `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', - `is_delete` tinyint unsigned DEFAULT 0 COMMENT '逻辑删除:0-未删,1-已删', - PRIMARY KEY (`id`) -) COMMENT='用户与店铺绑定关系表'; - -CALL sp_add_column_if_not_exists('t_user_shop_binding', 'status', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''绑定状态:1-正常,0-禁用'''); -CALL sp_add_column_if_not_exists('t_user_shop_binding', 'create_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间'''); -CALL sp_add_column_if_not_exists('t_user_shop_binding', 'update_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT ''更新时间'''); -CALL sp_add_column_if_not_exists('t_user_shop_binding', 'is_delete', 'tinyint unsigned DEFAULT 0 COMMENT ''逻辑删除:0-未删,1-已删'''); - -CALL sp_add_index_if_not_exists('t_user_shop_binding', 'idx_t_user_shop_binding_user_id', '(`user_id`)'); -CALL sp_add_index_if_not_exists('t_user_shop_binding', 'idx_t_user_shop_binding_shop_id', '(`shop_id`)'); -CALL sp_add_index_if_not_exists('t_user_shop_binding', 'idx_t_user_shop_binding_status', '(`status`)'); -CALL sp_add_unique_index_if_not_exists('t_user_shop_binding', 'uk_t_user_shop_binding_user_shop', '(`user_id`, `shop_id`)'); - -INSERT INTO t_user_shop_binding ( - user_id, - shop_id, - status, - create_time, - update_time, - is_delete -) -SELECT - u.id, - u.shop_id, - CASE - WHEN COALESCE(u.status, 1) = 1 THEN 1 - ELSE 0 - END AS binding_status, - COALESCE(u.create_time, NOW()), - COALESCE(u.update_time, NOW()), - 0 -FROM t_user u -INNER JOIN t_shop s ON s.id = u.shop_id AND COALESCE(s.is_delete, 0) = 0 -LEFT JOIN t_user_shop_binding b - ON b.user_id = u.id - AND b.shop_id = u.shop_id - AND COALESCE(b.is_delete, 0) = 0 -WHERE COALESCE(u.is_delete, 0) = 0 - AND u.shop_id IS NOT NULL - AND u.shop_id > 0 - AND b.id IS NULL; - -UPDATE t_user_shop_binding b -INNER JOIN t_user u ON u.id = b.user_id -SET b.status = CASE - WHEN b.status IS NULL THEN CASE WHEN COALESCE(u.status, 1) = 1 THEN 1 ELSE 0 END - ELSE b.status - END, - b.is_delete = COALESCE(b.is_delete, 0), - b.update_time = COALESCE(b.update_time, NOW()) -WHERE b.status IS NULL - OR b.is_delete IS NULL - OR b.update_time IS NULL; - -DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists; -DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists; -DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists; diff --git a/YumiNail-Core/src/main/resources/files/2026-03-27_artist_order_process_default_permission_patch.sql b/YumiNail-Core/src/main/resources/files/2026-03-27_artist_order_process_default_permission_patch.sql deleted file mode 100644 index 2495e4cd..00000000 --- a/YumiNail-Core/src/main/resources/files/2026-03-27_artist_order_process_default_permission_patch.sql +++ /dev/null @@ -1,29 +0,0 @@ --- 为历史美甲师账号补齐“处理订单”默认权限 --- 说明: --- 1. 该补丁可重复执行 --- 2. 仅影响 type = 3 的美甲师账号 --- 3. 若现有系统已通过后台登录触发默认权限同步,也可以不手工执行本文件 - -INSERT INTO t_permission (permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) -SELECT 'order:process', '处理订单', '订单管理', '处理订单状态或由美甲师完结订单', NOW(), NOW(), 0 -WHERE NOT EXISTS ( - SELECT 1 - FROM t_permission - WHERE permission_code = 'order:process' - AND is_delete = 0 -); - -INSERT INTO t_user_permission (user_id, permission_id, create_time, update_time, create_by, update_by, is_delete) -SELECT u.id, p.id, NOW(), NOW(), 0, 0, 0 -FROM t_user u -INNER JOIN t_permission p - ON p.permission_code = 'order:process' - AND p.is_delete = 0 -WHERE u.is_delete = 0 - AND u.type = 3 - AND NOT EXISTS ( - SELECT 1 - FROM t_user_permission up - WHERE up.user_id = u.id - AND up.permission_id = p.id - ); diff --git a/YumiNail-Core/src/main/resources/files/2026-03-30_snowflake_id_alignment_patch.sql b/YumiNail-Core/src/main/resources/files/2026-03-30_snowflake_id_alignment_patch.sql deleted file mode 100644 index 3484f8db..00000000 --- a/YumiNail-Core/src/main/resources/files/2026-03-30_snowflake_id_alignment_patch.sql +++ /dev/null @@ -1,74 +0,0 @@ --- YumiNail 雪花 ID 主键口径对齐补丁 --- 适用场景: --- 1. 已经执行过旧版 YumiNail.sql 的存量库 --- 2. 需要将运行时已切到应用层雪花 ID 的表,去掉数据库侧 AUTO_INCREMENT --- --- 注意: --- 1. 如果你的数据库名不是 nailart,请先修改下面的 use 语句 --- 2. 本补丁不会改动已有数据,只会调整 id 列定义 - -USE nailart; - -DROP PROCEDURE IF EXISTS sp_drop_auto_increment_on_id_if_exists; - -DELIMITER $$ - -CREATE PROCEDURE sp_drop_auto_increment_on_id_if_exists(IN p_table_name VARCHAR(64)) -BEGIN - DECLARE v_column_type VARCHAR(128) DEFAULT NULL; - DECLARE v_column_comment VARCHAR(255) DEFAULT NULL; - DECLARE v_extra VARCHAR(128) DEFAULT NULL; - - SELECT COLUMN_TYPE, COLUMN_COMMENT, EXTRA - INTO v_column_type, v_column_comment, v_extra - FROM information_schema.COLUMNS - WHERE TABLE_SCHEMA = DATABASE() - AND TABLE_NAME = p_table_name - AND COLUMN_NAME = 'id' - LIMIT 1; - - IF v_column_type IS NOT NULL AND v_extra LIKE '%auto_increment%' THEN - SET @alter_sql = CONCAT( - 'ALTER TABLE `', p_table_name, '` MODIFY COLUMN `id` ', - v_column_type, - ' NOT NULL' - ); - - IF v_column_comment IS NOT NULL AND v_column_comment <> '' THEN - SET @alter_sql = CONCAT(@alter_sql, ' COMMENT ', QUOTE(v_column_comment)); - END IF; - - PREPARE stmt FROM @alter_sql; - EXECUTE stmt; - DEALLOCATE PREPARE stmt; - END IF; -END$$ - -DELIMITER ; - -CALL sp_drop_auto_increment_on_id_if_exists('t_balance'); -CALL sp_drop_auto_increment_on_id_if_exists('t_balance_change_detail'); -CALL sp_drop_auto_increment_on_id_if_exists('t_cart'); -CALL sp_drop_auto_increment_on_id_if_exists('t_comment'); -CALL sp_drop_auto_increment_on_id_if_exists('t_coupon'); -CALL sp_drop_auto_increment_on_id_if_exists('t_coupon_tag'); -CALL sp_drop_auto_increment_on_id_if_exists('t_effect_diagram'); -CALL sp_drop_auto_increment_on_id_if_exists('t_login_identity'); -CALL sp_drop_auto_increment_on_id_if_exists('t_nail_artist_info'); -CALL sp_drop_auto_increment_on_id_if_exists('t_object_storage_file'); -CALL sp_drop_auto_increment_on_id_if_exists('t_order'); -CALL sp_drop_auto_increment_on_id_if_exists('t_order_item'); -CALL sp_drop_auto_increment_on_id_if_exists('t_permission'); -CALL sp_drop_auto_increment_on_id_if_exists('t_product'); -CALL sp_drop_auto_increment_on_id_if_exists('t_product_like'); -CALL sp_drop_auto_increment_on_id_if_exists('t_shop'); -CALL sp_drop_auto_increment_on_id_if_exists('t_tag'); -CALL sp_drop_auto_increment_on_id_if_exists('t_user'); -CALL sp_drop_auto_increment_on_id_if_exists('t_user_coupon'); -CALL sp_drop_auto_increment_on_id_if_exists('t_user_permission'); -CALL sp_drop_auto_increment_on_id_if_exists('t_vip_benefit'); -CALL sp_drop_auto_increment_on_id_if_exists('t_vip_info'); -CALL sp_drop_auto_increment_on_id_if_exists('t_wishlist'); -CALL sp_drop_auto_increment_on_id_if_exists('t_user_shop_binding'); - -DROP PROCEDURE IF EXISTS sp_drop_auto_increment_on_id_if_exists; diff --git a/YumiNail-Core/src/main/resources/files/2026-04-02_wechat_mini_binding_patch.sql b/YumiNail-Core/src/main/resources/files/2026-04-02_wechat_mini_binding_patch.sql deleted file mode 100644 index 2bd28740..00000000 --- a/YumiNail-Core/src/main/resources/files/2026-04-02_wechat_mini_binding_patch.sql +++ /dev/null @@ -1,55 +0,0 @@ -CREATE TABLE IF NOT EXISTS t_wechat_mini_binding -( - id BIGINT UNSIGNED NOT NULL COMMENT '微信小程序绑定主键ID(雪花ID)', - user_id BIGINT UNSIGNED NOT NULL COMMENT '关联用户ID', - app_id VARCHAR(64) NOT NULL COMMENT '微信小程序appId', - openid VARCHAR(100) NOT NULL COMMENT '微信小程序openid', - unionid VARCHAR(100) NULL COMMENT '微信开放平台unionid', - status TINYINT UNSIGNED DEFAULT 1 NULL COMMENT '状态:1-有效,0-失效', - create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL COMMENT '创建时间', - update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', - PRIMARY KEY (id) -) COMMENT = '微信小程序账号绑定表'; - -DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists; -DELIMITER $$ -CREATE PROCEDURE sp_add_index_if_not_exists( - IN p_table_name VARCHAR(64), - IN p_index_name VARCHAR(64), - IN p_index_sql TEXT -) -BEGIN - IF NOT EXISTS ( - SELECT 1 - FROM information_schema.statistics - WHERE table_schema = DATABASE() - AND table_name = p_table_name - AND index_name = p_index_name - ) THEN - SET @index_sql = p_index_sql; - PREPARE stmt FROM @index_sql; - EXECUTE stmt; - DEALLOCATE PREPARE stmt; - END IF; -END$$ -DELIMITER ; - -CALL sp_add_index_if_not_exists( - 't_wechat_mini_binding', - 'idx_wechat_mini_unionid', - 'CREATE INDEX idx_wechat_mini_unionid ON t_wechat_mini_binding (unionid)' -); - -CALL sp_add_index_if_not_exists( - 't_wechat_mini_binding', - 'uk_wechat_mini_app_openid', - 'ALTER TABLE t_wechat_mini_binding ADD CONSTRAINT uk_wechat_mini_app_openid UNIQUE (app_id, openid)' -); - -CALL sp_add_index_if_not_exists( - 't_wechat_mini_binding', - 'uk_wechat_mini_app_user', - 'ALTER TABLE t_wechat_mini_binding ADD CONSTRAINT uk_wechat_mini_app_user UNIQUE (app_id, user_id)' -); - -DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists; diff --git a/YumiNail-Core/src/main/resources/files/YumiNail-back.sql b/YumiNail-Core/src/main/resources/files/YumiNail-back.sql deleted file mode 100644 index 98a4bda4..00000000 --- a/YumiNail-Core/src/main/resources/files/YumiNail-back.sql +++ /dev/null @@ -1,661 +0,0 @@ --- 用户余额信息表 -create table t_balance -( - id bigint unsigned auto_increment comment '余额记录唯一主键ID(雪花ID)' - primary key comment '余额表主键索引', - user_id bigint unsigned not null comment '关联用户表主键', - amount decimal(10, 2) default 0.00 not null comment '当前余额', - create_time datetime default CURRENT_TIMESTAMP not null comment '余额账户创建时间', - last_update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '最近一次更新时间', - constraint uk_user_id - unique (user_id) comment '用户余额唯一索引(一个用户对应一条余额记录)' -) - comment '用户余额信息表'; --- 用户余额变动明细表 -create table t_balance_change_detail -( - id bigint unsigned auto_increment comment '变动记录唯一主键ID(雪花ID)' - primary key comment '余额变动明细主键索引', - user_id bigint unsigned not null comment '关联用户表主键', - amount decimal(10, 2) not null comment '本次变动金额(正数为增加,负数为减少)', - type varchar(20) not null comment '变动类型(如充值、消费、退款)', - current_balance decimal(10, 2) not null comment '变动后的当前余额', - change_time datetime default CURRENT_TIMESTAMP not null comment '变动时间' -) - comment '用户余额变动明细表'; - -create index idx_change_time - on t_balance_change_detail (change_time) - comment '按时间查询余额变动的索引'; - -create index idx_user_id - on t_balance_change_detail (user_id) - comment '按用户查询余额变动的索引'; - --- 用户评论信息表 -create table t_comment -( - id bigint unsigned auto_increment comment '评论唯一主键ID(雪花ID)' - primary key comment '评论主键索引', - user_id bigint unsigned not null comment '评论用户ID,关联用户表主键', - shop_id bigint unsigned default 0 null comment '关联店铺表主键(0表示非店铺评论)', - product_id bigint unsigned default 0 null comment '关联商品表主键(0表示非商品评论)', - comment_content text not null comment '评论内容', - parent_comment_id bigint unsigned default 0 null comment '父级评论ID(0表示为根评论)', - like_count int unsigned default 0 null comment '评论点赞数', - create_time datetime default CURRENT_TIMESTAMP not null comment '评论创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '评论更新时间', - is_delete tinyint unsigned default 0 null comment '逻辑删除标识:0-未删除,1-已删除' -) - comment '用户评论信息表'; - -create index idx_parent_comment_id - on t_comment (parent_comment_id) - comment '按父级评论查询回复的索引'; - -create index idx_product_id - on t_comment (product_id) - comment '按商品查询评论的索引'; - -create index idx_shop_id - on t_comment (shop_id) - comment '按店铺查询评论的索引'; - -create index idx_user_id - on t_comment (user_id) - comment '按用户查询评论的索引'; - - - --- 商品效果图信息表 -create table t_effect_diagram -( - id bigint unsigned auto_increment comment '效果图唯一主键ID(雪花id)' - primary key comment '效果图主键索引', - product_id bigint unsigned not null comment '所属商品ID,关联商品表主键', - category varchar(50) default '' null comment '效果图类别', - image_file_ids text null comment '图片文件ID集合,多ID以逗号分隔', - description text null comment '效果图描述', - price decimal(10, 2) default 0.00 null comment '效果图对应服务价格', - duration varchar(50) default '' null comment '效果图对应服务耗时', - tag varchar(50) default '' null comment '效果图标签', - like_count int unsigned default 0 null comment '效果图点赞数', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' -) - comment '商品效果图信息表'; - -create index idx_product_id - on t_effect_diagram (product_id) - comment '按商品查询效果图的索引'; - --- 用户登录标识信息表 -create table t_login_identity -( - id bigint unsigned auto_increment comment '登录标识唯一主键ID(雪花id)' - primary key comment '登录标识主键索引', - user_id bigint unsigned not null comment '关联用户表主键', - login_method varchar(50) not null comment '登录方式(0-手机号、1-账号、2-邮箱)', - input_value varchar(100) not null comment '前端输入的具体值(如手机号、账号、邮箱)', - input_time datetime not null comment '输入时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - status tinyint unsigned default 1 null comment '状态:1-有效,0-无效' -) - comment '用户登录标识信息表'; - -create index idx_login_method - on t_login_identity (login_method) - comment '按登录方式查询的索引'; - -create index idx_user_id - on t_login_identity (user_id) - comment '按用户查询登录标识的索引'; - --- 对象存储文件信息表 -create table t_object_storage_file -( - id bigint unsigned auto_increment comment '文件记录唯一主键ID(雪花ID)' - primary key comment '对象存储文件主键索引', - file_name varchar(100) not null comment '文件名称', - file_url text not null comment '文件访问链接', - create_time datetime default CURRENT_TIMESTAMP not null comment '文件上传时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '文件更新时间', - status tinyint unsigned default 1 null comment '文件状态:1-可用,0-不可用,2-回收站', - delete_time datetime null comment '文件删除时间(NULL表示未删除)', - recycle_time datetime null comment '文件移入回收站时间(NULL表示未移入)' -) - comment '对象存储文件信息表'; - -create index idx_status - on t_object_storage_file (status) - comment '按文件状态查询的索引'; - - --- 系统权限表 -create table t_permission -( - id bigint unsigned auto_increment comment '权限唯一主键ID' - primary key, - permission_code varchar(100) not null comment '权限编码(唯一标识)', - permission_name varchar(100) not null comment '权限名称', - permission_group varchar(50) not null comment '权限分组(商品管理、用户管理等)', - description varchar(255) null comment '权限描述', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', - constraint uk_permission_code - unique (permission_code) comment '权限编码唯一索引' -) - comment '系统权限表'; - --- 商品信息表 -create table t_product -( - id bigint unsigned auto_increment comment '商品唯一主键ID(雪花id)' - primary key comment '商品主键索引', - shop_id bigint unsigned not null comment '所属店铺ID,关联店铺表主键', - title varchar(100) not null comment '商品标题', - description text null comment '商品描述', - image_file_ids text null comment '图片文件ID集合,多个ID以逗号分隔', - price decimal(10, 2) not null comment '商品价格,保留2位小数', - tags varchar(512) default '' null comment '标签集合,多个标签以逗号分隔,最多5个', - like_count int unsigned default 0 null comment '商品点赞数', - collect_count int unsigned default 0 null comment '商品收藏数', - approximate_duration varchar(50) default '' null comment '商品对应的服务大约耗时(如“30分钟”)', - bookable_artists varchar(200) default '' null comment '可预约的美甲师ID集合,多个ID以逗号分隔', - available_coupons text null comment '可用的优惠券ID集合,多个ID以逗号分隔', - create_time datetime default CURRENT_TIMESTAMP not null comment '商品创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '商品信息最后更新时间', - is_delete tinyint unsigned default 0 null comment '逻辑删除标识:0-未删除,1-已删除' -) - comment '商品信息表'; - -create index idx_price - on t_product (price) - comment '按价格筛选商品的索引'; - -create index idx_shop_id - on t_product (shop_id) - comment '按所属店铺查询商品的索引'; - -create index idx_tags - on t_product (tags) - comment '按标签筛选商品的索引'; - -create index idx_title - on t_product (title) - comment '商品标题搜索的索引'; - --- 店铺信息表 -create table t_shop -( - id bigint unsigned comment '店铺唯一主键ID(雪花ID)' - primary key comment '店铺主键索引', - shop_name varchar(100) not null comment '店铺名称', - description text null comment '店铺描述', - address varchar(200) not null comment '店铺地址', - business_hours varchar(100) default '' null comment '店铺营业时间', - cover_image_file_id varchar(50) default '' null comment '店铺封面图文件ID', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', - image_file_ids text null comment '图片文件ID集合,多个ID以逗号分隔' -) - comment '店铺信息表'; - -create index idx_shop_name - on t_shop (shop_name) - comment '按店铺名称查询的索引'; - - --- 系统标签信息表 -create table t_tag -( - id bigint unsigned auto_increment comment '标签唯一主键ID' - primary key comment '标签主键索引', - tag_name varchar(50) not null comment '标签名称', - text_color varchar(20) default '#333333' null comment '标签文字颜色(16进制)', - bg_color varchar(20) default '#FFFFFF' null comment '标签背景颜色(16进制)', - border_color varchar(20) default '#E5E5E5' null comment '标签边框颜色(16进制)', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', - shop_id bigint null comment '店铺ID', - constraint uk_tag_name - unique (tag_name) comment '标签名称唯一索引' -) - comment '系统标签信息表'; - --- 系统用户信息表 -create table t_user -( - id bigint unsigned comment '用户唯一主键ID(雪花ID)' - primary key comment '用户主键索引', - shop_id bigint unsigned default 0 null comment '所属店铺ID,关联店铺表主键(0表示无所属店铺)', - nickname varchar(50) not null comment '用户昵称', - account varchar(50) not null comment '用户账号(登录用)', - phone varchar(50) null comment '手机号', - email varchar(100) null comment '邮箱', - phone_verified tinyint unsigned default 0 null comment '手机号是否已验证:0-未验证,1-已验证', - email_verified tinyint unsigned default 0 null comment '邮箱是否已验证:0-未验证,1-已验证', - password varchar(100) not null comment '用户密码(加密存储)', - signature varchar(200) default '' null comment '用户签名', - level varchar(20) default '普通' null comment '用户等级', - type tinyint not null comment '用户类型,(0-用户,2-店长,3-美甲师,4-管理员)', - vip_id bigint unsigned default 0 null comment '关联VIP信息表主键(0表示非VIP)', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', - status tinyint unsigned default 1 null comment '用户状态:1-正常,0-禁用', - avatar varchar(512) null comment '头像链接', - constraint uk_account - unique (account) comment '用户账号唯一索引' -) - comment '系统用户信息表'; - -create index idx_email - on t_user (email) - comment '按邮箱查询的索引'; - -create index idx_phone - on t_user (phone) - comment '按手机号查询的索引'; - -create index idx_shop_id - on t_user (shop_id) - comment '按店铺查询用户的索引'; - -create index idx_type - on t_user (type) - comment '按用户类型查询的索引'; - --- 用户权限关联表 -create table t_user_permission -( - id bigint unsigned auto_increment comment '关联ID' - primary key, - user_id bigint unsigned not null comment '用户ID', - permission_id bigint unsigned not null comment '权限ID', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - create_by bigint unsigned null comment '创建人ID', - update_by bigint unsigned null comment '更新人ID', - is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', - constraint uk_user_permission - unique (user_id, permission_id) comment '用户-权限唯一索引' -) - comment '用户权限关联表'; - -create index idx_permission_id - on t_user_permission (permission_id) - comment '权限ID索引'; - -create index idx_user_id - on t_user_permission (user_id) - comment '用户ID索引'; - - --- VIP权益信息表 -create table t_vip_benefit -( - id bigint unsigned auto_increment comment 'VIP权益唯一主键ID(雪花ID)' - primary key comment 'VIP权益主键索引', - benefit_info text not null comment '权益详情(如折扣、专属服务)', - required_vip_level varchar(20) not null comment '所需VIP等级', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间' -) - comment 'VIP权益信息表'; - -create index idx_required_vip_level - on t_vip_benefit (required_vip_level) - comment '按VIP等级查询权益的索引'; - --- 用户VIP信息表 -create table t_vip_info -( - id bigint unsigned auto_increment comment 'VIP信息唯一主键ID(雪花ID)' - primary key comment 'VIP信息主键索引', - vip_level varchar(20) not null comment 'VIP等级(如青铜、白银)', - start_time datetime not null comment 'VIP开通时间', - expire_time datetime not null comment 'VIP到期时间', - activation_method varchar(50) not null comment 'VIP开通方式(如购买、赠送)', - benefit_id bigint unsigned not null comment '关联VIP权益信息表主键', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间' -) - comment '用户VIP信息表'; - -create index idx_vip_level - on t_vip_info (vip_level) - comment '按VIP等级查询的索引'; - - - --- 清空现有数据 -DELETE FROM t_user_permission WHERE 1=1; -DELETE FROM t_permission WHERE 1=1; -DELETE FROM t_user WHERE 1=1; - --- 插入完整的系统权限 -INSERT INTO t_permission (permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) VALUES --- 首页权限 -('home:view', '查看首页', '首页', '查看系统首页', NOW(), NOW(), 0), - --- 仪表盘权限 -('dashboard:view', '查看仪表盘', '仪表盘', '查看系统仪表盘', NOW(), NOW(), 0), - --- 用户管理权限 -('user:view', '查看用户', '用户管理', '查看用户列表和详情', NOW(), NOW(), 0), -('user:create', '新增用户', '用户管理', '新增用户', NOW(), NOW(), 0), -('user:edit', '编辑用户', '用户管理', '编辑用户信息', NOW(), NOW(), 0), -('user:reset_password', '重置密码', '用户管理', '重置用户密码', NOW(), NOW(), 0), -('user:delete', '删除用户', '用户管理', '删除用户', NOW(), NOW(), 0), - --- 商品管理权限 -('product:view', '查看商品', '商品管理', '查看商品列表和详情', NOW(), NOW(), 0), -('product:create', '新增商品', '商品管理', '新增商品', NOW(), NOW(), 0), -('product:edit', '编辑商品', '商品管理', '编辑商品信息', NOW(), NOW(), 0), -('product:delete', '删除商品', '商品管理', '删除商品', NOW(), NOW(), 0), -('product:category:manage', '管理商品分类', '商品管理', '管理商品分类', NOW(), NOW(), 0), - --- 店铺管理权限 -('shop:view', '查看店铺', '店铺管理', '查看店铺列表和详情', NOW(), NOW(), 0), -('shop:create', '新增店铺', '店铺管理', '新增店铺', NOW(), NOW(), 0), -('shop:edit', '编辑店铺', '店铺管理', '编辑店铺信息', NOW(), NOW(), 0), -('shop:delete', '删除店铺', '店铺管理', '删除店铺', NOW(), NOW(), 0), -('shop:staff:manage', '管理店铺员工', '店铺管理', '管理店铺员工', NOW(), NOW(), 0), - --- 权限管理权限 -('permission:view', '查看权限', '权限管理', '查看权限列表', NOW(), NOW(), 0), -('permission:create', '新增权限', '权限管理', '新增系统权限', NOW(), NOW(), 0), -('permission:edit', '编辑权限', '权限管理', '编辑系统权限', NOW(), NOW(), 0), -('permission:delete', '删除权限', '权限管理', '删除系统权限', NOW(), NOW(), 0), -('permission:assign', '分配权限', '权限管理', '为用户分配权限', NOW(), NOW(), 0), - --- 标签管理权限 -('tag:view', '查看标签', '标签管理', '查看标签列表和详情', NOW(), NOW(), 0), -('tag:create', '新增标签', '标签管理', '新增标签', NOW(), NOW(), 0), -('tag:edit', '编辑标签', '标签管理', '编辑标签信息', NOW(), NOW(), 0), -('tag:delete', '删除标签', '标签管理', '删除标签', NOW(), NOW(), 0), -('tag:assign', '分配标签', '标签管理', '为商品分配标签', NOW(), NOW(), 0), - --- 优惠券管理权限 -('coupon:view', '查看优惠券', '优惠券管理', '查看优惠券列表和详情', NOW(), NOW(), 0), -('coupon:create', '新增优惠券', '优惠券管理', '新增优惠券', NOW(), NOW(), 0), -('coupon:edit', '编辑优惠券', '优惠券管理', '编辑优惠券信息', NOW(), NOW(), 0), -('coupon:delete', '删除优惠券', '优惠券管理', '删除优惠券', NOW(), NOW(), 0), -('coupon:assign', '分配优惠券', '优惠券管理', '为用户分配优惠券', NOW(), NOW(), 0), - --- 订单管理权限 -('order:view', '查看订单', '订单管理', '查看订单列表和详情', NOW(), NOW(), 0), -('order:edit', '编辑订单', '订单管理', '编辑订单信息', NOW(), NOW(), 0), -('order:delete', '删除订单', '订单管理', '删除订单', NOW(), NOW(), 0), -('order:process', '处理订单', '订单管理', '处理订单状态', NOW(), NOW(), 0); - --- 初始化admin用户,密码为123456 --- 密码使用BCrypt加密,123456的加密值为:$2a$10$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW -INSERT INTO t_user (id, shop_id, nickname, account, password, type, status, create_time, update_time, is_delete) VALUES -(1, 0, '管理员', 'admin', '$2a$10$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW', 4, 1, NOW(), NOW(), 0); - --- 为管理员分配权限 --- 首页的全部权限 --- 仪表盘的全部权限 --- 所有店铺的用户管理的全部权限 --- 所有店铺的商品管理的查看权限,无新增编辑删除管理商品分类权限 --- 所有店铺的店铺管理的全部权限 --- 所有店铺的权限管理的全部权限 --- 所有店铺的标签管理的查看权限无新增编辑删除权限 --- 所有店铺的优惠券管理的查看权限 --- 所有店铺的订单管理的查看权限 -INSERT INTO t_user_permission (user_id, permission_id, create_time, update_time, create_by) -SELECT - 1 as user_id, - p.id as permission_id, - NOW() as create_time, - NOW() as update_time, - 1 as create_by -FROM t_permission p -WHERE p.is_delete = 0 -AND p.permission_code IN ( - 'home:view', - 'dashboard:view', - 'user:view', - 'user:create', - 'user:edit', - 'user:reset_password', - 'user:delete', - 'product:view', - 'shop:view', - 'shop:create', - 'shop:edit', - 'shop:delete', - 'shop:staff:manage', - 'permission:view', - 'permission:create', - 'permission:edit', - 'permission:delete', - 'permission:assign', - 'tag:view', - 'coupon:view', - 'order:view' -); - --- 注意:店长和美甲师的权限需要在系统中手动分配,因为需要关联具体的店铺 --- 这里只初始化管理员的权限 - --- 优惠券信息表 -create table t_coupon -( - id bigint unsigned auto_increment comment '优惠券唯一主键ID' - primary key comment '优惠券主键索引', - coupon_code varchar(50) not null comment '优惠券编码', - coupon_name varchar(100) not null comment '优惠券名称', - coupon_type tinyint not null comment '优惠券类型:1-折扣券,2-满减券', - discount_value decimal(10, 2) default 0.00 null comment '折扣值(如9.5表示95折)', - min_amount decimal(10, 2) default 0.00 null comment '满减券最低消费金额', - reduce_amount decimal(10, 2) default 0.00 null comment '满减券减免金额', - total_count int unsigned default 100 not null comment '优惠券总数量', - used_count int unsigned default 0 not null comment '已使用数量', - start_time datetime not null comment '开始时间', - end_time datetime not null comment '结束时间', - status tinyint unsigned default 1 not null comment '状态:1-可用,2-已过期,3-已用完', - shop_id bigint unsigned not null comment '所属店铺ID', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', - constraint uk_coupon_code - unique (coupon_code) comment '优惠券编码唯一索引' -) comment '优惠券信息表'; - -create index idx_status - on t_coupon (status) comment '按状态查询优惠券的索引'; - -create index idx_shop_id - on t_coupon (shop_id) comment '按店铺查询优惠券的索引'; - --- 用户优惠券关联表 -create table t_user_coupon -( - id bigint unsigned auto_increment comment '用户优惠券关联唯一主键ID' - primary key comment '用户优惠券关联主键索引', - user_id bigint unsigned not null comment '关联用户表主键', - coupon_id bigint unsigned not null comment '关联优惠券表主键', - status tinyint unsigned default 1 not null comment '状态:1-未使用,2-已使用,3-已过期', - obtain_time datetime default CURRENT_TIMESTAMP not null comment '获取时间', - use_time datetime null comment '使用时间', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', - constraint uk_user_coupon - unique (user_id, coupon_id) comment '用户-优惠券唯一索引' -) comment '用户优惠券关联表'; - -create index idx_status - on t_user_coupon (status) comment '按状态查询用户优惠券的索引'; - -create index idx_user_id - on t_user_coupon (user_id) comment '按用户查询优惠券的索引'; - --- 优惠券标签关联表 -create table t_coupon_tag -( - id bigint unsigned auto_increment comment '优惠券标签关联唯一主键ID' - primary key comment '优惠券标签关联主键索引', - coupon_id bigint unsigned not null comment '关联优惠券表主键', - tag_id bigint unsigned not null comment '关联标签表主键', - is_available tinyint unsigned default 1 not null comment '是否可用:1-可用,0-不可用', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', - constraint uk_coupon_tag - unique (coupon_id, tag_id) comment '优惠券-标签唯一索引' -) comment '优惠券标签关联表'; - -create index idx_coupon_id - on t_coupon_tag (coupon_id) comment '按优惠券查询标签的索引'; - -create index idx_tag_id - on t_coupon_tag (tag_id) comment '按标签查询优惠券的索引'; - --- 购物车表 -create table t_cart -( - id bigint unsigned auto_increment comment '购物车唯一主键ID' - primary key comment '购物车主键索引', - user_id bigint unsigned not null comment '关联用户表主键', - product_id bigint unsigned not null comment '关联商品表主键', - quantity int unsigned default 1 not null comment '商品数量', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', - constraint uk_user_product - unique (user_id, product_id) comment '用户-商品唯一索引' -) comment '购物车表'; - -create index idx_user_id - on t_cart (user_id) comment '按用户查询购物车的索引'; - --- 订单表 -create table t_order -( - id bigint unsigned auto_increment comment '订单唯一主键ID' - primary key comment '订单主键索引', - order_no varchar(50) not null comment '订单编号', - user_id bigint unsigned not null comment '关联用户表主键', - total_amount decimal(10, 2) not null comment '订单总金额', - actual_amount decimal(10, 2) not null comment '实际支付金额', - coupon_id bigint unsigned default 0 null comment '使用的优惠券ID', - status tinyint unsigned default 1 not null comment '订单状态:1-待使用,2-已完成,3-已取消', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', - constraint uk_order_no - unique (order_no) comment '订单编号唯一索引' -) comment '订单表'; - -create index idx_status - on t_order (status) comment '按状态查询订单的索引'; - -create index idx_user_id - on t_order (user_id) comment '按用户查询订单的索引'; - --- 订单商品表 -create table t_order_item -( - id bigint unsigned auto_increment comment '订单商品唯一主键ID' - primary key comment '订单商品主键索引', - order_id bigint unsigned not null comment '关联订单表主键', - product_id bigint unsigned not null comment '关联商品表主键', - quantity int unsigned not null comment '商品数量', - price decimal(10, 2) not null comment '商品单价', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' -) comment '订单商品表'; - -create index idx_order_id - on t_order_item (order_id) comment '按订单查询商品的索引'; - - --- 商品收藏表 -create table t_wishlist -( - id bigint unsigned auto_increment comment '收藏记录唯一主键ID' - primary key comment '商品收藏主键索引', - user_id bigint unsigned not null comment '关联用户表主键', - product_id bigint unsigned not null comment '关联商品表主键', - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', - is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删除,1-已删除', - constraint uk_user_product - unique (user_id, product_id) comment '用户-商品唯一索引' -) comment '商品收藏表'; - -create index idx_user_id - on t_wishlist (user_id) comment '按用户查询收藏的索引'; - -create index idx_product_id - on t_wishlist (product_id) comment '按商品查询收藏的索引'; - - --- 美甲师信息表 -CREATE TABLE t_nail_artist_info ( - id BIGINT UNSIGNED AUTO_INCREMENT COMMENT '美甲师信息唯一主键ID' - PRIMARY KEY COMMENT '美甲师信息主键索引', - user_id BIGINT UNSIGNED NOT NULL COMMENT '关联用户表主键(美甲师用户)', - identity VARCHAR(50) DEFAULT '' NULL COMMENT '身份', - experience INT UNSIGNED DEFAULT 0 NULL COMMENT '从业年限', - skills TEXT NULL COMMENT '技能标签ID集合,多个ID以逗号分隔', - rating DECIMAL(3, 1) DEFAULT 0.0 NULL COMMENT '评分', - status TINYINT UNSIGNED DEFAULT 1 NULL COMMENT '状态:1-营业中,0-休息中', - portfolio TEXT NULL COMMENT '作品集商品ID集合,多个ID以逗号分隔', - create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL COMMENT '创建时间', - update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', - is_delete TINYINT UNSIGNED DEFAULT 0 NULL COMMENT '逻辑删除:0-未删,1-已删', - CONSTRAINT uk_user_id - UNIQUE (user_id) COMMENT '用户ID唯一索引(一个美甲师对应一条信息记录)' -) COMMENT '美甲师信息表'; - --- 为美甲师信息表添加索引 -CREATE INDEX idx_user_id ON t_nail_artist_info (user_id) COMMENT '按用户查询美甲师信息的索引'; -CREATE INDEX idx_status ON t_nail_artist_info (status) COMMENT '按状态查询美甲师的索引'; - --- 添加美甲师管理相关权限 -INSERT INTO t_permission (permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) VALUES - ('nail_artist:view', '查看美甲师', '美甲师管理', '查看美甲师列表和详情', NOW(), NOW(), 0), - ('nail_artist:edit', '编辑美甲师', '美甲师管理', '编辑美甲师信息', NOW(), NOW(), 0); - --- 为管理员分配美甲师管理权限 -INSERT INTO t_user_permission (user_id, permission_id, create_time, update_time, create_by) -SELECT - 1 as user_id, - p.id as permission_id, - NOW() as create_time, - NOW() as update_time, - 1 as create_by -FROM t_permission p -WHERE p.is_delete = 0 - AND p.permission_code IN ( - 'nail_artist:view', - 'nail_artist:edit' - ); --- 商品点赞记录表 -CREATE TABLE t_product_like ( - id BIGINT UNSIGNED AUTO_INCREMENT COMMENT '点赞记录唯一主键ID' - PRIMARY KEY COMMENT '商品点赞主键索引', - user_id BIGINT UNSIGNED NOT NULL COMMENT '关联用户表主键', - product_id BIGINT UNSIGNED NOT NULL COMMENT '关联商品表主键', - create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL COMMENT '创建时间', - update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', - is_delete TINYINT UNSIGNED DEFAULT 0 NULL COMMENT '逻辑删除:0-未删除,1-已删除', - CONSTRAINT uk_user_product_like - UNIQUE (user_id, product_id) COMMENT '用户-商品唯一索引' -) COMMENT '商品点赞记录表'; - -CREATE INDEX idx_user_id_like ON t_product_like (user_id) COMMENT '按用户查询点赞的索引'; -CREATE INDEX idx_product_id_like ON t_product_like (product_id) COMMENT '按商品查询点赞的索引'; - - -ALTER TABLE t_order_item ADD COLUMN artist_id BIGINT UNSIGNED DEFAULT NULL COMMENT '关联美甲师ID' AFTER price; \ No newline at end of file diff --git a/YumiNail-Core/src/main/resources/files/YumiNail.sql b/YumiNail-Core/src/main/resources/files/YumiNail.sql index e63a2772..3e00c8d5 100644 --- a/YumiNail-Core/src/main/resources/files/YumiNail.sql +++ b/YumiNail-Core/src/main/resources/files/YumiNail.sql @@ -228,6 +228,9 @@ create table t_nail_artist_info skills text null comment '技能标签ID集合,多个ID以逗号分隔', rating decimal(3, 1) default 0.0 null comment '评分', status tinyint unsigned default 1 null comment '状态:1-营业中,0-休息中', + participate_production tinyint unsigned default 1 not null comment '是否参与美甲制作:1-参与,0-不参与', + work_start_time time null comment '工作开始时间', + work_end_time time null comment '工作结束时间', portfolio text null comment '作品集商品ID集合,多个ID以逗号分隔', create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', @@ -245,6 +248,9 @@ create index idx_user_id on t_nail_artist_info (user_id) comment '按用户查询美甲师信息的索引'; +create index idx_t_nail_artist_info_participate + on t_nail_artist_info (participate_production, status); + -- auto-generated definition create table t_object_storage_file ( @@ -397,6 +403,9 @@ create table t_shop shop_name varchar(100) not null comment '店铺名称', description text null comment '店铺描述', address varchar(200) not null comment '店铺地址', + map_provider varchar(20) default 'TENCENT' not null comment '地图服务商:TENCENT/AMAP', + longitude decimal(12, 8) null comment '店铺经度', + latitude decimal(12, 8) null comment '店铺纬度', business_hours varchar(100) default '' null comment '店铺营业时间', cover_image_file_id varchar(50) default '' null comment '店铺封面图文件ID', create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', @@ -522,6 +531,101 @@ create index idx_user_id on t_user_permission (user_id) comment '用户ID索引'; +create table if not exists t_system_message +( + id bigint unsigned auto_increment comment '站内消息主键' + primary key, + title varchar(100) not null comment '消息标题', + content text not null comment '消息内容', + image_file_id bigint unsigned null comment '消息图片文件ID', + publisher_id bigint unsigned not null comment '发布人ID', + publisher_name varchar(100) default '' null comment '发布人名称', + publisher_type tinyint not null comment '发布人类型:2-店长,4-管理员', + target_type varchar(30) not null comment '目标范围:PLATFORM_ALL/CURRENT_SHOP_ALL/SHOP_ALL/SELECTED_SHOPS/SELECTED_USERS', + target_ids text null comment '目标ID集合,多个ID以逗号分隔', + popup_enabled tinyint unsigned default 1 not null comment '是否弹窗:1-弹窗,0-不弹窗', + status tinyint unsigned default 1 not null comment '状态:1-已发布,0-已撤回', + publish_time datetime default CURRENT_TIMESTAMP not null comment '发布时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '站内消息表'; + +create index idx_t_system_message_publish_time + on t_system_message (publish_time); + +create index idx_t_system_message_target + on t_system_message (target_type, status); + +create table if not exists t_system_message_user_state +( + id bigint unsigned auto_increment comment '用户消息状态主键' + primary key, + message_id bigint unsigned not null comment '消息ID', + user_id bigint unsigned not null comment '用户ID', + popup_shown tinyint unsigned default 0 not null comment '是否已弹窗:1-是,0-否', + read_status tinyint unsigned default 0 not null comment '是否已读:1-是,0-否', + popup_time datetime null comment '首次弹窗时间', + read_time datetime null comment '阅读时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删', + constraint uk_t_system_message_user + unique (message_id, user_id) +) + comment '用户站内消息状态表'; + +create index idx_t_system_message_user_state_user + on t_system_message_user_state (user_id, read_status, popup_shown); + +create table if not exists t_announcement +( + id bigint unsigned auto_increment comment '公告主键' + primary key, + title varchar(100) not null comment '公告标题', + content text not null comment '公告内容', + publisher_id bigint unsigned not null comment '发布人ID', + publisher_name varchar(100) default '' null comment '发布人名称', + publisher_type tinyint not null comment '发布人类型:2-店长,4-管理员', + target_type varchar(30) not null comment '目标范围', + target_ids text null comment '目标ID集合,多个ID以逗号分隔', + status tinyint unsigned default 1 not null comment '状态:1-已发布,0-已撤回', + sort_order int default 0 not null comment '排序值', + publish_time datetime default CURRENT_TIMESTAMP not null comment '发布时间', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment '首页滚动公告表'; + +create index idx_t_announcement_target + on t_announcement (target_type, status); + +create index idx_t_announcement_sort_time + on t_announcement (sort_order, publish_time); + +create table if not exists t_vip_recharge_plan +( + id bigint unsigned auto_increment comment 'VIP充值档位主键' + primary key, + shop_id bigint unsigned not null comment '所属店铺ID', + title varchar(100) not null comment '档位标题', + recharge_amount decimal(10, 2) not null comment '充值金额', + gift_amount decimal(10, 2) default 0.00 not null comment '赠送金额', + vip_level varchar(20) not null comment '对应VIP等级', + description varchar(255) null comment '展示说明', + sort_order int default 0 not null comment '排序值', + status tinyint unsigned default 1 not null comment '状态:1-启用,0-停用', + create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', + is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删' +) + comment 'VIP充值展示档位表'; + +create index idx_t_vip_recharge_plan_shop_status + on t_vip_recharge_plan (shop_id, status, sort_order); + -- auto-generated definition create table t_vip_benefit ( @@ -1008,6 +1112,10 @@ END$$ DELIMITER ; CALL sp_add_column_if_not_exists('t_shop', 'status', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''店铺状态:1-启用,0-停用'''); +CALL sp_add_column_if_not_exists('t_shop', 'authorization_expire_time', 'datetime NULL COMMENT ''店铺授权有效期,空表示长期有效'''); +CALL sp_add_column_if_not_exists('t_shop', 'map_provider', 'varchar(20) NOT NULL DEFAULT ''TENCENT'' COMMENT ''地图服务商:TENCENT/AMAP'''); +CALL sp_add_column_if_not_exists('t_shop', 'longitude', 'decimal(12,8) NULL COMMENT ''店铺经度'''); +CALL sp_add_column_if_not_exists('t_shop', 'latitude', 'decimal(12,8) NULL COMMENT ''店铺纬度'''); UPDATE t_shop SET status = 1 @@ -1077,6 +1185,33 @@ WHERE b.status IS NULL OR b.is_delete IS NULL OR b.update_time IS NULL; +CALL sp_add_column_if_not_exists('t_nail_artist_info', 'participate_production', 'tinyint unsigned NOT NULL DEFAULT 1 COMMENT ''是否参与美甲制作:1-参与,0-不参与'''); +CALL sp_add_column_if_not_exists('t_nail_artist_info', 'work_start_time', 'time NULL COMMENT ''工作开始时间'''); +CALL sp_add_column_if_not_exists('t_nail_artist_info', 'work_end_time', 'time NULL COMMENT ''工作结束时间'''); +CALL sp_add_index_if_not_exists('t_nail_artist_info', 'idx_t_nail_artist_info_participate', '(`participate_production`, `status`)'); +CALL sp_add_column_if_not_exists('t_system_message', 'image_file_id', 'bigint unsigned NULL COMMENT ''消息图片文件ID'''); + +CREATE TABLE IF NOT EXISTS `t_messagehub_push_config` ( + `id` bigint unsigned NOT NULL COMMENT '主键ID', + `scene_code` varchar(80) NOT NULL COMMENT '业务场景编码', + `scene_name` varchar(100) NOT NULL COMMENT '业务场景名称', + `platform` varchar(20) NOT NULL DEFAULT 'SMS' COMMENT 'MessageHub 平台类型:SMS/EMAIL/QQ', + `msg_type` varchar(30) NOT NULL DEFAULT 'VERIFICATION' COMMENT 'MessageHub 消息类型', + `queue_name` varchar(100) NOT NULL DEFAULT 'smsQueue' COMMENT '投递到 MessageHub 的队列名', + `source_system` varchar(80) NOT NULL DEFAULT 'yuminail' COMMENT 'MessageHub 来源系统编码', + `template_code` varchar(100) NOT NULL COMMENT 'MessageHub 模板编码', + `channel_id` bigint unsigned NULL COMMENT 'MessageHub 通道ID,不填则由 MessageHub 自动选择', + `send_method` varchar(30) NULL COMMENT '兼容旧短信 DTO 的发送方式,如 SPUG/OTHER', + `enabled` tinyint unsigned NOT NULL DEFAULT 1 COMMENT '是否启用:1-启用,0-停用', + `remark` varchar(255) NULL COMMENT '备注', + `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + `is_delete` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '逻辑删除:0-未删除,1-已删除', + PRIMARY KEY (`id`), + UNIQUE KEY `uk_messagehub_push_config_scene` (`scene_code`), + KEY `idx_messagehub_push_config_enabled` (`enabled`, `is_delete`) +) COMMENT='YumiNail按业务场景投递MessageHub的配置'; + DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists; DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists; DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists; @@ -1134,7 +1269,38 @@ VALUES ('order:edit', '编辑订单', '订单管理', '编辑订单信息的预留权限', NOW(), NOW(), 0), ('order:delete', '删除订单', '订单管理', '删除订单的预留权限', NOW(), NOW(), 0), ('nail_artist:view', '查看美甲师', '美甲师管理', '查看美甲师信息与排班入口', NOW(), NOW(), 0), - ('nail_artist:edit', '编辑美甲师', '美甲师管理', '编辑美甲师信息', NOW(), NOW(), 0) + ('nail_artist:edit', '编辑美甲师', '美甲师管理', '编辑美甲师信息', NOW(), NOW(), 0), + ('message:view', '查看消息', '消息管理', '查看站内消息发布与通知', NOW(), NOW(), 0), + ('message:create', '发布消息', '消息管理', '发布站内消息', NOW(), NOW(), 0), + ('message:delete', '撤回消息', '消息管理', '撤回已发布站内消息', NOW(), NOW(), 0) + , + ('announcement:view', 'View Announcements', 'Announcement Management', 'View announcement list and detail', NOW(), NOW(), 0), + ('announcement:create', 'Create Announcements', 'Announcement Management', 'Publish announcements', NOW(), NOW(), 0), + ('announcement:delete', 'Withdraw Announcements', 'Announcement Management', 'Withdraw published announcements', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + update_time = NOW(), + is_delete = 0; + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (910000000008001, 'message:view', '查看消息', '消息管理', '查看站内消息发布与通知', NOW(), NOW(), 0), + (910000000008002, 'message:create', '发布消息', '消息管理', '发布站内消息', NOW(), NOW(), 0), + (910000000008003, 'message:delete', '撤回消息', '消息管理', '撤回已发布站内消息', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + update_time = NOW(), + is_delete = 0; + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (910000000008011, 'announcement:view', 'View Announcements', 'Announcement Management', 'View announcement list and detail', NOW(), NOW(), 0), + (910000000008012, 'announcement:create', 'Create Announcements', 'Announcement Management', 'Publish announcements', NOW(), NOW(), 0), + (910000000008013, 'announcement:delete', 'Withdraw Announcements', 'Announcement Management', 'Withdraw published announcements', NOW(), NOW(), 0) ON DUPLICATE KEY UPDATE permission_name = VALUES(permission_name), permission_group = VALUES(permission_group), @@ -1229,7 +1395,13 @@ INNER JOIN t_permission p 'order:edit', 'order:delete', 'nail_artist:view', - 'nail_artist:edit' + 'nail_artist:edit', + 'message:view', + 'message:create', + 'message:delete', + 'announcement:view', + 'announcement:create', + 'announcement:delete' ) WHERE u.is_delete = 0 AND u.type = 4 @@ -1283,7 +1455,11 @@ INNER JOIN t_permission p 'order:edit', 'order:delete', 'nail_artist:view', - 'nail_artist:edit' + 'nail_artist:edit', + 'message:view', + 'message:create', + 'announcement:view', + 'announcement:create' ) WHERE u.is_delete = 0 AND u.type = 2 @@ -1323,6 +1499,224 @@ WHERE u.is_delete = 0 AND up.permission_id = p.id ); + +INSERT INTO t_user_permission (id, user_id, permission_id, create_time, update_time, create_by, update_by, is_delete) +SELECT 910000000009000 + ((u.id % 1000000) * 10) + CASE p.permission_code + WHEN 'message:view' THEN 1 + WHEN 'message:create' THEN 2 + WHEN 'message:delete' THEN 3 + WHEN 'announcement:view' THEN 4 + WHEN 'announcement:create' THEN 5 + WHEN 'announcement:delete' THEN 6 + ELSE 0 + END, + u.id, + p.id, + NOW(), + NOW(), + u.id, + u.id, + 0 +FROM t_user u +INNER JOIN t_permission p + ON p.is_delete = 0 + AND ( + (u.type = 4 AND p.permission_code IN ('message:view', 'message:create', 'message:delete', 'announcement:view', 'announcement:create', 'announcement:delete')) + OR (u.type = 2 AND p.permission_code IN ('message:view', 'message:create', 'announcement:view', 'announcement:create')) + ) +WHERE u.is_delete = 0 + AND NOT EXISTS ( + SELECT 1 + FROM t_user_permission up + WHERE up.user_id = u.id + AND up.permission_id = p.id + ) +ON DUPLICATE KEY UPDATE + is_delete = 0, + update_time = NOW(); + +-- YumiNail 手工验收种子数据 +INSERT INTO t_nail_artist_info (user_id, identity, experience, skills, rating, status, participate_production, work_start_time, work_end_time, portfolio, create_time, update_time, is_delete) +SELECT u.id, '店长', 3, '', 5.0, 1, 0, '09:00:00', '18:00:00', '', NOW(), NOW(), 0 +FROM t_user u +WHERE u.type = 2 AND u.is_delete = 0 + AND NOT EXISTS (SELECT 1 FROM t_nail_artist_info nai WHERE nai.user_id = u.id AND nai.is_delete = 0); + +UPDATE t_nail_artist_info nai +INNER JOIN t_user u ON u.id = nai.user_id AND u.type = 3 +SET nai.participate_production = 1 +WHERE nai.participate_production IS NULL; + +UPDATE t_nail_artist_info nai +INNER JOIN t_user u ON u.id = nai.user_id AND u.type = 2 +SET nai.participate_production = COALESCE(nai.participate_production, 0); + +-- 小型全覆盖验收数据,便于人工抽检。 +-- Password hash matches the existing admin seed password hash; reset in non-local environments if needed. +INSERT INTO t_shop (id, shop_name, description, address, business_hours, cover_image_file_id, create_time, update_time, is_delete, image_file_ids, status) +SELECT 910000000000001, '验收主店', '用于验收的主门店', '验收路 1 号', '09:00-21:00', '', NOW(), NOW(), 0, '', 1 +WHERE NOT EXISTS (SELECT 1 FROM t_shop WHERE id = 910000000000001); + +INSERT INTO t_shop (id, shop_name, description, address, business_hours, cover_image_file_id, create_time, update_time, is_delete, image_file_ids, status) +SELECT 910000000000002, '验收分店', '用于验收的分门店', '验收路 2 号', '10:00-20:00', '', NOW(), NOW(), 0, '', 1 +WHERE NOT EXISTS (SELECT 1 FROM t_shop WHERE id = 910000000000002); + +INSERT INTO t_vip_info (id, vip_level, start_time, expire_time, activation_method, benefit_id, create_time, update_time) +SELECT 910000000000101, '青铜会员', NOW(), DATE_ADD(NOW(), INTERVAL 1 YEAR), '验收种子数据', COALESCE((SELECT id FROM t_vip_benefit WHERE level_rank = 1 LIMIT 1), 0), NOW(), NOW() +WHERE NOT EXISTS (SELECT 1 FROM t_vip_info WHERE id = 910000000000101); + +INSERT INTO t_vip_info (id, vip_level, start_time, expire_time, activation_method, benefit_id, create_time, update_time) +SELECT 910000000000102, '白银会员', NOW(), DATE_ADD(NOW(), INTERVAL 1 YEAR), '验收种子数据', COALESCE((SELECT id FROM t_vip_benefit WHERE level_rank = 2 LIMIT 1), 0), NOW(), NOW() +WHERE NOT EXISTS (SELECT 1 FROM t_vip_info WHERE id = 910000000000102); + +INSERT INTO t_vip_info (id, vip_level, start_time, expire_time, activation_method, benefit_id, create_time, update_time) +SELECT 910000000000103, '黄金会员', NOW(), DATE_ADD(NOW(), INTERVAL 1 YEAR), '验收种子数据', COALESCE((SELECT id FROM t_vip_benefit WHERE level_rank = 3 LIMIT 1), 0), NOW(), NOW() +WHERE NOT EXISTS (SELECT 1 FROM t_vip_info WHERE id = 910000000000103); + +INSERT INTO t_user (id, shop_id, nickname, account, phone, email, phone_verified, email_verified, password, signature, level, type, vip_id, create_time, update_time, is_delete, status, avatar) +VALUES + (910000000001001, 910000000000001, '验收普通用户', 'accept_user_normal', '18800001001', NULL, 1, 0, '$2a$10$9v.6PztWy3.vmJiVMaOyKuWeVqAnpuHB3hQ3Dgiuz6L8IwBe7Cn9W', '', '普通用户', 0, 0, NOW(), NOW(), 0, 1, NULL), + (910000000001002, 910000000000001, '验收青铜用户', 'accept_user_bronze', '18800001002', NULL, 1, 0, '$2a$10$9v.6PztWy3.vmJiVMaOyKuWeVqAnpuHB3hQ3Dgiuz6L8IwBe7Cn9W', '', '青铜会员', 0, 910000000000101, NOW(), NOW(), 0, 1, NULL), + (910000000001003, 910000000000001, '验收白银用户', 'accept_user_silver', '18800001003', NULL, 1, 0, '$2a$10$9v.6PztWy3.vmJiVMaOyKuWeVqAnpuHB3hQ3Dgiuz6L8IwBe7Cn9W', '', '白银会员', 0, 910000000000102, NOW(), NOW(), 0, 1, NULL), + (910000000001004, 910000000000001, '验收黄金用户', 'accept_user_gold', '18800001004', NULL, 1, 0, '$2a$10$9v.6PztWy3.vmJiVMaOyKuWeVqAnpuHB3hQ3Dgiuz6L8IwBe7Cn9W', '', '黄金会员', 0, 910000000000103, NOW(), NOW(), 0, 1, NULL), + (910000000002001, 910000000000001, '验收店长', 'accept_manager_main', '18800002001', NULL, 1, 0, '$2a$10$9v.6PztWy3.vmJiVMaOyKuWeVqAnpuHB3hQ3Dgiuz6L8IwBe7Cn9W', '', '店长', 2, 0, NOW(), NOW(), 0, 1, NULL), + (910000000002002, 910000000000001, '验收参与制作店长', 'accept_manager_artist', '18800002002', NULL, 1, 0, '$2a$10$9v.6PztWy3.vmJiVMaOyKuWeVqAnpuHB3hQ3Dgiuz6L8IwBe7Cn9W', '', '店长', 2, 0, NOW(), NOW(), 0, 1, NULL), + (910000000002003, 910000000000002, '验收分店店长', 'accept_manager_branch', '18800002003', NULL, 1, 0, '$2a$10$9v.6PztWy3.vmJiVMaOyKuWeVqAnpuHB3hQ3Dgiuz6L8IwBe7Cn9W', '', '店长', 2, 0, NOW(), NOW(), 0, 1, NULL), + (910000000003001, 910000000000001, '验收美甲师', 'accept_artist_main', '18800003001', NULL, 1, 0, '$2a$10$9v.6PztWy3.vmJiVMaOyKuWeVqAnpuHB3hQ3Dgiuz6L8IwBe7Cn9W', '', '美甲师', 3, 0, NOW(), NOW(), 0, 1, NULL), + (910000000003002, 910000000000002, '验收分店美甲师', 'accept_artist_branch', '18800003002', NULL, 1, 0, '$2a$10$9v.6PztWy3.vmJiVMaOyKuWeVqAnpuHB3hQ3Dgiuz6L8IwBe7Cn9W', '', '美甲师', 3, 0, NOW(), NOW(), 0, 1, NULL) +ON DUPLICATE KEY UPDATE + shop_id = VALUES(shop_id), + nickname = VALUES(nickname), + phone = VALUES(phone), + level = VALUES(level), + type = VALUES(type), + vip_id = VALUES(vip_id), + status = VALUES(status), + is_delete = 0, + update_time = NOW(); + +INSERT INTO t_user_shop_binding (user_id, shop_id, status, create_time, update_time, is_delete) +SELECT u.id, u.shop_id, 1, NOW(), NOW(), 0 +FROM t_user u +WHERE u.id BETWEEN 910000000001001 AND 910000000003002 + AND u.shop_id > 0 +ON DUPLICATE KEY UPDATE + status = 1, + is_delete = 0, + update_time = NOW(); + +INSERT INTO t_nail_artist_info (user_id, identity, experience, skills, rating, status, participate_production, work_start_time, work_end_time, portfolio, create_time, update_time, is_delete) +VALUES + (910000000002001, '店长', 5, '门店管理', 5.0, 1, 0, '09:00:00', '18:00:00', '', NOW(), NOW(), 0), + (910000000002002, '参与制作店长', 8, '美甲设计', 5.0, 1, 1, '09:30:00', '20:00:00', '', NOW(), NOW(), 0), + (910000000002003, '分店店长', 4, '分店管理', 4.8, 1, 1, '10:00:00', '19:00:00', '', NOW(), NOW(), 0), + (910000000003001, '美甲师', 3, '凝胶,护理', 4.9, 1, 1, '10:00:00', '21:00:00', '', NOW(), NOW(), 0), + (910000000003002, '分店美甲师', 2, '基础护理,修复', 4.7, 1, 1, '10:00:00', '19:00:00', '', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + identity = VALUES(identity), + experience = VALUES(experience), + skills = VALUES(skills), + rating = VALUES(rating), + status = VALUES(status), + participate_production = VALUES(participate_production), + work_start_time = VALUES(work_start_time), + work_end_time = VALUES(work_end_time), + is_delete = 0, + update_time = NOW(); + +INSERT INTO t_balance (user_id, amount, create_time, last_update_time, total_recharge_amount, last_recharge_time) +VALUES + (910000000001001, 68.00, NOW(), NOW(), 100.00, DATE_SUB(NOW(), INTERVAL 10 DAY)), + (910000000001002, 288.00, NOW(), NOW(), 600.00, DATE_SUB(NOW(), INTERVAL 8 DAY)), + (910000000001003, 588.00, NOW(), NOW(), 1200.00, DATE_SUB(NOW(), INTERVAL 6 DAY)), + (910000000001004, 988.00, NOW(), NOW(), 2600.00, DATE_SUB(NOW(), INTERVAL 4 DAY)) +ON DUPLICATE KEY UPDATE + amount = VALUES(amount), + total_recharge_amount = VALUES(total_recharge_amount), + last_recharge_time = VALUES(last_recharge_time), + last_update_time = NOW(); + +INSERT INTO t_balance_change_detail (id, user_id, amount, type, current_balance, change_time) +VALUES + (910000000007001, 910000000001001, 100.00, 'RECHARGE', 100.00, DATE_SUB(NOW(), INTERVAL 10 DAY)), + (910000000007002, 910000000001001, -32.00, 'CONSUME', 68.00, DATE_SUB(NOW(), INTERVAL 9 DAY)), + (910000000007003, 910000000001002, 600.00, 'RECHARGE', 600.00, DATE_SUB(NOW(), INTERVAL 8 DAY)), + (910000000007004, 910000000001002, -312.00, 'CONSUME', 288.00, DATE_SUB(NOW(), INTERVAL 7 DAY)), + (910000000007005, 910000000001003, 1200.00, 'RECHARGE', 1200.00, DATE_SUB(NOW(), INTERVAL 6 DAY)), + (910000000007006, 910000000001003, -612.00, 'CONSUME', 588.00, DATE_SUB(NOW(), INTERVAL 5 DAY)), + (910000000007007, 910000000001004, 2600.00, 'RECHARGE', 2600.00, DATE_SUB(NOW(), INTERVAL 4 DAY)), + (910000000007008, 910000000001004, -1612.00, 'CONSUME', 988.00, DATE_SUB(NOW(), INTERVAL 3 DAY)) +ON DUPLICATE KEY UPDATE + amount = VALUES(amount), + type = VALUES(type), + current_balance = VALUES(current_balance), + change_time = VALUES(change_time); + +INSERT INTO t_product (id, shop_id, title, description, image_file_ids, price, tags, like_count, collect_count, approximate_duration, bookable_artists, available_coupons, create_time, update_time, is_delete) +VALUES + (910000000004001, 910000000000001, '验收凝胶美甲', '可由普通美甲师和参与制作店长预约服务。', '', 168.00, '验收,凝胶', 0, 0, '90 分钟', '910000000003001,910000000002002', '', NOW(), NOW(), 0), + (910000000004002, 910000000000001, '验收店长专属款', '用于验证参与制作店长的预约流程。', '', 268.00, '验收,店长', 0, 0, '120 分钟', '910000000002002', '', NOW(), NOW(), 0), + (910000000004003, 910000000000002, '验收分店护理', '用于验证跨店不可预约的分店商品。', '', 128.00, '验收,分店', 0, 0, '60 分钟', '910000000003002,910000000002003', '', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + shop_id = VALUES(shop_id), + title = VALUES(title), + description = VALUES(description), + price = VALUES(price), + tags = VALUES(tags), + approximate_duration = VALUES(approximate_duration), + bookable_artists = VALUES(bookable_artists), + is_delete = 0, + update_time = NOW(); + +INSERT INTO t_cart (user_id, product_id, quantity, create_time, update_time, is_delete) +VALUES (910000000001004, 910000000004001, 1, NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + quantity = VALUES(quantity), + is_delete = 0, + update_time = NOW(); + +INSERT INTO t_order (id, order_no, user_id, total_amount, actual_amount, coupon_id, status, create_time, update_time, is_delete) +SELECT 910000000005001, 'ACCEPTANCE-ORDER-001', 910000000001004, 168.00, 168.00, 0, 1, NOW(), NOW(), 0 +WHERE NOT EXISTS (SELECT 1 FROM t_order WHERE order_no = 'ACCEPTANCE-ORDER-001'); + +INSERT INTO t_order_item (order_id, product_id, quantity, price, artist_id, create_time, update_time, is_delete) +SELECT 910000000005001, 910000000004001, 1, 168.00, 910000000002002, NOW(), NOW(), 0 +WHERE EXISTS (SELECT 1 FROM t_order WHERE id = 910000000005001) + AND NOT EXISTS (SELECT 1 FROM t_order_item WHERE order_id = 910000000005001 AND product_id = 910000000004001); + +INSERT INTO t_system_message (id, title, content, publisher_id, publisher_name, publisher_type, target_type, target_ids, popup_enabled, status, publish_time, create_time, update_time, is_delete) +VALUES + (910000000006001, '平台验收通知', '这是一条面向当前和后续新增用户的平台通知。', 910000000001001, '验收管理员', 4, 'PLATFORM_ALL', '', 1, 1, NOW(), NOW(), NOW(), 0), + (910000000006002, '本店验收通知', '这是一条面向本店动态用户范围的店铺通知。', 910000000002002, '参与制作店长', 2, 'CURRENT_SHOP_ALL', '910000000000001', 1, 1, NOW(), NOW(), NOW(), 0), + (910000000006003, '指定用户验收通知', '这是一条仅指定用户可见的通知。', 910000000002002, '参与制作店长', 2, 'SELECTED_USERS', '910000000001004', 1, 1, NOW(), NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + title = VALUES(title), + content = VALUES(content), + publisher_id = VALUES(publisher_id), + publisher_name = VALUES(publisher_name), + publisher_type = VALUES(publisher_type), + target_type = VALUES(target_type), + target_ids = VALUES(target_ids), + popup_enabled = VALUES(popup_enabled), + status = VALUES(status), + is_delete = 0, + update_time = NOW(); + +INSERT INTO t_system_message_user_state (message_id, user_id, popup_shown, read_status, popup_time, read_time, create_time, update_time, is_delete) +VALUES + (910000000006001, 910000000001001, 1, 1, DATE_SUB(NOW(), INTERVAL 1 DAY), DATE_SUB(NOW(), INTERVAL 1 DAY), NOW(), NOW(), 0), + (910000000006002, 910000000001002, 1, 0, DATE_SUB(NOW(), INTERVAL 2 HOUR), NULL, NOW(), NOW(), 0), + (910000000006003, 910000000001004, 0, 0, NULL, NULL, NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + popup_shown = VALUES(popup_shown), + read_status = VALUES(read_status), + popup_time = VALUES(popup_time), + read_time = VALUES(read_time), + is_delete = 0, + update_time = NOW(); + +-- 小型全覆盖抽检数据可在空库初始化后按需扩展:管理员、店长、美甲师、普通用户、VIP 等级、商品、余额流水均由本初始化文件统一承载。 + -- ======================================== -- 雪花 ID 口径收口区:去掉运行时主键表的 AUTO_INCREMENT -- 说明: @@ -1331,6 +1725,43 @@ WHERE u.is_delete = 0 -- 3. 与 2026-03-30_snowflake_id_alignment_patch.sql 保持同口径 -- ======================================== +INSERT INTO t_announcement (id, title, content, publisher_id, publisher_name, publisher_type, target_type, target_ids, status, sort_order, publish_time, create_time, update_time, is_delete) +VALUES + (910000000010001, '平台公告', '平台公告:欢迎体验首页滚动公告功能。', 910000000001001, '验收管理员', 4, 'PLATFORM_ALL', '', 1, 10, NOW(), NOW(), NOW(), 0), + (910000000010002, '本店公告', '本店公告:今日可预约店长参与制作服务。', 910000000002002, '参与制作店长', 2, 'CURRENT_SHOP_ALL', '910000000000001', 1, 20, NOW(), NOW(), NOW(), 0), + (910000000010003, '专属公告', '专属公告:这是指定用户可见的验收公告。', 910000000002002, '参与制作店长', 2, 'SELECTED_USERS', '910000000001004', 1, 30, NOW(), NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + title = VALUES(title), + content = VALUES(content), + publisher_id = VALUES(publisher_id), + publisher_name = VALUES(publisher_name), + publisher_type = VALUES(publisher_type), + target_type = VALUES(target_type), + target_ids = VALUES(target_ids), + status = VALUES(status), + sort_order = VALUES(sort_order), + is_delete = 0, + update_time = NOW(); + +INSERT INTO t_vip_recharge_plan (id, shop_id, title, recharge_amount, gift_amount, vip_level, description, sort_order, status, create_time, update_time, is_delete) +VALUES + (910000000011001, 910000000000001, '充100送10', 100.00, 10.00, '青铜VIP', '适合轻量体验用户,仅展示不发起支付。', 10, 1, NOW(), NOW(), 0), + (910000000011002, 910000000000001, '充500送80', 500.00, 80.00, '白银VIP', '适合常规护理用户,仅展示不发起支付。', 20, 1, NOW(), NOW(), 0), + (910000000011003, 910000000000001, '充1000送200', 1000.00, 200.00, '黄金VIP', '适合高频预约用户,仅展示不发起支付。', 30, 1, NOW(), NOW(), 0), + (910000000011004, 910000000000002, '分店充100送10', 100.00, 10.00, '青铜VIP', '分店验收充值档位。', 10, 1, NOW(), NOW(), 0), + (910000000011005, 910000000000002, '分店充500送80', 500.00, 80.00, '白银VIP', '分店验收充值档位。', 20, 1, NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + shop_id = VALUES(shop_id), + title = VALUES(title), + recharge_amount = VALUES(recharge_amount), + gift_amount = VALUES(gift_amount), + vip_level = VALUES(vip_level), + description = VALUES(description), + sort_order = VALUES(sort_order), + status = VALUES(status), + is_delete = 0, + update_time = NOW(); + DROP PROCEDURE IF EXISTS sp_drop_auto_increment_on_id_if_exists; DELIMITER $$ @@ -1393,5 +1824,267 @@ CALL sp_drop_auto_increment_on_id_if_exists('t_vip_benefit'); CALL sp_drop_auto_increment_on_id_if_exists('t_vip_info'); CALL sp_drop_auto_increment_on_id_if_exists('t_wishlist'); CALL sp_drop_auto_increment_on_id_if_exists('t_user_shop_binding'); +CALL sp_drop_auto_increment_on_id_if_exists('t_system_message'); +CALL sp_drop_auto_increment_on_id_if_exists('t_system_message_user_state'); +CALL sp_drop_auto_increment_on_id_if_exists('t_announcement'); +CALL sp_drop_auto_increment_on_id_if_exists('t_vip_recharge_plan'); DROP PROCEDURE IF EXISTS sp_drop_auto_increment_on_id_if_exists; + +CREATE TABLE IF NOT EXISTS t_shop_role ( + id BIGINT UNSIGNED NOT NULL COMMENT '店铺角色ID' PRIMARY KEY, + shop_id BIGINT UNSIGNED NOT NULL COMMENT '店铺ID', + role_name VARCHAR(100) NOT NULL COMMENT '角色名称', + creator_id BIGINT UNSIGNED NULL COMMENT '创建人', + status TINYINT UNSIGNED NOT NULL DEFAULT 1 COMMENT '状态', + remark VARCHAR(255) NULL COMMENT '备注', + sort_order INT NOT NULL DEFAULT 0 COMMENT '排序', + create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, + update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP, + is_delete TINYINT UNSIGNED DEFAULT 0 COMMENT '逻辑删除' +) COMMENT='店铺自定义角色表'; + +CREATE TABLE IF NOT EXISTS t_shop_role_permission ( + id BIGINT UNSIGNED NOT NULL COMMENT '主键' PRIMARY KEY, + role_id BIGINT UNSIGNED NOT NULL COMMENT '角色ID', + permission_id BIGINT UNSIGNED NOT NULL COMMENT '权限ID', + create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, + update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP, + is_delete TINYINT UNSIGNED DEFAULT 0 +) COMMENT='店铺角色权限关联表'; + +CREATE TABLE IF NOT EXISTS t_user_shop_role ( + id BIGINT UNSIGNED NOT NULL COMMENT '主键' PRIMARY KEY, + user_id BIGINT UNSIGNED NOT NULL COMMENT '用户ID', + shop_id BIGINT UNSIGNED NOT NULL COMMENT '店铺ID', + role_id BIGINT UNSIGNED NOT NULL COMMENT '角色ID', + status TINYINT UNSIGNED NOT NULL DEFAULT 1 COMMENT '状态', + create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, + update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP, + is_delete TINYINT UNSIGNED DEFAULT 0 +) COMMENT='用户店铺角色绑定表'; + +CREATE TABLE IF NOT EXISTS t_user_relation ( + id BIGINT UNSIGNED NOT NULL COMMENT '主键' PRIMARY KEY, + user_id BIGINT UNSIGNED NOT NULL COMMENT '用户ID', + shop_id BIGINT UNSIGNED NULL COMMENT '店铺ID', + parent_user_id BIGINT UNSIGNED NULL COMMENT '直属上级用户ID', + parent_role_type INT NULL COMMENT '上级身份类型', + source_type VARCHAR(32) NULL COMMENT '来源类型', + creator_id BIGINT UNSIGNED NULL COMMENT '创建人', + create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, + update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP, + is_delete TINYINT UNSIGNED DEFAULT 0 +) COMMENT='用户归属关系表'; + +CREATE TABLE IF NOT EXISTS t_user_invite_code ( + id BIGINT UNSIGNED NOT NULL COMMENT '主键' PRIMARY KEY, + invite_code VARCHAR(64) NOT NULL COMMENT '邀请码', + owner_user_id BIGINT UNSIGNED NOT NULL COMMENT '所属人', + shop_id BIGINT UNSIGNED NOT NULL COMMENT '店铺ID', + status TINYINT UNSIGNED NOT NULL DEFAULT 1 COMMENT '状态', + use_count INT NOT NULL DEFAULT 0 COMMENT '使用次数', + expire_time DATETIME NULL COMMENT '过期时间', + create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, + update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP, + is_delete TINYINT UNSIGNED DEFAULT 0, + UNIQUE KEY uk_invite_code (invite_code) +) COMMENT='邀请码表'; + +-- Indexes are created by the corresponding migration path in environments that need them. +-- Existing databases already have these indexes, and MySQL 5.7 does not support CREATE INDEX IF NOT EXISTS. + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (313931273555136490, 'messagehub:config:manage', '管理MessageHub配置', '消息配置', '管理YumiNail投递MessageHub的场景级对接参数', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + is_delete = 0, + update_time = NOW(); + +INSERT INTO t_user_permission (user_id, permission_id, create_time, update_time, create_by, update_by, is_delete) +SELECT u.id, p.id, NOW(), NOW(), u.id, u.id, 0 +FROM t_user u +INNER JOIN t_permission p + ON p.is_delete = 0 + AND p.permission_code = 'messagehub:config:manage' +WHERE u.is_delete = 0 + AND u.type = 4 + AND NOT EXISTS ( + SELECT 1 + FROM t_user_permission up + WHERE up.user_id = u.id + AND up.permission_id = p.id + AND up.is_delete = 0 + ); + +INSERT INTO t_messagehub_push_config ( + id, + scene_code, + scene_name, + platform, + msg_type, + queue_name, + source_system, + template_code, + channel_id, + send_method, + enabled, + remark, + create_time, + update_time, + is_delete +) +VALUES + (313931273555137001, 'USER_REGISTER_SMS_CODE', '用户注册验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'yuminail', 'SPUG0001', NULL, 'SPUG', 1, '注册功能发送验证码时使用', NOW(), NOW(), 0), + (313931273555137002, 'USER_LOGIN_SMS_CODE', '手机号登录验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'yuminail', 'SPUG0001', NULL, 'SPUG', 1, '手机号验证码登录时使用', NOW(), NOW(), 0), + (313931273555137003, 'USER_RESET_PASSWORD_SMS_CODE', '找回密码验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'yuminail', 'SPUG0001', NULL, 'SPUG', 1, '找回密码时使用', NOW(), NOW(), 0), + (313931273555137004, 'USER_BIND_PHONE_SMS_CODE', '绑定手机号验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'yuminail', 'SPUG0001', NULL, 'SPUG', 1, '绑定手机号时使用', NOW(), NOW(), 0), + (313931273555137005, 'USER_CHANGE_PHONE_SMS_CODE', '修改手机号验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'yuminail', 'SPUG0001', NULL, 'SPUG', 1, '修改手机号时使用', NOW(), NOW(), 0), + (313931273555137006, 'USER_CHANGE_PASSWORD_SMS_CODE', '修改密码验证码', 'SMS', 'VERIFICATION', 'smsQueue', 'yuminail', 'SPUG0001', NULL, 'SPUG', 1, '修改密码时使用', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + scene_name = VALUES(scene_name), + platform = VALUES(platform), + msg_type = VALUES(msg_type), + queue_name = VALUES(queue_name), + source_system = VALUES(source_system), + template_code = VALUES(template_code), + channel_id = VALUES(channel_id), + send_method = VALUES(send_method), + enabled = VALUES(enabled), + remark = VALUES(remark), + is_delete = 0, + update_time = NOW(); + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (313931273555136501, 'role:view', '查看店铺角色', '角色管理', '查看店铺自定义角色', NOW(), NOW(), 0), + (313931273555136502, 'role:create', '新增店铺角色', '角色管理', '创建店铺自定义角色', NOW(), NOW(), 0), + (313931273555136503, 'role:edit', '编辑店铺角色', '角色管理', '编辑角色权限和绑定员工', NOW(), NOW(), 0), + (313931273555136504, 'role:delete', '删除店铺角色', '角色管理', '删除店铺自定义角色', NOW(), NOW(), 0), + (313931273555136505, 'user:relation:view', '查看用户所属', '用户管理', '查看用户归属关系', NOW(), NOW(), 0), + (313931273555136506, 'user:relation:edit', '编辑用户所属', '用户管理', '调整用户店铺和直属上级', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + id = VALUES(id), + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + is_delete = 0, + update_time = NOW(); + +-- 2026-05-18 协议管理、用户协议同意记录与安全审计日志 +CREATE TABLE IF NOT EXISTS t_legal_agreement ( + id bigint NOT NULL COMMENT '协议ID', + agreement_type varchar(32) NOT NULL COMMENT '协议类型:USER_TERMS/PRIVACY_POLICY', + title varchar(100) NOT NULL COMMENT '协议标题', + version varchar(32) NOT NULL COMMENT '协议版本号', + content longtext NOT NULL COMMENT '协议正文', + status tinyint NOT NULL DEFAULT 0 COMMENT '状态:0草稿/停用,1已发布启用', + effective_time datetime NULL COMMENT '生效时间', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint NOT NULL DEFAULT 0 COMMENT '逻辑删除:0否,1是', + PRIMARY KEY (id), + UNIQUE KEY uk_legal_agreement_type_version (agreement_type, version, is_delete), + KEY idx_legal_agreement_current (agreement_type, status, effective_time, is_delete) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户协议与隐私政策'; + +CREATE TABLE IF NOT EXISTS t_user_agreement_consent ( + id bigint NOT NULL COMMENT '同意记录ID', + user_id bigint NOT NULL COMMENT '用户ID', + agreement_type varchar(32) NOT NULL COMMENT '协议类型', + version varchar(32) NOT NULL COMMENT '同意版本号', + entry varchar(64) NULL COMMENT '同意入口:login/register/phone-login/wechat-mini', + client_type varchar(32) NULL COMMENT '客户端类型:WEB/WECHAT_MINI', + ip_address varchar(64) NULL COMMENT '同意IP', + device_id varchar(128) NULL COMMENT '设备ID', + consent_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '同意时间', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id), + UNIQUE KEY uk_user_agreement_consent (user_id, agreement_type, version), + KEY idx_user_agreement_user (user_id, agreement_type) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户协议同意记录'; + +CREATE TABLE IF NOT EXISTS t_security_audit_log ( + id bigint NOT NULL COMMENT '审计日志ID', + user_id bigint NULL COMMENT '操作用户ID', + account varchar(100) NULL COMMENT '操作账号', + action varchar(64) NOT NULL COMMENT '安全动作', + result varchar(32) NOT NULL COMMENT '结果:SUCCESS/FAIL', + reason varchar(255) NULL COMMENT '失败或补充原因', + ip_address varchar(64) NULL COMMENT '请求IP', + device_id varchar(128) NULL COMMENT '设备ID', + operate_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '操作时间', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id), + KEY idx_security_audit_action_time (action, operate_time), + KEY idx_security_audit_account_time (account, operate_time) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='安全审计日志'; + +CREATE TABLE IF NOT EXISTS t_system_parameter_config ( + id bigint NOT NULL COMMENT '配置ID', + config_group varchar(50) NOT NULL COMMENT '配置分组', + config_key varchar(100) NOT NULL COMMENT '配置键', + config_name varchar(100) NOT NULL COMMENT '配置名称', + config_value varchar(1000) NULL COMMENT '配置值', + enabled tinyint NOT NULL DEFAULT 1 COMMENT '是否启用:1启用,0停用', + remark varchar(255) NULL COMMENT '备注', + create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + is_delete tinyint NOT NULL DEFAULT 0 COMMENT '逻辑删除:0否,1是', + PRIMARY KEY (id), + UNIQUE KEY uk_system_parameter_group_key (config_group, config_key, is_delete) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='系统参数配置'; + +INSERT INTO t_legal_agreement (id, agreement_type, title, version, content, status, effective_time, create_time, update_time, is_delete) +VALUES + (313931273555138001, 'USER_TERMS', '用户协议', '2026.05.18', '欢迎使用 YumiNail。请在使用账号、预约、订单、会员、消息等功能前仔细阅读本协议。继续登录或注册即表示你已理解并同意平台基础服务规则、账号安全要求、订单预约规则和依法合规使用要求。', 1, NOW(), NOW(), NOW(), 0), + (313931273555138002, 'PRIVACY_POLICY', '隐私政策', '2026.05.18', 'YumiNail 会在提供登录注册、预约下单、会员余额、消息通知和客户服务时处理必要的手机号、昵称、门店归属、订单与设备信息。我们仅在业务需要和法律允许范围内使用这些信息,并采取访问控制、脱敏展示和审计记录等措施保护数据安全。', 1, NOW(), NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + title = VALUES(title), + content = VALUES(content), + status = VALUES(status), + effective_time = VALUES(effective_time), + is_delete = 0, + update_time = NOW(); + +INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete) +VALUES + (313931273555136601, 'legal_agreement:manage', '协议管理', '安全管理', '管理用户协议和隐私政策版本', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + permission_name = VALUES(permission_name), + permission_group = VALUES(permission_group), + description = VALUES(description), + is_delete = 0, + update_time = NOW(); + +INSERT INTO t_user_permission (user_id, permission_id, create_time, update_time, create_by, update_by, is_delete) +SELECT u.id, p.id, NOW(), NOW(), u.id, u.id, 0 +FROM t_user u +INNER JOIN t_permission p + ON p.is_delete = 0 + AND p.permission_code = 'legal_agreement:manage' +WHERE u.is_delete = 0 + AND u.type = 4 + AND NOT EXISTS ( + SELECT 1 + FROM t_user_permission up + WHERE up.user_id = u.id + AND up.permission_id = p.id + AND up.is_delete = 0 + ); + +INSERT INTO t_system_parameter_config ( + id, config_group, config_key, config_name, config_value, enabled, remark, create_time, update_time, is_delete +) +VALUES + (313931273555139001, 'MAP', 'TENCENT_MAP_KEY', '腾讯位置服务 Key', '', 0, '用于后台店铺选点和腾讯地图展示;请在后台参数管理中填入真实 Key 后启用', NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + config_name = VALUES(config_name), + remark = VALUES(remark), + is_delete = 0, + update_time = NOW(); diff --git a/Frontend/.vscode/extensions.json b/YumiNail-Frontend/.vscode/extensions.json similarity index 100% rename from Frontend/.vscode/extensions.json rename to YumiNail-Frontend/.vscode/extensions.json diff --git a/YumiNail-Frontend/src/App.vue b/YumiNail-Frontend/src/App.vue index dd92616b..73d6bda9 100644 --- a/YumiNail-Frontend/src/App.vue +++ b/YumiNail-Frontend/src/App.vue @@ -14,17 +14,24 @@ @@ -112,4 +176,123 @@ onMounted(async () => { .page-content.no-nav-padding { padding-bottom: 0; } + +.yumi-date-picker-panel { + padding: 6px; +} + +.yumi-date-picker-panel .ant-picker-panel-container { + overflow: hidden; + border-radius: 12px; + box-shadow: 0 18px 44px rgba(34, 40, 49, 0.18); +} + +.yumi-date-picker-panel .ant-picker-panel { + border: 0; +} + +.yumi-date-picker-panel .ant-picker-header { + padding: 8px 12px; + border-bottom-color: #eef1f5; +} + +.yumi-date-picker-panel .ant-picker-header button { + min-width: 34px; + height: 34px; + border-radius: 8px; +} + +.yumi-date-picker-panel .ant-picker-header-view { + line-height: 34px; + font-weight: 700; +} + +.yumi-date-picker-panel .ant-picker-content th { + height: 34px; + color: #7b8494; + font-weight: 600; +} + +.yumi-date-picker-panel .ant-picker-cell { + padding: 4px 0; +} + +.yumi-date-picker-panel .ant-picker-cell-inner { + min-width: 34px; + height: 34px !important; + line-height: 34px !important; + border-radius: 8px !important; + transition: background .18s ease, color .18s ease, transform .18s ease; +} + +.yumi-date-picker-panel .ant-picker-cell:hover .ant-picker-cell-inner { + background: #eef6ff; + transform: translateY(-1px); +} + +.yumi-date-picker-panel .ant-picker-cell-selected .ant-picker-cell-inner, +.yumi-date-picker-panel .ant-picker-cell-range-start .ant-picker-cell-inner, +.yumi-date-picker-panel .ant-picker-cell-range-end .ant-picker-cell-inner { + background: #1677ff; + color: #fff; + font-weight: 700; +} + +.yumi-date-picker-panel .ant-picker-footer { + border-top-color: #eef1f5; +} + +.yumi-date-time-panel .ant-picker-time-panel, +.yumi-time-panel .ant-picker-time-panel { + min-width: 150px; +} + +.yumi-date-time-panel .ant-picker-time-panel-column, +.yumi-time-panel .ant-picker-time-panel-column { + width: 76px; + padding: 8px 6px; +} + +.yumi-date-time-panel .ant-picker-time-panel-cell-inner, +.yumi-time-panel .ant-picker-time-panel-cell-inner { + height: 34px !important; + line-height: 34px !important; + border-radius: 8px !important; + text-align: center; +} + +.yumi-date-time-panel .ant-picker-time-panel-cell-selected .ant-picker-time-panel-cell-inner, +.yumi-time-panel .ant-picker-time-panel-cell-selected .ant-picker-time-panel-cell-inner { + background: #eef6ff; + color: #1677ff; + font-weight: 700; +} + +.ant-picker { + border-radius: 8px; +} + +.ant-picker-focused, +.ant-picker:hover { + border-color: #1677ff; + box-shadow: 0 0 0 3px rgba(22, 119, 255, 0.12); +} + +.popup-message-body { + display: grid; + gap: 12px; +} + +.popup-message-content { + white-space: pre-wrap; + line-height: 1.8; +} + +.popup-message-image { + width: 100%; + max-height: 360px; + object-fit: contain; + border-radius: 8px; + background: #fff7f8; +} diff --git a/YumiNail-Frontend/src/api/admin.ts b/YumiNail-Frontend/src/api/admin.ts index c3f8a5f3..6c2d7083 100644 --- a/YumiNail-Frontend/src/api/admin.ts +++ b/YumiNail-Frontend/src/api/admin.ts @@ -1,3 +1,7 @@ +/** + * Front-end API wrapper for this module. + * Call guide: import the named API object, then call the matching method from a Vue page or composable. + */ import axios, { AxiosError, type AxiosProgressEvent } from 'axios' import { message } from 'ant-design-vue' import { ADMIN_API_BASE_URL } from '../config/api' @@ -181,24 +185,81 @@ export interface LoginShopSelectionResponse { }> } +export interface LegalAgreementAdminVO { + id: IdType + agreementType: 'USER_TERMS' | 'PRIVACY_POLICY' + agreementTypeName?: string + title: string + version: string + content: string + status: number + statusText?: string + effectiveTime?: string + createTime?: string + updateTime?: string +} + +export interface LegalAgreementAdminRequest { + agreementType: 'USER_TERMS' | 'PRIVACY_POLICY' + title: string + version: string + content: string +} + +/** + * adminAuthApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ export const adminAuthApi = { + /** + * `login` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: AdminLoginRequest caller-supplied value for `data: AdminLoginRequest` + */ login: (data: AdminLoginRequest) => { return adminApi.post('/auth/login', data) }, + /** + * `getLoginShops` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param account: string caller-supplied value for `account: string` + */ getLoginShops: (account: string) => { return adminApi.get(`/auth/login-shops/${encodeURIComponent(account)}`) }, + /** + * `logout` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ logout: () => { return adminApi.post('/auth/logout') }, + /** + * `switchShop` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param shopId?: IdType caller-supplied value for `shopId?: IdType` + */ switchShop: (shopId?: IdType) => { return adminApi.post('/auth/switch-shop', { shopId }) }, + /** + * `refreshToken` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param refreshToken: string caller-supplied value for `refreshToken: string` + */ refreshToken: (refreshToken: string) => { return adminApi.post<{ accessToken: string; refreshToken: string }>('/auth/refresh', { refreshToken }) } } +export const adminLegalAgreementApi = { + list: () => adminApi.get('/legal-agreement/list'), + create: (data: LegalAgreementAdminRequest) => adminApi.post('/legal-agreement/create', data), + update: (id: IdType, data: LegalAgreementAdminRequest) => adminApi.put(`/legal-agreement/${id}`, data), + publish: (id: IdType) => adminApi.put(`/legal-agreement/${id}/publish`), + disable: (id: IdType) => adminApi.put(`/legal-agreement/${id}/disable`) +} + export interface ObjectStorageFileVO { id: IdType fileName: string @@ -222,7 +283,16 @@ export interface ChunkUploadSessionVO { uploadedChunks: number[] } +/** + * adminFileApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ export const adminFileApi = { + /** + * `uploadFile` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param file: File caller-supplied value for `file: File` + */ uploadFile: (file: File) => { const formData = new FormData() formData.append('file', file) @@ -230,8 +300,13 @@ export const adminFileApi = { headers: { 'Content-Type': 'multipart/form-data' } - }) + }) as unknown as Promise }, + /** + * `initChunkUpload` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: ChunkUploadInitRequest caller-supplied value for `data: ChunkUploadInitRequest` + */ initChunkUpload: (data: ChunkUploadInitRequest) => { return adminApi.post('/object-storage-file/upload/init', data) as unknown as Promise }, @@ -252,14 +327,29 @@ export const adminFileApi = { onUploadProgress: config?.onUploadProgress }) }, + /** + * `completeChunkUpload` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param uploadId: string caller-supplied value for `uploadId: string` + */ completeChunkUpload: (uploadId: string) => { return adminApi.post('/object-storage-file/upload/complete', { uploadId }) as unknown as Promise }, + /** + * `cancelChunkUpload` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param uploadId: string caller-supplied value for `uploadId: string` + */ cancelChunkUpload: (uploadId: string) => { return adminApi.delete(`/object-storage-file/upload/${uploadId}`) }, + /** + * `getSignedUrl` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ getSignedUrl: (id: IdType) => { - return adminApi.get(`/object-storage-file/get-signed-url/${id}`) + return adminApi.get(`/object-storage-file/get-signed-url/${id}`) as unknown as Promise } } @@ -271,23 +361,54 @@ export interface Tag { borderColor?: string shopId?: IdType shopName?: string + type?: number + typeName?: string createTime: string updateTime: string } +/** + * adminTagApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ export const adminTagApi = { + /** + * `listAllTags` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ listAllTags: () => { return adminApi.get('/tag/list/all') as unknown as Promise }, + /** + * `listTagsByShopId` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param shopId: IdType caller-supplied value for `shopId: IdType` + */ listTagsByShopId: (shopId: IdType) => { return adminApi.get(`/tag/list/by-shop/${shopId}`) as unknown as Promise }, + /** + * `createTag` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: { tagName: string; textColor?: string; bgColor?: string; borderColor?: string; shopId?: IdType } caller-supplied value for `data: { tagName: string; textColor?: string; bgColor?: string; borderColor?: string; shopId?: IdType }` + */ createTag: (data: { tagName: string; textColor?: string; bgColor?: string; borderColor?: string; shopId?: IdType }) => { return adminApi.post('/tag/create', data) }, + /** + * `updateTag` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + * @param data: { tagName: string; textColor?: string; bgColor?: string; borderColor?: string; shopId?: IdType } caller-supplied value for `data: { tagName: string; textColor?: string; bgColor?: string; borderColor?: string; shopId?: IdType }` + */ updateTag: (id: IdType, data: { tagName: string; textColor?: string; bgColor?: string; borderColor?: string; shopId?: IdType }) => { return adminApi.put(`/tag/update/${id}`, data) }, + /** + * `deleteTag` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ deleteTag: (id: IdType) => { return adminApi.delete(`/tag/delete/${id}`) } @@ -304,7 +425,16 @@ export interface Artist { updateTime: string } +/** + * adminArtistApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ export const adminArtistApi = { + /** + * `listArtists` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param shopId?: IdType caller-supplied value for `shopId?: IdType` + */ listArtists: (shopId?: IdType) => { const params: any = {} if (shopId) { @@ -341,20 +471,50 @@ export interface Coupon { updateTime: string } +/** + * adminCouponApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ export const adminCouponApi = { + /** + * `listAllCoupons` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param shopId?: IdType caller-supplied value for `shopId?: IdType` + */ listAllCoupons: (shopId?: IdType) => { const params = shopId ? { shopId } : {} return adminApi.get('/coupon/list/all', { params }) as unknown as Promise }, + /** + * `createCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: any caller-supplied value for `data: any` + */ createCoupon: (data: any) => { return adminApi.post('/coupon/create', data) }, + /** + * `updateCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + * @param data: any caller-supplied value for `data: any` + */ updateCoupon: (id: IdType, data: any) => { return adminApi.put(`/coupon/update/${id}`, data) }, + /** + * `deleteCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ deleteCoupon: (id: IdType) => { return adminApi.delete(`/coupon/delete/${id}`) }, + /** + * `distributeCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: any caller-supplied value for `data: any` + */ distributeCoupon: (data: any) => { return adminApi.post('/coupon/distribute', null, { params: data }) } @@ -374,10 +534,24 @@ export interface AdminCommentVO { createTime?: string } +/** + * adminCommentApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ export const adminCommentApi = { + /** + * `listComments` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param params: { productId?: IdType; userId?: IdType; shopId?: IdType; keyword?: string } caller-supplied value for `params: { productId?: IdType; userId?: IdType; shopId?: IdType; keyword?: string }` + */ listComments: (params: { productId?: IdType; userId?: IdType; shopId?: IdType; keyword?: string }) => { return adminApi.get('/comment/list', { params }) as unknown as Promise }, + /** + * `deleteComment` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ deleteComment: (id: IdType) => { return adminApi.delete(`/comment/delete/${id}`) as unknown as Promise } @@ -404,19 +578,48 @@ export interface Product { updateTime: string } +/** + * adminProductApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ export const adminProductApi = { + /** + * `listProducts` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param params: { page: number; size: number; keyword?: string; shopId?: IdType } caller-supplied value for `params: { page: number; size: number; keyword?: string; shopId?: IdType }` + */ listProducts: (params: { page: number; size: number; keyword?: string; shopId?: IdType }) => { return adminApi.get<{ list: Product[]; total: number; page: number; size: number }>('/product/list', { params }) }, + /** + * `listAllProducts` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ listAllProducts: () => { return adminApi.get('/product/list/all') }, + /** + * `createProduct` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: any caller-supplied value for `data: any` + */ createProduct: (data: any) => { return adminApi.post('/product/create', data) }, + /** + * `updateProduct` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + * @param data: any caller-supplied value for `data: any` + */ updateProduct: (id: IdType, data: any) => { return adminApi.put(`/product/update/${id}`, data) }, + /** + * `deleteProduct` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ deleteProduct: (id: IdType) => { return adminApi.delete(`/product/delete/${id}`) } @@ -427,12 +630,18 @@ export interface Shop { shopName: string description: string address: string + mapProvider?: string + longitude?: number | string + latitude?: number | string businessHours: string status?: number coverImageFileId?: string coverImageUrls?: string[] imageFileIds?: string imageUrls?: string[] + authorizationExpireTime?: string + authorizationExpired?: boolean + authorizationStatusText?: string createTime: string updateTime: string } @@ -448,28 +657,67 @@ export interface CreateShopRequest { shopName: string description: string address: string + mapProvider?: string + longitude?: number | string + latitude?: number | string businessHours: string coverImageFileId?: string imageFileIds?: string status?: number + authorizationExpireTime?: string } +/** + * adminShopApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ export const adminShopApi = { + /** + * `listShops` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param params: { page: number; size: number; keyword?: string; shopId?: IdType } caller-supplied value for `params: { page: number; size: number; keyword?: string; shopId?: IdType }` + */ listShops: (params: { page: number; size: number; keyword?: string; shopId?: IdType }) => { return adminApi.get('/shops/list', { params }) as unknown as Promise }, + /** + * `listAllShops` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ listAllShops: () => { return adminApi.get('/shops/list/all') as unknown as Promise }, + /** + * `createShop` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: CreateShopRequest caller-supplied value for `data: CreateShopRequest` + */ createShop: (data: CreateShopRequest) => { return adminApi.post('/shops/create', data) }, + /** + * `updateShop` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + * @param data: CreateShopRequest caller-supplied value for `data: CreateShopRequest` + */ updateShop: (id: IdType, data: CreateShopRequest) => { return adminApi.put(`/shops/update/${id}`, data) }, + /** + * `updateShopStatus` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + * @param status: number caller-supplied value for `status: number` + */ updateShopStatus: (id: IdType, status: number) => { return adminApi.put(`/shops/status/${id}`, { status }) }, + /** + * `deleteShop` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ deleteShop: (id: IdType) => { return adminApi.delete(`/shops/delete/${id}`) } @@ -479,6 +727,8 @@ export interface UserVO { id: IdType shopId?: IdType shopName?: string + shopAuthorizationExpireTime?: string + shopAuthorizationExpired?: boolean shopIds?: IdType[] shopNames?: string[] nickname: string @@ -494,6 +744,31 @@ export interface UserVO { status?: number } +export interface UserRelationVO { + userId: IdType + shopId?: IdType + shopName?: string + parentUserId?: IdType + parentUserName?: string + parentRoleType?: number + parentRoleTypeName?: string + sourceType?: string + sourceTypeName?: string +} + +export interface UserStatisticsVO { + totalUserCount: number + normalUserCount: number + employeeCount: number + managerCount: number + artistCount: number + vipUserCount: number + newUserCount: number + byShop?: Record + byRole?: Record + byParent?: Record +} + export interface PageResult { list: T[] total: number @@ -501,46 +776,149 @@ export interface PageResult { size: number } +/** + * adminUserApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ export const adminUserApi = { - listUsers: (params: { page: number; size: number; keyword?: string; type?: number; shopId?: IdType; status?: number }) => { + // 后台用户列表支持多维筛选;页面侧应优先展示 maskedPhone/maskedEmail, + // 避免在列表中直接暴露完整手机号或邮箱。 + /** + * `listUsers` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param params: { page: number; size: number; keyword?: string; type?: number; shopId?: IdType; roleId?: IdType; parentUserId?: IdType; sourceType?: string; status?: number; vipLevel?: string; createdFrom?: string; createdTo?: string; hasPhone?: boolean; hasOrder?: boolean } caller-supplied value for `params: { page: number; size: number; keyword?: string; type?: number; shopId?: IdType; roleId?: IdType; parentUserId?: IdType; sourceType?: string; status?: number; vipLevel?: string; createdFrom?: string; createdTo?: string; hasPhone?: boolean; hasOrder?: boolean }` + */ + listUsers: (params: { page: number; size: number; keyword?: string; type?: number; shopId?: IdType; roleId?: IdType; parentUserId?: IdType; sourceType?: string; status?: number; vipLevel?: string; createdFrom?: string; createdTo?: string; hasPhone?: boolean; hasOrder?: boolean }) => { return adminApi.get>('/user/list', { params }) as unknown as Promise> }, + /** + * `getUserStatistics` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param params: { keyword?: string; type?: number; shopId?: IdType; roleId?: IdType; parentUserId?: IdType; sourceType?: string; status?: number; vipLevel?: string; createdFrom?: string; createdTo?: string; hasPhone?: boolean; hasOrder?: boolean } caller-supplied value for `params: { keyword?: string; type?: number; shopId?: IdType; roleId?: IdType; parentUserId?: IdType; sourceType?: string; status?: number; vipLevel?: string; createdFrom?: string; createdTo?: string; hasPhone?: boolean; hasOrder?: boolean }` + */ + getUserStatistics: (params: { keyword?: string; type?: number; shopId?: IdType; roleId?: IdType; parentUserId?: IdType; sourceType?: string; status?: number; vipLevel?: string; createdFrom?: string; createdTo?: string; hasPhone?: boolean; hasOrder?: boolean }) => { + return adminApi.get('/user/statistics', { params }) as unknown as Promise + }, + /** + * `listAllUsers` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ listAllUsers: () => { return adminApi.get('/user/list/all') as unknown as Promise }, + /** + * `createUser` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: any caller-supplied value for `data: any` + */ createUser: (data: any) => { return adminApi.post('/user/create', data) }, + /** + * `updateUser` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + * @param data: any caller-supplied value for `data: any` + */ updateUser: (id: IdType, data: any) => { return adminApi.put(`/user/update/${id}`, data) }, + /** + * `deleteUser` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ deleteUser: (id: IdType) => { return adminApi.delete(`/user/delete/${id}`) }, + /** + * `unbindUser` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ unbindUser: (id: IdType) => { return adminApi.put(`/user/unbind/${id}`, {}) }, + /** + * `updateUserStatus` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + * @param status: number caller-supplied value for `status: number` + */ updateUserStatus: (id: IdType, status: number) => { return adminApi.put(`/user/status/${id}`, { status }) }, + /** + * `getRelationOptions` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param shopId?: IdType caller-supplied value for `shopId?: IdType` + */ + getRelationOptions: (shopId?: IdType) => { + return adminApi.get(`/user/relation/options`, { params: { shopId } }) as unknown as Promise + }, + /** + * `updateUserRelation` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + * @param data: { shopId?: IdType; parentUserId?: IdType; parentRoleType?: number; sourceType?: string } caller-supplied value for `data: { shopId?: IdType; parentUserId?: IdType; parentRoleType?: number; sourceType?: string }` + */ + updateUserRelation: (id: IdType, data: { shopId?: IdType; parentUserId?: IdType; parentRoleType?: number; sourceType?: string }) => { + return adminApi.put(`/user/${id}/relation`, data) as unknown as Promise + }, + /** + * `resetPassword` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ resetPassword: (id: IdType) => { return adminApi.post(`/user/reset-password/${id}`) }, + /** + * `getUserInfo` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ getUserInfo: () => { return adminApi.get('/user/info') as unknown as Promise }, + /** + * `getUserAsset` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ getUserAsset: (id: IdType) => { return adminApi.get(`/user/${id}/asset`) as unknown as Promise }, + /** + * `getUserBalanceHistory` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ getUserBalanceHistory: (id: IdType) => { return adminApi.get(`/user/${id}/balance/history`) as unknown as Promise }, + /** + * `changeUserBalance` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + * @param data: AdminUserBalanceChangeRequest caller-supplied value for `data: AdminUserBalanceChangeRequest` + */ changeUserBalance: (id: IdType, data: AdminUserBalanceChangeRequest) => { return adminApi.post(`/user/${id}/balance/change`, data) as unknown as Promise }, + /** + * `overrideUserVip` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + * @param data: AdminUserVipOverrideRequest caller-supplied value for `data: AdminUserVipOverrideRequest` + */ overrideUserVip: (id: IdType, data: AdminUserVipOverrideRequest) => { return adminApi.post(`/user/${id}/vip/override`, data) as unknown as Promise }, + /** + * `recalculateUserVip` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ recalculateUserVip: (id: IdType) => { return adminApi.post(`/user/${id}/vip/recalculate`) as unknown as Promise } @@ -613,10 +991,25 @@ export interface OrderVO { updateTime: string } +/** + * adminOrderApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ export const adminOrderApi = { + /** + * `listOrders` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param params: { page: number; size: number; keyword?: string; status?: number; shopId?: IdType } caller-supplied value for `params: { page: number; size: number; keyword?: string; status?: number; shopId?: IdType }` + */ listOrders: (params: { page: number; size: number; keyword?: string; status?: number; shopId?: IdType }) => { return adminApi.get>('/order/list', { params }) }, + /** + * `updateOrderStatus` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + * @param status: number caller-supplied value for `status: number` + */ updateOrderStatus: (id: IdType, status: number) => { return adminApi.put(`/order/update-status/${id}`, { status }) } @@ -648,7 +1041,15 @@ export interface DashboardStats { recentActivities: RecentActivityVO[] } +/** + * adminDashboardApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ export const adminDashboardApi = { + /** + * `getStats` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ getStats: () => { return adminApi.get('/dashboard/stats') } @@ -666,19 +1067,351 @@ export interface NailArtistInfoVO { nickname: string shopId: IdType shopName: string + userType?: number + userTypeName?: string + participateProduction?: number + workStartTime?: string + workEndTime?: string } +/** + * adminNailArtistApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ export const adminNailArtistApi = { + /** + * `listNailArtists` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ listNailArtists: () => { return adminApi.get('/nail-artist/list') }, + /** + * `getNailArtistInfo` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param userId: IdType caller-supplied value for `userId: IdType` + */ getNailArtistInfo: (userId: IdType) => { return adminApi.get(`/nail-artist/get/${userId}`) }, + /** + * `saveNailArtistInfo` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: any caller-supplied value for `data: any` + */ saveNailArtistInfo: (data: any) => { return adminApi.post('/nail-artist/save', data) } } +export interface SystemMessageVO { + id: IdType + title: string + content: string + imageFileId?: IdType + imageUrl?: string + publisherId: IdType + publisherName?: string + publisherType: number + targetType: string + targetTypeName?: string + targetIds?: IdType[] + popupEnabled: number + status: number + publishTime?: string + createTime?: string + popupShown?: number + readStatus?: number +} + +export interface MessageTargetOptionsVO { + shops: Array<{ id: IdType; shopName: string }> + users: Array<{ id: IdType; nickname: string; account: string; shopId?: IdType; shopName?: string; type?: number }> +} + +export interface SystemMessageCreateRequest { + title: string + content: string + imageFileId?: IdType + targetType: string + shopIds?: IdType[] + userIds?: IdType[] + popupEnabled?: number +} + +/** + * adminSystemMessageApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ +export const adminSystemMessageApi = { + // 消息通知会进入用户“消息通知”列表;如果 popupEnabled=1, + // 前端展示弹窗后必须调用 mark popup-shown,保证每人每条只弹一次。 + /** + * `listMessages` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ + listMessages: () => { + return adminApi.get('/system-message/admin/list') as unknown as Promise + }, + /** + * `createMessage` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: SystemMessageCreateRequest caller-supplied value for `data: SystemMessageCreateRequest` + */ + createMessage: (data: SystemMessageCreateRequest) => { + return adminApi.post('/system-message/admin/create', data) + }, + /** + * `revokeMessage` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ + revokeMessage: (id: IdType) => { + return adminApi.put(`/system-message/admin/${id}/revoke`) + }, + /** + * `getTargetOptions` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ + getTargetOptions: () => { + return adminApi.get('/system-message/admin/target-options') as unknown as Promise + } +} + +export interface AnnouncementVO { + id: IdType + title: string + content: string + publisherId?: IdType + publisherName?: string + publisherType?: number + targetType: string + targetTypeName?: string + targetIds?: IdType[] + status: number + sortOrder?: number + publishTime?: string + createTime?: string +} + +export interface AnnouncementCreateRequest { + title: string + content: string + targetType: string + shopIds?: IdType[] + userIds?: IdType[] + sortOrder?: number +} + +/** + * adminAnnouncementApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ +export const adminAnnouncementApi = { + // 公告只在首页顶部滚动显示,不写入消息已读/未读状态。 + /** + * `listAnnouncements` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ + listAnnouncements: () => { + return adminApi.get('/announcement/admin/list') as unknown as Promise + }, + /** + * `createAnnouncement` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: AnnouncementCreateRequest caller-supplied value for `data: AnnouncementCreateRequest` + */ + createAnnouncement: (data: AnnouncementCreateRequest) => { + return adminApi.post('/announcement/admin/create', data) + }, + /** + * `revokeAnnouncement` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ + revokeAnnouncement: (id: IdType) => { + return adminApi.put(`/announcement/admin/${id}/revoke`) + }, + /** + * `getTargetOptions` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ + getTargetOptions: () => { + return adminApi.get('/announcement/admin/target-options') as unknown as Promise + } +} + +export interface VipRechargePlanVO { + id: IdType + shopId: IdType + shopName?: string + title: string + rechargeAmount: number + giftAmount: number + vipLevel: string + description?: string + sortOrder?: number + status: number + createTime?: string + updateTime?: string +} + +export interface VipRechargePlanRequest { + shopId?: IdType + title: string + rechargeAmount: number + giftAmount: number + vipLevel: string + description?: string + sortOrder?: number + status?: number +} + +/** + * adminVipRechargePlanApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ +export const adminVipRechargePlanApi = { + /** + * `listPlans` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param shopId?: IdType caller-supplied value for `shopId?: IdType` + */ + listPlans: (shopId?: IdType) => { + const params = shopId ? { shopId } : {} + return adminApi.get('/vip-recharge-plan/admin/list', { params }) as unknown as Promise + }, + /** + * `createPlan` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: VipRechargePlanRequest caller-supplied value for `data: VipRechargePlanRequest` + */ + createPlan: (data: VipRechargePlanRequest) => { + return adminApi.post('/vip-recharge-plan/admin/create', data) + }, + /** + * `updatePlan` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + * @param data: VipRechargePlanRequest caller-supplied value for `data: VipRechargePlanRequest` + */ + updatePlan: (id: IdType, data: VipRechargePlanRequest) => { + return adminApi.put(`/vip-recharge-plan/admin/${id}`, data) + }, + /** + * `updateStatus` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + * @param status: number caller-supplied value for `status: number` + */ + updateStatus: (id: IdType, status: number) => { + return adminApi.put(`/vip-recharge-plan/admin/${id}/status`, null, { params: { status } }) + } +} + +export interface MessageHubPushConfigVO { + id: IdType + sceneCode: string + sceneName: string + platform: string + msgType: string + queueName: string + sourceSystem: string + templateCode: string + channelId?: IdType + sendMethod?: string + enabled: number + remark?: string + createTime?: string + updateTime?: string +} + +export interface MessageHubPushConfigRequest { + sceneCode: string + sceneName: string + platform: string + msgType: string + queueName: string + sourceSystem: string + templateCode: string + channelId?: IdType + sendMethod?: string + enabled?: number + remark?: string +} + +/** + * adminMessageHubPushConfigApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ +export const adminMessageHubPushConfigApi = { + /** + * `listConfigs` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ + listConfigs: () => { + return adminApi.get('/messagehub-push-config/admin/list') as unknown as Promise + }, + /** + * `createConfig` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: MessageHubPushConfigRequest caller-supplied value for `data: MessageHubPushConfigRequest` + */ + createConfig: (data: MessageHubPushConfigRequest) => { + return adminApi.post('/messagehub-push-config/admin/create', data) + }, + /** + * `updateConfig` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + * @param data: MessageHubPushConfigRequest caller-supplied value for `data: MessageHubPushConfigRequest` + */ + updateConfig: (id: IdType, data: MessageHubPushConfigRequest) => { + return adminApi.put(`/messagehub-push-config/admin/${id}`, data) + }, + /** + * `updateStatus` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + * @param enabled: number caller-supplied value for `enabled: number` + */ + updateStatus: (id: IdType, enabled: number) => { + return adminApi.put(`/messagehub-push-config/admin/${id}/status`, null, { params: { enabled } }) + }, + /** + * `testConfig` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + * @param phone: string caller-supplied value for `phone: string` + */ + testConfig: (id: IdType, phone: string) => { + return adminApi.post(`/messagehub-push-config/admin/${id}/test`, { phone }) + } +} + +export interface SystemParameterConfigVO { + id?: IdType + configGroup: string + configKey: string + configName: string + configValue: string + enabled: number + remark?: string + createTime?: string + updateTime?: string +} + +export const adminSystemParameterConfigApi = { + listConfigs: (configGroup?: string) => { + return adminApi.get('/system-parameter-config/admin/list', { params: { configGroup } }) as unknown as Promise + }, + saveConfig: (data: SystemParameterConfigVO) => { + return adminApi.post('/system-parameter-config/admin/save', data) + }, + getTencentMapKey: () => { + return adminApi.get<{ key: string }>('/system-parameter-config/admin/tencent-map') as unknown as Promise<{ key: string }> + } +} + export { adminApi } export default adminApi diff --git a/YumiNail-Frontend/src/api/auth.ts b/YumiNail-Frontend/src/api/auth.ts index d43d2405..33213073 100644 --- a/YumiNail-Frontend/src/api/auth.ts +++ b/YumiNail-Frontend/src/api/auth.ts @@ -1,8 +1,13 @@ +/** + * Front-end API wrapper for this module. + * Call guide: import the named API object, then call the matching method from a Vue page or composable. + */ import api from './index' import type { IdType } from '@/utils/id' export interface SendVerificationCodeRequest { phone: string + sceneCode?: string } export interface LoginRequest { @@ -10,12 +15,18 @@ export interface LoginRequest { password: string rememberMe?: boolean shopId?: string | number + agreementAccepted?: boolean + agreementVersions?: Record + clientType?: string } export interface PhoneLoginRequest { phone: string verificationCode: string shopId?: string | number + agreementAccepted?: boolean + agreementVersions?: Record + clientType?: string } export interface RegisterRequest { @@ -23,8 +34,24 @@ export interface RegisterRequest { password: string nickname: string shopId?: string | number + inviteCode?: string phone?: string verificationCode?: string + agreementAccepted?: boolean + agreementVersions?: Record + clientType?: string +} + +export interface LegalAgreement { + id: IdType + agreementType: 'USER_TERMS' | 'PRIVACY_POLICY' + agreementTypeName: string + title: string + version: string + content: string + status: number + statusText?: string + effectiveTime?: string } export interface LoginResponse { @@ -42,6 +69,8 @@ export interface UserInfo { type?: number shopId?: IdType shopName?: string + shopAuthorizationExpireTime?: string + shopAuthorizationExpired?: boolean shopIds?: IdType[] shopNames?: string[] createTime: string @@ -67,44 +96,108 @@ export interface SwitchShopRequest { shopId?: string | number } +/** + * authApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ export const authApi = { + /** + * `sendVerificationCode` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: SendVerificationCodeRequest caller-supplied value for `data: SendVerificationCodeRequest` + */ sendVerificationCode: (data: SendVerificationCodeRequest) => { return api.post('/user/send-verification-code', data) }, + /** + * `login` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: LoginRequest caller-supplied value for `data: LoginRequest` + */ login: (data: LoginRequest) => { return api.post('/user/login', data) }, + /** + * `phoneLogin` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: PhoneLoginRequest caller-supplied value for `data: PhoneLoginRequest` + */ phoneLogin: (data: PhoneLoginRequest) => { return api.post('/user/phone-login', data) }, + /** + * `adminLogin` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: LoginRequest caller-supplied value for `data: LoginRequest` + */ adminLogin: (data: LoginRequest) => { return api.post('/admin/auth/login', data) }, + /** + * `register` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: RegisterRequest caller-supplied value for `data: RegisterRequest` + */ register: (data: RegisterRequest) => { return api.post('/user/register', data) }, + /** + * `refreshToken` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: RefreshTokenRequest caller-supplied value for `data: RefreshTokenRequest` + */ refreshToken: (data: RefreshTokenRequest) => { return api.post('/user/refresh-token', data) }, + /** + * `logout` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ logout: () => { return api.post('/user/logout') }, + /** + * `switchShop` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: SwitchShopRequest caller-supplied value for `data: SwitchShopRequest` + */ switchShop: (data: SwitchShopRequest) => { return api.post('/user/switch-shop', data) }, + /** + * `getUserInfo` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ getUserInfo: () => { return api.get('/user/info') }, + /** + * `resetPasswordByPhone` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: ResetPasswordRequest caller-supplied value for `data: ResetPasswordRequest` + */ resetPasswordByPhone: (data: ResetPasswordRequest) => { return api.post('/user/reset-password-by-phone', data) } } + +export const legalAgreementApi = { + listCurrent: () => { + return api.get('/legal-agreement/current') + }, + getCurrent: (type: 'USER_TERMS' | 'PRIVACY_POLICY') => { + return api.get(`/legal-agreement/current/${type}`) + }, + getMyConsent: () => { + return api.get<{ consentVersions: Record }>('/user/agreement-consent/me') + } +} diff --git a/YumiNail-Frontend/src/api/cart.ts b/YumiNail-Frontend/src/api/cart.ts index 4f173e1b..3d07b343 100644 --- a/YumiNail-Frontend/src/api/cart.ts +++ b/YumiNail-Frontend/src/api/cart.ts @@ -1,3 +1,7 @@ +/** + * Front-end API wrapper for this module. + * Call guide: import the named API object, then call the matching method from a Vue page or composable. + */ import api from './index' import type { IdType } from '@/utils/id' @@ -6,33 +10,65 @@ interface CartItem { quantity: number } +/** + * cartApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ export const cartApi = { // 添加作品到购物车 + /** + * `addToCart` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param item: CartItem caller-supplied value for `item: CartItem` + */ addToCart: (item: CartItem) => { return api.post('/cart/add', item) }, // 从购物车移除作品 + /** + * `removeFromCart` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param productId: IdType caller-supplied value for `productId: IdType` + */ removeFromCart: (productId: IdType) => { return api.delete(`/cart/remove/${productId}`) }, // 批量从购物车移除作品 + /** + * `batchRemoveFromCart` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param cartItemIds: IdType[] caller-supplied value for `cartItemIds: IdType[]` + */ batchRemoveFromCart: (cartItemIds: IdType[]) => { return api.post('/cart/batch-remove', cartItemIds) }, // 更新购物车作品数量 + /** + * `updateCartQuantity` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param item: CartItem caller-supplied value for `item: CartItem` + */ updateCartQuantity: (item: CartItem) => { return api.put('/cart/update', item) }, // 获取购物车列表 + /** + * `getCartList` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ getCartList: () => { return api.get('/cart/list') }, // 清空购物车 + /** + * `clearCart` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ clearCart: () => { return api.delete('/cart/clear') } diff --git a/YumiNail-Frontend/src/api/comment.ts b/YumiNail-Frontend/src/api/comment.ts index 3a7d526b..e1bf8e7e 100644 --- a/YumiNail-Frontend/src/api/comment.ts +++ b/YumiNail-Frontend/src/api/comment.ts @@ -1,3 +1,7 @@ +/** + * Front-end API wrapper for this module. + * Call guide: import the named API object, then call the matching method from a Vue page or composable. + */ import api from './index' import type { IdType } from '@/utils/id' @@ -18,13 +22,32 @@ export interface CommentVO { replies?: CommentVO[] } +/** + * commentApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ export const commentApi = { + /** + * `listByProduct` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param productId: IdType caller-supplied value for `productId: IdType` + */ listByProduct: (productId: IdType) => { return api.get(`/comment/list/product/${productId}`) as unknown as Promise }, + /** + * `create` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: { productId: IdType; shopId?: IdType | null; parentCommentId?: IdType | null; commentContent: string } caller-supplied value for `data: { productId: IdType; shopId?: IdType | null; parentCommentId?: IdType | null; commentContent: string }` + */ create: (data: { productId: IdType; shopId?: IdType | null; parentCommentId?: IdType | null; commentContent: string }) => { return api.post('/comment/create', data) as unknown as Promise }, + /** + * `delete` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ delete: (id: IdType) => { return api.delete(`/comment/delete/${id}`) as unknown as Promise } diff --git a/YumiNail-Frontend/src/api/coupon.ts b/YumiNail-Frontend/src/api/coupon.ts index f718a175..565b5b1c 100644 --- a/YumiNail-Frontend/src/api/coupon.ts +++ b/YumiNail-Frontend/src/api/coupon.ts @@ -1,3 +1,7 @@ +/** + * Front-end API wrapper for this module. + * Call guide: import the named API object, then call the matching method from a Vue page or composable. + */ import request from './index' import type { IdType } from '@/utils/id' @@ -74,8 +78,17 @@ export interface CouponListResponse { size: number } +/** + * couponApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ export const couponApi = { // 创建优惠券 + /** + * `createCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: CreateCouponRequest caller-supplied value for `data: CreateCouponRequest` + */ createCoupon: (data: CreateCouponRequest) => { return request({ url: '/coupon/create', @@ -85,6 +98,12 @@ export const couponApi = { }, // 更新优惠券 + /** + * `updateCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + * @param data: CreateCouponRequest caller-supplied value for `data: CreateCouponRequest` + */ updateCoupon: (id: IdType, data: CreateCouponRequest) => { return request({ url: `/coupon/update/${id}`, @@ -94,6 +113,11 @@ export const couponApi = { }, // 删除优惠券 + /** + * `deleteCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ deleteCoupon: (id: IdType) => { return request({ url: `/coupon/delete/${id}`, @@ -102,6 +126,11 @@ export const couponApi = { }, // 获取优惠券详情 + /** + * `getCouponById` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ getCouponById: (id: IdType) => { return request({ url: `/coupon/detail/${id}`, @@ -110,6 +139,11 @@ export const couponApi = { }, // 获取优惠券列表 + /** + * `listCoupons` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param params: { page: number; size: number; shopId?: IdType } caller-supplied value for `params: { page: number; size: number; shopId?: IdType }` + */ listCoupons: (params: { page: number; size: number; shopId?: IdType }) => { return request({ url: '/coupon/list', @@ -119,6 +153,12 @@ export const couponApi = { }, // 为用户分配优惠券 + /** + * `assignCouponToUser` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param userId: IdType caller-supplied value for `userId: IdType` + * @param couponId: IdType caller-supplied value for `couponId: IdType` + */ assignCouponToUser: (userId: IdType, couponId: IdType) => { return request({ url: '/coupon/assign', @@ -137,6 +177,11 @@ export const couponApi = { }, // 使用优惠券 + /** + * `useCoupon` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param userCouponId: IdType caller-supplied value for `userCouponId: IdType` + */ useCoupon: (userCouponId: IdType) => { return request({ url: '/coupon/use', diff --git a/YumiNail-Frontend/src/api/file.ts b/YumiNail-Frontend/src/api/file.ts index 79fbcdbd..266b7000 100644 --- a/YumiNail-Frontend/src/api/file.ts +++ b/YumiNail-Frontend/src/api/file.ts @@ -1,3 +1,7 @@ +/** + * Front-end API wrapper for this module. + * Call guide: import the named API object, then call the matching method from a Vue page or composable. + */ import type { AxiosProgressEvent } from 'axios' import api from './index' import type { IdType } from '@/utils/id' @@ -17,7 +21,16 @@ export interface ChunkUploadSessionVO { uploadedChunks: number[] } +/** + * fileApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ export const fileApi = { + /** + * `uploadAvatar` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param file: File caller-supplied value for `file: File` + */ uploadAvatar: (file: File) => { const formData = new FormData() formData.append('file', file) @@ -27,6 +40,11 @@ export const fileApi = { } }) }, + /** + * `initAvatarChunkUpload` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: ChunkUploadInitRequest caller-supplied value for `data: ChunkUploadInitRequest` + */ initAvatarChunkUpload: (data: ChunkUploadInitRequest) => { return api.post('/user/upload-avatar/init', data) as unknown as Promise }, @@ -47,13 +65,29 @@ export const fileApi = { onUploadProgress: config?.onUploadProgress }) }, + /** + * `completeAvatarChunkUpload` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param uploadId: string caller-supplied value for `uploadId: string` + */ completeAvatarChunkUpload: (uploadId: string) => { return api.post('/user/upload-avatar/complete', { uploadId }) as unknown as Promise }, + /** + * `cancelAvatarChunkUpload` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param uploadId: string caller-supplied value for `uploadId: string` + */ cancelAvatarChunkUpload: (uploadId: string) => { return api.delete(`/user/upload-avatar/${uploadId}`) }, + /** + * `getSignedUrl` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param fileId: IdType caller-supplied value for `fileId: IdType` + * @param expiryTimeInMinutes?: number caller-supplied value for `expiryTimeInMinutes?: number` + */ getSignedUrl: (fileId: IdType, expiryTimeInMinutes?: number) => { return api.get(`/file/get-signed-url/${fileId}`, { params: { expiryTimeInMinutes } diff --git a/YumiNail-Frontend/src/api/index.ts b/YumiNail-Frontend/src/api/index.ts index 8b37ab2a..78e13f36 100644 --- a/YumiNail-Frontend/src/api/index.ts +++ b/YumiNail-Frontend/src/api/index.ts @@ -1,3 +1,7 @@ +/** + * Front-end API wrapper for this module. + * Call guide: import the named API object, then call the matching method from a Vue page or composable. + */ import axios, { AxiosError } from 'axios' import { authApi } from './auth' import { adminAuthApi } from './admin' @@ -58,6 +62,8 @@ const isAuthFreePath = (url?: string) => { '/user/phone-login', '/user/wechat-mini/', '/user/reset-password-by-phone', + '/legal-agreement/current', + '/api/legal-agreement/current', '/product/get/', '/product/list/', '/comment/list/product/', @@ -149,6 +155,7 @@ api.interceptors.response.use( url?.includes('/user/refresh-token') || url?.includes('/user/send-verification-code') || url?.includes('/user/phone-login') || + url?.includes('/legal-agreement/current') || url?.includes('/product/get/') || url?.includes('/product/list/') || url?.includes('/comment/list/product/') || @@ -235,7 +242,17 @@ api.interceptors.response.use( } ) +/** + * fileApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ export const fileApi = { + /** + * `getSignedUrl` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param fileId: IdType caller-supplied value for `fileId: IdType` + * @param expiryTimeInMinutes?: number caller-supplied value for `expiryTimeInMinutes?: number` + */ getSignedUrl: (fileId: IdType, expiryTimeInMinutes?: number) => { return api.get(`/file/get-signed-url/${fileId}`, { params: { expiryTimeInMinutes } diff --git a/YumiNail-Frontend/src/api/order.ts b/YumiNail-Frontend/src/api/order.ts index a8f98eac..048d8822 100644 --- a/YumiNail-Frontend/src/api/order.ts +++ b/YumiNail-Frontend/src/api/order.ts @@ -1,3 +1,7 @@ +/** + * Front-end API wrapper for this module. + * Call guide: import the named API object, then call the matching method from a Vue page or composable. + */ import api from './index' import type { IdType } from '@/utils/id' @@ -14,8 +18,39 @@ interface CreateOrderRequest { items: OrderItem[] } +export interface ArtistCalendarAppointment { + orderId: IdType + orderNo: string + totalAmount?: number + actualAmount?: number + orderStatus: number + orderStatusText: string + orderItemId: IdType + productId: IdType + productTitle: string + artistId: IdType + artistName?: string + customerNickname?: string + customerPhoneMasked?: string + shopId?: IdType + shopName?: string + appointmentStartTime: string + appointmentEndTime: string + quantity: number + durationMinutes: number +} + +/** + * orderApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ export const orderApi = { // 创建订单 + /** + * `createOrder` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: CreateOrderRequest caller-supplied value for `data: CreateOrderRequest` + */ createOrder: (data: CreateOrderRequest) => { return api.post('/order/create', data) }, @@ -26,21 +61,41 @@ export const orderApi = { }, // 获取订单详情 + /** + * `getOrderDetail` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param orderId: IdType caller-supplied value for `orderId: IdType` + */ getOrderDetail: (orderId: IdType) => { return api.get(`/order/detail/${orderId}`) }, // 取消订单 + /** + * `cancelOrder` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param orderId: IdType caller-supplied value for `orderId: IdType` + */ cancelOrder: (orderId: IdType) => { return api.put(`/order/cancel/${orderId}`) }, // 后台获取所有订单 + /** + * `getAllOrders` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ getAllOrders: () => { return api.get('/order/admin/list') }, // 后台处理订单 + /** + * `processOrder` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param orderId: IdType caller-supplied value for `orderId: IdType` + * @param status: number caller-supplied value for `status: number` + */ processOrder: (orderId: IdType, status: number) => { return api.put(`/order/admin/process/${orderId}`, {}, { params: { status } @@ -48,11 +103,33 @@ export const orderApi = { }, // 美甲师查看自己的订单 + /** + * `getArtistOrders` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ getArtistOrders: () => { return api.get('/order/artist/list') }, + // 预约日历:recent 取未来 7 天概览,day 传 yyyy-MM-dd 查某天明细。 + /** + * `completeArtistOrder` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param orderId: IdType caller-supplied value for `orderId: IdType` + */ completeArtistOrder: (orderId: IdType) => { return api.put(`/order/artist/complete/${orderId}`) + }, + + getArtistCalendarRecent: async (days = 7): Promise => { + return await api.get('/order/artist/calendar/recent', { + params: { days } + }) as unknown as ArtistCalendarAppointment[] + }, + + getArtistCalendarDay: async (date: string): Promise => { + return await api.get('/order/artist/calendar/day', { + params: { date } + }) as unknown as ArtistCalendarAppointment[] } } diff --git a/YumiNail-Frontend/src/api/permission.ts b/YumiNail-Frontend/src/api/permission.ts index 9302d808..fe1ffdc4 100644 --- a/YumiNail-Frontend/src/api/permission.ts +++ b/YumiNail-Frontend/src/api/permission.ts @@ -1,3 +1,7 @@ +/** + * Front-end API wrapper for this module. + * Call guide: import the named API object, then call the matching method from a Vue page or composable. + */ import { adminApi } from './admin' import type { IdType } from '@/utils/id' @@ -25,7 +29,16 @@ export interface UpdatePermissionRequest { description?: string } +/** + * permissionApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ export const permissionApi = { + /** + * `getUserPermissions` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param userId?: IdType caller-supplied value for `userId?: IdType` + */ getUserPermissions: (userId?: IdType) => { if (userId) { return adminApi.get(`/permission/user/${userId}`) @@ -33,26 +46,57 @@ export const permissionApi = { return adminApi.get('/permission/user/current') }, + /** + * `getAssignablePermissionIds` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param userId: IdType caller-supplied value for `userId: IdType` + */ getAssignablePermissionIds: (userId: IdType) => { return adminApi.get(`/permission/assignable/${userId}`) }, + /** + * `listAllPermissions` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ listAllPermissions: () => { return adminApi.get('/permission/list/all') }, + /** + * `createPermission` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: CreatePermissionRequest caller-supplied value for `data: CreatePermissionRequest` + */ createPermission: (data: CreatePermissionRequest) => { return adminApi.post('/permission/create', data) }, + /** + * `updatePermission` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + * @param data: UpdatePermissionRequest caller-supplied value for `data: UpdatePermissionRequest` + */ updatePermission: (id: IdType, data: UpdatePermissionRequest) => { return adminApi.put(`/permission/update/${id}`, data) }, + /** + * `deletePermission` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ deletePermission: (id: IdType) => { return adminApi.delete(`/permission/delete/${id}`) }, + /** + * `assignUserPermissions` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param userId: IdType caller-supplied value for `userId: IdType` + * @param permissionIds: IdType[] caller-supplied value for `permissionIds: IdType[]` + */ assignUserPermissions: (userId: IdType, permissionIds: IdType[]) => { return adminApi.post(`/permission/assign/${userId}`, { permissionIds }) } diff --git a/YumiNail-Frontend/src/api/product.ts b/YumiNail-Frontend/src/api/product.ts index 4affb141..d6339736 100644 --- a/YumiNail-Frontend/src/api/product.ts +++ b/YumiNail-Frontend/src/api/product.ts @@ -1,3 +1,7 @@ +/** + * Front-end API wrapper for this module. + * Call guide: import the named API object, then call the matching method from a Vue page or composable. + */ import api from './index' import type { IdType } from '@/utils/id' @@ -65,6 +69,10 @@ export interface UpdateProductRequest { shopId?: IdType | null } +/** + * productApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ export const productApi = { getAllProducts: async (): Promise => { return await api.get('/product/list/all') as unknown as ProductVO[] diff --git a/YumiNail-Frontend/src/api/productLike.ts b/YumiNail-Frontend/src/api/productLike.ts index 29e7db96..5ce0831d 100644 --- a/YumiNail-Frontend/src/api/productLike.ts +++ b/YumiNail-Frontend/src/api/productLike.ts @@ -1,11 +1,24 @@ +/** + * Front-end API wrapper for this module. + * Call guide: import the named API object, then call the matching method from a Vue page or composable. + */ import api from './index' import type { IdType } from '@/utils/id' +/** + * productLikeApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ export const productLikeApi = { /** * 点赞作品 * @param productId 作品ID */ + /** + * `likeProduct` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param productId: IdType caller-supplied value for `productId: IdType` + */ likeProduct: (productId: IdType) => { return api.post(`/product-like/like/${productId}`) }, @@ -14,6 +27,11 @@ export const productLikeApi = { * 取消点赞作品 * @param productId 作品ID */ + /** + * `unlikeProduct` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param productId: IdType caller-supplied value for `productId: IdType` + */ unlikeProduct: (productId: IdType) => { return api.post(`/product-like/unlike/${productId}`) }, @@ -22,6 +40,11 @@ export const productLikeApi = { * 检查用户是否已点赞作品 * @param productId 作品ID */ + /** + * `checkLikeStatus` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param productId: IdType caller-supplied value for `productId: IdType` + */ checkLikeStatus: (productId: IdType) => { return api.get(`/product-like/check/${productId}`) } diff --git a/YumiNail-Frontend/src/api/shop.ts b/YumiNail-Frontend/src/api/shop.ts index ee1aa917..3e7fe106 100644 --- a/YumiNail-Frontend/src/api/shop.ts +++ b/YumiNail-Frontend/src/api/shop.ts @@ -1,3 +1,7 @@ +/** + * Front-end API wrapper for this module. + * Call guide: import the named API object, then call the matching method from a Vue page or composable. + */ import api from './index' import type { IdType } from '@/utils/id' @@ -6,8 +10,15 @@ export interface ShopVO { shopName: string description: string address: string + mapProvider?: string + longitude?: number | string + latitude?: number | string + navigationUrls?: Record businessHours: string status?: number + authorizationExpireTime?: string + authorizationExpired?: boolean + authorizationStatusText?: string coverImageFileId?: string coverImageUrls?: string[] imageFileIds: string @@ -36,6 +47,7 @@ export interface CreateShopRequest { address: string businessHours: string status: number + authorizationExpireTime?: string } export interface UpdateShopRequest { @@ -46,8 +58,13 @@ export interface UpdateShopRequest { address?: string businessHours?: string status?: number + authorizationExpireTime?: string } +/** + * shopApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ export const shopApi = { getAllShops: async (): Promise => { return await api.get('/shop/list/all') as unknown as ShopVO[] diff --git a/YumiNail-Frontend/src/api/tag.ts b/YumiNail-Frontend/src/api/tag.ts index 965b5ce9..218e7d2e 100644 --- a/YumiNail-Frontend/src/api/tag.ts +++ b/YumiNail-Frontend/src/api/tag.ts @@ -1,3 +1,7 @@ +/** + * Front-end API wrapper for this module. + * Call guide: import the named API object, then call the matching method from a Vue page or composable. + */ import api from './index' import type { IdType } from '@/utils/id' @@ -18,23 +22,52 @@ export interface TagDTO { borderColor: string } +/** + * tagApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ export const tagApi = { + /** + * `getAllTags` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ getAllTags: () => { return api.get('/tag/list/all') }, + /** + * `getTagById` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ getTagById: (id: IdType) => { return api.get(`/tag/get/${id}`) }, + /** + * `createTag` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: TagDTO caller-supplied value for `data: TagDTO` + */ createTag: (data: TagDTO) => { return api.post('/tag/add', data) }, + /** + * `updateTag` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + * @param data: TagDTO caller-supplied value for `data: TagDTO` + */ updateTag: (id: IdType, data: TagDTO) => { return api.put(`/tag/update/${id}`, data) }, + /** + * `deleteTag` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ deleteTag: (id: IdType) => { return api.delete(`/tag/delete/${id}`) } diff --git a/YumiNail-Frontend/src/api/user.ts b/YumiNail-Frontend/src/api/user.ts index 4e165063..697efbd3 100644 --- a/YumiNail-Frontend/src/api/user.ts +++ b/YumiNail-Frontend/src/api/user.ts @@ -1,3 +1,7 @@ +/** + * Front-end API wrapper for this module. + * Call guide: import the named API object, then call the matching method from a Vue page or composable. + */ import api from './index' import type { UserInfo } from './auth' import type { IdType } from '@/utils/id' @@ -19,6 +23,15 @@ export interface UserVO extends UserInfo { updateTime: string status: number phone?: string + email?: string + maskedPhone?: string + maskedEmail?: string + shopRoleId?: IdType + shopRoleName?: string + parentUserId?: IdType + parentUserName?: string + parentUserTypeName?: string + relationSourceType?: string } export interface UpdateUserInfoRequest { @@ -84,25 +97,160 @@ export interface LoginShopSelectionResponse { }> } +export interface UserRelationVO { + userId: IdType + shopId?: IdType + shopName?: string + parentUserId?: IdType + parentUserName?: string + parentRoleType?: number + parentRoleTypeName?: string + sourceType?: string + sourceTypeName?: string +} + +// 用户端常用接口约定: +// - relation 表示当前用户的门店和直属上级归属; +// - announcement 只用于首页滚动公告,不进入消息通知历史; +// - system-message 才是站内消息,popup/read 分开记录。 +export interface InviteCodeVO { + id: IdType + inviteCode: string + ownerUserId?: IdType + ownerUserName?: string + shopId?: IdType + shopName?: string + status?: number + useCount?: number + expireTime?: string + createTime?: string +} + export interface UpdatePhoneRequest { oldPhone: string newPhone: string verificationCode: string } +export interface UserAssetVO { + userId: IdType + nickname: string + balance: number + totalRechargeAmount: number + lastRechargeTime?: string + vipInfoId?: IdType + vipLevel: string + benefitId?: IdType + benefitInfo?: string + manualOverride?: boolean + vipStartTime?: string + vipExpireTime?: string +} + +export interface BalanceHistoryItem { + id: IdType + userId: IdType + userNickname?: string + amount: number + type?: string + currentBalance?: number + beforeBalance?: number + afterBalance?: number + changeScene?: string + relatedOrderId?: IdType + relatedOrderNo?: string + externalOrderNo?: string + remark?: string + changeTime?: string +} + +export interface SystemMessageVO { + id: IdType + title: string + content: string + imageFileId?: IdType + imageUrl?: string + publisherName?: string + targetType?: string + targetTypeName?: string + popupEnabled?: number + popupShown?: number + readStatus?: number + publishTime?: string + createTime?: string +} + +export interface AnnouncementVO { + id: IdType + title: string + content: string + publisherName?: string + targetType?: string + status?: number + sortOrder?: number + publishTime?: string +} + +export interface VipRechargePlanVO { + id: IdType + shopId: IdType + shopName?: string + title: string + rechargeAmount: number + giftAmount: number + vipLevel: string + description?: string + sortOrder?: number + status: number +} + +export interface ContactInfoVO { + contactUserId?: IdType + contactName?: string + roleLabel?: string + phone?: string + phoneAvailable?: boolean + platformContactAvailable?: boolean + platformContactText?: string +} + +/** + * userApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ export const userApi = { getUserInfo: async (): Promise => { return await api.get('/user/info') as unknown as UserVO }, + /** + * `updateUserInfo` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: UpdateUserInfoRequest caller-supplied value for `data: UpdateUserInfoRequest` + */ updateUserInfo: (data: UpdateUserInfoRequest) => { return api.put('/user/update', data) }, + /** + * `updatePassword` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: UpdatePasswordRequest caller-supplied value for `data: UpdatePasswordRequest` + */ updatePassword: (data: UpdatePasswordRequest) => { return api.put('/user/password', data) }, + /** + * `bindPhone` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: BindPhoneRequest caller-supplied value for `data: BindPhoneRequest` + */ bindPhone: (data: BindPhoneRequest) => { return api.post('/user/bind-phone', data) }, + /** + * `updatePhone` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: UpdatePhoneRequest caller-supplied value for `data: UpdatePhoneRequest` + */ updatePhone: (data: UpdatePhoneRequest) => { return api.put('/user/phone', data) }, @@ -127,12 +275,86 @@ export const userApi = { listUsersByType: async (type: number): Promise => { return await api.get(`/user/list/type/${type}`) as unknown as UserVO[] }, - sendVerificationCode: (data: { phone: string }) => { + /** + * `sendVerificationCode` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param data: { phone: string; sceneCode?: string } caller-supplied value for `data: { phone: string; sceneCode?: string }` + */ + sendVerificationCode: (data: { phone: string; sceneCode?: string }) => { return api.post('/user/send-verification-code', data) }, + /** + * `switchShop` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param shopId?: string | number caller-supplied value for `shopId?: string | number` + */ switchShop: (shopId?: string | number) => { return api.post('/user/switch-shop', { shopId }) }, + getMyAsset: async (): Promise => { + return await api.get('/user/asset/me') as unknown as UserAssetVO + }, + getMyBalanceHistory: async (): Promise => { + return await api.get('/user/balance/history/me') as unknown as BalanceHistoryItem[] + }, + listMyMessages: async (): Promise => { + return await api.get('/system-message/my/list') as unknown as SystemMessageVO[] + }, + listMyPopupMessages: async (): Promise => { + return await api.get('/system-message/my/popup') as unknown as SystemMessageVO[] + }, + getMyUnreadMessageCount: async (): Promise<{ unreadCount: number }> => { + return await api.get<{ unreadCount: number }>('/system-message/my/unread-count') as unknown as { unreadCount: number } + }, + getMyMessage: async (id: IdType): Promise => { + return await api.get(`/system-message/my/${id}`) as unknown as SystemMessageVO + }, + /** + * `markMessagePopupShown` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ + markMessagePopupShown: (id: IdType) => { + return api.put(`/system-message/my/${id}/popup-shown`, {}) + }, + /** + * `markMessageRead` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + * @param id: IdType caller-supplied value for `id: IdType` + */ + markMessageRead: (id: IdType) => { + return api.put(`/system-message/my/${id}/read`, {}) + }, + listMyAnnouncements: async (): Promise => { + return await api.get('/announcement/my/list') as unknown as AnnouncementVO[] + }, + listMyVipRechargePlans: async (): Promise => { + return await api.get('/vip-recharge-plan/my/list') as unknown as VipRechargePlanVO[] + }, + getMyRelation: async (): Promise => { + return await api.get('/user/relation/me') as unknown as UserRelationVO + }, + // 注册页输入邀请码时先解析,给用户展示“将归属到谁/哪个店铺”。 + resolveInviteCode: async (code: string): Promise => { + return await api.get('/user/invite-code/resolve', { params: { code } }) as unknown as InviteCodeVO + }, + getShopManagerContact: async (shopId: IdType): Promise => { + return await api.get(`/contact-info/shop/${shopId}/manager`) as unknown as ContactInfoVO + }, + getProductArtistContact: async (productId: IdType, artistId: IdType): Promise => { + return await api.get(`/contact-info/product/${productId}/artist/${artistId}`) as unknown as ContactInfoVO + }, + getOrderArtistContact: async (orderId: IdType, artistId?: IdType): Promise => { + const params = artistId ? { artistId } : {} + return await api.get(`/contact-info/order/${orderId}/artist`, { params }) as unknown as ContactInfoVO + }, + getPlatformContact: async (): Promise => { + return await api.get('/contact-info/platform') as unknown as ContactInfoVO + }, + /** + * `deactivateAccount` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. + * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. + */ deactivateAccount: () => { return api.delete('/user/deactivate') } diff --git a/YumiNail-Frontend/src/api/wishlist.ts b/YumiNail-Frontend/src/api/wishlist.ts index c0099324..08041a12 100644 --- a/YumiNail-Frontend/src/api/wishlist.ts +++ b/YumiNail-Frontend/src/api/wishlist.ts @@ -1,3 +1,7 @@ +/** + * Front-end API wrapper for this module. + * Call guide: import the named API object, then call the matching method from a Vue page or composable. + */ import api from './index' import type { IdType } from '@/utils/id' @@ -27,6 +31,10 @@ export interface WishlistItem { } } +/** + * wishlistApi groups all API calls for this page domain. + * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. + */ export const wishlistApi = { addToWishlist: async (productId: IdType): Promise => { return await api.post('/wishlist/add', { productId }) as unknown as boolean diff --git a/YumiNail-Frontend/src/components/BottomNav.vue b/YumiNail-Frontend/src/components/BottomNav.vue index 72ae9bef..112d9254 100644 --- a/YumiNail-Frontend/src/components/BottomNav.vue +++ b/YumiNail-Frontend/src/components/BottomNav.vue @@ -45,6 +45,10 @@ + + diff --git a/YumiNail-Frontend/src/views/ArtistOrderView.vue b/YumiNail-Frontend/src/views/ArtistOrderView.vue index 40cecf7a..825b7405 100644 --- a/YumiNail-Frontend/src/views/ArtistOrderView.vue +++ b/YumiNail-Frontend/src/views/ArtistOrderView.vue @@ -5,17 +5,58 @@

美甲师订单

-
+ 日历
+
+ +
+ + 全部来源 + 客户预约我的订单 + 我下的订单 + 两者都有 + + + 全部状态 + 待使用 + 已完成 + 已取消 + +
+
+ + + +
+
+ 共 {{ filteredOrders.length }} / {{ orders.length }} 个订单 + 重置 +
+
+ 刷新 + + 清空筛选 + - +
- 订单号:{{ order.orderNo }} +
+ 订单号:{{ order.orderNo }} + + {{ order.artistOrderSourceText }} + +
{{ order.statusText }}
@@ -38,7 +79,7 @@ @@ -48,8 +89,12 @@ + + diff --git a/YumiNail-Frontend/src/views/OrderView.vue b/YumiNail-Frontend/src/views/OrderView.vue index f6f79f98..d324022b 100644 --- a/YumiNail-Frontend/src/views/OrderView.vue +++ b/YumiNail-Frontend/src/views/OrderView.vue @@ -9,15 +9,38 @@
+
+ +
+ + 全部状态 + 待使用 + 已完成 + 已取消 + + +
+
+ + + 重置 +
+
共 {{ filteredOrders.length }} / {{ orders.length }} 个订单
+
+ 去逛逛 + + 清空筛选 + - +
订单号:{{ order.orderNo }} {{ order.statusText }}
+
所属店铺:{{ order.shopName }}
@@ -42,27 +65,81 @@ diff --git a/YumiNail-Frontend/src/views/SettingsView.vue b/YumiNail-Frontend/src/views/SettingsView.vue index 1937447c..ed282bc9 100644 --- a/YumiNail-Frontend/src/views/SettingsView.vue +++ b/YumiNail-Frontend/src/views/SettingsView.vue @@ -46,6 +46,10 @@ + + diff --git a/YumiNail-Frontend/src/views/WishlistView.vue b/YumiNail-Frontend/src/views/WishlistView.vue index be9e7950..50897d68 100644 --- a/YumiNail-Frontend/src/views/WishlistView.vue +++ b/YumiNail-Frontend/src/views/WishlistView.vue @@ -48,6 +48,10 @@ + + diff --git a/YumiNail-Frontend/src/views/admin/CommentsView.vue b/YumiNail-Frontend/src/views/admin/CommentsView.vue index 73f8e888..41f41eb5 100644 --- a/YumiNail-Frontend/src/views/admin/CommentsView.vue +++ b/YumiNail-Frontend/src/views/admin/CommentsView.vue @@ -33,12 +33,18 @@ + + diff --git a/YumiNail-Frontend/src/views/admin/ManageView.vue b/YumiNail-Frontend/src/views/admin/ManageView.vue index 004dd11a..98bbdd10 100644 --- a/YumiNail-Frontend/src/views/admin/ManageView.vue +++ b/YumiNail-Frontend/src/views/admin/ManageView.vue @@ -40,6 +40,10 @@ + + diff --git a/YumiNail-Frontend/src/views/admin/NailArtistsView.vue b/YumiNail-Frontend/src/views/admin/NailArtistsView.vue index d5ae95f3..21dcd6cb 100644 --- a/YumiNail-Frontend/src/views/admin/NailArtistsView.vue +++ b/YumiNail-Frontend/src/views/admin/NailArtistsView.vue @@ -43,6 +43,19 @@ {{ getStatusText(record.status) }} + + + + + diff --git a/YumiNail-Frontend/src/views/admin/TagsView.vue b/YumiNail-Frontend/src/views/admin/TagsView.vue index 9f1f1da6..3d51af43 100644 --- a/YumiNail-Frontend/src/views/admin/TagsView.vue +++ b/YumiNail-Frontend/src/views/admin/TagsView.vue @@ -234,6 +234,10 @@ + + diff --git a/YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/filter/AuthGlobalFilter.java b/YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/filter/AuthGlobalFilter.java index 15ada215..306a7ede 100644 --- a/YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/filter/AuthGlobalFilter.java +++ b/YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/filter/AuthGlobalFilter.java @@ -39,6 +39,8 @@ public class AuthGlobalFilter implements GlobalFilter, Ordered { "/api/user/phone-login", "/api/user/wechat-mini/**", "/api/user/reset-password-by-phone", + "/api/legal-agreement/current", + "/api/legal-agreement/current/**", "/api/product/get/**", "/api/product/list/**", "/api/shop/get/**", diff --git a/YumiNail-Gateway/src/main/resources/application.yaml b/YumiNail-Gateway/src/main/resources/application.yaml index 8aa8eaab..14bd4cab 100644 --- a/YumiNail-Gateway/src/main/resources/application.yaml +++ b/YumiNail-Gateway/src/main/resources/application.yaml @@ -128,6 +128,8 @@ yuminail: - /api/user/wechat-mini/** - /api/user/reset-password-by-phone - /api/shop/list/simple + - /api/legal-agreement/current + - /api/legal-agreement/current/** - /api/health/** - /api/error - /api/admin/auth/login diff --git a/docs/changes/2026-05-16-announcement-vip-recharge-contact-test-report.md b/docs/changes/2026-05-16-announcement-vip-recharge-contact-test-report.md new file mode 100644 index 00000000..3d264b9d --- /dev/null +++ b/docs/changes/2026-05-16-announcement-vip-recharge-contact-test-report.md @@ -0,0 +1,31 @@ +# 2026-05-16 公告、VIP 充值展示与一键联系测试报告 + +## 范围 +- 后端新增公告、VIP 充值档位、一键联系接口。 +- Web 后台新增公告管理、VIP 充值配置。 +- Web 用户端新增首页公告滚动、VIP 充值档位展示、店铺一键联系。 +- 小程序新增首页公告滚动、VIP 充值档位展示,并补齐用户端相关 API。 +- SQL 继续集中在 `YumiNail-Core/src/main/resources/files/YumiNail.sql`。 + +## 数据库与 SQL +- 当前会话未暴露 MySQL MCP 工具,本机也未检测到 `mysql` CLI,因此本轮未能实际执行落库 SQL。 +- 已确认 SQL 目录仅保留 `YumiNail.sql`。 +- `YumiNail.sql` 已补充: + - `t_announcement` + - `t_vip_recharge_plan` + - `announcement:view/create/delete` 权限种子与默认授权 + - 3 条验收公告 + - 5 条 VIP 充值档位验收数据 + - 新表雪花 ID 收口调用 + +## 自动化验证 +- `YumiNail-Core`: `rtk mvn -q -DskipTests compile` 通过。 +- `YumiNail-Gateway`: `rtk mvn -q -DskipTests compile` 通过。 +- `YumiNail-Frontend`: `rtk npm run build` 通过。 +- `WeChatProgram`: 全量 `node --check` 通过。 +- `rtk git diff --check` 通过。 + +## 剩余风险 +- SQL 尚未在真实 MySQL 数据库执行,需要在 MySQL MCP 可用或安装 MySQL CLI 后执行 `YumiNail.sql` 并回查新表、权限和验收数据。 +- 未连接 WeChat DevTools MCP 做真机页面流转验证;已完成 JS 语法级检查。 +- Web UI 已构建通过,但本轮未启动浏览器做视觉截图验收。 diff --git a/docs/changes/2026-05-16-system-message-and-mysql-mcp-followup.md b/docs/changes/2026-05-16-system-message-and-mysql-mcp-followup.md new file mode 100644 index 00000000..f5aafb4a --- /dev/null +++ b/docs/changes/2026-05-16-system-message-and-mysql-mcp-followup.md @@ -0,0 +1,49 @@ +# 2026-05-16 System Message And MySQL MCP Follow-up + +## Scope + +- Added system message publishing for admins and store managers. +- Added Web admin message publishing, Web user notifications, and WeChat mini program notifications. +- Kept SQL consolidated in `YumiNail-Core/src/main/resources/files/YumiNail.sql`; no extra SQL files were added. +- Added acceptance seed messages and message user state rows. + +## MySQL MCP Status + +- Nacos `YumiNail-Dev / DEFAULT_GROUP / datasource.yaml` was read successfully. +- Datasource target used for verification: `192.168.5.15:3306/nailart`, user `root`; password was read from Nacos and was not printed. +- `C:\Users\21616\.codex\config.toml` was updated so both `mcp_servers.mysql` and `mcp_servers.toolbox-mysql` point to the Nacos datasource; MySQL MCP write flags were enabled for this test. +- The active Codex session still did not hot-load MySQL MCP tools after config update, so SQL execution used a temporary Node `mysql2` runner as the configured-connection fallback. +- `YumiNail.sql` was executed against `nailart` on 2026-05-16. The runner completed with 143 executed statements and 80 ignored already-existing/repeat-seed statements. + +## Database Verification + +- Message tables present: `t_system_message`, `t_system_message_user_state`. +- Message permissions present: `message:view`, `message:create`, `message:delete`. +- Acceptance messages present: 3. +- Participating production records present: 2. +- SQL directory check: only `YumiNail.sql` remains. + +## Verification + +- `rtk mvn -q -DskipTests compile` in `YumiNail-Core`: passed. +- `rtk npm run build` in `YumiNail-Frontend`: passed, with the existing Vite large chunk warning. +- Full WeChat mini program JavaScript syntax check with `node --check`: passed. +- `rtk git diff --check`: passed. +- SQL execution fallback: passed against Nacos datasource database. + +## Acceptance Data Added + +- `t_system_message` + - `Acceptance Platform Notice` + - `Acceptance Shop Notice` + - `Acceptance Selected User Notice` +- `t_system_message_user_state` + - Covers read, unread, popup shown, and popup pending states. + +## Remaining Manual Checks + +- Verify admin can publish platform, shop, and selected-user messages. +- Verify store manager can publish only current-shop and selected current-shop-user messages. +- Verify user popup messages appear once, then remain visible in the notification list. +- Verify dynamic shop targeting by binding a user to a target shop after message creation and confirming the message becomes visible. +- Restart Codex or open a new session to expose the reconfigured MySQL MCP tools directly. diff --git a/docs/changes/2026-05-16-店长参与制作与VIP中心测试报告.md b/docs/changes/2026-05-16-店长参与制作与VIP中心测试报告.md new file mode 100644 index 00000000..c8cc104d --- /dev/null +++ b/docs/changes/2026-05-16-店长参与制作与VIP中心测试报告.md @@ -0,0 +1,49 @@ +# 店长参与制作与 VIP 中心测试报告 + +## 变更范围 + +- 后端支持 `type=2` 店长通过 `participate_production` 开关进入可预约服务人员体系。 +- Web 后台美甲师管理展示人员类型、参与制作状态、工作时间,并支持编辑保存。 +- Web 用户端新增 `/vip-center`,展示 VIP、余额和余额变动记录。 +- 小程序新增 `pages/vip-center/index`,个人中心增加 VIP 中心入口,购物车选择服务人员时展示“店长 · 参与制作”。 +- SQL 已收口到 `YumiNail-Core/src/main/resources/files/YumiNail.sql`,同目录其他 `.sql` 文件已删除。 + +## 自动验证结果 + +- `YumiNail-Core`: `rtk mvn -q -DskipTests compile` 通过。 +- `YumiNail-Gateway`: `rtk mvn -q -DskipTests compile` 通过。 +- `YumiNail-Frontend`: `rtk npm run build` 通过,仅存在 Vite 大 chunk 提示。 +- `WeChatProgram`: 全量 `node --check` 通过。 +- `git diff --check` 通过。 + +## SQL 与测试数据 + +- 当前会话未暴露 MySQL MCP;本机也未发现可用 `mysql` 命令,因此没有直接执行数据库 DDL/DML。 +- 已在 `YumiNail.sql` 中集中加入: + - `t_nail_artist_info.participate_production` + - `t_nail_artist_info.work_start_time` + - `t_nail_artist_info.work_end_time` + - 参与制作状态索引 + - 店长默认服务资料初始化与美甲师默认参与制作修复 SQL +- 小型全覆盖测试数据已写入初始化 SQL,包含: + - 店铺:`Acceptance Main Shop`、`Acceptance Branch Shop` + - 用户:`accept_user_normal`、`accept_user_bronze`、`accept_user_silver`、`accept_user_gold` + - 店长:`accept_manager_main`(不参与制作)、`accept_manager_artist`(参与制作)、`accept_manager_branch`(分店参与制作) + - 美甲师:`accept_artist_main`、`accept_artist_branch` + - 商品:`Acceptance Gel Manicure`、`Acceptance Manager Exclusive Design`、`Acceptance Branch Care` + - 余额与流水:普通、Bronze、Silver、Gold 用户均有余额、累计充值和充值/消费流水 + - 预约样例:`ACCEPTANCE-ORDER-001` 指向参与制作店长 +- 真实库执行仍需在有 MySQL MCP 或 MySQL 客户端连接后完成。 + +## 人工抽检建议 + +- 后台:使用管理员进入美甲师管理,确认普通美甲师和已开启参与制作的店长均出现,并能保存工作时间。 +- 后台:商品管理选择可预约人员,确认参与制作店长可被选中。 +- 用户端 Web:进入个人中心 -> VIP 中心,确认等级、余额、累计充值和流水展示。 +- 小程序:进入我的 -> VIP 中心;进入购物车选择服务人员,确认店长显示“店长 · 参与制作”。 +- 下单:同一商品分别选择普通美甲师、参与制作店长验证可下单;关闭店长参与制作后应不可再作为可约人员。 + +## 剩余风险 + +- 当前未能直接执行 MySQL 变更,真实环境首次运行前必须先执行 `YumiNail.sql` 或对应字段补齐 SQL。 +- 小程序 DevTools MCP 未在本轮连接验证,已完成静态语法检查,交互流程仍需在微信开发者工具中人工抽检。 diff --git a/docs/changes/2026-05-17-newcomer-call-guide.md b/docs/changes/2026-05-17-newcomer-call-guide.md new file mode 100644 index 00000000..83f52074 --- /dev/null +++ b/docs/changes/2026-05-17-newcomer-call-guide.md @@ -0,0 +1,73 @@ +# 新人调用说明 + +这份文档只记录最近新增功能的调用入口,方便新同学先跑通流程,再回头看实现细节。 + +## 预约日历 + +- Web API 文件:`YumiNail-Frontend/src/api/order.ts` +- 后端入口:`YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/OrderController.java` + +常用接口: + +```http +GET /order/artist/calendar/recent?days=7 +GET /order/artist/calendar/day?date=2026-05-17 +PUT /order/artist/complete/{orderId} +``` + +说明: + +- 登录人必须是美甲师,或开启了“参与制作”的店长。 +- 后端已经按当前登录人过滤预约,前端不要再自己拼 artistId。 +- `date` 统一传 `yyyy-MM-dd`。 + +## 公告与消息 + +公告用于首页顶部滚动展示,不进入消息通知历史: + +```http +GET /announcement/my/list +POST /announcement/admin/create +GET /announcement/admin/target-options +``` + +消息用于消息通知列表和一次性弹窗: + +```http +GET /system-message/my/list +GET /system-message/my/popup +PUT /system-message/my/{id}/popup-shown +PUT /system-message/my/{id}/read +``` + +说明: + +- 弹窗展示后必须调用 `popup-shown`,否则刷新页面还会继续弹。 +- 已弹窗和已读是两件事,点击详情或进入消息详情时再标记已读。 + +## VIP 充值档位 + +```http +GET /vip-recharge-plan/my/list +``` + +说明: + +- 当前只是展示店长配置的充值档位。 +- 不创建充值订单,不调用支付,不改余额流水。 + +## 用户归属与邀请码 + +```http +GET /user/relation/me +GET /user/invite-code/resolve?code=INVITE001 +GET /admin/shop-role/invite-code/list +POST /admin/shop-role/invite-code/create +``` + +说明: + +- 注册页可先调用 `resolve` 展示邀请码对应的所属人和店铺。 +- 不填邀请码时,默认归属到当前店铺店长。 +- 后台用户列表默认使用脱敏字段,例如 `maskedPhone`、`maskedEmail`。 +