From a3df262fae31b30c988b4aa738991bf39ad7e9e6 Mon Sep 17 00:00:00 2001 From: xiaowang Date: Mon, 20 Apr 2026 16:02:57 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8A=9F=E8=83=BD=EF=BC=9A=E6=94=B6=E5=8F=A3?= =?UTF-8?q?=E5=B0=8F=E7=A8=8B=E5=BA=8F=E5=89=8D=E5=90=8E=E5=8F=B0=E5=AE=89?= =?UTF-8?q?=E5=85=A8=E4=B8=8E=E9=98=B2=E9=87=8D=E5=A4=8D=E6=8F=90=E4=BA=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- WeChatProgram/api/product.js | 7 + WeChatProgram/api/user.js | 85 +++ WeChatProgram/app.js | 47 ++ .../components/product-card/product-card.js | 12 + .../components/product-card/product-card.wxml | 16 +- .../components/product-card/product-card.wxss | 156 ++++- WeChatProgram/pages/auth/index.js | 15 +- WeChatProgram/pages/auth/index.wxml | 18 +- WeChatProgram/pages/cart/index.wxml | 16 +- WeChatProgram/pages/coupons/index.js | 43 +- WeChatProgram/pages/coupons/index.wxml | 45 +- WeChatProgram/pages/coupons/index.wxss | 26 + WeChatProgram/pages/home/index.js | 156 +++-- WeChatProgram/pages/home/index.wxml | 27 +- WeChatProgram/pages/home/index.wxss | 11 + WeChatProgram/pages/index/index.wxml | 2 +- WeChatProgram/pages/orders/index.js | 50 +- WeChatProgram/pages/orders/index.wxml | 8 +- WeChatProgram/pages/product-detail/index.js | 95 ++- WeChatProgram/pages/product-detail/index.wxml | 10 +- WeChatProgram/pages/products/index.js | 322 +++++++-- WeChatProgram/pages/products/index.wxml | 43 +- WeChatProgram/pages/products/index.wxss | 125 ++-- WeChatProgram/pages/profile/index.js | 141 ++-- WeChatProgram/pages/profile/index.wxml | 14 +- WeChatProgram/pages/settings/index.js | 632 +++++++++++++++++- WeChatProgram/pages/settings/index.wxml | 149 ++++- WeChatProgram/pages/settings/index.wxss | 120 +++- WeChatProgram/pages/shop-detail/index.wxml | 3 +- WeChatProgram/pages/wishlist/index.js | 119 +++- WeChatProgram/pages/wishlist/index.wxml | 18 +- WeChatProgram/pages/wishlist/index.wxss | 13 +- WeChatProgram/utils/action-guard.js | 78 +++ WeChatProgram/utils/auth.js | 70 +- WeChatProgram/utils/cache.js | 108 +++ WeChatProgram/utils/config.js | 66 +- WeChatProgram/utils/config.local.example.js | 12 + WeChatProgram/utils/crypto.js | 177 +++++ WeChatProgram/utils/device.js | 20 + WeChatProgram/utils/file.js | 37 +- WeChatProgram/utils/form-draft.js | 73 ++ WeChatProgram/utils/idle-session.js | 165 +++++ WeChatProgram/utils/product.js | 4 +- WeChatProgram/utils/request.js | 189 +++++- WeChatProgram/utils/storage.js | 3 +- YumiNail-Admin-Program/README.md | 91 +++ YumiNail-Admin-Program/api/auth.js | 44 ++ YumiNail-Admin-Program/api/coupon.js | 64 ++ YumiNail-Admin-Program/api/dashboard.js | 9 + YumiNail-Admin-Program/api/file.js | 116 ++++ YumiNail-Admin-Program/api/nail-artist.js | 23 + YumiNail-Admin-Program/api/order.js | 21 + YumiNail-Admin-Program/api/permission.js | 60 ++ YumiNail-Admin-Program/api/product.js | 39 ++ YumiNail-Admin-Program/api/shop.js | 55 ++ YumiNail-Admin-Program/api/tag.js | 44 ++ YumiNail-Admin-Program/api/user.js | 112 ++++ YumiNail-Admin-Program/app.js | 140 ++++ YumiNail-Admin-Program/app.json | 68 ++ YumiNail-Admin-Program/app.wxss | 481 +++++++++++++ .../assets/tabbar/manage-active.png | Bin 0 -> 688 bytes .../assets/tabbar/manage.png | Bin 0 -> 585 bytes .../assets/tabbar/orders-active.png | Bin 0 -> 979 bytes .../assets/tabbar/orders.png | Bin 0 -> 950 bytes .../assets/tabbar/profile-active.png | Bin 0 -> 890 bytes .../assets/tabbar/profile.png | Bin 0 -> 871 bytes .../assets/tabbar/workbench-active.png | Bin 0 -> 780 bytes .../assets/tabbar/workbench.png | Bin 0 -> 793 bytes .../navigation-bar/navigation-bar.js | 110 +++ .../navigation-bar/navigation-bar.json | 5 + .../navigation-bar/navigation-bar.wxml | 64 ++ .../navigation-bar/navigation-bar.wxss | 99 +++ .../pages/artist-form/index.js | 328 +++++++++ .../pages/artist-form/index.json | 5 + .../pages/artist-form/index.wxml | 82 +++ .../pages/artist-form/index.wxss | 4 + YumiNail-Admin-Program/pages/artists/index.js | 55 ++ .../pages/artists/index.json | 5 + .../pages/artists/index.wxml | 42 ++ .../pages/artists/index.wxss | 3 + .../pages/coupon-distribute/index.js | 87 +++ .../pages/coupon-distribute/index.json | 5 + .../pages/coupon-distribute/index.wxml | 28 + .../pages/coupon-distribute/index.wxss | 4 + .../pages/coupon-form/index.js | 291 ++++++++ .../pages/coupon-form/index.json | 5 + .../pages/coupon-form/index.wxml | 111 +++ .../pages/coupon-form/index.wxss | 4 + YumiNail-Admin-Program/pages/coupons/index.js | 95 +++ .../pages/coupons/index.json | 5 + .../pages/coupons/index.wxml | 44 ++ .../pages/coupons/index.wxss | 3 + YumiNail-Admin-Program/pages/login/index.js | 210 ++++++ YumiNail-Admin-Program/pages/login/index.json | 5 + YumiNail-Admin-Program/pages/login/index.wxml | 45 ++ YumiNail-Admin-Program/pages/login/index.wxss | 3 + YumiNail-Admin-Program/pages/manage/index.js | 44 ++ .../pages/manage/index.json | 5 + .../pages/manage/index.wxml | 26 + .../pages/manage/index.wxss | 3 + .../pages/order-detail/index.js | 28 + .../pages/order-detail/index.json | 5 + .../pages/order-detail/index.wxml | 41 ++ .../pages/order-detail/index.wxss | 3 + YumiNail-Admin-Program/pages/orders/index.js | 162 +++++ .../pages/orders/index.json | 6 + .../pages/orders/index.wxml | 63 ++ .../pages/orders/index.wxss | 3 + .../pages/permission-form/index.js | 165 +++++ .../pages/permission-form/index.json | 5 + .../pages/permission-form/index.wxml | 51 ++ .../pages/permission-form/index.wxss | 4 + .../pages/permissions/index.js | 85 +++ .../pages/permissions/index.json | 5 + .../pages/permissions/index.wxml | 50 ++ .../pages/permissions/index.wxss | 3 + .../pages/product-form/index.js | 349 ++++++++++ .../pages/product-form/index.json | 5 + .../pages/product-form/index.wxml | 92 +++ .../pages/product-form/index.wxss | 4 + .../pages/products/index.js | 128 ++++ .../pages/products/index.json | 5 + .../pages/products/index.wxml | 50 ++ .../pages/products/index.wxss | 3 + YumiNail-Admin-Program/pages/profile/index.js | 118 ++++ .../pages/profile/index.json | 5 + .../pages/profile/index.wxml | 52 ++ .../pages/profile/index.wxss | 3 + .../pages/shop-form/index.js | 183 +++++ .../pages/shop-form/index.json | 5 + .../pages/shop-form/index.wxml | 55 ++ .../pages/shop-form/index.wxss | 3 + YumiNail-Admin-Program/pages/shops/index.js | 141 ++++ YumiNail-Admin-Program/pages/shops/index.json | 5 + YumiNail-Admin-Program/pages/shops/index.wxml | 51 ++ YumiNail-Admin-Program/pages/shops/index.wxss | 3 + .../pages/tag-form/index.js | 139 ++++ .../pages/tag-form/index.json | 5 + .../pages/tag-form/index.wxml | 34 + .../pages/tag-form/index.wxss | 3 + YumiNail-Admin-Program/pages/tags/index.js | 75 +++ YumiNail-Admin-Program/pages/tags/index.json | 5 + YumiNail-Admin-Program/pages/tags/index.wxml | 38 ++ YumiNail-Admin-Program/pages/tags/index.wxss | 3 + .../pages/user-detail/index.js | 284 ++++++++ .../pages/user-detail/index.json | 5 + .../pages/user-detail/index.wxml | 128 ++++ .../pages/user-detail/index.wxss | 3 + .../pages/user-form/index.js | 256 +++++++ .../pages/user-form/index.json | 5 + .../pages/user-form/index.wxml | 51 ++ .../pages/user-form/index.wxss | 4 + YumiNail-Admin-Program/pages/users/index.js | 119 ++++ YumiNail-Admin-Program/pages/users/index.json | 5 + YumiNail-Admin-Program/pages/users/index.wxml | 63 ++ YumiNail-Admin-Program/pages/users/index.wxss | 3 + .../pages/workbench/index.js | 168 +++++ .../pages/workbench/index.json | 5 + .../pages/workbench/index.wxml | 73 ++ .../pages/workbench/index.wxss | 3 + YumiNail-Admin-Program/project.config.json | 41 ++ .../project.private.config.json | 22 + YumiNail-Admin-Program/sitemap.json | 3 + YumiNail-Admin-Program/utils/action-guard.js | 78 +++ YumiNail-Admin-Program/utils/auth.js | 99 +++ YumiNail-Admin-Program/utils/cache.js | 83 +++ YumiNail-Admin-Program/utils/config.js | 107 +++ .../utils/config.local.example.js | 12 + YumiNail-Admin-Program/utils/crypto.js | 177 +++++ YumiNail-Admin-Program/utils/device.js | 20 + YumiNail-Admin-Program/utils/form-draft.js | 68 ++ YumiNail-Admin-Program/utils/format.js | 148 ++++ YumiNail-Admin-Program/utils/idle-session.js | 165 +++++ YumiNail-Admin-Program/utils/loading.js | 51 ++ YumiNail-Admin-Program/utils/navigation.js | 146 ++++ YumiNail-Admin-Program/utils/page-state.js | 28 + YumiNail-Admin-Program/utils/permission.js | 189 ++++++ YumiNail-Admin-Program/utils/request.js | 401 +++++++++++ YumiNail-Admin-Program/utils/storage.js | 49 ++ YumiNail-Admin-Program/utils/upload.js | 198 ++++++ YumiNail-Core/pom.xml | 6 + .../annotation/OperationGuard.java | 21 + .../aspect/OperationGuardAspect.java | 54 ++ .../yuminailcore/aspect/PermissionAspect.java | 3 + .../config/AppCacheProperties.java | 40 ++ .../yuminailcore/config/AuthInterceptor.java | 52 +- .../yuminailcore/config/JwtProperties.java | 39 ++ .../config/RateLimitProperties.java | 38 ++ .../config/RequestSignatureProperties.java | 29 + .../controller/AdminAuthController.java | 16 +- .../controller/AdminCouponController.java | 6 + .../controller/AdminNailArtistController.java | 2 + .../controller/AdminOrderController.java | 2 + .../controller/AdminPermissionController.java | 5 + .../controller/AdminProductController.java | 4 + .../controller/AdminShopController.java | 5 + .../controller/AdminTagController.java | 4 + .../controller/AdminUserController.java | 10 + .../controller/CartController.java | 9 +- .../controller/CouponController.java | 14 +- .../controller/FrontendFileController.java | 36 +- .../ObjectStorageFileController.java | 121 ++-- .../controller/OrderController.java | 5 + .../controller/PermissionController.java | 8 +- .../controller/ProductController.java | 17 +- .../controller/ProductLikeController.java | 4 + .../controller/ShopController.java | 2 +- .../controller/TagController.java | 8 +- .../controller/UserController.java | 62 +- .../controller/WishlistController.java | 4 + .../filter/RequestBodyCacheFilter.java | 56 ++ .../yuminailcore/service/ProductService.java | 10 + .../yuminailcore/service/UserService.java | 6 +- .../service/impl/CartServiceImpl.java | 6 +- .../service/impl/OrderServiceImpl.java | 6 +- .../service/impl/ProductServiceImpl.java | 278 +++++++- .../service/impl/ShopServiceImpl.java | 76 ++- .../service/impl/TagServiceImpl.java | 93 ++- .../service/impl/UserServiceImpl.java | 98 ++- .../support/ObjectStorageUrlSupport.java | 127 ++++ .../support/cache/MultiLevelCacheService.java | 165 +++++ .../CachedBodyHttpServletRequest.java | 59 ++ .../security/OperationGuardService.java | 296 ++++++++ .../security/OperationGuardStrategy.java | 6 + .../security/RequestSignatureService.java | 162 +++++ .../security/RequestThrottleService.java | 96 +++ .../support/security/UserSessionService.java | 146 ++++ .../xiaowang/yuminailcore/utils/JwtUtil.java | 47 +- .../src/main/resources/application.yaml | 45 ++ YumiNail-Core/src/main/resources/log4j2.xml | 1 + YumiNail-Gateway/pom.xml | 18 + .../yumitailgateway/config/JwtProperties.java | 20 + .../filter/AuthGlobalFilter.java | 14 +- .../filter/GatewayJwtValidator.java | 40 ++ .../src/main/resources/application.yaml | 4 + .../src/main/resources/log4j2.xml | 1 + ...26-04-20-小程序前后台防呆与重复提交收口.md | 55 ++ 237 files changed, 14068 insertions(+), 728 deletions(-) create mode 100644 WeChatProgram/utils/action-guard.js create mode 100644 WeChatProgram/utils/cache.js create mode 100644 WeChatProgram/utils/config.local.example.js create mode 100644 WeChatProgram/utils/crypto.js create mode 100644 WeChatProgram/utils/device.js create mode 100644 WeChatProgram/utils/form-draft.js create mode 100644 WeChatProgram/utils/idle-session.js create mode 100644 YumiNail-Admin-Program/README.md create mode 100644 YumiNail-Admin-Program/api/auth.js create mode 100644 YumiNail-Admin-Program/api/coupon.js create mode 100644 YumiNail-Admin-Program/api/dashboard.js create mode 100644 YumiNail-Admin-Program/api/file.js create mode 100644 YumiNail-Admin-Program/api/nail-artist.js create mode 100644 YumiNail-Admin-Program/api/order.js create mode 100644 YumiNail-Admin-Program/api/permission.js create mode 100644 YumiNail-Admin-Program/api/product.js create mode 100644 YumiNail-Admin-Program/api/shop.js create mode 100644 YumiNail-Admin-Program/api/tag.js create mode 100644 YumiNail-Admin-Program/api/user.js create mode 100644 YumiNail-Admin-Program/app.js create mode 100644 YumiNail-Admin-Program/app.json create mode 100644 YumiNail-Admin-Program/app.wxss create mode 100644 YumiNail-Admin-Program/assets/tabbar/manage-active.png create mode 100644 YumiNail-Admin-Program/assets/tabbar/manage.png create mode 100644 YumiNail-Admin-Program/assets/tabbar/orders-active.png create mode 100644 YumiNail-Admin-Program/assets/tabbar/orders.png create mode 100644 YumiNail-Admin-Program/assets/tabbar/profile-active.png create mode 100644 YumiNail-Admin-Program/assets/tabbar/profile.png create mode 100644 YumiNail-Admin-Program/assets/tabbar/workbench-active.png create mode 100644 YumiNail-Admin-Program/assets/tabbar/workbench.png create mode 100644 YumiNail-Admin-Program/components/navigation-bar/navigation-bar.js create mode 100644 YumiNail-Admin-Program/components/navigation-bar/navigation-bar.json create mode 100644 YumiNail-Admin-Program/components/navigation-bar/navigation-bar.wxml create mode 100644 YumiNail-Admin-Program/components/navigation-bar/navigation-bar.wxss create mode 100644 YumiNail-Admin-Program/pages/artist-form/index.js create mode 100644 YumiNail-Admin-Program/pages/artist-form/index.json create mode 100644 YumiNail-Admin-Program/pages/artist-form/index.wxml create mode 100644 YumiNail-Admin-Program/pages/artist-form/index.wxss create mode 100644 YumiNail-Admin-Program/pages/artists/index.js create mode 100644 YumiNail-Admin-Program/pages/artists/index.json create mode 100644 YumiNail-Admin-Program/pages/artists/index.wxml create mode 100644 YumiNail-Admin-Program/pages/artists/index.wxss create mode 100644 YumiNail-Admin-Program/pages/coupon-distribute/index.js create mode 100644 YumiNail-Admin-Program/pages/coupon-distribute/index.json create mode 100644 YumiNail-Admin-Program/pages/coupon-distribute/index.wxml create mode 100644 YumiNail-Admin-Program/pages/coupon-distribute/index.wxss create mode 100644 YumiNail-Admin-Program/pages/coupon-form/index.js create mode 100644 YumiNail-Admin-Program/pages/coupon-form/index.json create mode 100644 YumiNail-Admin-Program/pages/coupon-form/index.wxml create mode 100644 YumiNail-Admin-Program/pages/coupon-form/index.wxss create mode 100644 YumiNail-Admin-Program/pages/coupons/index.js create mode 100644 YumiNail-Admin-Program/pages/coupons/index.json create mode 100644 YumiNail-Admin-Program/pages/coupons/index.wxml create mode 100644 YumiNail-Admin-Program/pages/coupons/index.wxss create mode 100644 YumiNail-Admin-Program/pages/login/index.js create mode 100644 YumiNail-Admin-Program/pages/login/index.json create mode 100644 YumiNail-Admin-Program/pages/login/index.wxml create mode 100644 YumiNail-Admin-Program/pages/login/index.wxss create mode 100644 YumiNail-Admin-Program/pages/manage/index.js create mode 100644 YumiNail-Admin-Program/pages/manage/index.json create mode 100644 YumiNail-Admin-Program/pages/manage/index.wxml create mode 100644 YumiNail-Admin-Program/pages/manage/index.wxss create mode 100644 YumiNail-Admin-Program/pages/order-detail/index.js create mode 100644 YumiNail-Admin-Program/pages/order-detail/index.json create mode 100644 YumiNail-Admin-Program/pages/order-detail/index.wxml create mode 100644 YumiNail-Admin-Program/pages/order-detail/index.wxss create mode 100644 YumiNail-Admin-Program/pages/orders/index.js create mode 100644 YumiNail-Admin-Program/pages/orders/index.json create mode 100644 YumiNail-Admin-Program/pages/orders/index.wxml create mode 100644 YumiNail-Admin-Program/pages/orders/index.wxss create mode 100644 YumiNail-Admin-Program/pages/permission-form/index.js create mode 100644 YumiNail-Admin-Program/pages/permission-form/index.json create mode 100644 YumiNail-Admin-Program/pages/permission-form/index.wxml create mode 100644 YumiNail-Admin-Program/pages/permission-form/index.wxss create mode 100644 YumiNail-Admin-Program/pages/permissions/index.js create mode 100644 YumiNail-Admin-Program/pages/permissions/index.json create mode 100644 YumiNail-Admin-Program/pages/permissions/index.wxml create mode 100644 YumiNail-Admin-Program/pages/permissions/index.wxss create mode 100644 YumiNail-Admin-Program/pages/product-form/index.js create mode 100644 YumiNail-Admin-Program/pages/product-form/index.json create mode 100644 YumiNail-Admin-Program/pages/product-form/index.wxml create mode 100644 YumiNail-Admin-Program/pages/product-form/index.wxss create mode 100644 YumiNail-Admin-Program/pages/products/index.js create mode 100644 YumiNail-Admin-Program/pages/products/index.json create mode 100644 YumiNail-Admin-Program/pages/products/index.wxml create mode 100644 YumiNail-Admin-Program/pages/products/index.wxss create mode 100644 YumiNail-Admin-Program/pages/profile/index.js create mode 100644 YumiNail-Admin-Program/pages/profile/index.json create mode 100644 YumiNail-Admin-Program/pages/profile/index.wxml create mode 100644 YumiNail-Admin-Program/pages/profile/index.wxss create mode 100644 YumiNail-Admin-Program/pages/shop-form/index.js create mode 100644 YumiNail-Admin-Program/pages/shop-form/index.json create mode 100644 YumiNail-Admin-Program/pages/shop-form/index.wxml create mode 100644 YumiNail-Admin-Program/pages/shop-form/index.wxss create mode 100644 YumiNail-Admin-Program/pages/shops/index.js create mode 100644 YumiNail-Admin-Program/pages/shops/index.json create mode 100644 YumiNail-Admin-Program/pages/shops/index.wxml create mode 100644 YumiNail-Admin-Program/pages/shops/index.wxss create mode 100644 YumiNail-Admin-Program/pages/tag-form/index.js create mode 100644 YumiNail-Admin-Program/pages/tag-form/index.json create mode 100644 YumiNail-Admin-Program/pages/tag-form/index.wxml create mode 100644 YumiNail-Admin-Program/pages/tag-form/index.wxss create mode 100644 YumiNail-Admin-Program/pages/tags/index.js create mode 100644 YumiNail-Admin-Program/pages/tags/index.json create mode 100644 YumiNail-Admin-Program/pages/tags/index.wxml create mode 100644 YumiNail-Admin-Program/pages/tags/index.wxss create mode 100644 YumiNail-Admin-Program/pages/user-detail/index.js create mode 100644 YumiNail-Admin-Program/pages/user-detail/index.json create mode 100644 YumiNail-Admin-Program/pages/user-detail/index.wxml create mode 100644 YumiNail-Admin-Program/pages/user-detail/index.wxss create mode 100644 YumiNail-Admin-Program/pages/user-form/index.js create mode 100644 YumiNail-Admin-Program/pages/user-form/index.json create mode 100644 YumiNail-Admin-Program/pages/user-form/index.wxml create mode 100644 YumiNail-Admin-Program/pages/user-form/index.wxss create mode 100644 YumiNail-Admin-Program/pages/users/index.js create mode 100644 YumiNail-Admin-Program/pages/users/index.json create mode 100644 YumiNail-Admin-Program/pages/users/index.wxml create mode 100644 YumiNail-Admin-Program/pages/users/index.wxss create mode 100644 YumiNail-Admin-Program/pages/workbench/index.js create mode 100644 YumiNail-Admin-Program/pages/workbench/index.json create mode 100644 YumiNail-Admin-Program/pages/workbench/index.wxml create mode 100644 YumiNail-Admin-Program/pages/workbench/index.wxss create mode 100644 YumiNail-Admin-Program/project.config.json create mode 100644 YumiNail-Admin-Program/project.private.config.json create mode 100644 YumiNail-Admin-Program/sitemap.json create mode 100644 YumiNail-Admin-Program/utils/action-guard.js create mode 100644 YumiNail-Admin-Program/utils/auth.js create mode 100644 YumiNail-Admin-Program/utils/cache.js create mode 100644 YumiNail-Admin-Program/utils/config.js create mode 100644 YumiNail-Admin-Program/utils/config.local.example.js create mode 100644 YumiNail-Admin-Program/utils/crypto.js create mode 100644 YumiNail-Admin-Program/utils/device.js create mode 100644 YumiNail-Admin-Program/utils/form-draft.js create mode 100644 YumiNail-Admin-Program/utils/format.js create mode 100644 YumiNail-Admin-Program/utils/idle-session.js create mode 100644 YumiNail-Admin-Program/utils/loading.js create mode 100644 YumiNail-Admin-Program/utils/navigation.js create mode 100644 YumiNail-Admin-Program/utils/page-state.js create mode 100644 YumiNail-Admin-Program/utils/permission.js create mode 100644 YumiNail-Admin-Program/utils/request.js create mode 100644 YumiNail-Admin-Program/utils/storage.js create mode 100644 YumiNail-Admin-Program/utils/upload.js create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/annotation/OperationGuard.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/aspect/OperationGuardAspect.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/AppCacheProperties.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/JwtProperties.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/RateLimitProperties.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/RequestSignatureProperties.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/filter/RequestBodyCacheFilter.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/ObjectStorageUrlSupport.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/cache/MultiLevelCacheService.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/security/CachedBodyHttpServletRequest.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/security/OperationGuardService.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/security/OperationGuardStrategy.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/security/RequestSignatureService.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/security/RequestThrottleService.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/security/UserSessionService.java create mode 100644 YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/config/JwtProperties.java create mode 100644 YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/filter/GatewayJwtValidator.java create mode 100644 docs/changes/2026-04-20-小程序前后台防呆与重复提交收口.md diff --git a/WeChatProgram/api/product.js b/WeChatProgram/api/product.js index 4ff93a73..d80eb67a 100644 --- a/WeChatProgram/api/product.js +++ b/WeChatProgram/api/product.js @@ -1,6 +1,13 @@ const request = require('../utils/request') module.exports = { + getProductPage(params) { + return request({ + url: '/product/list/page', + params + }) + }, + getAllProducts() { return request({ url: '/product/list/all' diff --git a/WeChatProgram/api/user.js b/WeChatProgram/api/user.js index c0eac509..72ad07cd 100644 --- a/WeChatProgram/api/user.js +++ b/WeChatProgram/api/user.js @@ -1,4 +1,36 @@ const request = require('../utils/request') +const actionGuard = require('../utils/action-guard') +const { API_BASE_URL, REQUEST_TIMEOUT } = require('../utils/config') + +function normalizeUploadResponse(response) { + if (!response) { + throw new Error('头像上传失败') + } + + if (response.statusCode === 401) { + throw new Error('登录已过期,请重新登录') + } + + if (response.statusCode >= 400) { + throw new Error('头像上传失败') + } + + let payload = response.data + if (typeof payload === 'string') { + try { + payload = JSON.parse(payload) + } catch (error) {} + } + + if (payload && typeof payload === 'object' && Object.prototype.hasOwnProperty.call(payload, 'code')) { + if (payload.code === 200) { + return payload.data + } + throw new Error(payload.message || '头像上传失败') + } + + return payload +} module.exports = { getUserInfo() { @@ -23,6 +55,59 @@ module.exports = { }) }, + bindPhone(data) { + return request({ + url: '/user/bind-phone', + method: 'POST', + data + }) + }, + + updatePhone(data) { + return request({ + url: '/user/phone', + method: 'PUT', + data + }) + }, + + deactivateAccount() { + return request({ + url: '/user/deactivate', + method: 'DELETE' + }) + }, + + uploadAvatar(filePath) { + const signedHeaders = request.buildSignatureHeaders({ + url: '/user/upload-avatar', + method: 'POST', + formData: {} + }) + + return actionGuard.run(null, `POST:/user/upload-avatar:${filePath || ''}`, () => new Promise((resolve, reject) => { + wx.uploadFile({ + url: `${API_BASE_URL}/user/upload-avatar`, + filePath, + name: 'file', + timeout: REQUEST_TIMEOUT, + header: signedHeaders, + success: response => { + try { + resolve(normalizeUploadResponse(response)) + } catch (error) { + reject(error) + } + }, + fail: error => { + reject(new Error(error.errMsg || '头像上传失败')) + } + }) + }), { + message: '上传处理中,请勿重复操作' + }) + }, + checkAccountAvailability(account) { return request({ url: `/user/check/account/${encodeURIComponent(account)}` diff --git a/WeChatProgram/app.js b/WeChatProgram/app.js index f9213977..5b796396 100644 --- a/WeChatProgram/app.js +++ b/WeChatProgram/app.js @@ -1,6 +1,9 @@ const authApi = require('./api/auth') const cartApi = require('./api/cart') +const userApi = require('./api/user') const auth = require('./utils/auth') +const idleSession = require('./utils/idle-session') +const { IDLE_TIMEOUT_MS, IDLE_WARNING_MS } = require('./utils/config') App({ globalData: { @@ -13,12 +16,26 @@ App({ }, onLaunch() { + idleSession.init({ + timeoutMs: IDLE_TIMEOUT_MS, + warningMs: IDLE_WARNING_MS, + isLoggedIn: () => auth.isLoggedIn(), + onLogout: () => this.handleIdleLogout() + }) this.bootstrapSession() if (!auth.isLoggedIn()) { this.tryWechatMiniAutoLogin() } }, + onShow() { + idleSession.onAppShow() + }, + + onHide() { + idleSession.onAppHide() + }, + bootstrapSession() { const userInfo = auth.getStoredUserInfo() const isLoggedIn = auth.isLoggedIn() @@ -30,6 +47,7 @@ App({ } if (isLoggedIn) { + this.refreshSessionUserInfo() this.updateCartBadge() return } @@ -168,6 +186,35 @@ App({ this.clearCartBadge() }, + async refreshSessionUserInfo() { + if (!auth.isLoggedIn()) { + return + } + try { + const userInfo = await userApi.getUserInfo() + this.refreshUserInfo(userInfo) + } catch (error) {} + }, + + async handleIdleLogout() { + if (!auth.isLoggedIn()) { + return + } + try { + await authApi.logout() + } catch (error) {} + this.clearUserSession() + wx.showToast({ + title: '长时间未操作,已退出登录', + icon: 'none' + }) + setTimeout(() => { + wx.reLaunch({ + url: '/pages/auth/index' + }) + }, 260) + }, + async updateCartBadge() { if (!auth.isLoggedIn()) { this.clearCartBadge() diff --git a/WeChatProgram/components/product-card/product-card.js b/WeChatProgram/components/product-card/product-card.js index f3945dc6..c0b219e8 100644 --- a/WeChatProgram/components/product-card/product-card.js +++ b/WeChatProgram/components/product-card/product-card.js @@ -11,12 +11,24 @@ Component({ showStats: { type: Boolean, value: false + }, + showQuickAdd: { + type: Boolean, + value: false + }, + inCart: { + type: Boolean, + value: false } }, methods: { handleTap() { this.triggerEvent('select', this.properties.item) + }, + + handleQuickAdd() { + this.triggerEvent('quickadd', this.properties.item) } } }) diff --git a/WeChatProgram/components/product-card/product-card.wxml b/WeChatProgram/components/product-card/product-card.wxml index e61e7ffb..7013ef40 100644 --- a/WeChatProgram/components/product-card/product-card.wxml +++ b/WeChatProgram/components/product-card/product-card.wxml @@ -1,6 +1,6 @@ - + {{item.metaText}} @@ -15,7 +15,19 @@ {{item.priceText}} {{item.statsText}} - 查看 + + + + + + + + + + + + 购物车已有 + diff --git a/WeChatProgram/components/product-card/product-card.wxss b/WeChatProgram/components/product-card/product-card.wxss index c8430e7d..04208aa2 100644 --- a/WeChatProgram/components/product-card/product-card.wxss +++ b/WeChatProgram/components/product-card/product-card.wxss @@ -1,8 +1,9 @@ .product-card { display: flex; flex-direction: column; + min-width: 0; overflow: hidden; - border-radius: 30rpx; + border-radius: 28rpx; background: #ffffff; border: 1rpx solid rgba(239, 216, 224, 0.84); box-shadow: 0 18rpx 42rpx rgba(122, 67, 88, 0.08); @@ -14,7 +15,7 @@ .product-cover { width: 100%; - height: 300rpx; + height: 288rpx; background: #f7ecf0; } @@ -29,60 +30,72 @@ .product-meta-badge { position: absolute; - left: 18rpx; - top: 18rpx; - max-width: calc(100% - 36rpx); - padding: 10rpx 16rpx; + left: 16rpx; + top: 16rpx; + max-width: calc(100% - 32rpx); + padding: 8rpx 14rpx; border-radius: 999rpx; background: rgba(255, 255, 255, 0.92); color: #7a5262; - font-size: 20rpx; + font-size: 19rpx; font-weight: 700; } .product-body { display: flex; flex-direction: column; - gap: 12rpx; - padding: 22rpx 22rpx 24rpx; + gap: 10rpx; + min-height: 220rpx; + padding: 20rpx 20rpx 22rpx; } .product-title { - font-size: 28rpx; + min-height: 74rpx; + font-size: 27rpx; font-weight: 700; - line-height: 1.5; + line-height: 1.38; color: #2d2430; + word-break: break-all; + overflow: hidden; + text-overflow: ellipsis; + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; } .product-meta { - font-size: 24rpx; + font-size: 22rpx; color: #8d7a84; - line-height: 1.5; + line-height: 1.4; } .product-tags { display: flex; flex-wrap: wrap; - gap: 10rpx; + gap: 8rpx; } .tag-item { display: inline-flex; align-items: center; justify-content: center; - padding: 8rpx 16rpx; + max-width: 100%; + padding: 6rpx 14rpx; border-radius: 999rpx; background: #fbecf1; color: #c6597d; - font-size: 20rpx; + font-size: 18rpx; + line-height: 1; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; } .product-footer { display: flex; align-items: flex-end; - justify-content: space-between; - gap: 16rpx; - margin-top: 4rpx; + gap: 14rpx; + margin-top: auto; } .product-price-wrap { @@ -90,30 +103,115 @@ min-width: 0; } +.product-actions { + display: flex; + align-items: center; + flex-shrink: 0; +} + .product-price { display: block; - font-size: 30rpx; - font-weight: 700; + font-size: 34rpx; + line-height: 1.12; + font-weight: 800; color: #d5536f; } .product-stats { display: block; - margin-top: 8rpx; - font-size: 22rpx; + margin-top: 6rpx; + font-size: 20rpx; + line-height: 1.4; color: #9d8a92; } -.product-arrow { +.product-quick-add { display: inline-flex; align-items: center; justify-content: center; - min-width: 96rpx; - height: 52rpx; + width: 64rpx; + height: 64rpx; + border-radius: 22rpx; + background: linear-gradient(135deg, #ff8cb0 0%, #c6597d 100%); + box-shadow: 0 14rpx 30rpx rgba(198, 89, 125, 0.22); +} + +.product-quick-add-icon { + position: relative; + width: 32rpx; + height: 28rpx; +} + +.product-quick-add-handle { + position: absolute; + left: 2rpx; + top: 2rpx; + width: 12rpx; + height: 4rpx; + border-radius: 999rpx; + background: #ffffff; + transform: rotate(20deg); + transform-origin: left center; +} + +.product-quick-add-basket { + position: absolute; + left: 6rpx; + top: 8rpx; + width: 18rpx; + height: 11rpx; + border: 3rpx solid #ffffff; + border-top: 0; + border-radius: 0 0 6rpx 6rpx; +} + +.product-quick-add-wheel { + position: absolute; + top: 22rpx; + width: 6rpx; + height: 6rpx; + border-radius: 50%; + background: #ffffff; +} + +.product-quick-add-wheel--left { + left: 10rpx; +} + +.product-quick-add-wheel--right { + left: 22rpx; +} + +.product-quick-add-plus { + position: absolute; + border-radius: 999rpx; + background: #ffffff; +} + +.product-quick-add-plus--horizontal { + top: 2rpx; + right: 0; + width: 10rpx; + height: 3rpx; +} + +.product-quick-add-plus--vertical { + top: -1rpx; + right: 4rpx; + width: 3rpx; + height: 10rpx; +} + +.product-in-cart { + display: inline-flex; + align-items: center; + justify-content: center; + height: 56rpx; padding: 0 18rpx; border-radius: 999rpx; - background: #fff1f5; - color: #c6597d; - font-size: 22rpx; + background: #f8eef1; + color: #8f6e7a; + font-size: 20rpx; font-weight: 700; + white-space: nowrap; } diff --git a/WeChatProgram/pages/auth/index.js b/WeChatProgram/pages/auth/index.js index ed19c070..4315a8c1 100644 --- a/WeChatProgram/pages/auth/index.js +++ b/WeChatProgram/pages/auth/index.js @@ -2,6 +2,7 @@ const authApi = require('../../api/auth') const shopApi = require('../../api/shop') const userApi = require('../../api/user') const authStore = require('../../utils/auth') +const actionGuard = require('../../utils/action-guard') const navigation = require('../../utils/navigation') const { runWithLoading } = require('../../utils/loading') @@ -86,14 +87,14 @@ Page({ const systemInfo = wx.getSystemInfoSync() if (systemInfo && systemInfo.platform === 'devtools') { supported = false - disabledReason = '开发者工具暂不支持微信手机号一键登录,请使用真机调试或传统登录。' + disabledReason = '开发者工具暂不支持一键登录,请用真机或其他方式登录' } } catch (error) { supported = false } if (!supported && !disabledReason) { - disabledReason = '当前微信环境暂不支持手机号一键登录,请使用账号密码或验证码登录。' + disabledReason = '当前环境暂不支持一键登录,请使用其他方式登录' } this.setData({ @@ -385,7 +386,7 @@ Page({ } catch (error) { this.applyLoginShopSelection({ allowShoplessLogin: true, - message: '当前暂无法预加载可登录门店,可直接尝试登录。', + message: '暂时无法加载门店,可直接登录', shops: [] }) } @@ -398,7 +399,7 @@ Page({ } catch (error) { this.applyLoginShopSelection({ allowShoplessLogin: true, - message: '当前暂无法预加载可登录门店,可直接尝试登录。', + message: '暂时无法加载门店,可直接登录', shops: [] }) } @@ -907,11 +908,11 @@ Page({ buildAuthHelperText(activeTab, loginType) { if (activeTab === 'register') { - return '注册前会检查账号和手机号是否可用,并要求先选择门店。' + return '注册前请先选门店' } if (loginType === 'phone') { - return '验证码登录时,若手机号未注册,会先选择门店后自动注册。' + return '未注册手机号会先选门店' } - return '若账号绑定了多家门店,登录前需要先选择本次门店。' + return '多门店账号需先选门店' } }) diff --git a/WeChatProgram/pages/auth/index.wxml b/WeChatProgram/pages/auth/index.wxml index 368132e4..0ce20078 100644 --- a/WeChatProgram/pages/auth/index.wxml +++ b/WeChatProgram/pages/auth/index.wxml @@ -12,7 +12,7 @@ + + + + diff --git a/YumiNail-Admin-Program/pages/artist-form/index.wxss b/YumiNail-Admin-Program/pages/artist-form/index.wxss new file mode 100644 index 00000000..e7250734 --- /dev/null +++ b/YumiNail-Admin-Program/pages/artist-form/index.wxss @@ -0,0 +1,4 @@ +checkbox { + transform: scale(0.75); + margin-right: 8rpx; +} diff --git a/YumiNail-Admin-Program/pages/artists/index.js b/YumiNail-Admin-Program/pages/artists/index.js new file mode 100644 index 00000000..2d074a6a --- /dev/null +++ b/YumiNail-Admin-Program/pages/artists/index.js @@ -0,0 +1,55 @@ +const artistApi = require('../../api/nail-artist') +const navigation = require('../../utils/navigation') +const { setTempRecord, clearTempRecord } = require('../../utils/storage') + +Page({ + data: { + list: [], + canCreate: false + }, + + onShow() { + if (!navigation.ensureLogin('进入美甲师管理')) { + return + } + + const permissionCodes = getApp().globalData.permissionCodes || [] + this.setData({ + canCreate: permissionCodes.includes('user:create') || permissionCodes.includes('nail_artist:edit') + }) + this.loadArtists() + }, + + async loadArtists() { + try { + const list = await artistApi.listNailArtists() + this.setData({ + list: (Array.isArray(list) ? list : []).map(item => ({ + ...item, + displayStatusText: Number(item.status) === 0 ? '休息中' : '营业中' + })) + }) + } catch (error) { + wx.showToast({ + title: error.message || '美甲师列表加载失败', + icon: 'none' + }) + } + }, + + handleCreate() { + clearTempRecord('currentArtist') + navigation.navigate('/pages/artist-form/index', { + mode: 'create' + }).catch(() => undefined) + }, + + handleEdit(event) { + const artist = event.currentTarget.dataset.artist + setTempRecord('currentArtist', artist) + navigation.navigate('/pages/artist-form/index', { + mode: 'edit', + userId: artist.userId + }).catch(() => undefined) + } +}) diff --git a/YumiNail-Admin-Program/pages/artists/index.json b/YumiNail-Admin-Program/pages/artists/index.json new file mode 100644 index 00000000..8632c9b0 --- /dev/null +++ b/YumiNail-Admin-Program/pages/artists/index.json @@ -0,0 +1,5 @@ +{ + "usingComponents": { + "navigation-bar": "/components/navigation-bar/navigation-bar" + } +} diff --git a/YumiNail-Admin-Program/pages/artists/index.wxml b/YumiNail-Admin-Program/pages/artists/index.wxml new file mode 100644 index 00000000..304b40c6 --- /dev/null +++ b/YumiNail-Admin-Program/pages/artists/index.wxml @@ -0,0 +1,42 @@ + + + + + + 美甲师列表 + 店长只能看到并管理自己门店的美甲师;平台管理员可跨店查看,移动端表单集中处理账号和档案两部分信息。 + + + + + + + {{item.nickname}} + {{item.identity || '未设置身份'}} · {{item.shopName || '当前店铺'}} + + {{item.displayStatusText}} + + + + 从业年限 + {{item.experience || 0}} 年 + + + 评分 + {{item.rating || 0}} + + + + 编辑 + + + + + + 还没有美甲师 + 可以先新增一个美甲师账号,再补充技能、作品集和营业状态。 + + + + + + diff --git a/YumiNail-Admin-Program/pages/artists/index.wxss b/YumiNail-Admin-Program/pages/artists/index.wxss new file mode 100644 index 00000000..09b20ffe --- /dev/null +++ b/YumiNail-Admin-Program/pages/artists/index.wxss @@ -0,0 +1,3 @@ +.page-shell { + background: transparent; +} diff --git a/YumiNail-Admin-Program/pages/coupon-distribute/index.js b/YumiNail-Admin-Program/pages/coupon-distribute/index.js new file mode 100644 index 00000000..d8da2343 --- /dev/null +++ b/YumiNail-Admin-Program/pages/coupon-distribute/index.js @@ -0,0 +1,87 @@ +const couponApi = require('../../api/coupon') +const userApi = require('../../api/user') +const navigation = require('../../utils/navigation') +const { getTempRecord, clearTempRecord } = require('../../utils/storage') + +Page({ + data: { + coupon: null, + users: [], + quantity: 1 + }, + + onLoad() { + const coupon = getTempRecord('currentCoupon', null) + this.setData({ + coupon + }) + this.loadUsers() + }, + + onUnload() { + clearTempRecord('currentCoupon') + }, + + async loadUsers() { + try { + const users = await userApi.listAllUsers() + this.setData({ + users: (Array.isArray(users) ? users : []).map(item => ({ + ...item, + valueId: String(item.id), + checked: false + })) + }) + } catch (error) { + wx.showToast({ + title: error.message || '可发放用户加载失败', + icon: 'none' + }) + } + }, + + handleUserCheck(event) { + const selected = event.detail.value || [] + this.setData({ + users: this.data.users.map(item => ({ + ...item, + checked: selected.includes(item.valueId) + })) + }) + }, + + handleQuantityInput(event) { + this.setData({ + quantity: event.detail.value + }) + }, + + async handleSubmit() { + const selectedUserIds = this.data.users.filter(item => item.checked).map(item => Number(item.id)) + if (!selectedUserIds.length) { + wx.showToast({ + title: '请至少选择一个用户', + icon: 'none' + }) + return + } + + try { + await couponApi.distributeCoupon({ + couponId: this.data.coupon.id, + userIds: selectedUserIds, + quantity: Number(this.data.quantity || 1) + }) + wx.showToast({ + title: '优惠券已发放', + icon: 'none' + }) + navigation.goBack('/pages/coupons/index') + } catch (error) { + wx.showToast({ + title: error.message || '发放失败', + icon: 'none' + }) + } + } +}) diff --git a/YumiNail-Admin-Program/pages/coupon-distribute/index.json b/YumiNail-Admin-Program/pages/coupon-distribute/index.json new file mode 100644 index 00000000..8632c9b0 --- /dev/null +++ b/YumiNail-Admin-Program/pages/coupon-distribute/index.json @@ -0,0 +1,5 @@ +{ + "usingComponents": { + "navigation-bar": "/components/navigation-bar/navigation-bar" + } +} diff --git a/YumiNail-Admin-Program/pages/coupon-distribute/index.wxml b/YumiNail-Admin-Program/pages/coupon-distribute/index.wxml new file mode 100644 index 00000000..99c31e7f --- /dev/null +++ b/YumiNail-Admin-Program/pages/coupon-distribute/index.wxml @@ -0,0 +1,28 @@ + + + + + + {{coupon.couponName}} + 选择用户后批量发放,数量默认 1。移动端只保留高频发放能力,不把 Web 的宽表格搬过来。 + + 发放数量 + + + + 选择用户 + + + + + + + + + + + + diff --git a/YumiNail-Admin-Program/pages/coupon-distribute/index.wxss b/YumiNail-Admin-Program/pages/coupon-distribute/index.wxss new file mode 100644 index 00000000..e7250734 --- /dev/null +++ b/YumiNail-Admin-Program/pages/coupon-distribute/index.wxss @@ -0,0 +1,4 @@ +checkbox { + transform: scale(0.75); + margin-right: 8rpx; +} diff --git a/YumiNail-Admin-Program/pages/coupon-form/index.js b/YumiNail-Admin-Program/pages/coupon-form/index.js new file mode 100644 index 00000000..3f3f8fdf --- /dev/null +++ b/YumiNail-Admin-Program/pages/coupon-form/index.js @@ -0,0 +1,291 @@ +const couponApi = require('../../api/coupon') +const tagApi = require('../../api/tag') +const shopApi = require('../../api/shop') +const navigation = require('../../utils/navigation') +const format = require('../../utils/format') +const { getTempRecord, clearTempRecord } = require('../../utils/storage') + +function normalizeId(value) { + return value === undefined || value === null ? '' : String(value) +} + +function buildCheckableList(list, selectedIds, labelKey) { + return (Array.isArray(list) ? list : []).map(item => ({ + ...item, + valueId: normalizeId(item.id), + labelText: item[labelKey], + checked: selectedIds.includes(normalizeId(item.id)) + })) +} + +function syncSelectedIds(selectedIds, list) { + const availableIds = new Set((Array.isArray(list) ? list : []).map(item => normalizeId(item.id))) + return (Array.isArray(selectedIds) ? selectedIds : []).filter(id => availableIds.has(normalizeId(id))) +} + +Page({ + data: { + mode: 'create', + couponId: '', + shops: [], + shopIndex: 0, + shopLabel: '', + couponTypeOptions: ['折扣券', '满减券'], + couponTypeIndex: 0, + couponTypeLabel: '折扣券', + vipLevelOptions: ['普通', '青铜', '白银', '黄金'], + vipLevelIndex: 0, + vipLevelLabel: '普通', + startDate: '', + startTime: '', + endDate: '', + endTime: '', + availableTags: [], + unavailableTags: [], + form: { + couponName: '', + couponCode: '', + discountValue: '', + minAmount: '', + reduceAmount: '', + totalCount: '', + couponScene: '', + autoMatch: false + } + }, + + onLoad(options) { + const mode = options && options.mode ? options.mode : 'create' + const currentCoupon = getTempRecord('currentCoupon', null) + this.setData({ + mode, + couponId: options && options.id ? options.id : '' + }) + + this._selectedAvailableTagIds = [] + this._selectedUnavailableTagIds = [] + + if (mode === 'edit' && currentCoupon) { + const start = format.parseDateTimeToPicker(currentCoupon.startTime) + const end = format.parseDateTimeToPicker(currentCoupon.endTime) + this._selectedAvailableTagIds = Array.isArray(currentCoupon.availableTags) ? currentCoupon.availableTags.map(item => String(item.id)) : [] + this._selectedUnavailableTagIds = Array.isArray(currentCoupon.unavailableTags) ? currentCoupon.unavailableTags.map(item => String(item.id)) : [] + this._initialShopId = currentCoupon.shopId + this.setData({ + form: { + couponName: currentCoupon.couponName || '', + couponCode: currentCoupon.couponCode || '', + discountValue: currentCoupon.discountValue || '', + minAmount: currentCoupon.minAmount || '', + reduceAmount: currentCoupon.reduceAmount || '', + totalCount: currentCoupon.totalCount || '', + couponScene: currentCoupon.couponScene || '', + autoMatch: Number(currentCoupon.autoMatch) === 1 + }, + couponTypeIndex: Number(currentCoupon.couponType) === 2 ? 1 : 0, + couponTypeLabel: Number(currentCoupon.couponType) === 2 ? '满减券' : '折扣券', + vipLevelIndex: this.data.vipLevelOptions.findIndex(item => item === (currentCoupon.requiredVipLevel || '普通')), + vipLevelLabel: currentCoupon.requiredVipLevel || '普通', + startDate: start.date, + startTime: start.time, + endDate: end.date, + endTime: end.time + }) + } + + this.loadDependencies() + }, + + onUnload() { + clearTempRecord('currentCoupon') + }, + + async loadDependencies() { + const app = getApp() + const currentShop = app.globalData.currentShop + const operator = app.globalData.userInfo || {} + + try { + const shopList = await shopApi.listAllShops() + + let shops = Array.isArray(shopList) ? shopList : [] + if (Number(operator.type) !== 4 && currentShop) { + shops = shops.filter(item => normalizeId(item.id) === normalizeId(currentShop.id)) + } + + let shopIndex = 0 + if (this._initialShopId) { + const index = shops.findIndex(item => normalizeId(item.id) === normalizeId(this._initialShopId)) + if (index >= 0) { + shopIndex = index + } + } + const selectedShop = shops[shopIndex] + + this.setData({ + shops, + shopIndex, + shopLabel: selectedShop ? selectedShop.shopName : '' + }) + + await this.loadTagOptions(selectedShop ? selectedShop.id : '') + } catch (error) { + wx.showToast({ + title: error.message || '初始化优惠券表单失败', + icon: 'none' + }) + } + }, + + async loadTagOptions(shopId) { + if (!normalizeId(shopId)) { + this._selectedAvailableTagIds = [] + this._selectedUnavailableTagIds = [] + this.setData({ + availableTags: [], + unavailableTags: [] + }) + return + } + + try { + const tagList = await tagApi.listTagsByShopId(shopId) + this._selectedAvailableTagIds = syncSelectedIds(this._selectedAvailableTagIds, tagList) + this._selectedUnavailableTagIds = syncSelectedIds(this._selectedUnavailableTagIds, tagList) + this.setData({ + availableTags: buildCheckableList(tagList, this._selectedAvailableTagIds, 'tagName'), + unavailableTags: buildCheckableList(tagList, this._selectedUnavailableTagIds, 'tagName') + }) + } catch (error) { + this.setData({ + availableTags: [], + unavailableTags: [] + }) + wx.showToast({ + title: error.message || '可用标签加载失败', + icon: 'none' + }) + } + }, + + handleInputChange(event) { + const field = event.currentTarget.dataset.field + const value = event.detail.value + this.setData({ + [`form.${field}`]: value + }) + }, + + handleShopChange(event) { + const shopIndex = Number(event.detail.value) + const selectedShop = this.data.shops[shopIndex] + this.setData({ + shopIndex, + shopLabel: selectedShop ? selectedShop.shopName : '' + }) + this.loadTagOptions(selectedShop ? selectedShop.id : '') + }, + + handleCouponTypeChange(event) { + const couponTypeIndex = Number(event.detail.value) + this.setData({ + couponTypeIndex, + couponTypeLabel: this.data.couponTypeOptions[couponTypeIndex] + }) + }, + + handleVipLevelChange(event) { + const vipLevelIndex = Number(event.detail.value) + this.setData({ + vipLevelIndex, + vipLevelLabel: this.data.vipLevelOptions[vipLevelIndex] + }) + }, + + handleDateTimeChange(event) { + const field = event.currentTarget.dataset.field + this.setData({ + [field]: event.detail.value + }) + }, + + handleAutoMatchChange(event) { + this.setData({ + 'form.autoMatch': event.detail.value + }) + }, + + handleAvailableTagChange(event) { + this._selectedAvailableTagIds = event.detail.value || [] + this.setData({ + availableTags: this.data.availableTags.map(item => ({ + ...item, + checked: this._selectedAvailableTagIds.includes(item.valueId) + })) + }) + }, + + handleUnavailableTagChange(event) { + this._selectedUnavailableTagIds = event.detail.value || [] + this.setData({ + unavailableTags: this.data.unavailableTags.map(item => ({ + ...item, + checked: this._selectedUnavailableTagIds.includes(item.valueId) + })) + }) + }, + + async handleSubmit() { + const selectedShop = this.data.shops[this.data.shopIndex] + if (!this.data.form.couponName) { + wx.showToast({ + title: '请输入优惠券名称', + icon: 'none' + }) + return + } + if (!selectedShop) { + wx.showToast({ + title: '请选择所属店铺', + icon: 'none' + }) + return + } + + const payload = { + couponCode: this.data.form.couponCode || undefined, + couponName: this.data.form.couponName, + couponType: this.data.couponTypeIndex === 1 ? 2 : 1, + discountValue: this.data.couponTypeIndex === 0 ? Number(this.data.form.discountValue || 0) : undefined, + minAmount: this.data.couponTypeIndex === 1 ? Number(this.data.form.minAmount || 0) : undefined, + reduceAmount: this.data.couponTypeIndex === 1 ? Number(this.data.form.reduceAmount || 0) : undefined, + totalCount: this.data.form.totalCount ? Number(this.data.form.totalCount) : undefined, + startTime: format.buildDateTime(this.data.startDate, this.data.startTime), + endTime: format.buildDateTime(this.data.endDate, this.data.endTime), + shopId: selectedShop.id, + couponScene: this.data.form.couponScene || undefined, + requiredVipLevel: this.data.vipLevelLabel || undefined, + autoMatch: this.data.form.autoMatch ? 1 : 0, + availableTagIds: this._selectedAvailableTagIds.map(item => Number(item)), + unavailableTagIds: this._selectedUnavailableTagIds.map(item => Number(item)) + } + + try { + if (this.data.mode === 'edit') { + await couponApi.updateCoupon(this.data.couponId, payload) + } else { + await couponApi.createCoupon(payload) + } + wx.showToast({ + title: this.data.mode === 'edit' ? '优惠券已更新' : '优惠券已创建', + icon: 'none' + }) + navigation.goBack('/pages/coupons/index') + } catch (error) { + wx.showToast({ + title: error.message || '保存失败', + icon: 'none' + }) + } + } +}) diff --git a/YumiNail-Admin-Program/pages/coupon-form/index.json b/YumiNail-Admin-Program/pages/coupon-form/index.json new file mode 100644 index 00000000..8632c9b0 --- /dev/null +++ b/YumiNail-Admin-Program/pages/coupon-form/index.json @@ -0,0 +1,5 @@ +{ + "usingComponents": { + "navigation-bar": "/components/navigation-bar/navigation-bar" + } +} diff --git a/YumiNail-Admin-Program/pages/coupon-form/index.wxml b/YumiNail-Admin-Program/pages/coupon-form/index.wxml new file mode 100644 index 00000000..4be784a5 --- /dev/null +++ b/YumiNail-Admin-Program/pages/coupon-form/index.wxml @@ -0,0 +1,111 @@ + + + + + + 优惠券信息 + + 优惠券名称 + + + + 所属店铺 + + {{shopLabel || '请选择店铺'}} + + + + 券类型 + + {{couponTypeLabel}} + + + + 优惠编码 + + + + 折扣值 + + + + + 满多少可用 + + + + 减免金额 + + + + + 总数量 + + + + 优惠场景 + + + + VIP 等级限制 + + {{vipLevelLabel}} + + + + 开始日期 / 时间 + + + {{startDate || '开始日期'}} + + + {{startTime || '开始时间'}} + + + + + 结束日期 / 时间 + + + {{endDate || '结束日期'}} + + + {{endTime || '结束时间'}} + + + + + 自动匹配 + + + + + 可用标签 + + + + + + + + + 不可用标签 + + + + + + + + + + + + + diff --git a/YumiNail-Admin-Program/pages/coupon-form/index.wxss b/YumiNail-Admin-Program/pages/coupon-form/index.wxss new file mode 100644 index 00000000..e7250734 --- /dev/null +++ b/YumiNail-Admin-Program/pages/coupon-form/index.wxss @@ -0,0 +1,4 @@ +checkbox { + transform: scale(0.75); + margin-right: 8rpx; +} diff --git a/YumiNail-Admin-Program/pages/coupons/index.js b/YumiNail-Admin-Program/pages/coupons/index.js new file mode 100644 index 00000000..826a38b7 --- /dev/null +++ b/YumiNail-Admin-Program/pages/coupons/index.js @@ -0,0 +1,95 @@ +const couponApi = require('../../api/coupon') +const format = require('../../utils/format') +const navigation = require('../../utils/navigation') +const { setTempRecord, clearTempRecord } = require('../../utils/storage') + +Page({ + data: { + list: [], + canCreate: false + }, + + onShow() { + if (!navigation.ensureLogin('进入优惠券管理')) { + return + } + + const permissionCodes = getApp().globalData.permissionCodes || [] + this.setData({ + canCreate: permissionCodes.includes('coupon:create') + }) + this.loadCoupons() + }, + + async loadCoupons() { + try { + const result = await couponApi.listCoupons({ + page: 1, + size: 20 + }) + this.setData({ + list: (Array.isArray(result && result.list) ? result.list : []).map(item => ({ + ...item, + displayTypeText: format.getCouponTypeText(item.couponType), + displayValueText: format.getCouponValueText(item), + displayShopName: item.shopName || '当前店铺' + })) + }) + } catch (error) { + wx.showToast({ + title: error.message || '优惠券加载失败', + icon: 'none' + }) + } + }, + + handleCreate() { + clearTempRecord('currentCoupon') + navigation.navigate('/pages/coupon-form/index', { + mode: 'create' + }).catch(() => undefined) + }, + + handleEdit(event) { + const coupon = event.currentTarget.dataset.coupon + setTempRecord('currentCoupon', coupon) + navigation.navigate('/pages/coupon-form/index', { + mode: 'edit', + id: coupon.id + }).catch(() => undefined) + }, + + handleDistribute(event) { + const coupon = event.currentTarget.dataset.coupon + setTempRecord('currentCoupon', coupon) + navigation.navigate('/pages/coupon-distribute/index', { + id: coupon.id + }).catch(() => undefined) + }, + + handleDelete(event) { + const coupon = event.currentTarget.dataset.coupon + wx.showModal({ + title: '删除优惠券', + content: `确认删除优惠券“${coupon.couponName}”吗?`, + success: async result => { + if (!result.confirm) { + return + } + try { + await couponApi.deleteCoupon(coupon.id) + wx.showToast({ + title: '优惠券已删除', + icon: 'none' + }) + this.loadCoupons() + } catch (error) { + wx.showToast({ + title: error.message || '优惠券删除失败', + icon: 'none' + }) + } + } + }) + } +}) diff --git a/YumiNail-Admin-Program/pages/coupons/index.json b/YumiNail-Admin-Program/pages/coupons/index.json new file mode 100644 index 00000000..8632c9b0 --- /dev/null +++ b/YumiNail-Admin-Program/pages/coupons/index.json @@ -0,0 +1,5 @@ +{ + "usingComponents": { + "navigation-bar": "/components/navigation-bar/navigation-bar" + } +} diff --git a/YumiNail-Admin-Program/pages/coupons/index.wxml b/YumiNail-Admin-Program/pages/coupons/index.wxml new file mode 100644 index 00000000..1c738ea0 --- /dev/null +++ b/YumiNail-Admin-Program/pages/coupons/index.wxml @@ -0,0 +1,44 @@ + + + + + + 优惠券列表 + 普通券、VIP 自动券都在这里维护;发放动作单独收口到移动端发放页,避免一屏塞太多字段。 + + + + + + + {{item.couponName}} + {{item.displayShopName}} · {{item.displayTypeText}} + + {{item.displayValueText}} + + + + 可用时间 + {{item.startTime}} ~ {{item.endTime}} + + + 剩余数量 + {{item.remainingCount || item.totalCount || '--'}} + + + + 发放 + 编辑 + 删除 + + + + + + 暂无优惠券 + 可以先创建普通券,也可以为每家店铺维护自己的 VIP 自动券模板。 + + + + + + diff --git a/YumiNail-Admin-Program/pages/coupons/index.wxss b/YumiNail-Admin-Program/pages/coupons/index.wxss new file mode 100644 index 00000000..09b20ffe --- /dev/null +++ b/YumiNail-Admin-Program/pages/coupons/index.wxss @@ -0,0 +1,3 @@ +.page-shell { + background: transparent; +} diff --git a/YumiNail-Admin-Program/pages/login/index.js b/YumiNail-Admin-Program/pages/login/index.js new file mode 100644 index 00000000..0f2f6727 --- /dev/null +++ b/YumiNail-Admin-Program/pages/login/index.js @@ -0,0 +1,210 @@ +const authApi = require('../../api/auth') +const auth = require('../../utils/auth') +const navigation = require('../../utils/navigation') +const { runWithLoading } = require('../../utils/loading') + +const ACCOUNT_REGEX = /[^A-Za-z0-9]/g + +Page({ + data: { + redirect: '', + form: { + account: '', + password: '', + shopId: '' + }, + loginShops: [], + loginShopIndex: -1, + loginShopDisplayName: '', + allowShoplessLogin: false, + loginShopMessage: '', + accountStatusText: '', + accountStatusType: '', + loading: false + }, + + onLoad(options) { + this._lookupTicket = 0 + this.setData({ + redirect: options && options.redirect ? options.redirect : '' + }) + + if (auth.isLoggedIn()) { + navigation.redirectAfterLogin(this.data.redirect).catch(() => undefined) + } + }, + + onUnload() { + if (this._accountTimer) { + clearTimeout(this._accountTimer) + } + }, + + handleInputChange(event) { + const field = event.currentTarget.dataset.field + let value = event.detail.value + + if (field === 'account') { + value = String(value || '').replace(ACCOUNT_REGEX, '') + this.resetAccountState() + if (value) { + this.scheduleAccountLookup(value) + } + } + + this.setData({ + [`form.${field}`]: value + }) + }, + + handleShopChange(event) { + const index = Number(event.detail.value) + const shop = this.data.loginShops[index] + + this.setData({ + loginShopIndex: index, + loginShopDisplayName: shop ? shop.shopName || '' : '', + 'form.shopId': shop ? shop.id : '' + }) + }, + + resetAccountState() { + if (this._accountTimer) { + clearTimeout(this._accountTimer) + } + + this._lookupTicket += 1 + + this.setData({ + accountStatusText: '', + accountStatusType: '', + loginShops: [], + loginShopIndex: -1, + loginShopDisplayName: '', + allowShoplessLogin: false, + loginShopMessage: '', + 'form.shopId': '' + }) + }, + + scheduleAccountLookup(account) { + if (this._accountTimer) { + clearTimeout(this._accountTimer) + } + + const ticket = this._lookupTicket + 1 + this._lookupTicket = ticket + this._accountTimer = setTimeout(() => { + this.loadLoginShops(account, ticket) + }, 420) + }, + + applyLoginShopSelection(selection) { + const shops = Array.isArray(selection && selection.shops) ? selection.shops : [] + const allowShoplessLogin = Boolean(selection && selection.allowShoplessLogin) + let loginShopIndex = -1 + let loginShopDisplayName = '' + let shopId = '' + + if (!allowShoplessLogin && shops.length === 1) { + loginShopIndex = 0 + loginShopDisplayName = shops[0].shopName || '' + shopId = shops[0].id + } + + this.setData({ + loginShops: shops, + allowShoplessLogin, + loginShopMessage: (selection && selection.message) || '', + loginShopIndex, + loginShopDisplayName, + 'form.shopId': shopId, + accountStatusText: shops.length || allowShoplessLogin ? '该账号可用于后台登录' : '当前账号暂时不可用于后台登录', + accountStatusType: shops.length || allowShoplessLogin ? 'success' : 'warning' + }) + }, + + async loadLoginShops(account, ticket) { + if (!account) { + this.resetAccountState() + return + } + + try { + const result = await authApi.getLoginShops(account) + if (ticket !== this._lookupTicket || this.data.form.account !== account) { + return + } + this.applyLoginShopSelection(result) + } catch (error) { + if (ticket !== this._lookupTicket || this.data.form.account !== account) { + return + } + this.setData({ + loginShops: [], + loginShopIndex: -1, + loginShopDisplayName: '', + allowShoplessLogin: false, + loginShopMessage: '', + 'form.shopId': '', + accountStatusText: error.message || '该后台账号不存在或不可登录', + accountStatusType: 'error' + }) + } + }, + + validateForm() { + const form = this.data.form + if (!form.account) { + return '请输入后台账号' + } + if (!form.password) { + return '请输入登录密码' + } + if (!this.data.allowShoplessLogin && this.data.loginShops.length && !form.shopId) { + return '请选择登录店铺' + } + return '' + }, + + async handleSubmit() { + const errorMessage = this.validateForm() + if (errorMessage) { + wx.showToast({ + title: errorMessage, + icon: 'none' + }) + return + } + + this.setData({ + loading: true + }) + + try { + const payload = await runWithLoading(() => authApi.login({ + account: this.data.form.account, + password: this.data.form.password, + shopId: this.data.form.shopId || undefined + })) + + await getApp().setAdminSession(payload) + + wx.showToast({ + title: '登录成功', + icon: 'none' + }) + + await navigation.redirectAfterLogin(this.data.redirect) + } catch (error) { + wx.showToast({ + title: error.message || '登录失败', + icon: 'none' + }) + } finally { + this.setData({ + loading: false + }) + } + } +}) diff --git a/YumiNail-Admin-Program/pages/login/index.json b/YumiNail-Admin-Program/pages/login/index.json new file mode 100644 index 00000000..8632c9b0 --- /dev/null +++ b/YumiNail-Admin-Program/pages/login/index.json @@ -0,0 +1,5 @@ +{ + "usingComponents": { + "navigation-bar": "/components/navigation-bar/navigation-bar" + } +} diff --git a/YumiNail-Admin-Program/pages/login/index.wxml b/YumiNail-Admin-Program/pages/login/index.wxml new file mode 100644 index 00000000..ad2e5f19 --- /dev/null +++ b/YumiNail-Admin-Program/pages/login/index.wxml @@ -0,0 +1,45 @@ + + + + + diff --git a/YumiNail-Admin-Program/pages/login/index.wxss b/YumiNail-Admin-Program/pages/login/index.wxss new file mode 100644 index 00000000..1334c8cb --- /dev/null +++ b/YumiNail-Admin-Program/pages/login/index.wxss @@ -0,0 +1,3 @@ +.login-stack { + padding-top: 40rpx; +} diff --git a/YumiNail-Admin-Program/pages/manage/index.js b/YumiNail-Admin-Program/pages/manage/index.js new file mode 100644 index 00000000..88e9eae8 --- /dev/null +++ b/YumiNail-Admin-Program/pages/manage/index.js @@ -0,0 +1,44 @@ +const navigation = require('../../utils/navigation') +const permission = require('../../utils/permission') + +Page({ + data: { + userInfo: null, + currentShop: null, + modules: [] + }, + + onShow() { + if (!navigation.ensureLogin('进入经营模块')) { + return + } + + const app = getApp() + const userInfo = app.globalData.userInfo + const currentShop = app.globalData.currentShop + const permissionCodes = app.globalData.permissionCodes || [] + + this.setData({ + userInfo, + currentShop, + modules: permission.getManageModules(userInfo, permissionCodes, currentShop) + }) + }, + + handleOpenModule(event) { + const module = event.currentTarget.dataset.module + if (!module) { + return + } + + if (!module.allowed) { + wx.showToast({ + title: module.disabledReason || '当前账号没有进入该模块的权限', + icon: 'none' + }) + return + } + + navigation.navigate(module.path).catch(() => undefined) + } +}) diff --git a/YumiNail-Admin-Program/pages/manage/index.json b/YumiNail-Admin-Program/pages/manage/index.json new file mode 100644 index 00000000..8632c9b0 --- /dev/null +++ b/YumiNail-Admin-Program/pages/manage/index.json @@ -0,0 +1,5 @@ +{ + "usingComponents": { + "navigation-bar": "/components/navigation-bar/navigation-bar" + } +} diff --git a/YumiNail-Admin-Program/pages/manage/index.wxml b/YumiNail-Admin-Program/pages/manage/index.wxml new file mode 100644 index 00000000..25b078d2 --- /dev/null +++ b/YumiNail-Admin-Program/pages/manage/index.wxml @@ -0,0 +1,26 @@ + + + + + + 按权限展示 + {{currentShop ? currentShop.shopName : '平台级入口'}} + 这里不复刻网页后台的大表格首页,而是把可用模块拆成移动端更好点到的入口卡片。 + + + 当前是无店铺管理员登录状态。用户、作品、优惠券、标签、美甲师等强店铺模块会先置灰,避免误操作。 + + + + + + {{item.title}} + {{item.description}} + + {{item.allowed ? '可进入' : '待解锁'}} + + {{item.disabledReason}} + + + + diff --git a/YumiNail-Admin-Program/pages/manage/index.wxss b/YumiNail-Admin-Program/pages/manage/index.wxss new file mode 100644 index 00000000..09b20ffe --- /dev/null +++ b/YumiNail-Admin-Program/pages/manage/index.wxss @@ -0,0 +1,3 @@ +.page-shell { + background: transparent; +} diff --git a/YumiNail-Admin-Program/pages/order-detail/index.js b/YumiNail-Admin-Program/pages/order-detail/index.js new file mode 100644 index 00000000..b38a11df --- /dev/null +++ b/YumiNail-Admin-Program/pages/order-detail/index.js @@ -0,0 +1,28 @@ +const navigation = require('../../utils/navigation') +const format = require('../../utils/format') +const { getTempRecord, clearTempRecord } = require('../../utils/storage') + +Page({ + data: { + order: null + }, + + onLoad() { + const order = getTempRecord('currentOrder', null) + this.setData({ + order: order ? { + ...order, + displayStatusText: format.getOrderStatusText(order), + displayCreateTime: format.formatDateTime(order.createTime) + } : null + }) + }, + + onUnload() { + clearTempRecord('currentOrder') + }, + + handleBack() { + navigation.goBack('/pages/orders/index') + } +}) diff --git a/YumiNail-Admin-Program/pages/order-detail/index.json b/YumiNail-Admin-Program/pages/order-detail/index.json new file mode 100644 index 00000000..8632c9b0 --- /dev/null +++ b/YumiNail-Admin-Program/pages/order-detail/index.json @@ -0,0 +1,5 @@ +{ + "usingComponents": { + "navigation-bar": "/components/navigation-bar/navigation-bar" + } +} diff --git a/YumiNail-Admin-Program/pages/order-detail/index.wxml b/YumiNail-Admin-Program/pages/order-detail/index.wxml new file mode 100644 index 00000000..290a780b --- /dev/null +++ b/YumiNail-Admin-Program/pages/order-detail/index.wxml @@ -0,0 +1,41 @@ + + + + + + {{order.orderNo}} + {{order.displayStatusText}} · {{order.displayCreateTime}} + + + 用户昵称 + {{order.customerNickname || order.userNickname || '--'}} + + + 脱敏手机号 + {{order.customerPhoneMasked || '--'}} + + + 所属店铺 + {{order.shopName || '--'}} + + + 美甲师 + {{order.artistName || '--'}} + + + 应付金额 + ¥{{order.payAmount || '--'}} + + + 备注 + {{order.remark || '暂无备注'}} + + + + + + 订单详情暂不可用 + 当前详情页优先复用列表页已拉取的数据。如果你是直接打开该页面,请先回到订单列表重新进入。 + + + diff --git a/YumiNail-Admin-Program/pages/order-detail/index.wxss b/YumiNail-Admin-Program/pages/order-detail/index.wxss new file mode 100644 index 00000000..09b20ffe --- /dev/null +++ b/YumiNail-Admin-Program/pages/order-detail/index.wxss @@ -0,0 +1,3 @@ +.page-shell { + background: transparent; +} diff --git a/YumiNail-Admin-Program/pages/orders/index.js b/YumiNail-Admin-Program/pages/orders/index.js new file mode 100644 index 00000000..885fb364 --- /dev/null +++ b/YumiNail-Admin-Program/pages/orders/index.js @@ -0,0 +1,162 @@ +const orderApi = require('../../api/order') +const navigation = require('../../utils/navigation') +const permission = require('../../utils/permission') +const format = require('../../utils/format') +const { setTempRecord } = require('../../utils/storage') +const { consumeDirty, markDirty } = require('../../utils/page-state') + +const STATUS_OPTIONS = [ + { label: '全部', value: '' }, + { label: '待服务', value: 1 }, + { label: '已完成', value: 2 }, + { label: '已取消', value: 0 } +] + +Page({ + data: { + keyword: '', + status: '', + statusOptions: STATUS_OPTIONS, + list: [], + total: 0, + loading: false, + userInfo: null, + initialized: false + }, + + onShow() { + if (!navigation.ensureLogin('进入订单管理')) { + return + } + + this.setData({ + userInfo: getApp().globalData.userInfo + }) + + if (!this.data.initialized || consumeDirty('admin-orders')) { + this.loadOrders() + } + }, + + onPullDownRefresh() { + this.loadOrders().finally(() => { + wx.stopPullDownRefresh() + }) + }, + + handleKeywordInput(event) { + this.setData({ + keyword: event.detail.value + }) + }, + + handleStatusChange(event) { + const status = event.currentTarget.dataset.status + this.setData({ + status + }) + this.loadOrders() + }, + + async loadOrders() { + const requestId = (this._loadRequestId || 0) + 1 + this._loadRequestId = requestId + this.setData({ + loading: true + }) + + try { + const result = await orderApi.listOrders({ + page: 1, + size: 20, + keyword: this.data.keyword || undefined, + status: this.data.status === '' ? undefined : this.data.status + }) + + if (requestId !== this._loadRequestId) { + return + } + + this.setData({ + list: (Array.isArray(result && result.list) ? result.list : []).map(item => ({ + ...item, + displayStatusText: format.getOrderStatusText(item), + displayCreateTime: format.formatDateTime(item.createTime) + })), + total: Number(result && result.total) || 0, + initialized: true + }) + } catch (error) { + if (requestId !== this._loadRequestId) { + return + } + wx.showToast({ + title: error.message || '订单加载失败', + icon: 'none' + }) + } finally { + if (requestId === this._loadRequestId) { + this.setData({ + loading: false + }) + } + } + }, + + handleSearch() { + this.loadOrders() + }, + + handleOpenOrder(event) { + const order = event.currentTarget.dataset.order + if (!order) { + return + } + + setTempRecord('currentOrder', order) + navigation.navigate('/pages/order-detail/index', { + id: order.id + }).catch(() => undefined) + }, + + async handleProcessOrder(event) { + const order = event.currentTarget.dataset.order + if (!order) { + return + } + + const isArtist = permission.isNailArtist(this.data.userInfo) + const options = isArtist + ? [{ label: '标记为已完成', status: 2 }] + : [ + { label: '调整为待服务', status: 1 }, + { label: '标记为已完成', status: 2 }, + { label: '标记为已取消', status: 0 } + ] + + wx.showActionSheet({ + itemList: options.map(item => item.label), + success: async result => { + const target = options[result.tapIndex] + if (!target) { + return + } + + try { + await orderApi.updateOrderStatus(order.id, target.status) + markDirty('admin-workbench') + wx.showToast({ + title: '订单状态已更新', + icon: 'none' + }) + this.loadOrders() + } catch (error) { + wx.showToast({ + title: error.message || '订单处理失败', + icon: 'none' + }) + } + } + }) + } +}) diff --git a/YumiNail-Admin-Program/pages/orders/index.json b/YumiNail-Admin-Program/pages/orders/index.json new file mode 100644 index 00000000..c1f072ae --- /dev/null +++ b/YumiNail-Admin-Program/pages/orders/index.json @@ -0,0 +1,6 @@ +{ + "usingComponents": { + "navigation-bar": "/components/navigation-bar/navigation-bar" + }, + "enablePullDownRefresh": true +} diff --git a/YumiNail-Admin-Program/pages/orders/index.wxml b/YumiNail-Admin-Program/pages/orders/index.wxml new file mode 100644 index 00000000..2e3d97c8 --- /dev/null +++ b/YumiNail-Admin-Program/pages/orders/index.wxml @@ -0,0 +1,63 @@ + + + + + + 预约履约 + 按当前角色范围查看订单 + 店长和平台管理员看当前权限范围订单,美甲师仅看属于自己的预约单,并只能完成属于自己的订单。 + + + + 筛选条件 + + + + + + + {{item.label}} + + + + + + + + + {{item.orderNo}} + {{item.customerNickname || item.userNickname || '未命名用户'}} · {{item.customerPhoneMasked || '--'}} + + {{item.displayStatusText}} + + + + 订单金额 + ¥{{item.payAmount}} + + + 所属门店 + {{item.shopName || '--'}} + + + 美甲师 + {{item.artistName || '--'}} + + + 下单时间 + {{item.displayCreateTime}} + + + + 查看详情 + 处理订单 + + + + + + 暂无订单 + 当前筛选条件下没有符合的订单记录,切换状态或清空关键字后再试一次。 + + + diff --git a/YumiNail-Admin-Program/pages/orders/index.wxss b/YumiNail-Admin-Program/pages/orders/index.wxss new file mode 100644 index 00000000..09b20ffe --- /dev/null +++ b/YumiNail-Admin-Program/pages/orders/index.wxss @@ -0,0 +1,3 @@ +.page-shell { + background: transparent; +} diff --git a/YumiNail-Admin-Program/pages/permission-form/index.js b/YumiNail-Admin-Program/pages/permission-form/index.js new file mode 100644 index 00000000..707160ea --- /dev/null +++ b/YumiNail-Admin-Program/pages/permission-form/index.js @@ -0,0 +1,165 @@ +const permissionApi = require('../../api/permission') +const navigation = require('../../utils/navigation') +const permissionUtils = require('../../utils/permission') +const { getTempRecord, clearTempRecord } = require('../../utils/storage') + +function buildPermissionGroups(list, checkedIds, assignableIds) { + const groups = permissionUtils.groupPermissionsByGroup(list) + return Object.keys(groups).map(group => ({ + group, + items: groups[group].map(item => ({ + ...item, + valueId: String(item.id), + checked: checkedIds.includes(String(item.id)), + disabled: assignableIds.length ? !assignableIds.includes(String(item.id)) : false + })) + })) +} + +Page({ + data: { + mode: 'definition-create', + title: '', + userId: '', + currentUser: null, + permissionGroups: [], + form: { + permissionCode: '', + permissionName: '', + permissionGroup: '', + description: '' + } + }, + + onLoad(options) { + const mode = options && options.mode ? options.mode : 'definition-create' + this.setData({ + mode, + userId: options && options.userId ? options.userId : '', + title: mode === 'assign' ? '分配权限' : (mode === 'definition-edit' ? '编辑权限' : '新增权限') + }) + + if (mode === 'assign') { + this.loadAssignData() + return + } + + const currentPermission = getTempRecord('currentPermission', null) + if (mode === 'definition-edit' && currentPermission) { + this.setData({ + form: { + permissionCode: currentPermission.permissionCode || '', + permissionName: currentPermission.permissionName || '', + permissionGroup: currentPermission.permissionGroup || '', + description: currentPermission.description || '' + } + }) + } + }, + + onUnload() { + clearTempRecord('currentPermission') + }, + + async loadAssignData() { + const currentUser = getTempRecord('currentUser', null) + this.setData({ + currentUser + }) + + try { + const [allPermissions, currentPermissions, assignableIds] = await Promise.all([ + permissionApi.listAllPermissions(), + permissionApi.getUserPermissions(this.data.userId), + permissionApi.getAssignablePermissionIds(this.data.userId) + ]) + + const checkedIds = (Array.isArray(currentPermissions) ? currentPermissions : []).map(item => String(item.id)) + const normalizedAssignableIds = (Array.isArray(assignableIds) ? assignableIds : []).map(item => String(item)) + + this.setData({ + permissionGroups: buildPermissionGroups(allPermissions, checkedIds, normalizedAssignableIds) + }) + } catch (error) { + wx.showToast({ + title: error.message || '权限数据加载失败', + icon: 'none' + }) + } + }, + + handleInputChange(event) { + const field = event.currentTarget.dataset.field + this.setData({ + [`form.${field}`]: event.detail.value + }) + }, + + handlePermissionCheck(event) { + const selected = event.detail.value || [] + this.setData({ + permissionGroups: this.data.permissionGroups.map(group => ({ + ...group, + items: group.items.map(item => ({ + ...item, + checked: item.disabled ? item.checked : selected.includes(item.valueId) + })) + })) + }) + }, + + async handleSubmit() { + if (this.data.mode === 'assign') { + const permissionIds = [] + this.data.permissionGroups.forEach(group => { + group.items.forEach(item => { + if (item.checked) { + permissionIds.push(Number(item.id)) + } + }) + }) + + try { + await permissionApi.assignUserPermissions(this.data.userId, permissionIds) + wx.showToast({ + title: '权限已保存', + icon: 'none' + }) + navigation.goBack('/pages/permissions/index') + } catch (error) { + wx.showToast({ + title: error.message || '权限保存失败', + icon: 'none' + }) + } + return + } + + if (!this.data.form.permissionCode || !this.data.form.permissionName) { + wx.showToast({ + title: '请补全权限编码和名称', + icon: 'none' + }) + return + } + + try { + if (this.data.mode === 'definition-edit') { + const currentPermission = getTempRecord('currentPermission', null) + await permissionApi.updatePermission(currentPermission.id, this.data.form) + } else { + await permissionApi.createPermission(this.data.form) + } + wx.showToast({ + title: '权限定义已保存', + icon: 'none' + }) + navigation.goBack('/pages/permissions/index') + } catch (error) { + wx.showToast({ + title: error.message || '保存失败', + icon: 'none' + }) + } + } +}) diff --git a/YumiNail-Admin-Program/pages/permission-form/index.json b/YumiNail-Admin-Program/pages/permission-form/index.json new file mode 100644 index 00000000..8632c9b0 --- /dev/null +++ b/YumiNail-Admin-Program/pages/permission-form/index.json @@ -0,0 +1,5 @@ +{ + "usingComponents": { + "navigation-bar": "/components/navigation-bar/navigation-bar" + } +} diff --git a/YumiNail-Admin-Program/pages/permission-form/index.wxml b/YumiNail-Admin-Program/pages/permission-form/index.wxml new file mode 100644 index 00000000..64659f5a --- /dev/null +++ b/YumiNail-Admin-Program/pages/permission-form/index.wxml @@ -0,0 +1,51 @@ + + + + + + {{currentUser.nickname || currentUser.account}} + 只能勾选当前账号被允许拥有的权限。超出允许范围的权限会直接置灰,避免前端只给出“保存失败”的笼统提示。 + + + + {{item.group}} + + + + + + + + + + + + + + + 权限定义 + + 权限编码 + + + + 权限名称 + + + + 权限分组 + + + + 描述 + + + + + + + + diff --git a/YumiNail-Admin-Program/pages/permission-form/index.wxss b/YumiNail-Admin-Program/pages/permission-form/index.wxss new file mode 100644 index 00000000..e7250734 --- /dev/null +++ b/YumiNail-Admin-Program/pages/permission-form/index.wxss @@ -0,0 +1,4 @@ +checkbox { + transform: scale(0.75); + margin-right: 8rpx; +} diff --git a/YumiNail-Admin-Program/pages/permissions/index.js b/YumiNail-Admin-Program/pages/permissions/index.js new file mode 100644 index 00000000..f803a83c --- /dev/null +++ b/YumiNail-Admin-Program/pages/permissions/index.js @@ -0,0 +1,85 @@ +const permissionApi = require('../../api/permission') +const userApi = require('../../api/user') +const navigation = require('../../utils/navigation') +const { setTempRecord, clearTempRecord } = require('../../utils/storage') + +function groupPermissions(list) { + const map = {} + ;(Array.isArray(list) ? list : []).forEach(item => { + const group = item.permissionGroup || '未分组' + if (!map[group]) { + map[group] = [] + } + map[group].push(item) + }) + + return Object.keys(map).map(group => ({ + group, + items: map[group] + })) +} + +Page({ + data: { + permissionGroups: [], + users: [], + canCreate: false, + canAssign: false + }, + + onShow() { + if (!navigation.ensureLogin('进入权限管理')) { + return + } + + const permissionCodes = getApp().globalData.permissionCodes || [] + this.setData({ + canCreate: permissionCodes.includes('permission:create'), + canAssign: permissionCodes.includes('permission:assign') + }) + this.loadPageData() + }, + + async loadPageData() { + try { + const [permissions, users] = await Promise.all([ + permissionApi.listAllPermissions(), + userApi.listAllUsers().catch(() => []) + ]) + this.setData({ + permissionGroups: groupPermissions(permissions), + users: Array.isArray(users) ? users : [] + }) + } catch (error) { + wx.showToast({ + title: error.message || '权限数据加载失败', + icon: 'none' + }) + } + }, + + handleCreatePermission() { + clearTempRecord('currentPermission') + navigation.navigate('/pages/permission-form/index', { + mode: 'definition-create' + }).catch(() => undefined) + }, + + handleEditPermission(event) { + const permission = event.currentTarget.dataset.permission + setTempRecord('currentPermission', permission) + navigation.navigate('/pages/permission-form/index', { + mode: 'definition-edit', + id: permission.id + }).catch(() => undefined) + }, + + handleAssignUser(event) { + const user = event.currentTarget.dataset.user + setTempRecord('currentUser', user) + navigation.navigate('/pages/permission-form/index', { + mode: 'assign', + userId: user.id + }).catch(() => undefined) + } +}) diff --git a/YumiNail-Admin-Program/pages/permissions/index.json b/YumiNail-Admin-Program/pages/permissions/index.json new file mode 100644 index 00000000..8632c9b0 --- /dev/null +++ b/YumiNail-Admin-Program/pages/permissions/index.json @@ -0,0 +1,5 @@ +{ + "usingComponents": { + "navigation-bar": "/components/navigation-bar/navigation-bar" + } +} diff --git a/YumiNail-Admin-Program/pages/permissions/index.wxml b/YumiNail-Admin-Program/pages/permissions/index.wxml new file mode 100644 index 00000000..54a006cf --- /dev/null +++ b/YumiNail-Admin-Program/pages/permissions/index.wxml @@ -0,0 +1,50 @@ + + + + + + 用户授权 + 移动端不再铺宽表格,先选用户,再进入分组权限页勾选保存。服务端会继续兜底拦截超范围授权。 + + + + + {{item.nickname || item.account}} + {{item.account}} · {{item.shopName || '多店铺账号'}} + + {{item.type === 4 ? '管理员' : item.type === 2 ? '店长' : item.type === 3 ? '美甲师' : '用户'}} + + + 配置权限 + + + + + + + + + 权限字典 + 当前代码真实使用的权限定义都集中在这里,便于在手机上快速检查分组和描述是否合理。 + + 新增 + + + + {{item.group}} + + + + + {{item.permissionCode}} + {{item.permissionName}} + {{item.description || '暂无描述'}} + + 编辑 + + + + + + + diff --git a/YumiNail-Admin-Program/pages/permissions/index.wxss b/YumiNail-Admin-Program/pages/permissions/index.wxss new file mode 100644 index 00000000..09b20ffe --- /dev/null +++ b/YumiNail-Admin-Program/pages/permissions/index.wxss @@ -0,0 +1,3 @@ +.page-shell { + background: transparent; +} diff --git a/YumiNail-Admin-Program/pages/product-form/index.js b/YumiNail-Admin-Program/pages/product-form/index.js new file mode 100644 index 00000000..15b0b60f --- /dev/null +++ b/YumiNail-Admin-Program/pages/product-form/index.js @@ -0,0 +1,349 @@ +const productApi = require('../../api/product') +const tagApi = require('../../api/tag') +const userApi = require('../../api/user') +const couponApi = require('../../api/coupon') +const shopApi = require('../../api/shop') +const navigation = require('../../utils/navigation') +const format = require('../../utils/format') +const cache = require('../../utils/cache') +const upload = require('../../utils/upload') +const { getTempRecord, clearTempRecord } = require('../../utils/storage') +const { getDraftValue, clearDraft, scheduleDraftSave, clearDraftTimer } = require('../../utils/form-draft') +const { markDirty } = require('../../utils/page-state') +const { CACHE_TTL } = require('../../utils/config') + +const DRAFT_KEY = 'admin-product-form' + +function normalizeId(value) { + return value === undefined || value === null ? '' : String(value) +} + +function buildCheckableList(list, selectedIds, labelKey) { + return (Array.isArray(list) ? list : []).map(item => ({ + ...item, + valueId: normalizeId(item.id), + labelText: item[labelKey], + checked: selectedIds.includes(normalizeId(item.id)) + })) +} + +function syncSelectedIds(selectedIds, list) { + const availableIds = new Set((Array.isArray(list) ? list : []).map(item => normalizeId(item.id))) + return (Array.isArray(selectedIds) ? selectedIds : []).filter(id => availableIds.has(normalizeId(id))) +} + +Page({ + data: { + mode: 'create', + productId: '', + shops: [], + shopIndex: 0, + shopLabel: '', + tags: [], + artists: [], + coupons: [], + uploading: false, + uploadProgress: 0, + form: { + title: '', + description: '', + price: '', + approximateDuration: '', + likeCount: '', + collectCount: '', + imageFileIds: [], + shopId: '' + } + }, + + onLoad(options) { + const mode = options && options.mode ? options.mode : 'create' + const currentProduct = getTempRecord('currentProduct', null) + const draft = getDraftValue(DRAFT_KEY, null) + this.setData({ + mode, + productId: options && options.id ? options.id : '' + }) + + this._selectedTagIds = [] + this._selectedArtistIds = [] + this._selectedCouponIds = [] + + if (mode === 'edit' && currentProduct) { + this._selectedTagIds = format.splitCsv(currentProduct.tags) + this._selectedArtistIds = format.splitCsv(currentProduct.bookableArtists) + this._selectedCouponIds = format.splitCsv(currentProduct.availableCoupons) + this._initialShopId = currentProduct.shopId + this.setData({ + form: { + title: currentProduct.title || '', + description: currentProduct.description || '', + price: currentProduct.price || '', + approximateDuration: currentProduct.approximateDuration || '', + likeCount: currentProduct.likeCount || '', + collectCount: currentProduct.collectCount || '', + imageFileIds: format.splitCsv(currentProduct.imageFileIds), + shopId: currentProduct.shopId || '' + } + }) + } + + if (draft && draft.mode === mode) { + this._selectedTagIds = Array.isArray(draft.selectedTagIds) ? draft.selectedTagIds : this._selectedTagIds + this._selectedArtistIds = Array.isArray(draft.selectedArtistIds) ? draft.selectedArtistIds : this._selectedArtistIds + this._selectedCouponIds = Array.isArray(draft.selectedCouponIds) ? draft.selectedCouponIds : this._selectedCouponIds + this._initialShopId = draft.form && draft.form.shopId ? draft.form.shopId : this._initialShopId + this.setData({ + form: { + ...this.data.form, + ...(draft.form || {}) + } + }) + } + + this.loadDependencies() + }, + + onUnload() { + clearTempRecord('currentProduct') + clearDraftTimer(this) + }, + + scheduleProductDraft() { + scheduleDraftSave(this, DRAFT_KEY, () => ({ + mode: this.data.mode, + form: { + ...this.data.form, + imageFileIds: this.data.form.imageFileIds.slice() + }, + selectedTagIds: this._selectedTagIds.slice(), + selectedArtistIds: this._selectedArtistIds.slice(), + selectedCouponIds: this._selectedCouponIds.slice() + })) + }, + + async loadDependencies() { + const app = getApp() + const currentShop = app.globalData.currentShop + const operator = app.globalData.userInfo || {} + + try { + const shopList = await cache.remember('admin:shops:all', CACHE_TTL.dict, () => shopApi.listAllShops()) + + let shops = Array.isArray(shopList) ? shopList : [] + if (Number(operator.type) !== 4 && currentShop) { + shops = shops.filter(item => normalizeId(item.id) === normalizeId(currentShop.id)) + } + + let shopIndex = 0 + if (this._initialShopId) { + const index = shops.findIndex(item => normalizeId(item.id) === normalizeId(this._initialShopId)) + if (index >= 0) { + shopIndex = index + } + } + const selectedShop = shops[shopIndex] + + this.setData({ + shops, + shopIndex, + shopLabel: selectedShop ? selectedShop.shopName : '', + 'form.shopId': selectedShop ? selectedShop.id : '' + }) + + await this.loadShopScopedOptions(selectedShop ? selectedShop.id : '') + } catch (error) { + wx.showToast({ + title: error.message || '初始化作品表单失败', + icon: 'none' + }) + } + }, + + async loadShopScopedOptions(shopId) { + if (!normalizeId(shopId)) { + this._selectedTagIds = [] + this._selectedArtistIds = [] + this._selectedCouponIds = [] + this.setData({ + tags: [], + artists: [], + coupons: [] + }) + return + } + + try { + const [tagList, artistList, couponList] = await Promise.all([ + tagApi.listTagsByShopId(shopId), + userApi.listArtists(shopId), + couponApi.listAllCoupons(shopId) + ]) + + this._selectedTagIds = syncSelectedIds(this._selectedTagIds, tagList) + this._selectedArtistIds = syncSelectedIds(this._selectedArtistIds, artistList) + this._selectedCouponIds = syncSelectedIds(this._selectedCouponIds, couponList) + + this.setData({ + tags: buildCheckableList(tagList, this._selectedTagIds, 'tagName'), + artists: buildCheckableList(artistList, this._selectedArtistIds, 'nickname'), + coupons: buildCheckableList(couponList, this._selectedCouponIds, 'couponName') + }) + this.scheduleProductDraft() + } catch (error) { + this.setData({ + tags: [], + artists: [], + coupons: [] + }) + wx.showToast({ + title: error.message || '店铺关联数据加载失败', + icon: 'none' + }) + } + }, + + handleInputChange(event) { + const field = event.currentTarget.dataset.field + this.setData({ + [`form.${field}`]: event.detail.value + }) + this.scheduleProductDraft() + }, + + handleShopChange(event) { + const shopIndex = Number(event.detail.value) + const selectedShop = this.data.shops[shopIndex] + this.setData({ + shopIndex, + shopLabel: selectedShop ? selectedShop.shopName : '', + 'form.shopId': selectedShop ? selectedShop.id : '' + }) + this.loadShopScopedOptions(selectedShop ? selectedShop.id : '') + this.scheduleProductDraft() + }, + + handleTagChange(event) { + this._selectedTagIds = event.detail.value || [] + this.setData({ + tags: this.data.tags.map(item => ({ + ...item, + checked: this._selectedTagIds.includes(item.valueId) + })) + }) + this.scheduleProductDraft() + }, + + handleArtistChange(event) { + this._selectedArtistIds = event.detail.value || [] + this.setData({ + artists: this.data.artists.map(item => ({ + ...item, + checked: this._selectedArtistIds.includes(item.valueId) + })) + }) + this.scheduleProductDraft() + }, + + handleCouponChange(event) { + this._selectedCouponIds = event.detail.value || [] + this.setData({ + coupons: this.data.coupons.map(item => ({ + ...item, + checked: this._selectedCouponIds.includes(item.valueId) + })) + }) + this.scheduleProductDraft() + }, + + async handleUploadImages() { + try { + const files = await upload.chooseImageFiles({ count: 9 }) + this.setData({ + uploading: true, + uploadProgress: 0 + }) + const result = await upload.uploadImageFiles({ + files, + scene: 'admin-product-image', + onProgress: progress => { + this.setData({ + uploadProgress: Math.round(progress) + }) + } + }) + + this.setData({ + 'form.imageFileIds': this.data.form.imageFileIds.concat(result.map(item => String(item.id))) + }) + this.scheduleProductDraft() + } catch (error) { + wx.showToast({ + title: error.message || '图片上传失败', + icon: 'none' + }) + } finally { + this.setData({ + uploading: false + }) + } + }, + + async handleSubmit() { + if (!this.data.form.title) { + wx.showToast({ + title: '请输入作品标题', + icon: 'none' + }) + return + } + if (!this.data.form.shopId) { + wx.showToast({ + title: '请选择所属店铺', + icon: 'none' + }) + return + } + if (!this.data.form.price) { + wx.showToast({ + title: '请输入作品价格', + icon: 'none' + }) + return + } + + const payload = { + shopId: this.data.form.shopId || undefined, + title: this.data.form.title, + description: this.data.form.description || undefined, + imageFileIds: this.data.form.imageFileIds.join(',') || undefined, + price: Number(this.data.form.price), + tags: this._selectedTagIds.join(',') || undefined, + likeCount: this.data.form.likeCount ? Number(this.data.form.likeCount) : undefined, + collectCount: this.data.form.collectCount ? Number(this.data.form.collectCount) : undefined, + approximateDuration: this.data.form.approximateDuration || undefined, + bookableArtists: this._selectedArtistIds.join(',') || undefined, + availableCoupons: this._selectedCouponIds.join(',') || undefined + } + + try { + if (this.data.mode === 'edit') { + await productApi.updateProduct(this.data.productId, payload) + } else { + await productApi.createProduct(payload) + } + clearDraft(DRAFT_KEY) + markDirty('admin-products') + wx.showToast({ + title: this.data.mode === 'edit' ? '作品已更新' : '作品已创建', + icon: 'none' + }) + navigation.goBack('/pages/products/index') + } catch (error) { + wx.showToast({ + title: error.message || '保存失败', + icon: 'none' + }) + } + } +}) diff --git a/YumiNail-Admin-Program/pages/product-form/index.json b/YumiNail-Admin-Program/pages/product-form/index.json new file mode 100644 index 00000000..8632c9b0 --- /dev/null +++ b/YumiNail-Admin-Program/pages/product-form/index.json @@ -0,0 +1,5 @@ +{ + "usingComponents": { + "navigation-bar": "/components/navigation-bar/navigation-bar" + } +} diff --git a/YumiNail-Admin-Program/pages/product-form/index.wxml b/YumiNail-Admin-Program/pages/product-form/index.wxml new file mode 100644 index 00000000..147b1644 --- /dev/null +++ b/YumiNail-Admin-Program/pages/product-form/index.wxml @@ -0,0 +1,92 @@ + + + + + + 作品信息 + + 作品标题 + + + + 所属店铺 + + {{shopLabel || '请选择店铺'}} + + + + 作品价格 + + + + 大约耗时 + + + + 作品描述 + + + + 点赞数量 + + + + 收藏数量 + + + + + 作品图片 + + 上传图片 + + + + {{item}} + + + + + + 绑定标签 + + + + + + + + + 可预约美甲师 + + + + + + + + + 可用优惠券 + + + + + + + + 图片上传中,当前进度 {{uploadProgress}}% + + + + + + diff --git a/YumiNail-Admin-Program/pages/product-form/index.wxss b/YumiNail-Admin-Program/pages/product-form/index.wxss new file mode 100644 index 00000000..e7250734 --- /dev/null +++ b/YumiNail-Admin-Program/pages/product-form/index.wxss @@ -0,0 +1,4 @@ +checkbox { + transform: scale(0.75); + margin-right: 8rpx; +} diff --git a/YumiNail-Admin-Program/pages/products/index.js b/YumiNail-Admin-Program/pages/products/index.js new file mode 100644 index 00000000..d5401687 --- /dev/null +++ b/YumiNail-Admin-Program/pages/products/index.js @@ -0,0 +1,128 @@ +const productApi = require('../../api/product') +const navigation = require('../../utils/navigation') +const format = require('../../utils/format') +const { setTempRecord, clearTempRecord } = require('../../utils/storage') +const { consumeDirty } = require('../../utils/page-state') + +const PAGE_KEY = 'admin-products' + +Page({ + data: { + keyword: '', + list: [], + loading: false, + canCreate: false, + initialized: false + }, + + onShow() { + if (!navigation.ensureLogin('进入作品管理')) { + return + } + + const permissionCodes = getApp().globalData.permissionCodes || [] + this.setData({ + canCreate: permissionCodes.includes('product:create') + }) + + if (!this.data.initialized || consumeDirty(PAGE_KEY)) { + this.loadProducts() + } + }, + + handleKeywordInput(event) { + this.setData({ + keyword: event.detail.value + }) + }, + + handleSearch() { + this.loadProducts() + }, + + async loadProducts() { + const requestId = (this._loadRequestId || 0) + 1 + this._loadRequestId = requestId + this.setData({ + loading: true + }) + + try { + const result = await productApi.listProducts({ + page: 1, + size: 20, + keyword: this.data.keyword || undefined + }) + if (requestId !== this._loadRequestId) { + return + } + + this.setData({ + list: (Array.isArray(result && result.list) ? result.list : []).map(item => ({ + ...item, + displayPrice: format.formatPrice(item.price), + displayShopName: item.shopName || '当前店铺', + displayDuration: item.approximateDuration || '未设置时长', + displayTagText: Array.isArray(item.tagList) ? item.tagList.join(' / ') : (item.tags || '未设置标签') + })), + initialized: true + }) + } catch (error) { + if (requestId !== this._loadRequestId) { + return + } + wx.showToast({ + title: error.message || '作品列表加载失败', + icon: 'none' + }) + } finally { + if (requestId === this._loadRequestId) { + this.setData({ + loading: false + }) + } + } + }, + + handleCreate() { + clearTempRecord('currentProduct') + navigation.navigate('/pages/product-form/index', { + mode: 'create' + }).catch(() => undefined) + }, + + handleEdit(event) { + const product = event.currentTarget.dataset.product + setTempRecord('currentProduct', product) + navigation.navigate('/pages/product-form/index', { + mode: 'edit', + id: product.id + }).catch(() => undefined) + }, + + handleDelete(event) { + const product = event.currentTarget.dataset.product + wx.showModal({ + title: '删除作品', + content: `确认删除作品“${product.title}”吗?`, + success: async result => { + if (!result.confirm) { + return + } + try { + await productApi.deleteProduct(product.id) + wx.showToast({ + title: '作品已删除', + icon: 'none' + }) + this.loadProducts() + } catch (error) { + wx.showToast({ + title: error.message || '作品删除失败', + icon: 'none' + }) + } + } + }) + } +}) diff --git a/YumiNail-Admin-Program/pages/products/index.json b/YumiNail-Admin-Program/pages/products/index.json new file mode 100644 index 00000000..8632c9b0 --- /dev/null +++ b/YumiNail-Admin-Program/pages/products/index.json @@ -0,0 +1,5 @@ +{ + "usingComponents": { + "navigation-bar": "/components/navigation-bar/navigation-bar" + } +} diff --git a/YumiNail-Admin-Program/pages/products/index.wxml b/YumiNail-Admin-Program/pages/products/index.wxml new file mode 100644 index 00000000..5c72da57 --- /dev/null +++ b/YumiNail-Admin-Program/pages/products/index.wxml @@ -0,0 +1,50 @@ + + + + + + 作品列表 + + + + + + + + + + + {{item.title}} + {{item.displayShopName}} · {{item.displayDuration}} + + ¥{{item.displayPrice}} + + + + 标签 + {{item.displayTagText}} + + + 点赞 / 收藏 + {{item.likeCount || 0}} / {{item.collectCount || 0}} + + + + 编辑 + 删除 + + + + + + 正在加载作品列表 + + + + 还没有作品 + 先上传图片、绑定标签和美甲师后,就可以把完整作品发布到门店里。 + + + + + + diff --git a/YumiNail-Admin-Program/pages/products/index.wxss b/YumiNail-Admin-Program/pages/products/index.wxss new file mode 100644 index 00000000..09b20ffe --- /dev/null +++ b/YumiNail-Admin-Program/pages/products/index.wxss @@ -0,0 +1,3 @@ +.page-shell { + background: transparent; +} diff --git a/YumiNail-Admin-Program/pages/profile/index.js b/YumiNail-Admin-Program/pages/profile/index.js new file mode 100644 index 00000000..972c12c7 --- /dev/null +++ b/YumiNail-Admin-Program/pages/profile/index.js @@ -0,0 +1,118 @@ +const authApi = require('../../api/auth') +const navigation = require('../../utils/navigation') +const permission = require('../../utils/permission') + +Page({ + data: { + userInfo: null, + currentShop: null, + permissionCodes: [], + roleLabel: '', + shopScopeText: '', + currentShopText: '' + }, + + onShow() { + if (!navigation.ensureLogin('进入个人中心')) { + return + } + + const app = getApp() + const userInfo = app.globalData.userInfo + const currentShop = app.globalData.currentShop + const shopScopeText = userInfo + ? (Array.isArray(userInfo.shopNames) && userInfo.shopNames.length + ? userInfo.shopNames.join(' / ') + : (userInfo.shopName || '--')) + : '--' + + this.setData({ + userInfo, + currentShop, + permissionCodes: app.globalData.permissionCodes || [], + roleLabel: userInfo ? permission.getRoleLabel(userInfo.type) : '--', + shopScopeText, + currentShopText: currentShop ? `当前店铺:${currentShop.shopName}` : '当前为无店铺登录' + }) + }, + + handleOpenOrders() { + navigation.switchTab('/pages/orders/index').catch(() => undefined) + }, + + handleOpenManage() { + navigation.switchTab('/pages/manage/index').catch(() => undefined) + }, + + async handleSwitchShop() { + const userInfo = this.data.userInfo + if (!userInfo || !userInfo.account) { + return + } + + try { + const result = await authApi.getLoginShops(userInfo.account) + const shops = Array.isArray(result && result.shops) ? result.shops : [] + const allowShoplessLogin = Boolean(result && result.allowShoplessLogin) + const items = shops.map(shop => ({ + label: shop.shopName, + value: shop.id + })) + + if (allowShoplessLogin && permission.isPlatformAdmin(userInfo)) { + items.unshift({ + label: '无店铺登录', + value: '' + }) + } + + if (!items.length) { + wx.showToast({ + title: '当前账号没有可切换的店铺', + icon: 'none' + }) + return + } + + wx.showActionSheet({ + itemList: items.map(item => item.label), + success: async action => { + const target = items[action.tapIndex] + if (!target) { + return + } + + try { + await getApp().switchAdminShop(target.value || undefined) + wx.showToast({ + title: '店铺已切换', + icon: 'none' + }) + this.onShow() + } catch (error) { + wx.showToast({ + title: error.message || '切换店铺失败', + icon: 'none' + }) + } + } + }) + } catch (error) { + wx.showToast({ + title: error.message || '店铺列表加载失败', + icon: 'none' + }) + } + }, + + async handleLogout() { + try { + await authApi.logout().catch(() => undefined) + } finally { + getApp().clearAdminSession() + wx.reLaunch({ + url: '/pages/login/index' + }) + } + } +}) diff --git a/YumiNail-Admin-Program/pages/profile/index.json b/YumiNail-Admin-Program/pages/profile/index.json new file mode 100644 index 00000000..8632c9b0 --- /dev/null +++ b/YumiNail-Admin-Program/pages/profile/index.json @@ -0,0 +1,5 @@ +{ + "usingComponents": { + "navigation-bar": "/components/navigation-bar/navigation-bar" + } +} diff --git a/YumiNail-Admin-Program/pages/profile/index.wxml b/YumiNail-Admin-Program/pages/profile/index.wxml new file mode 100644 index 00000000..993b8275 --- /dev/null +++ b/YumiNail-Admin-Program/pages/profile/index.wxml @@ -0,0 +1,52 @@ + + + + + + {{userInfo.account || '后台账号'}} + {{userInfo.nickname || '未设置昵称'}} + 当前角色:{{roleLabel}}。{{currentShopText}} + + + + 账号信息 + + + 账号 + {{userInfo.account || '--'}} + + + 权限数 + {{permissionCodes.length}} + + + 店铺状态 + {{currentShop ? currentShop.shopName : '无店铺登录'}} + + + 可登录店铺 + {{shopScopeText}} + + + + + + + + + 常用入口 + + 查看订单 + 经营模块 + + + + + 退出登录 + 退出后会清理管理端会话、当前店铺和权限快照;再次进入需要重新登录。 + + + + + + diff --git a/YumiNail-Admin-Program/pages/profile/index.wxss b/YumiNail-Admin-Program/pages/profile/index.wxss new file mode 100644 index 00000000..09b20ffe --- /dev/null +++ b/YumiNail-Admin-Program/pages/profile/index.wxss @@ -0,0 +1,3 @@ +.page-shell { + background: transparent; +} diff --git a/YumiNail-Admin-Program/pages/shop-form/index.js b/YumiNail-Admin-Program/pages/shop-form/index.js new file mode 100644 index 00000000..0114bb33 --- /dev/null +++ b/YumiNail-Admin-Program/pages/shop-form/index.js @@ -0,0 +1,183 @@ +const shopApi = require('../../api/shop') +const navigation = require('../../utils/navigation') +const upload = require('../../utils/upload') +const { getTempRecord, clearTempRecord } = require('../../utils/storage') +const { getDraftValue, clearDraft, scheduleDraftSave, clearDraftTimer } = require('../../utils/form-draft') +const { markDirty } = require('../../utils/page-state') + +const DRAFT_KEY = 'admin-shop-form' + +Page({ + data: { + mode: 'create', + shopId: '', + uploading: false, + uploadProgress: 0, + statusOptions: ['启用', '停用'], + statusIndex: 0, + form: { + shopName: '', + description: '', + address: '', + businessHours: '', + coverImageFileId: '', + imageFileIds: [] + } + }, + + onLoad(options) { + const mode = options && options.mode ? options.mode : 'create' + const currentShop = getTempRecord('currentShopRecord', null) + const draft = getDraftValue(DRAFT_KEY, null) + + this.setData({ + mode, + shopId: options && options.id ? options.id : '' + }) + + if (mode === 'edit' && currentShop) { + this.setData({ + form: { + shopName: currentShop.shopName || '', + description: currentShop.description || '', + address: currentShop.address || '', + businessHours: currentShop.businessHours || '', + coverImageFileId: currentShop.coverImageFileId || '', + imageFileIds: currentShop.imageFileIds ? String(currentShop.imageFileIds).split(',').filter(Boolean) : [] + }, + statusIndex: Number(currentShop.status) === 0 ? 1 : 0 + }) + } + + if (draft && draft.mode === mode) { + this.setData({ + form: { + ...this.data.form, + ...draft.form + }, + statusIndex: draft.statusIndex === 1 ? 1 : this.data.statusIndex + }) + } + }, + + onUnload() { + clearTempRecord('currentShopRecord') + clearDraftTimer(this) + }, + + scheduleShopDraft() { + scheduleDraftSave(this, DRAFT_KEY, () => ({ + mode: this.data.mode, + statusIndex: this.data.statusIndex, + form: { + ...this.data.form, + imageFileIds: this.data.form.imageFileIds.slice() + } + })) + }, + + handleInputChange(event) { + const field = event.currentTarget.dataset.field + this.setData({ + [`form.${field}`]: event.detail.value + }) + this.scheduleShopDraft() + }, + + handleStatusChange(event) { + this.setData({ + statusIndex: Number(event.detail.value) + }) + this.scheduleShopDraft() + }, + + async handleUploadBanner() { + await this.handleUpload('admin-shop-banner', true) + }, + + async handleUploadImages() { + await this.handleUpload('admin-shop-image', false) + }, + + async handleUpload(scene, isBanner) { + try { + const files = await upload.chooseImageFiles({ + count: isBanner ? 1 : 9 + }) + this.setData({ + uploading: true, + uploadProgress: 0 + }) + const results = await upload.uploadImageFiles({ + files, + scene, + onProgress: progress => { + this.setData({ + uploadProgress: Math.round(progress) + }) + } + }) + + if (isBanner) { + this.setData({ + 'form.coverImageFileId': results[0] ? String(results[0].id) : '' + }) + } else { + this.setData({ + 'form.imageFileIds': this.data.form.imageFileIds.concat(results.map(item => String(item.id))) + }) + } + this.scheduleShopDraft() + } catch (error) { + wx.showToast({ + title: error.message || '图片上传失败', + icon: 'none' + }) + } finally { + this.setData({ + uploading: false + }) + } + }, + + async handleSubmit() { + if (!this.data.form.shopName) { + wx.showToast({ + title: '请输入店铺名称', + icon: 'none' + }) + return + } + + const payload = { + shopName: this.data.form.shopName, + description: this.data.form.description || undefined, + address: this.data.form.address || undefined, + businessHours: this.data.form.businessHours || undefined, + coverImageFileId: this.data.form.coverImageFileId || undefined, + imageFileIds: this.data.form.imageFileIds.join(',') || undefined, + status: this.data.statusIndex === 1 ? 0 : 1 + } + + try { + if (this.data.mode === 'edit') { + await shopApi.updateShop(this.data.shopId, payload) + } else { + await shopApi.createShop(payload) + } + clearDraft(DRAFT_KEY) + markDirty('admin-shops') + markDirty('admin-workbench') + wx.showToast({ + title: this.data.mode === 'edit' ? '店铺已更新' : '店铺已创建', + icon: 'none' + }) + navigation.goBack('/pages/shops/index') + } catch (error) { + wx.showToast({ + title: error.message || '保存失败', + icon: 'none' + }) + } + } +}) diff --git a/YumiNail-Admin-Program/pages/shop-form/index.json b/YumiNail-Admin-Program/pages/shop-form/index.json new file mode 100644 index 00000000..8632c9b0 --- /dev/null +++ b/YumiNail-Admin-Program/pages/shop-form/index.json @@ -0,0 +1,5 @@ +{ + "usingComponents": { + "navigation-bar": "/components/navigation-bar/navigation-bar" + } +} diff --git a/YumiNail-Admin-Program/pages/shop-form/index.wxml b/YumiNail-Admin-Program/pages/shop-form/index.wxml new file mode 100644 index 00000000..4a568352 --- /dev/null +++ b/YumiNail-Admin-Program/pages/shop-form/index.wxml @@ -0,0 +1,55 @@ + + + + + + 店铺信息 + + 店铺名称 + + + + 店铺地址 + + + + 营业时间 + + + + 店铺描述 + + + + 状态 + + {{statusOptions[statusIndex]}} + + + + Banner 图 + + 上传 Banner + + + {{form.coverImageFileId}} + + + + 店铺图片 + + 上传图片 + + + + {{item}} + + + + 图片上传中,当前进度 {{uploadProgress}}% + + + + + + diff --git a/YumiNail-Admin-Program/pages/shop-form/index.wxss b/YumiNail-Admin-Program/pages/shop-form/index.wxss new file mode 100644 index 00000000..09b20ffe --- /dev/null +++ b/YumiNail-Admin-Program/pages/shop-form/index.wxss @@ -0,0 +1,3 @@ +.page-shell { + background: transparent; +} diff --git a/YumiNail-Admin-Program/pages/shops/index.js b/YumiNail-Admin-Program/pages/shops/index.js new file mode 100644 index 00000000..f866ecf6 --- /dev/null +++ b/YumiNail-Admin-Program/pages/shops/index.js @@ -0,0 +1,141 @@ +const shopApi = require('../../api/shop') +const navigation = require('../../utils/navigation') +const { setTempRecord, clearTempRecord } = require('../../utils/storage') +const { consumeDirty } = require('../../utils/page-state') + +Page({ + data: { + keyword: '', + list: [], + loading: false, + canCreate: false, + initialized: false + }, + + onShow() { + if (!navigation.ensureLogin('进入店铺管理')) { + return + } + + const permissionCodes = getApp().globalData.permissionCodes || [] + this.setData({ + canCreate: permissionCodes.includes('shop:create') + }) + + if (!this.data.initialized || consumeDirty('admin-shops')) { + this.loadShops() + } + }, + + handleKeywordInput(event) { + this.setData({ + keyword: event.detail.value + }) + }, + + handleSearch() { + this.loadShops() + }, + + async loadShops() { + const requestId = (this._loadRequestId || 0) + 1 + this._loadRequestId = requestId + this.setData({ + loading: true + }) + + try { + const result = await shopApi.listShops({ + page: 1, + size: 20, + keyword: this.data.keyword || undefined + }) + if (requestId !== this._loadRequestId) { + return + } + + this.setData({ + list: (Array.isArray(result && result.list) ? result.list : []).map(item => ({ + ...item, + displayStatusText: Number(item.status) === 0 ? '已停用' : '启用中' + })), + initialized: true + }) + } catch (error) { + if (requestId !== this._loadRequestId) { + return + } + wx.showToast({ + title: error.message || '店铺加载失败', + icon: 'none' + }) + } finally { + if (requestId === this._loadRequestId) { + this.setData({ + loading: false + }) + } + } + }, + + handleCreate() { + clearTempRecord('currentShopRecord') + navigation.navigate('/pages/shop-form/index', { + mode: 'create' + }).catch(() => undefined) + }, + + handleEdit(event) { + const shop = event.currentTarget.dataset.shop + setTempRecord('currentShopRecord', shop) + navigation.navigate('/pages/shop-form/index', { + mode: 'edit', + id: shop.id + }).catch(() => undefined) + }, + + handleStatus(event) { + const shop = event.currentTarget.dataset.shop + const nextStatus = Number(shop.status) === 0 ? 1 : 0 + shopApi.updateShopStatus(shop.id, nextStatus) + .then(() => { + wx.showToast({ + title: '店铺状态已更新', + icon: 'none' + }) + this.loadShops() + }) + .catch(error => { + wx.showToast({ + title: error.message || '状态更新失败', + icon: 'none' + }) + }) + }, + + handleDelete(event) { + const shop = event.currentTarget.dataset.shop + wx.showModal({ + title: '删除店铺', + content: `确认删除店铺“${shop.shopName}”吗?该操作会联动清理店铺下资源。`, + success: async result => { + if (!result.confirm) { + return + } + try { + await shopApi.deleteShop(shop.id) + wx.showToast({ + title: '店铺已删除', + icon: 'none' + }) + this.loadShops() + } catch (error) { + wx.showToast({ + title: error.message || '店铺删除失败', + icon: 'none' + }) + } + } + }) + } +}) diff --git a/YumiNail-Admin-Program/pages/shops/index.json b/YumiNail-Admin-Program/pages/shops/index.json new file mode 100644 index 00000000..8632c9b0 --- /dev/null +++ b/YumiNail-Admin-Program/pages/shops/index.json @@ -0,0 +1,5 @@ +{ + "usingComponents": { + "navigation-bar": "/components/navigation-bar/navigation-bar" + } +} diff --git a/YumiNail-Admin-Program/pages/shops/index.wxml b/YumiNail-Admin-Program/pages/shops/index.wxml new file mode 100644 index 00000000..f2d235e6 --- /dev/null +++ b/YumiNail-Admin-Program/pages/shops/index.wxml @@ -0,0 +1,51 @@ + + + + + + 店铺列表 + + + + + + + + + + + {{item.shopName}} + {{item.address || '暂无地址'}} + + {{item.displayStatusText}} + + + + 营业时间 + {{item.businessHours || '--'}} + + + 描述 + {{item.description || '暂无描述'}} + + + + 编辑 + {{item.status === 0 ? '启用' : '停用'}} + 删除 + + + + + + 正在加载店铺列表 + + + + 暂无店铺 + 如果这是首次部署后的无店铺管理员登录,可以直接在这里创建第一家店铺。 + + + + + + diff --git a/YumiNail-Admin-Program/pages/shops/index.wxss b/YumiNail-Admin-Program/pages/shops/index.wxss new file mode 100644 index 00000000..09b20ffe --- /dev/null +++ b/YumiNail-Admin-Program/pages/shops/index.wxss @@ -0,0 +1,3 @@ +.page-shell { + background: transparent; +} diff --git a/YumiNail-Admin-Program/pages/tag-form/index.js b/YumiNail-Admin-Program/pages/tag-form/index.js new file mode 100644 index 00000000..be33cb27 --- /dev/null +++ b/YumiNail-Admin-Program/pages/tag-form/index.js @@ -0,0 +1,139 @@ +const tagApi = require('../../api/tag') +const shopApi = require('../../api/shop') +const navigation = require('../../utils/navigation') +const { getTempRecord, clearTempRecord } = require('../../utils/storage') + +Page({ + data: { + mode: 'create', + tagId: '', + shops: [], + shopIndex: -1, + shopLabel: '', + form: { + tagName: '', + textColor: '#2b2b2b', + bgColor: '#f6e5df', + borderColor: '#ef9a79' + } + }, + + onLoad(options) { + const mode = options && options.mode ? options.mode : 'create' + const currentTag = getTempRecord('currentTag', null) + this.setData({ + mode, + tagId: options && options.id ? options.id : '' + }) + + if (mode === 'edit' && currentTag) { + this.setData({ + form: { + tagName: currentTag.tagName || '', + textColor: currentTag.textColor || '#2b2b2b', + bgColor: currentTag.bgColor || '#f6e5df', + borderColor: currentTag.borderColor || '#ef9a79' + } + }) + this._initialShopId = currentTag.shopId + } + + this.loadShops() + }, + + onUnload() { + clearTempRecord('currentTag') + }, + + async loadShops() { + const app = getApp() + const operator = app.globalData.userInfo || {} + const currentShop = app.globalData.currentShop + + try { + const list = await shopApi.listAllShops() + let shops = Array.isArray(list) ? list : [] + + if (Number(operator.type) !== 4 && currentShop) { + shops = shops.filter(item => String(item.id) === String(currentShop.id)) + } + + let shopIndex = 0 + if (this._initialShopId) { + const targetIndex = shops.findIndex(item => String(item.id) === String(this._initialShopId)) + if (targetIndex >= 0) { + shopIndex = targetIndex + } + } + + const selectedShop = shops[shopIndex] + this.setData({ + shops, + shopIndex, + shopLabel: selectedShop ? selectedShop.shopName : '' + }) + } catch (error) { + wx.showToast({ + title: error.message || '初始化标签页面失败', + icon: 'none' + }) + } + }, + + handleInputChange(event) { + const field = event.currentTarget.dataset.field + this.setData({ + [`form.${field}`]: event.detail.value + }) + }, + + handleShopChange(event) { + const shopIndex = Number(event.detail.value) + const selectedShop = this.data.shops[shopIndex] + this.setData({ + shopIndex, + shopLabel: selectedShop ? selectedShop.shopName : '' + }) + }, + + async handleSubmit() { + const selectedShop = this.data.shops[this.data.shopIndex] + if (!this.data.form.tagName) { + wx.showToast({ + title: '请输入标签名称', + icon: 'none' + }) + return + } + if (!selectedShop) { + wx.showToast({ + title: '请选择所属店铺', + icon: 'none' + }) + return + } + + const payload = { + ...this.data.form, + shopId: selectedShop.id + } + + try { + if (this.data.mode === 'edit') { + await tagApi.updateTag(this.data.tagId, payload) + } else { + await tagApi.createTag(payload) + } + wx.showToast({ + title: this.data.mode === 'edit' ? '标签已更新' : '标签已创建', + icon: 'none' + }) + navigation.goBack('/pages/tags/index') + } catch (error) { + wx.showToast({ + title: error.message || '保存失败', + icon: 'none' + }) + } + } +}) diff --git a/YumiNail-Admin-Program/pages/tag-form/index.json b/YumiNail-Admin-Program/pages/tag-form/index.json new file mode 100644 index 00000000..8632c9b0 --- /dev/null +++ b/YumiNail-Admin-Program/pages/tag-form/index.json @@ -0,0 +1,5 @@ +{ + "usingComponents": { + "navigation-bar": "/components/navigation-bar/navigation-bar" + } +} diff --git a/YumiNail-Admin-Program/pages/tag-form/index.wxml b/YumiNail-Admin-Program/pages/tag-form/index.wxml new file mode 100644 index 00000000..78c8e223 --- /dev/null +++ b/YumiNail-Admin-Program/pages/tag-form/index.wxml @@ -0,0 +1,34 @@ + + + + + + 标签信息 + + 标签名称 + + + + 所属店铺 + + {{shopLabel || '请选择店铺'}} + + + + 文字颜色 + + + + 背景颜色 + + + + 边框颜色 + + + + + + + + diff --git a/YumiNail-Admin-Program/pages/tag-form/index.wxss b/YumiNail-Admin-Program/pages/tag-form/index.wxss new file mode 100644 index 00000000..09b20ffe --- /dev/null +++ b/YumiNail-Admin-Program/pages/tag-form/index.wxss @@ -0,0 +1,3 @@ +.page-shell { + background: transparent; +} diff --git a/YumiNail-Admin-Program/pages/tags/index.js b/YumiNail-Admin-Program/pages/tags/index.js new file mode 100644 index 00000000..bf702a89 --- /dev/null +++ b/YumiNail-Admin-Program/pages/tags/index.js @@ -0,0 +1,75 @@ +const tagApi = require('../../api/tag') +const navigation = require('../../utils/navigation') +const { setTempRecord, clearTempRecord } = require('../../utils/storage') + +Page({ + data: { + list: [] + }, + + onShow() { + if (!navigation.ensureLogin('进入标签管理')) { + return + } + this.loadTags() + }, + + async loadTags() { + try { + const list = await tagApi.listAllTags() + this.setData({ + list: (Array.isArray(list) ? list : []).map(item => ({ + ...item, + displayShopName: item.shopName || '当前店铺' + })) + }) + } catch (error) { + wx.showToast({ + title: error.message || '标签加载失败', + icon: 'none' + }) + } + }, + + handleCreate() { + clearTempRecord('currentTag') + navigation.navigate('/pages/tag-form/index', { + mode: 'create' + }).catch(() => undefined) + }, + + handleEdit(event) { + const tag = event.currentTarget.dataset.tag + setTempRecord('currentTag', tag) + navigation.navigate('/pages/tag-form/index', { + mode: 'edit', + id: tag.id + }).catch(() => undefined) + }, + + handleDelete(event) { + const tag = event.currentTarget.dataset.tag + wx.showModal({ + title: '删除标签', + content: `确认删除标签“${tag.tagName}”吗?`, + success: async result => { + if (!result.confirm) { + return + } + try { + await tagApi.deleteTag(tag.id) + wx.showToast({ + title: '标签已删除', + icon: 'none' + }) + this.loadTags() + } catch (error) { + wx.showToast({ + title: error.message || '标签删除失败', + icon: 'none' + }) + } + } + }) + } +}) diff --git a/YumiNail-Admin-Program/pages/tags/index.json b/YumiNail-Admin-Program/pages/tags/index.json new file mode 100644 index 00000000..8632c9b0 --- /dev/null +++ b/YumiNail-Admin-Program/pages/tags/index.json @@ -0,0 +1,5 @@ +{ + "usingComponents": { + "navigation-bar": "/components/navigation-bar/navigation-bar" + } +} diff --git a/YumiNail-Admin-Program/pages/tags/index.wxml b/YumiNail-Admin-Program/pages/tags/index.wxml new file mode 100644 index 00000000..cc4939af --- /dev/null +++ b/YumiNail-Admin-Program/pages/tags/index.wxml @@ -0,0 +1,38 @@ + + + + + + 标签列表 + 标签按店铺绑定,同名标签可以在不同店铺重复存在,适合移动端用卡片方式快速维护。 + + + + + + + {{item.tagName}} + {{item.displayShopName}} + + 颜色标签 + + + {{item.textColor || '#333333'}} + {{item.bgColor || '#f5f5f5'}} + {{item.borderColor || '#dddddd'}} + + + 编辑 + 删除 + + + + + + 还没有标签 + 先创建一组标签,后续作品和优惠券表单就可以直接复用它们。 + + + + + + diff --git a/YumiNail-Admin-Program/pages/tags/index.wxss b/YumiNail-Admin-Program/pages/tags/index.wxss new file mode 100644 index 00000000..09b20ffe --- /dev/null +++ b/YumiNail-Admin-Program/pages/tags/index.wxss @@ -0,0 +1,3 @@ +.page-shell { + background: transparent; +} diff --git a/YumiNail-Admin-Program/pages/user-detail/index.js b/YumiNail-Admin-Program/pages/user-detail/index.js new file mode 100644 index 00000000..d809f579 --- /dev/null +++ b/YumiNail-Admin-Program/pages/user-detail/index.js @@ -0,0 +1,284 @@ +const userApi = require('../../api/user') +const navigation = require('../../utils/navigation') +const format = require('../../utils/format') +const { getTempRecord, clearTempRecord, setTempRecord } = require('../../utils/storage') + +const CHANGE_SCENE_OPTIONS = ['MANUAL_RECHARGE', 'MANUAL_INCREASE', 'MANUAL_DEDUCT'] +const VIP_LEVEL_OPTIONS = ['普通', '青铜', '白银', '黄金'] + +Page({ + data: { + user: null, + asset: null, + balanceHistory: [], + changeSceneIndex: 0, + vipLevelIndex: 0, + balanceForm: { + amount: '', + externalOrderNo: '', + remark: '' + }, + vipRemark: '' + }, + + onLoad(options) { + const cached = getTempRecord('currentUser', null) + if (cached && (!options || !options.id || String(cached.id) === String(options.id))) { + this.setUser(cached) + } + }, + + onShow() { + if (!navigation.ensureLogin('进入用户详情')) { + return + } + this.loadAssetData() + }, + + onUnload() { + clearTempRecord('currentUser') + }, + + async loadAssetData() { + if (!this.data.user) { + return + } + + try { + const [asset, balanceHistory] = await Promise.all([ + userApi.getUserAsset(this.data.user.id).catch(() => null), + userApi.getUserBalanceHistory(this.data.user.id).catch(() => []) + ]) + + this.setData({ + asset, + balanceHistory: (Array.isArray(balanceHistory) ? balanceHistory : []).map(item => ({ + ...item, + displayChangeTime: format.formatDateTime(item.changeTime), + amountBadgeClass: Number(item.amount) >= 0 ? 'success-badge' : 'danger-badge' + })) + }) + } catch (error) { + wx.showToast({ + title: error.message || '用户资产数据加载失败', + icon: 'none' + }) + } + }, + + handleEdit() { + setTempRecord('currentUser', this.data.user) + navigation.navigate('/pages/user-form/index', { + mode: 'edit', + id: this.data.user.id + }).catch(() => undefined) + }, + + handlePermissionAssign() { + setTempRecord('currentUser', this.data.user) + navigation.navigate('/pages/permission-form/index', { + mode: 'assign', + userId: this.data.user.id + }).catch(() => undefined) + }, + + handleBalanceInput(event) { + const field = event.currentTarget.dataset.field + this.setData({ + [`balanceForm.${field}`]: event.detail.value + }) + }, + + handleVipRemarkInput(event) { + this.setData({ + vipRemark: event.detail.value + }) + }, + + handleSceneChange(event) { + this.setData({ + changeSceneIndex: Number(event.detail.value) + }) + }, + + handleVipLevelChange(event) { + this.setData({ + vipLevelIndex: Number(event.detail.value) + }) + }, + + async handleBalanceChange() { + try { + await userApi.changeUserBalance(this.data.user.id, { + amount: Number(this.data.balanceForm.amount), + changeScene: CHANGE_SCENE_OPTIONS[this.data.changeSceneIndex], + externalOrderNo: this.data.balanceForm.externalOrderNo || undefined, + remark: this.data.balanceForm.remark || undefined + }) + wx.showToast({ + title: '余额已调整', + icon: 'none' + }) + this.setData({ + balanceForm: { + amount: '', + externalOrderNo: '', + remark: '' + } + }) + this.loadAssetData() + } catch (error) { + wx.showToast({ + title: error.message || '余额调整失败', + icon: 'none' + }) + } + }, + + async handleVipOverride() { + try { + await userApi.overrideUserVip(this.data.user.id, { + vipLevel: VIP_LEVEL_OPTIONS[this.data.vipLevelIndex], + remark: this.data.vipRemark || undefined + }) + wx.showToast({ + title: 'VIP 等级已更新', + icon: 'none' + }) + this.loadAssetData() + } catch (error) { + wx.showToast({ + title: error.message || 'VIP 更新失败', + icon: 'none' + }) + } + }, + + async handleVipRecalculate() { + try { + await userApi.recalculateUserVip(this.data.user.id) + wx.showToast({ + title: '已恢复自动判级', + icon: 'none' + }) + this.loadAssetData() + } catch (error) { + wx.showToast({ + title: error.message || 'VIP 重算失败', + icon: 'none' + }) + } + }, + + async handleResetPassword() { + try { + await userApi.resetPassword(this.data.user.id) + wx.showToast({ + title: '密码已重置', + icon: 'none' + }) + } catch (error) { + wx.showToast({ + title: error.message || '密码重置失败', + icon: 'none' + }) + } + }, + + handleUserAction(event) { + const action = event.currentTarget.dataset.action + if (action === 'disable') { + this.updateUserStatus(this.data.user.status === 0 ? 1 : 0) + return + } + if (action === 'delete') { + this.confirmDelete() + return + } + if (action === 'unbind') { + this.confirmUnbind() + } + }, + + async updateUserStatus(status) { + try { + await userApi.updateUserStatus(this.data.user.id, status) + wx.showToast({ + title: '用户状态已更新', + icon: 'none' + }) + const user = { + ...this.data.user, + status + } + this.setUser(user) + setTempRecord('currentUser', user) + } catch (error) { + wx.showToast({ + title: error.message || '状态更新失败', + icon: 'none' + }) + } + }, + + confirmDelete() { + wx.showModal({ + title: '确认删除', + content: '删除后该账号将不再出现在前端可见列表中,确认继续吗?', + success: async result => { + if (!result.confirm) { + return + } + try { + await userApi.deleteUser(this.data.user.id) + wx.showToast({ + title: '用户已删除', + icon: 'none' + }) + navigation.goBack('/pages/users/index') + } catch (error) { + wx.showToast({ + title: error.message || '删除失败', + icon: 'none' + }) + } + } + }) + }, + + confirmUnbind() { + wx.showModal({ + title: '确认解绑', + content: '解绑后,该用户将无法登录当前店铺,确认继续吗?', + success: async result => { + if (!result.confirm) { + return + } + try { + await userApi.unbindUser(this.data.user.id) + wx.showToast({ + title: '已解除当前店铺绑定', + icon: 'none' + }) + } catch (error) { + wx.showToast({ + title: error.message || '解绑失败', + icon: 'none' + }) + } + } + }) + }, + + setUser(user) { + this.setData({ + user: user ? { + ...user, + displayTypeText: format.getUserTypeText(user.type), + displayShopName: format.buildShopName(user), + displayStatusText: format.getUserStatusText(user.status), + displayCreateTime: format.formatDateTime(user.createTime) + } : null + }) + } +}) diff --git a/YumiNail-Admin-Program/pages/user-detail/index.json b/YumiNail-Admin-Program/pages/user-detail/index.json new file mode 100644 index 00000000..8632c9b0 --- /dev/null +++ b/YumiNail-Admin-Program/pages/user-detail/index.json @@ -0,0 +1,5 @@ +{ + "usingComponents": { + "navigation-bar": "/components/navigation-bar/navigation-bar" + } +} diff --git a/YumiNail-Admin-Program/pages/user-detail/index.wxml b/YumiNail-Admin-Program/pages/user-detail/index.wxml new file mode 100644 index 00000000..549fa9a4 --- /dev/null +++ b/YumiNail-Admin-Program/pages/user-detail/index.wxml @@ -0,0 +1,128 @@ + + + + + + {{user.nickname || user.account}} + {{user.displayTypeText}} · {{user.displayShopName}} · {{user.displayStatusText}} + + + 账号 + {{user.account}} + + + 手机号 + {{user.phone || '--'}} + + + 签名 + {{user.signature || '暂无签名'}} + + + 创建时间 + {{user.displayCreateTime}} + + + + 编辑资料 + 分配权限 + 重置密码 + + + {{user.status === 0 ? '恢复启用' : '停用账号'}} + 解绑当前店铺 + 删除账号 + + + + + 余额与 VIP + + + 当前余额 + ¥{{asset.balance}} + + + 累计充值 + ¥{{asset.totalRechargeAmount}} + + + VIP 等级 + {{asset.vipLevel || '普通'}} + + + 人工覆盖 + {{asset.manualOverride ? '是' : '否'}} + + + + + + 余额调整 + + 金额(可填负数) + + + + 变动场景 + + {{['MANUAL_RECHARGE','MANUAL_INCREASE','MANUAL_DEDUCT'][changeSceneIndex]}} + + + + 外部单号 + + + + 备注 + + + + + + + + + VIP 管理 + + 手工等级 + + {{['普通','青铜','白银','黄金'][vipLevelIndex]}} + + + + 备注 + + + + + + + + + + 余额流水 + + + + + {{item.changeScene || item.type || '余额变动'}} + {{item.remark || '无备注'}} + + {{item.amount}} + + + + 变动后余额 + {{item.afterBalance || item.currentBalance || '--'}} + + + 变动时间 + {{item.displayChangeTime}} + + + + + + + diff --git a/YumiNail-Admin-Program/pages/user-detail/index.wxss b/YumiNail-Admin-Program/pages/user-detail/index.wxss new file mode 100644 index 00000000..09b20ffe --- /dev/null +++ b/YumiNail-Admin-Program/pages/user-detail/index.wxss @@ -0,0 +1,3 @@ +.page-shell { + background: transparent; +} diff --git a/YumiNail-Admin-Program/pages/user-form/index.js b/YumiNail-Admin-Program/pages/user-form/index.js new file mode 100644 index 00000000..276e6565 --- /dev/null +++ b/YumiNail-Admin-Program/pages/user-form/index.js @@ -0,0 +1,256 @@ +const userApi = require('../../api/user') +const shopApi = require('../../api/shop') +const navigation = require('../../utils/navigation') +const cache = require('../../utils/cache') +const { getTempRecord, clearTempRecord } = require('../../utils/storage') +const { getDraftValue, clearDraft, scheduleDraftSave, clearDraftTimer } = require('../../utils/form-draft') +const { markDirty } = require('../../utils/page-state') +const { CACHE_TTL } = require('../../utils/config') + +const ACCOUNT_REGEX = /[^A-Za-z0-9]/g +const PHONE_REGEX = /[^\d]/g +const DRAFT_KEY = 'admin-user-form' +const TYPE_OPTIONS = [ + { label: '普通用户', value: 0 }, + { label: '店长', value: 2 }, + { label: '美甲师', value: 3 }, + { label: '平台管理员', value: 4 } +] + +function normalizeId(value) { + return value === undefined || value === null ? '' : String(value) +} + +Page({ + data: { + mode: 'create', + userId: '', + typeOptions: TYPE_OPTIONS, + currentTypeLabel: TYPE_OPTIONS[0].label, + shops: [], + selectedShopIds: [], + form: { + nickname: '', + account: '', + phone: '', + password: '', + signature: '', + type: 0 + } + }, + + onLoad(options) { + const mode = options && options.mode ? options.mode : 'create' + const currentUser = getTempRecord('currentUser', null) + const draft = getDraftValue(DRAFT_KEY, null) + const app = getApp() + const operator = app.globalData.userInfo || {} + + let availableTypes = TYPE_OPTIONS + if (Number(operator.type) === 2) { + availableTypes = TYPE_OPTIONS.filter(item => item.value === 0 || item.value === 3) + } + + const baseState = { + mode, + userId: options && options.id ? options.id : '', + typeOptions: availableTypes, + currentTypeLabel: availableTypes[0] ? availableTypes[0].label : '' + } + + if (mode === 'edit' && currentUser) { + baseState.form = { + nickname: currentUser.nickname || '', + account: currentUser.account || '', + phone: currentUser.phone || '', + password: '', + signature: currentUser.signature || '', + type: Number(currentUser.type || 0) + } + baseState.selectedShopIds = Array.isArray(currentUser.shopIds) ? currentUser.shopIds.map(item => String(item)) : [] + } + + this.setData(baseState) + + if (draft && draft.mode === mode) { + this.setData({ + form: { + ...this.data.form, + ...draft.form, + password: '' + }, + selectedShopIds: Array.isArray(draft.selectedShopIds) ? draft.selectedShopIds : this.data.selectedShopIds + }) + } + + this.syncTypeLabel(Number(this.data.form.type || 0)) + this.loadShops() + }, + + onUnload() { + clearTempRecord('currentUser') + clearDraftTimer(this) + }, + + scheduleUserDraft() { + scheduleDraftSave(this, DRAFT_KEY, () => ({ + mode: this.data.mode, + form: { + nickname: this.data.form.nickname, + account: this.data.form.account, + phone: this.data.form.phone, + signature: this.data.form.signature, + type: Number(this.data.form.type) + }, + selectedShopIds: this.data.selectedShopIds.slice() + })) + }, + + async loadShops() { + try { + const shops = await cache.remember('admin:shops:all', CACHE_TTL.dict, () => shopApi.listAllShops()) + const app = getApp() + const operator = app.globalData.userInfo || {} + const currentShop = app.globalData.currentShop + + if (Number(operator.type) !== 4 && currentShop) { + this.setData({ + shops: (Array.isArray(shops) ? shops : []).filter(item => normalizeId(item.id) === normalizeId(currentShop.id)).map(item => ({ + ...item, + valueId: normalizeId(item.id), + checked: true + })), + selectedShopIds: [normalizeId(currentShop.id)] + }) + this.scheduleUserDraft() + return + } + + this.setData({ + shops: (Array.isArray(shops) ? shops : []).map(item => ({ + ...item, + valueId: normalizeId(item.id), + checked: this.data.selectedShopIds.includes(normalizeId(item.id)) + })) + }) + } catch (error) { + wx.showToast({ + title: error.message || '店铺列表加载失败', + icon: 'none' + }) + } + }, + + handleInputChange(event) { + const field = event.currentTarget.dataset.field + let value = event.detail.value + + if (field === 'account') { + value = String(value || '').replace(ACCOUNT_REGEX, '') + } + + if (field === 'phone') { + value = String(value || '').replace(PHONE_REGEX, '').slice(0, 11) + } + + this.setData({ + [`form.${field}`]: value + }) + if (field !== 'password') { + this.scheduleUserDraft() + } + }, + + handleTypeChange(event) { + const index = Number(event.detail.value) + const item = this.data.typeOptions[index] + this.setData({ + 'form.type': item ? item.value : 0, + currentTypeLabel: item ? item.label : '' + }) + this.scheduleUserDraft() + }, + + handleShopCheck(event) { + const selectedShopIds = event.detail.value || [] + this.setData({ + selectedShopIds, + shops: this.data.shops.map(item => ({ + ...item, + checked: selectedShopIds.includes(String(item.id)) + })) + }) + this.scheduleUserDraft() + }, + + validateForm() { + const form = this.data.form + if (!form.nickname) { + return '请输入用户昵称' + } + if (!form.account) { + return '请输入账号' + } + if (!form.phone || form.phone.length !== 11) { + return '请输入 11 位手机号' + } + if (this.data.mode === 'create' && !form.password) { + return '新增用户时必须设置密码' + } + if (!this.data.selectedShopIds.length) { + return '请至少绑定一个店铺' + } + return '' + }, + + async handleSubmit() { + const errorMessage = this.validateForm() + if (errorMessage) { + wx.showToast({ + title: errorMessage, + icon: 'none' + }) + return + } + + const payload = { + nickname: this.data.form.nickname, + account: this.data.form.account, + phone: this.data.form.phone, + signature: this.data.form.signature || undefined, + type: Number(this.data.form.type), + shopIds: this.data.selectedShopIds.map(item => Number(item)) + } + + if (this.data.form.password) { + payload.password = this.data.form.password + } + + try { + if (this.data.mode === 'edit') { + await userApi.updateUser(this.data.userId, payload) + } else { + await userApi.createUser(payload) + } + clearDraft(DRAFT_KEY) + markDirty('admin-users') + wx.showToast({ + title: this.data.mode === 'edit' ? '用户已更新' : '用户已创建', + icon: 'none' + }) + navigation.goBack('/pages/users/index') + } catch (error) { + wx.showToast({ + title: error.message || '保存失败', + icon: 'none' + }) + } + }, + + syncTypeLabel(type) { + const target = this.data.typeOptions.find(item => Number(item.value) === Number(type)) + this.setData({ + currentTypeLabel: target ? target.label : '' + }) + } +}) diff --git a/YumiNail-Admin-Program/pages/user-form/index.json b/YumiNail-Admin-Program/pages/user-form/index.json new file mode 100644 index 00000000..8632c9b0 --- /dev/null +++ b/YumiNail-Admin-Program/pages/user-form/index.json @@ -0,0 +1,5 @@ +{ + "usingComponents": { + "navigation-bar": "/components/navigation-bar/navigation-bar" + } +} diff --git a/YumiNail-Admin-Program/pages/user-form/index.wxml b/YumiNail-Admin-Program/pages/user-form/index.wxml new file mode 100644 index 00000000..2dc10b8b --- /dev/null +++ b/YumiNail-Admin-Program/pages/user-form/index.wxml @@ -0,0 +1,51 @@ + + + + + + {{mode === 'edit' ? '更新用户资料' : '创建后台账号'}} + 账号仅允许字母和数字,手机号保持全局唯一。店长创建美甲师时,这里会直接绑定当前店铺。 + + + 昵称 + + + + 账号 + + + + 手机号 + + + + {{mode === 'edit' ? '密码(留空则不修改)' : '登录密码'}} + + + + 签名 + + + + 角色 + + {{currentTypeLabel || '请选择角色'}} + + + + 绑定店铺 + + + + + + + + + + + + diff --git a/YumiNail-Admin-Program/pages/user-form/index.wxss b/YumiNail-Admin-Program/pages/user-form/index.wxss new file mode 100644 index 00000000..e7250734 --- /dev/null +++ b/YumiNail-Admin-Program/pages/user-form/index.wxss @@ -0,0 +1,4 @@ +checkbox { + transform: scale(0.75); + margin-right: 8rpx; +} diff --git a/YumiNail-Admin-Program/pages/users/index.js b/YumiNail-Admin-Program/pages/users/index.js new file mode 100644 index 00000000..a198ba7f --- /dev/null +++ b/YumiNail-Admin-Program/pages/users/index.js @@ -0,0 +1,119 @@ +const userApi = require('../../api/user') +const navigation = require('../../utils/navigation') +const format = require('../../utils/format') +const { setTempRecord, clearTempRecord } = require('../../utils/storage') +const { consumeDirty } = require('../../utils/page-state') + +const TYPE_OPTIONS = [ + { label: '全部角色', value: '' }, + { label: '普通用户', value: 0 }, + { label: '店长', value: 2 }, + { label: '美甲师', value: 3 }, + { label: '管理员', value: 4 } +] + +Page({ + data: { + keyword: '', + type: '', + typeOptions: TYPE_OPTIONS, + list: [], + loading: false, + initialized: false + }, + + onShow() { + if (!navigation.ensureLogin('进入用户管理')) { + return + } + if (!this.data.initialized || consumeDirty('admin-users')) { + this.loadUsers() + } + }, + + handleKeywordInput(event) { + this.setData({ + keyword: event.detail.value + }) + }, + + handleSearch() { + this.loadUsers() + }, + + handleTypeChange(event) { + this.setData({ + type: event.currentTarget.dataset.type + }) + this.loadUsers() + }, + + async loadUsers() { + const requestId = (this._loadRequestId || 0) + 1 + this._loadRequestId = requestId + this.setData({ + loading: true + }) + + try { + const result = await userApi.listUsers({ + page: 1, + size: 20, + keyword: this.data.keyword || undefined, + type: this.data.type === '' ? undefined : this.data.type + }) + + if (requestId !== this._loadRequestId) { + return + } + + this.setData({ + list: (Array.isArray(result && result.list) ? result.list : []).map(item => ({ + ...item, + displayShopName: format.buildShopName(item), + displayTypeText: format.getUserTypeText(item.type), + displayStatusText: format.getUserStatusText(item.status) + })), + initialized: true + }) + } catch (error) { + if (requestId !== this._loadRequestId) { + return + } + wx.showToast({ + title: error.message || '用户列表加载失败', + icon: 'none' + }) + } finally { + if (requestId === this._loadRequestId) { + this.setData({ + loading: false + }) + } + } + }, + + handleOpenDetail(event) { + const user = event.currentTarget.dataset.user + setTempRecord('currentUser', user) + navigation.navigate('/pages/user-detail/index', { + id: user.id + }).catch(() => undefined) + }, + + handleEdit(event) { + const user = event.currentTarget.dataset.user + setTempRecord('currentUser', user) + navigation.navigate('/pages/user-form/index', { + mode: 'edit', + id: user.id + }).catch(() => undefined) + }, + + handleCreate() { + clearTempRecord('currentUser') + navigation.navigate('/pages/user-form/index', { + mode: 'create' + }).catch(() => undefined) + } +}) diff --git a/YumiNail-Admin-Program/pages/users/index.json b/YumiNail-Admin-Program/pages/users/index.json new file mode 100644 index 00000000..8632c9b0 --- /dev/null +++ b/YumiNail-Admin-Program/pages/users/index.json @@ -0,0 +1,5 @@ +{ + "usingComponents": { + "navigation-bar": "/components/navigation-bar/navigation-bar" + } +} diff --git a/YumiNail-Admin-Program/pages/users/index.wxml b/YumiNail-Admin-Program/pages/users/index.wxml new file mode 100644 index 00000000..1fc6a285 --- /dev/null +++ b/YumiNail-Admin-Program/pages/users/index.wxml @@ -0,0 +1,63 @@ + + + + + + 筛选用户 + + + + + + + {{item.label}} + + + + + + + + + {{item.nickname || '未命名用户'}} · {{item.account}} + {{item.displayShopName}} + + {{item.displayStatusText}} + + + + 角色 + {{item.displayTypeText}} + + + 手机号 + {{item.phone || '--'}} + + + VIP + {{item.vipLevel || item.level || '普通'}} + + + 创建时间 + {{item.createTime}} + + + + 详情 + 编辑 + + + + + + 正在加载用户列表 + + + + 暂无匹配用户 + 可以先清空筛选条件,或者直接新增一个新用户。 + + + + + + diff --git a/YumiNail-Admin-Program/pages/users/index.wxss b/YumiNail-Admin-Program/pages/users/index.wxss new file mode 100644 index 00000000..09b20ffe --- /dev/null +++ b/YumiNail-Admin-Program/pages/users/index.wxss @@ -0,0 +1,3 @@ +.page-shell { + background: transparent; +} diff --git a/YumiNail-Admin-Program/pages/workbench/index.js b/YumiNail-Admin-Program/pages/workbench/index.js new file mode 100644 index 00000000..eb7512b8 --- /dev/null +++ b/YumiNail-Admin-Program/pages/workbench/index.js @@ -0,0 +1,168 @@ +const dashboardApi = require('../../api/dashboard') +const orderApi = require('../../api/order') +const navigation = require('../../utils/navigation') +const permission = require('../../utils/permission') +const cache = require('../../utils/cache') +const { CACHE_TTL } = require('../../utils/config') +const { consumeDirty } = require('../../utils/page-state') + +Page({ + data: { + userInfo: null, + currentShop: null, + permissionCount: 0, + shortcutModules: [], + stats: null, + pendingOrders: 0, + shoplessAdmin: false, + loading: false, + initialized: false + }, + + onShow() { + if (!navigation.ensureLogin('进入工作台')) { + return + } + + this.syncGlobalState() + const dirty = consumeDirty('admin-workbench') + if (!this.data.initialized || dirty) { + this.loadDashboard({ + force: dirty + }) + } + }, + + syncGlobalState() { + const app = getApp() + const userInfo = app.globalData.userInfo + const currentShop = app.globalData.currentShop + const permissionCodes = app.globalData.permissionCodes || [] + const modules = permission.getManageModules(userInfo, permissionCodes, currentShop) + + this.setData({ + userInfo, + currentShop, + permissionCount: permissionCodes.length, + shortcutModules: modules.filter(item => item.allowed).slice(0, 4), + shoplessAdmin: permission.isPlatformAdmin(userInfo) && !currentShop + }) + }, + + async loadDashboard(options) { + const requestId = (this._loadRequestId || 0) + 1 + this._loadRequestId = requestId + const force = Boolean(options && options.force) + const app = getApp() + const permissionCodes = app.globalData.permissionCodes || [] + const currentShopId = this.data.currentShop && this.data.currentShop.id ? String(this.data.currentShop.id) : 'none' + const statsCacheKey = `workbench:stats:${currentShopId}` + const pendingCacheKey = `workbench:pending:${currentShopId}` + + this.setData({ + loading: true + }) + + if (this.data.shoplessAdmin) { + if (requestId === this._loadRequestId) { + this.setData({ + stats: null, + pendingOrders: 0, + loading: false, + initialized: true + }) + } + return + } + + if (permission.hasPermission(permissionCodes, 'dashboard:view')) { + try { + if (force) { + cache.removeCache(statsCacheKey) + } + const stats = force + ? await dashboardApi.getStats() + : await cache.remember(statsCacheKey, CACHE_TTL.workbench, () => dashboardApi.getStats()) + if (requestId !== this._loadRequestId) { + return + } + this.setData({ + stats, + pendingOrders: Number(stats && stats.todayOrders) || 0, + loading: false, + initialized: true + }) + return + } catch (error) {} + } + + if (permission.hasPermission(permissionCodes, 'order:view')) { + try { + if (force) { + cache.removeCache(pendingCacheKey) + } + const result = force + ? await orderApi.listOrders({ + page: 1, + size: 20, + status: 1 + }) + : await cache.remember(pendingCacheKey, CACHE_TTL.workbench, () => orderApi.listOrders({ + page: 1, + size: 20, + status: 1 + })) + if (requestId !== this._loadRequestId) { + return + } + this.setData({ + stats: null, + pendingOrders: Number(result && result.total) || 0, + loading: false, + initialized: true + }) + } catch (error) { + if (requestId === this._loadRequestId) { + this.setData({ + stats: null, + pendingOrders: 0, + loading: false, + initialized: true + }) + } + } + return + } + + if (requestId === this._loadRequestId) { + this.setData({ + stats: null, + pendingOrders: 0, + loading: false, + initialized: true + }) + } + }, + + handleOpenModule(event) { + const path = event.currentTarget.dataset.path + if (!path) { + return + } + + if (path === '/pages/orders/index') { + navigation.switchTab(path) + return + } + + navigation.navigate(path).catch(() => undefined) + }, + + handleOpenShops() { + navigation.navigate('/pages/shops/index').catch(() => undefined) + }, + + handleOpenOrders() { + navigation.switchTab('/pages/orders/index').catch(() => undefined) + } +}) diff --git a/YumiNail-Admin-Program/pages/workbench/index.json b/YumiNail-Admin-Program/pages/workbench/index.json new file mode 100644 index 00000000..8632c9b0 --- /dev/null +++ b/YumiNail-Admin-Program/pages/workbench/index.json @@ -0,0 +1,5 @@ +{ + "usingComponents": { + "navigation-bar": "/components/navigation-bar/navigation-bar" + } +} diff --git a/YumiNail-Admin-Program/pages/workbench/index.wxml b/YumiNail-Admin-Program/pages/workbench/index.wxml new file mode 100644 index 00000000..08829e03 --- /dev/null +++ b/YumiNail-Admin-Program/pages/workbench/index.wxml @@ -0,0 +1,73 @@ + + + + + + {{userInfo.nickname || userInfo.account || '后台账号'}} + {{currentShop ? currentShop.shopName : '无店铺登录工作台'}} + 当前身份:{{userInfo ? userInfo.type === 4 ? '平台管理员' : userInfo.type === 2 ? '店长' : '美甲师' : '--'}}。已同步 {{permissionCount}} 项后台权限。 + + {{currentShop ? '当前店铺已锁定' : '当前无店铺上下文'}} + {{shoplessAdmin ? '先完成门店初始化' : '移动端工作流已就绪'}} + + + + + 先创建第一家店铺 + 当前是无店铺管理员登录状态。为避免误进入强店铺范围页面,首版仅建议先完成店铺初始化,再继续订单、商品和用户管理。 + + + + + + + 今日概览 + 把高频动作和最关键的经营数字集中到一屏,方便在手机上快速判断接下来该处理什么。 + + + 待处理订单 + {{pendingOrders}} + 优先处理预约确认与履约 + + + 当前权限 + {{permissionCount}} + 前端仅做显隐,服务端仍会兜底校验 + + + 用户总量 + {{stats.totalUsers || 0}} + 按当前角色与店铺范围计算 + + + 作品总量 + {{stats.totalProducts || 0}} + 支持后续直接跳去作品管理 + + + + + + + + + 快捷入口 + 只展示当前账号真实可进入的模块,避免手机端一屏堆太多无权限入口。 + + + + + {{item.title}} + {{item.description}} + + 进入 + + + + + 暂无可用快捷入口 + 当前账号没有可直接打开的后台模块,请先检查权限或切换店铺。 + + + + diff --git a/YumiNail-Admin-Program/pages/workbench/index.wxss b/YumiNail-Admin-Program/pages/workbench/index.wxss new file mode 100644 index 00000000..09b20ffe --- /dev/null +++ b/YumiNail-Admin-Program/pages/workbench/index.wxss @@ -0,0 +1,3 @@ +.page-shell { + background: transparent; +} diff --git a/YumiNail-Admin-Program/project.config.json b/YumiNail-Admin-Program/project.config.json new file mode 100644 index 00000000..cdaa2927 --- /dev/null +++ b/YumiNail-Admin-Program/project.config.json @@ -0,0 +1,41 @@ +{ + "appid": "wxb6d77f7c07020d51", + "compileType": "miniprogram", + "libVersion": "3.6.7", + "packOptions": { + "ignore": [], + "include": [] + }, + "setting": { + "urlCheck": false, + "es6": true, + "enhance": true, + "postcss": true, + "minified": true, + "packNpmRelationList": [], + "compileHotReLoad": true, + "skylineRenderEnable": false, + "compileWorklet": false, + "uglifyFileName": false, + "uploadWithSourceMap": true, + "packNpmManually": false, + "minifyWXSS": true, + "minifyWXML": true, + "localPlugins": false, + "disableUseStrict": false, + "useCompilerPlugins": false, + "condition": false, + "swc": false, + "disableSWC": true, + "babelSetting": { + "ignore": [], + "disablePlugins": [], + "outputPath": "" + } + }, + "condition": {}, + "projectname": "YumiNail-Admin-Program", + "simulatorType": "wechat", + "simulatorPluginLibVersion": {}, + "editorSetting": {} +} diff --git a/YumiNail-Admin-Program/project.private.config.json b/YumiNail-Admin-Program/project.private.config.json new file mode 100644 index 00000000..20e25a02 --- /dev/null +++ b/YumiNail-Admin-Program/project.private.config.json @@ -0,0 +1,22 @@ +{ + "libVersion": "3.15.2", + "condition": {}, + "projectname": "YumiNail-Admin-Program", + "setting": { + "urlCheck": false, + "coverView": false, + "lazyloadPlaceholderEnable": false, + "skylineRenderEnable": false, + "preloadBackgroundData": false, + "autoAudits": false, + "useApiHook": true, + "showShadowRootInWxmlPanel": false, + "useStaticServer": false, + "useLanDebug": false, + "showES6CompileOption": false, + "compileHotReLoad": true, + "checkInvalidKey": true, + "ignoreDevUnusedFiles": true, + "bigPackageSizeSupport": false + } +} diff --git a/YumiNail-Admin-Program/sitemap.json b/YumiNail-Admin-Program/sitemap.json new file mode 100644 index 00000000..f70da992 --- /dev/null +++ b/YumiNail-Admin-Program/sitemap.json @@ -0,0 +1,3 @@ +{ + "rules": [] +} diff --git a/YumiNail-Admin-Program/utils/action-guard.js b/YumiNail-Admin-Program/utils/action-guard.js new file mode 100644 index 00000000..c4f11ce8 --- /dev/null +++ b/YumiNail-Admin-Program/utils/action-guard.js @@ -0,0 +1,78 @@ +const inflightScopes = new Map() + +function resolveScopeId(scope) { + if (scope && typeof scope === 'string') { + return scope + } + if (scope && typeof scope.route === 'string' && scope.route) { + return scope.route + } + + const pages = typeof getCurrentPages === 'function' ? getCurrentPages() : [] + const current = pages[pages.length - 1] + if (current && current.route) { + return current.route + } + + return 'global' +} + +function getScopeMap(scopeId) { + if (!inflightScopes.has(scopeId)) { + inflightScopes.set(scopeId, new Map()) + } + return inflightScopes.get(scopeId) +} + +function createGuardError(message, scopeId, actionKey) { + const error = new Error(message || '\u64cd\u4f5c\u8fdb\u884c\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u70b9\u51fb') + error.isActionGuardError = true + error.scopeId = scopeId + error.actionKey = actionKey + return error +} + +async function run(scope, actionKey, task, options) { + const scopeId = resolveScopeId(scope) + const normalizedKey = String(actionKey || 'default') + const scopeMap = getScopeMap(scopeId) + + if (scopeMap.get(normalizedKey)) { + return Promise.reject(createGuardError((options && options.message) || '', scopeId, normalizedKey)) + } + + scopeMap.set(normalizedKey, true) + try { + return await Promise.resolve().then(() => task()) + } finally { + scopeMap.delete(normalizedKey) + if (!scopeMap.size) { + inflightScopes.delete(scopeId) + } + } +} + +function isRunning(scope, actionKey) { + const scopeId = resolveScopeId(scope) + const scopeMap = inflightScopes.get(scopeId) + if (!scopeMap) { + return false + } + return Boolean(scopeMap.get(String(actionKey || 'default'))) +} + +function clearScope(scope) { + inflightScopes.delete(resolveScopeId(scope)) +} + +function isGuardError(error) { + return Boolean(error && error.isActionGuardError) +} + +module.exports = { + run, + isRunning, + clearScope, + isGuardError, + createGuardError +} diff --git a/YumiNail-Admin-Program/utils/auth.js b/YumiNail-Admin-Program/utils/auth.js new file mode 100644 index 00000000..d73c6d96 --- /dev/null +++ b/YumiNail-Admin-Program/utils/auth.js @@ -0,0 +1,99 @@ +const { STORAGE_KEYS, getStorage, removeStorage, setStorage } = require('./storage') + +function getAccessToken() { + return getStorage(STORAGE_KEYS.ACCESS_TOKEN, '') +} + +function getRefreshToken() { + return getStorage(STORAGE_KEYS.REFRESH_TOKEN, '') +} + +function getStoredUserInfo() { + return getStorage(STORAGE_KEYS.USER_INFO, null) +} + +function getStoredPermissions() { + return getStorage(STORAGE_KEYS.PERMISSIONS, []) +} + +function getCurrentShop() { + return getStorage(STORAGE_KEYS.CURRENT_SHOP, null) +} + +function isLoggedIn() { + return Boolean(getAccessToken()) +} + +function setSession(payload) { + if (!payload || !payload.accessToken || !payload.refreshToken) { + return + } + + setStorage(STORAGE_KEYS.ACCESS_TOKEN, payload.accessToken) + setStorage(STORAGE_KEYS.REFRESH_TOKEN, payload.refreshToken) + + if (payload.userInfo) { + setStorage(STORAGE_KEYS.USER_INFO, payload.userInfo) + + if (payload.userInfo.shopId) { + setCurrentShop({ + id: payload.userInfo.shopId, + shopName: payload.userInfo.shopName || '' + }) + } else { + removeStorage(STORAGE_KEYS.CURRENT_SHOP) + } + } +} + +function updateStoredUserInfo(userInfo) { + if (!userInfo) { + removeStorage(STORAGE_KEYS.USER_INFO) + return + } + + setStorage(STORAGE_KEYS.USER_INFO, userInfo) +} + +function setPermissions(permissions) { + setStorage(STORAGE_KEYS.PERMISSIONS, Array.isArray(permissions) ? permissions : []) +} + +function clearPermissions() { + removeStorage(STORAGE_KEYS.PERMISSIONS) +} + +function setCurrentShop(shop) { + if (!shop || !shop.id) { + removeStorage(STORAGE_KEYS.CURRENT_SHOP) + return + } + + setStorage(STORAGE_KEYS.CURRENT_SHOP, { + id: shop.id, + shopName: shop.shopName || '' + }) +} + +function clearSession() { + removeStorage(STORAGE_KEYS.ACCESS_TOKEN) + removeStorage(STORAGE_KEYS.REFRESH_TOKEN) + removeStorage(STORAGE_KEYS.USER_INFO) + removeStorage(STORAGE_KEYS.PERMISSIONS) + removeStorage(STORAGE_KEYS.CURRENT_SHOP) +} + +module.exports = { + getAccessToken, + getRefreshToken, + getStoredUserInfo, + getStoredPermissions, + getCurrentShop, + isLoggedIn, + setSession, + updateStoredUserInfo, + setPermissions, + clearPermissions, + setCurrentShop, + clearSession +} diff --git a/YumiNail-Admin-Program/utils/cache.js b/YumiNail-Admin-Program/utils/cache.js new file mode 100644 index 00000000..379a6dbc --- /dev/null +++ b/YumiNail-Admin-Program/utils/cache.js @@ -0,0 +1,83 @@ +const CACHE_PREFIX = 'adminMiniCache:' +const memoryCache = {} +const inflightCache = {} + +function buildKey(key) { + return `${CACHE_PREFIX}${key}` +} + +function now() { + return Date.now() +} + +function getCache(key, defaultValue) { + if (!key) { + return defaultValue + } + + const memoryEntry = memoryCache[key] + if (memoryEntry && (!memoryEntry.expireAt || memoryEntry.expireAt > now())) { + return memoryEntry.value + } + delete memoryCache[key] + + try { + const storedEntry = wx.getStorageSync(buildKey(key)) + if (storedEntry && (!storedEntry.expireAt || storedEntry.expireAt > now())) { + memoryCache[key] = storedEntry + return storedEntry.value + } + wx.removeStorageSync(buildKey(key)) + } catch (error) {} + + return defaultValue +} + +function setCache(key, value, ttlMs) { + if (!key) { + return value + } + const entry = { + value, + expireAt: ttlMs && ttlMs > 0 ? now() + ttlMs : 0 + } + memoryCache[key] = entry + try { + wx.setStorageSync(buildKey(key), entry) + } catch (error) {} + return value +} + +function removeCache(key) { + if (!key) { + return + } + delete memoryCache[key] + try { + wx.removeStorageSync(buildKey(key)) + } catch (error) {} +} + +function remember(key, ttlMs, loader) { + const cached = getCache(key, undefined) + if (cached !== undefined) { + return Promise.resolve(cached) + } + if (inflightCache[key]) { + return inflightCache[key] + } + inflightCache[key] = Promise.resolve() + .then(() => loader()) + .then(value => setCache(key, value, ttlMs)) + .finally(() => { + delete inflightCache[key] + }) + return inflightCache[key] +} + +module.exports = { + getCache, + setCache, + removeCache, + remember +} diff --git a/YumiNail-Admin-Program/utils/config.js b/YumiNail-Admin-Program/utils/config.js new file mode 100644 index 00000000..e50e43ad --- /dev/null +++ b/YumiNail-Admin-Program/utils/config.js @@ -0,0 +1,107 @@ +function safeRequire(modulePath) { + try { + return require(modulePath) + } catch (error) { + return {} + } +} + +function getEnvVersion() { + if (typeof wx === 'undefined') { + return 'develop' + } + + try { + if (typeof wx.getAccountInfoSync === 'function') { + const accountInfo = wx.getAccountInfoSync() + const miniProgram = accountInfo && accountInfo.miniProgram + if (miniProgram && miniProgram.envVersion) { + return miniProgram.envVersion + } + } + } catch (error) {} + + return 'develop' +} + +function getRuntimePlatform() { + if (typeof wx === 'undefined') { + return 'devtools' + } + + try { + const systemInfo = wx.getSystemInfoSync() + if (systemInfo && systemInfo.platform) { + return systemInfo.platform + } + } catch (error) {} + + return 'unknown' +} + +function normalizeDomain(value, fallbackValue) { + const target = String(value || fallbackValue || '').trim() + return target.replace(/\/+$/, '') +} + +function ensureHttps(value, envVersion) { + if (!value) { + throw new Error(`Missing API domain for ${envVersion}`) + } + if (envVersion !== 'develop' && !value.startsWith('https://')) { + throw new Error(`${envVersion} environment must use HTTPS`) + } + return value +} + +const localOverride = safeRequire('./config.local') +const ENV_VERSION = getEnvVersion() +const RUNTIME_PLATFORM = getRuntimePlatform() +const IS_DEVTOOLS = RUNTIME_PLATFORM === 'devtools' + +const DEFAULT_DOMAINS = { + local: 'http://127.0.0.1:80', + tunnel: 'https://yunail.art', + 'dev-remote': 'https://yunail.art', + trial: 'https://yunail.art', + release: 'https://yunail.art' +} + +const DOMAIN_MAP = { + ...DEFAULT_DOMAINS, + ...(localOverride.domains || {}) +} + +const DEFAULT_DEVELOP_TARGET = IS_DEVTOOLS ? 'local' : 'dev-remote' +const DEVELOP_TARGET = String(localOverride.developTarget || DEFAULT_DEVELOP_TARGET) +const API_DOMAIN = ensureHttps( + ENV_VERSION === 'develop' + ? normalizeDomain(DOMAIN_MAP[DEVELOP_TARGET], DOMAIN_MAP['dev-remote']) + : normalizeDomain(DOMAIN_MAP[ENV_VERSION], DOMAIN_MAP.release), + ENV_VERSION +) + +module.exports = { + ENV_VERSION, + RUNTIME_PLATFORM, + IS_DEVTOOLS, + DEVELOP_TARGET, + API_DOMAIN, + ADMIN_API_BASE_URL: `${API_DOMAIN}/admin/api`, + IS_DEV_ENV: ENV_VERSION === 'develop', + REQUEST_TIMEOUT: Number(localOverride.requestTimeout || 10000), + ENABLE_REQUEST_SIGNING: localOverride.enableRequestSigning !== false, + IDLE_TIMEOUT_MS: 30 * 60 * 1000, + IDLE_WARNING_MS: 2 * 60 * 1000, + CACHE_TTL: { + permissions: 2 * 60 * 1000, + dict: 5 * 60 * 1000, + workbench: 60 * 1000 + }, + TAB_PAGES: [ + '/pages/workbench/index', + '/pages/orders/index', + '/pages/manage/index', + '/pages/profile/index' + ] +} diff --git a/YumiNail-Admin-Program/utils/config.local.example.js b/YumiNail-Admin-Program/utils/config.local.example.js new file mode 100644 index 00000000..4633d2c4 --- /dev/null +++ b/YumiNail-Admin-Program/utils/config.local.example.js @@ -0,0 +1,12 @@ +module.exports = { + developTarget: 'local', + requestTimeout: 10000, + enableRequestSigning: true, + domains: { + local: 'http://127.0.0.1:80', + tunnel: 'https://yunail.art', + 'dev-remote': 'https://yunail.art', + trial: 'https://yunail.art', + release: 'https://yunail.art' + } +} diff --git a/YumiNail-Admin-Program/utils/crypto.js b/YumiNail-Admin-Program/utils/crypto.js new file mode 100644 index 00000000..ce4e850a --- /dev/null +++ b/YumiNail-Admin-Program/utils/crypto.js @@ -0,0 +1,177 @@ +function utf8ToBytes(text) { + const encoded = unescape(encodeURIComponent(String(text || ''))) + const bytes = [] + for (let index = 0; index < encoded.length; index += 1) { + bytes.push(encoded.charCodeAt(index)) + } + return bytes +} + +function bytesToHex(bytes) { + return (Array.isArray(bytes) ? bytes : []).map(item => item.toString(16).padStart(2, '0')).join('') +} + +function rightRotate(value, amount) { + return (value >>> amount) | (value << (32 - amount)) +} + +function sha256Bytes(messageBytes) { + const k = [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, + 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, + 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, + 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, + 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, + 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, + 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, + 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, + 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 + ] + const h = [ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 + ] + const bytes = Array.isArray(messageBytes) ? messageBytes.slice() : [] + const bitLength = BigInt(bytes.length) * 8n + bytes.push(0x80) + while ((bytes.length % 64) !== 56) { + bytes.push(0) + } + for (let index = 7; index >= 0; index -= 1) { + bytes.push(Number((bitLength >> BigInt(index * 8)) & 0xffn)) + } + + const words = new Array(64) + for (let offset = 0; offset < bytes.length; offset += 64) { + for (let index = 0; index < 16; index += 1) { + const start = offset + index * 4 + words[index] = ( + (bytes[start] << 24) | + (bytes[start + 1] << 16) | + (bytes[start + 2] << 8) | + bytes[start + 3] + ) >>> 0 + } + + for (let index = 16; index < 64; index += 1) { + const s0 = (rightRotate(words[index - 15], 7) ^ rightRotate(words[index - 15], 18) ^ (words[index - 15] >>> 3)) >>> 0 + const s1 = (rightRotate(words[index - 2], 17) ^ rightRotate(words[index - 2], 19) ^ (words[index - 2] >>> 10)) >>> 0 + words[index] = (words[index - 16] + s0 + words[index - 7] + s1) >>> 0 + } + + let a = h[0] + let b = h[1] + let c = h[2] + let d = h[3] + let e = h[4] + let f = h[5] + let g = h[6] + let innerH = h[7] + + for (let index = 0; index < 64; index += 1) { + const s1 = (rightRotate(e, 6) ^ rightRotate(e, 11) ^ rightRotate(e, 25)) >>> 0 + const choice = ((e & f) ^ ((~e) & g)) >>> 0 + const temp1 = (innerH + s1 + choice + k[index] + words[index]) >>> 0 + const s0 = (rightRotate(a, 2) ^ rightRotate(a, 13) ^ rightRotate(a, 22)) >>> 0 + const majority = ((a & b) ^ (a & c) ^ (b & c)) >>> 0 + const temp2 = (s0 + majority) >>> 0 + + innerH = g + g = f + f = e + e = (d + temp1) >>> 0 + d = c + c = b + b = a + a = (temp1 + temp2) >>> 0 + } + + h[0] = (h[0] + a) >>> 0 + h[1] = (h[1] + b) >>> 0 + h[2] = (h[2] + c) >>> 0 + h[3] = (h[3] + d) >>> 0 + h[4] = (h[4] + e) >>> 0 + h[5] = (h[5] + f) >>> 0 + h[6] = (h[6] + g) >>> 0 + h[7] = (h[7] + innerH) >>> 0 + } + + const output = [] + h.forEach(value => { + output.push((value >>> 24) & 0xff) + output.push((value >>> 16) & 0xff) + output.push((value >>> 8) & 0xff) + output.push(value & 0xff) + }) + return output +} + +function sha256Hex(text) { + return bytesToHex(sha256Bytes(utf8ToBytes(text))) +} + +function hmacSha256Hex(secret, message) { + let keyBytes = utf8ToBytes(secret) + if (keyBytes.length > 64) { + keyBytes = sha256Bytes(keyBytes) + } + while (keyBytes.length < 64) { + keyBytes.push(0) + } + + const outer = [] + const inner = [] + for (let index = 0; index < 64; index += 1) { + outer[index] = keyBytes[index] ^ 0x5c + inner[index] = keyBytes[index] ^ 0x36 + } + + const innerDigest = sha256Bytes(inner.concat(utf8ToBytes(message))) + return bytesToHex(sha256Bytes(outer.concat(innerDigest))) +} + +function buildCanonicalParams(input) { + const source = input || {} + const keys = Object.keys(source) + .filter(key => source[key] !== undefined && source[key] !== null && source[key] !== '') + .sort() + + return keys.map(key => { + const rawValue = source[key] + const values = Array.isArray(rawValue) ? rawValue.slice() : [rawValue] + const normalized = values + .map(item => String(item)) + .sort() + .join(',') + return `${key}=${normalized}` + }).join('&') +} + +function buildJsonPayload(data) { + if (data === undefined || data === null || data === '') { + return '' + } + if (typeof data === 'string') { + return data + } + return JSON.stringify(data) +} + +function randomNonce() { + return `${Date.now()}-${Math.random().toString(36).slice(2, 10)}` +} + +module.exports = { + sha256Hex, + hmacSha256Hex, + buildCanonicalParams, + buildJsonPayload, + randomNonce +} diff --git a/YumiNail-Admin-Program/utils/device.js b/YumiNail-Admin-Program/utils/device.js new file mode 100644 index 00000000..45cfad05 --- /dev/null +++ b/YumiNail-Admin-Program/utils/device.js @@ -0,0 +1,20 @@ +const { STORAGE_KEYS, getStorage, setStorage } = require('./storage') + +function createDeviceId() { + const randomText = Math.random().toString(36).slice(2, 10) + return `admin-mini-device-${Date.now()}-${randomText}` +} + +function getDeviceId() { + let value = getStorage(STORAGE_KEYS.DEVICE_ID, '') + if (value) { + return value + } + value = createDeviceId() + setStorage(STORAGE_KEYS.DEVICE_ID, value) + return value +} + +module.exports = { + getDeviceId +} diff --git a/YumiNail-Admin-Program/utils/form-draft.js b/YumiNail-Admin-Program/utils/form-draft.js new file mode 100644 index 00000000..f2544502 --- /dev/null +++ b/YumiNail-Admin-Program/utils/form-draft.js @@ -0,0 +1,68 @@ +const DRAFT_PREFIX = 'adminMiniDraft:' + +function buildDraftKey(key) { + return `${DRAFT_PREFIX}${key}` +} + +function getDraftValue(key, defaultValue) { + if (!key) { + return defaultValue + } + try { + const record = wx.getStorageSync(buildDraftKey(key)) + if (!record || typeof record !== 'object' || !Object.prototype.hasOwnProperty.call(record, 'value')) { + return defaultValue + } + return record.value + } catch (error) { + return defaultValue + } +} + +function saveDraft(key, value) { + if (!key) { + return + } + try { + wx.setStorageSync(buildDraftKey(key), { + savedAt: Date.now(), + value + }) + } catch (error) {} +} + +function clearDraft(key) { + if (!key) { + return + } + try { + wx.removeStorageSync(buildDraftKey(key)) + } catch (error) {} +} + +function scheduleDraftSave(context, key, buildValue, delay) { + if (!context) { + return + } + if (context.__draftSaveTimer) { + clearTimeout(context.__draftSaveTimer) + } + context.__draftSaveTimer = setTimeout(() => { + saveDraft(key, buildValue()) + }, delay || 300) +} + +function clearDraftTimer(context) { + if (context && context.__draftSaveTimer) { + clearTimeout(context.__draftSaveTimer) + context.__draftSaveTimer = null + } +} + +module.exports = { + getDraftValue, + saveDraft, + clearDraft, + scheduleDraftSave, + clearDraftTimer +} diff --git a/YumiNail-Admin-Program/utils/format.js b/YumiNail-Admin-Program/utils/format.js new file mode 100644 index 00000000..802e2227 --- /dev/null +++ b/YumiNail-Admin-Program/utils/format.js @@ -0,0 +1,148 @@ +function toIdString(value) { + return value === undefined || value === null ? '' : String(value) +} + +function sameId(left, right) { + return toIdString(left) === toIdString(right) +} + +function splitCsv(value) { + return String(value || '') + .split(',') + .map(item => item.trim()) + .filter(Boolean) +} + +function formatPrice(value) { + return Number(value || 0).toFixed(2) +} + +function formatDateTime(value) { + if (!value) { + return '' + } + + return String(value).replace('T', ' ').slice(0, 16) +} + +function formatDate(value) { + return formatDateTime(value).slice(0, 10) +} + +function maskPhone(phone) { + const value = String(phone || '') + if (value.length !== 11) { + return value + } + return `${value.slice(0, 3)}****${value.slice(7)}` +} + +function truncateText(value, limit) { + const text = String(value || '') + if (!limit || text.length <= limit) { + return text + } + return `${text.slice(0, limit)}...` +} + +function buildShopName(record) { + if (!record) { + return '未绑定店铺' + } + + if (Array.isArray(record.shopNames) && record.shopNames.length) { + return record.shopNames.join(' / ') + } + + if (record.shopName) { + return record.shopName + } + + return '未绑定店铺' +} + +function getUserStatusText(status) { + return Number(status) === 0 ? '已停用' : '正常' +} + +function getUserTypeText(type) { + const value = Number(type) + if (value === 4) { + return '平台管理员' + } + if (value === 2) { + return '店长' + } + if (value === 3) { + return '美甲师' + } + return '普通用户' +} + +function getOrderStatusText(order) { + if (order && order.statusText) { + return order.statusText + } + + const status = Number(order && order.status) + if (status === 1) { + return '待服务' + } + if (status === 2) { + return '已完成' + } + return '已取消' +} + +function getCouponTypeText(type) { + return Number(type) === 1 ? '折扣券' : '满减券' +} + +function getCouponValueText(coupon) { + if (Number(coupon && coupon.couponType) === 1) { + return `${coupon && coupon.discountValue ? coupon.discountValue : '--'} 折` + } + return `满 ${formatPrice(coupon && coupon.minAmount)} 减 ${formatPrice(coupon && coupon.reduceAmount)}` +} + +function parseDateTimeToPicker(value) { + const text = formatDateTime(value) + if (!text) { + return { + date: '', + time: '' + } + } + + const parts = text.split(' ') + return { + date: parts[0] || '', + time: (parts[1] || '').slice(0, 5) + } +} + +function buildDateTime(date, time) { + if (!date || !time) { + return '' + } + return `${date} ${time}:00` +} + +module.exports = { + toIdString, + sameId, + splitCsv, + formatPrice, + formatDateTime, + formatDate, + maskPhone, + truncateText, + buildShopName, + getUserStatusText, + getUserTypeText, + getOrderStatusText, + getCouponTypeText, + getCouponValueText, + parseDateTimeToPicker, + buildDateTime +} diff --git a/YumiNail-Admin-Program/utils/idle-session.js b/YumiNail-Admin-Program/utils/idle-session.js new file mode 100644 index 00000000..793b5d8a --- /dev/null +++ b/YumiNail-Admin-Program/utils/idle-session.js @@ -0,0 +1,165 @@ +let options = null +let timer = null +let warningShown = false +let loggingOut = false +let hiddenAt = 0 +let lastActiveAt = Date.now() +let pagePatched = false + +function shouldTrackMethod(name) { + return ![ + 'onHide', + 'onUnload', + 'onShareAppMessage', + 'onShareTimeline' + ].includes(name) +} + +function ensurePagePatched() { + if (pagePatched || typeof Page !== 'function') { + return + } + const originalPage = Page + Page = function wrappedPage(definition) { + const nextDefinition = {} + Object.keys(definition || {}).forEach(key => { + const value = definition[key] + if (typeof value !== 'function') { + nextDefinition[key] = value + return + } + nextDefinition[key] = function wrappedHandler(...args) { + if (shouldTrackMethod(key)) { + markActive() + } + return value.apply(this, args) + } + }) + return originalPage(nextDefinition) + } + pagePatched = true +} + +function start() { + stop() + if (!options) { + return + } + timer = setInterval(check, 15000) +} + +function stop() { + if (timer) { + clearInterval(timer) + timer = null + } +} + +function isLoggedIn() { + return options && typeof options.isLoggedIn === 'function' ? Boolean(options.isLoggedIn()) : false +} + +function markActive() { + if (!options || !isLoggedIn() || loggingOut) { + return + } + lastActiveAt = Date.now() + warningShown = false +} + +function onAppShow() { + if (!options) { + return + } + if (hiddenAt > 0 && isLoggedIn()) { + const hiddenDuration = Date.now() - hiddenAt + if (hiddenDuration >= options.timeoutMs) { + forceLogout() + return + } + } + hiddenAt = 0 + markActive() + start() +} + +function onAppHide() { + hiddenAt = Date.now() + stop() +} + +function check() { + if (!options || !isLoggedIn() || loggingOut) { + return + } + const idleMs = Date.now() - lastActiveAt + if (idleMs >= options.timeoutMs) { + forceLogout() + return + } + if (idleMs >= options.timeoutMs - options.warningMs && !warningShown) { + showWarning() + } +} + +function showWarning() { + if (!options || warningShown || loggingOut) { + return + } + warningShown = true + wx.showModal({ + title: options.warningTitle || '登录即将过期', + content: options.warningContent || '长时间未操作,即将退出登录。', + confirmText: options.confirmText || '继续使用', + cancelText: options.cancelText || '退出登录', + success: result => { + warningShown = false + if (result.confirm) { + markActive() + if (typeof options.onContinue === 'function') { + options.onContinue() + } + return + } + forceLogout() + }, + fail: () => { + warningShown = false + } + }) +} + +function forceLogout() { + if (!options || loggingOut) { + return + } + loggingOut = true + Promise.resolve() + .then(() => (typeof options.onLogout === 'function' ? options.onLogout() : undefined)) + .catch(() => undefined) + .finally(() => { + loggingOut = false + warningShown = false + hiddenAt = 0 + lastActiveAt = Date.now() + }) +} + +function init(nextOptions) { + options = nextOptions || null + lastActiveAt = Date.now() + warningShown = false + loggingOut = false + hiddenAt = 0 + ensurePagePatched() + start() +} + +module.exports = { + init, + start, + stop, + markActive, + onAppShow, + onAppHide +} diff --git a/YumiNail-Admin-Program/utils/loading.js b/YumiNail-Admin-Program/utils/loading.js new file mode 100644 index 00000000..441097ce --- /dev/null +++ b/YumiNail-Admin-Program/utils/loading.js @@ -0,0 +1,51 @@ +let activeLoadingCount = 0 + +function showLoading(options) { + const config = options || {} + activeLoadingCount += 1 + + if (activeLoadingCount > 1) { + return + } + + wx.showLoading({ + title: config.title || '加载中', + mask: config.mask !== false + }) +} + +function hideLoading() { + activeLoadingCount = Math.max(0, activeLoadingCount - 1) + + if (activeLoadingCount > 0) { + return + } + + wx.hideLoading({ + fail() {} + }) +} + +function resetLoading() { + activeLoadingCount = 0 + wx.hideLoading({ + fail() {} + }) +} + +function runWithLoading(task, options) { + showLoading(options) + + return Promise.resolve() + .then(() => task()) + .finally(() => { + hideLoading() + }) +} + +module.exports = { + showLoading, + hideLoading, + resetLoading, + runWithLoading +} diff --git a/YumiNail-Admin-Program/utils/navigation.js b/YumiNail-Admin-Program/utils/navigation.js new file mode 100644 index 00000000..a5829c06 --- /dev/null +++ b/YumiNail-Admin-Program/utils/navigation.js @@ -0,0 +1,146 @@ +const auth = require('./auth') +const { TAB_PAGES } = require('./config') + +function buildUrl(path, params) { + const query = Object.keys(params || {}) + .filter(key => params[key] !== undefined && params[key] !== null && params[key] !== '') + .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`) + .join('&') + + return query ? `${path}?${query}` : path +} + +function getCurrentPageUrl() { + const pages = getCurrentPages() + const current = pages[pages.length - 1] + if (!current) { + return '/pages/workbench/index' + } + + return buildUrl(`/${current.route}`, current.options || {}) +} + +function isTabPage(path) { + const purePath = String(path || '').split('?')[0] + return TAB_PAGES.includes(purePath) +} + +function navigate(path, params) { + return new Promise((resolve, reject) => { + wx.navigateTo({ + url: buildUrl(path, params), + success: resolve, + fail: reject + }) + }) +} + +function redirect(path, params) { + return new Promise((resolve, reject) => { + wx.redirectTo({ + url: buildUrl(path, params), + success: resolve, + fail: reject + }) + }) +} + +function switchTab(path) { + return new Promise((resolve, reject) => { + wx.switchTab({ + url: path, + success: resolve, + fail: reject + }) + }) +} + +function goBack(fallbackPath) { + const pages = getCurrentPages() + if (pages.length > 1) { + wx.navigateBack() + return + } + + const target = fallbackPath || '/pages/workbench/index' + if (isTabPage(target)) { + wx.switchTab({ url: target }) + return + } + + wx.redirectTo({ url: target }) +} + +function decodeRedirectValue(value) { + let current = String(value || '') + + for (let index = 0; index < 3; index += 1) { + try { + const decoded = decodeURIComponent(current) + if (decoded === current) { + return decoded + } + current = decoded + } catch (error) { + return current + } + } + + return current +} + +function redirectAfterLogin(redirectValue) { + const target = redirectValue ? decodeRedirectValue(redirectValue) : '' + if (!target) { + return switchTab('/pages/workbench/index') + } + + const purePath = target.split('?')[0] + if (isTabPage(target)) { + return switchTab(purePath) + } + + return new Promise((resolve, reject) => { + wx.redirectTo({ + url: target, + success: resolve, + fail: reject + }) + }) +} + +function openLogin(redirectPath) { + return navigate('/pages/login/index', { + redirect: redirectPath || getCurrentPageUrl() + }) +} + +function ensureLogin(actionText) { + if (auth.isLoggedIn()) { + return true + } + + wx.showToast({ + title: `${actionText || '继续操作'}前请先登录`, + icon: 'none' + }) + + setTimeout(() => { + openLogin() + }, 160) + + return false +} + +module.exports = { + buildUrl, + getCurrentPageUrl, + isTabPage, + navigate, + redirect, + switchTab, + goBack, + redirectAfterLogin, + openLogin, + ensureLogin +} diff --git a/YumiNail-Admin-Program/utils/page-state.js b/YumiNail-Admin-Program/utils/page-state.js new file mode 100644 index 00000000..a1e9a7ad --- /dev/null +++ b/YumiNail-Admin-Program/utils/page-state.js @@ -0,0 +1,28 @@ +function ensureStore() { + const app = getApp() + app.globalData.pageDirtyFlags = app.globalData.pageDirtyFlags || {} + return app.globalData.pageDirtyFlags +} + +function markDirty(key) { + if (!key) { + return + } + const store = ensureStore() + store[key] = true +} + +function consumeDirty(key) { + if (!key) { + return false + } + const store = ensureStore() + const value = Boolean(store[key]) + delete store[key] + return value +} + +module.exports = { + markDirty, + consumeDirty +} diff --git a/YumiNail-Admin-Program/utils/permission.js b/YumiNail-Admin-Program/utils/permission.js new file mode 100644 index 00000000..92ae932b --- /dev/null +++ b/YumiNail-Admin-Program/utils/permission.js @@ -0,0 +1,189 @@ +const MANAGE_MODULES = [ + { + key: 'users', + title: '用户管理', + description: '用户资料、停用删除、解绑、余额与 VIP', + path: '/pages/users/index', + permissionCodes: ['user:view'], + requiresShopContext: true + }, + { + key: 'products', + title: '作品管理', + description: '作品新增、编辑、图片上传、点赞收藏维护', + path: '/pages/products/index', + permissionCodes: ['product:view'], + requiresShopContext: true + }, + { + key: 'coupons', + title: '优惠券', + description: '普通券、VIP 自动券、发放与活动配置', + path: '/pages/coupons/index', + permissionCodes: ['coupon:view'], + requiresShopContext: true + }, + { + key: 'tags', + title: '标签管理', + description: '店铺标签、颜色配置与作品关联', + path: '/pages/tags/index', + permissionCodes: ['tag:view'], + requiresShopContext: true + }, + { + key: 'artists', + title: '美甲师', + description: '美甲师资料、档期信息与作品绑定', + path: '/pages/artists/index', + permissionCodes: ['nail_artist:view'], + requiresShopContext: true + }, + { + key: 'shops', + title: '店铺管理', + description: '门店创建、启停、轮播图与店铺信息维护', + path: '/pages/shops/index', + permissionCodes: ['shop:view'], + requiresShopContext: false + }, + { + key: 'permissions', + title: '权限管理', + description: '权限字典、用户授权与范围控制', + path: '/pages/permissions/index', + permissionCodes: ['permission:view'], + requiresShopContext: false + } +] + +function getPermissionCodes(source) { + const list = Array.isArray(source) ? source : [] + + return list + .map(item => { + if (typeof item === 'string') { + return item + } + return item && item.permissionCode ? item.permissionCode : '' + }) + .filter(Boolean) +} + +function hasPermission(source, permissionCode) { + if (!permissionCode) { + return true + } + + const codes = getPermissionCodes(source) + return codes.includes(permissionCode) +} + +function hasAnyPermission(source, permissionCodes) { + const codes = Array.isArray(permissionCodes) ? permissionCodes : [] + if (!codes.length) { + return true + } + + return codes.some(code => hasPermission(source, code)) +} + +function hasAllPermissions(source, permissionCodes) { + const codes = Array.isArray(permissionCodes) ? permissionCodes : [] + if (!codes.length) { + return true + } + + return codes.every(code => hasPermission(source, code)) +} + +function isPlatformAdmin(userInfo) { + return Number(userInfo && userInfo.type) === 4 +} + +function isShopManager(userInfo) { + return Number(userInfo && userInfo.type) === 2 +} + +function isNailArtist(userInfo) { + return Number(userInfo && userInfo.type) === 3 +} + +function getRoleLabel(type) { + const value = Number(type) + if (value === 4) { + return '平台管理员' + } + if (value === 2) { + return '店长' + } + if (value === 3) { + return '美甲师' + } + return '用户' +} + +function groupPermissionsByGroup(permissions) { + return (Array.isArray(permissions) ? permissions : []).reduce((result, item) => { + const group = item && item.permissionGroup ? item.permissionGroup : '未分组' + if (!result[group]) { + result[group] = [] + } + result[group].push(item) + return result + }, {}) +} + +function checkModuleAccess(module, userInfo, permissionCodes, currentShop) { + if (!hasAnyPermission(permissionCodes, module.permissionCodes)) { + return { + allowed: false, + reason: '当前账号没有该板块权限' + } + } + + if (module.requiresShopContext && !currentShop) { + if (isPlatformAdmin(userInfo)) { + return { + allowed: false, + reason: '当前为无店铺登录,请先创建或切换店铺' + } + } + + return { + allowed: false, + reason: '当前账号没有可用店铺' + } + } + + return { + allowed: true, + reason: '' + } +} + +function getManageModules(userInfo, permissionCodes, currentShop) { + return MANAGE_MODULES.map(module => { + const access = checkModuleAccess(module, userInfo, permissionCodes, currentShop) + return { + ...module, + allowed: access.allowed, + disabledReason: access.reason + } + }) +} + +module.exports = { + MANAGE_MODULES, + getPermissionCodes, + hasPermission, + hasAnyPermission, + hasAllPermissions, + isPlatformAdmin, + isShopManager, + isNailArtist, + getRoleLabel, + groupPermissionsByGroup, + checkModuleAccess, + getManageModules +} diff --git a/YumiNail-Admin-Program/utils/request.js b/YumiNail-Admin-Program/utils/request.js new file mode 100644 index 00000000..dbb3a6f2 --- /dev/null +++ b/YumiNail-Admin-Program/utils/request.js @@ -0,0 +1,401 @@ +const auth = require('./auth') +const actionGuard = require('./action-guard') +const idleSession = require('./idle-session') +const { ADMIN_API_BASE_URL, REQUEST_TIMEOUT, ENABLE_REQUEST_SIGNING } = require('./config') +const { getDeviceId } = require('./device') +const { sha256Hex, hmacSha256Hex, buildCanonicalParams, buildJsonPayload, randomNonce } = require('./crypto') + +const DEVICE_ID_HEADER = 'X-Device-Id' +const HEADER_TIMESTAMP = 'X-Timestamp' +const HEADER_NONCE = 'X-Nonce' +const HEADER_SIGNATURE = 'X-Signature' +const HEADER_SIGNATURE_VERSION = 'X-Sign-Version' + +let isRefreshing = false +let requestQueue = [] +let redirectingToLogin = false +const inflightRequests = {} + +function buildRequestUrl(url, params) { + const query = Object.keys(params || {}) + .filter(key => params[key] !== undefined && params[key] !== null && params[key] !== '') + .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`) + .join('&') + + const target = `${ADMIN_API_BASE_URL}${url}` + return query ? `${target}${target.includes('?') ? '&' : '?'}${query}` : target +} + +function isAuthFreePath(url) { + return [ + '/auth/login', + '/auth/refresh', + '/auth/login-shops/' + ].some(path => String(url || '').includes(path)) +} + +function normalizeError(message, statusCode, raw) { + const error = new Error(message || '\u8bf7\u6c42\u5931\u8d25') + error.statusCode = statusCode + error.raw = raw + return error +} + +function rawRequest(options) { + idleSession.markActive() + return new Promise((resolve, reject) => { + wx.request({ + ...options, + success: resolve, + fail: reject + }) + }) +} + +function queueRequest(retry) { + return new Promise((resolve, reject) => { + requestQueue.push({ + resolve, + reject, + retry + }) + }) +} + +function flushQueue(error) { + const queue = requestQueue.slice() + requestQueue = [] + + queue.forEach(item => { + if (error) { + item.reject(error) + return + } + item.retry().then(item.resolve).catch(item.reject) + }) +} + +function redirectToLogin() { + if (redirectingToLogin) { + return + } + + const pages = getCurrentPages() + const current = pages[pages.length - 1] + if (current && current.route === 'pages/login/index') { + return + } + + redirectingToLogin = true + + const currentPath = current ? `/${current.route}` : '/pages/workbench/index' + const query = current && current.options ? current.options : {} + const queryString = Object.keys(query) + .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(query[key])}`) + .join('&') + const redirect = queryString ? `${currentPath}?${queryString}` : currentPath + + wx.showToast({ + title: '\u767b\u5f55\u5df2\u5931\u6548\uff0c\u8bf7\u91cd\u65b0\u767b\u5f55', + icon: 'none' + }) + + setTimeout(() => { + wx.reLaunch({ + url: `/pages/login/index?redirect=${encodeURIComponent(redirect)}`, + complete() { + redirectingToLogin = false + } + }) + }, 240) +} + +function buildSignatureHeaders(options) { + const headers = { + [DEVICE_ID_HEADER]: getDeviceId() + } + const method = String(options.method || 'GET').toUpperCase() + const accessToken = auth.getAccessToken() + if (accessToken && !isAuthFreePath(options.url)) { + headers.Authorization = `Bearer ${accessToken}` + } + + if (!ENABLE_REQUEST_SIGNING || !accessToken || isAuthFreePath(options.url) || ['GET', 'HEAD', 'OPTIONS'].includes(method)) { + return headers + } + + const contentType = String((options.header && options.header['Content-Type']) || options.contentType || 'application/json').toLowerCase() + const payload = contentType.includes('application/json') + ? buildJsonPayload(options.data) + : buildCanonicalParams(options.formData || options.data || options.params) + const timestamp = String(Date.now()) + const nonce = randomNonce() + const canonical = [ + method, + options.url, + timestamp, + nonce, + sha256Hex(payload) + ].join('\n') + + headers[HEADER_TIMESTAMP] = timestamp + headers[HEADER_NONCE] = nonce + headers[HEADER_SIGNATURE] = hmacSha256Hex(accessToken, canonical) + headers[HEADER_SIGNATURE_VERSION] = 'v1' + return headers +} + +async function refreshToken() { + const refreshTokenValue = auth.getRefreshToken() + if (!refreshTokenValue) { + throw normalizeError('\u7f3a\u5c11\u5237\u65b0\u4ee4\u724c', 401) + } + + const response = await rawRequest({ + url: `${ADMIN_API_BASE_URL}/auth/refresh`, + method: 'POST', + timeout: REQUEST_TIMEOUT, + header: { + 'Content-Type': 'application/json', + [DEVICE_ID_HEADER]: getDeviceId() + }, + data: { + refreshToken: refreshTokenValue + } + }) + + if (response.statusCode === 200 && response.data && response.data.code === 200 && response.data.data) { + auth.setSession(response.data.data) + const app = getApp() + if (app && typeof app.bootstrapSession === 'function') { + app.bootstrapSession() + } + return response.data.data + } + + throw normalizeError( + (response.data && response.data.message) || '\u5237\u65b0\u540e\u53f0\u767b\u5f55\u6001\u5931\u8d25', + response.statusCode, + response + ) +} + +async function handleUnauthorized(options) { + if (options._retry || isAuthFreePath(options.url)) { + const app = getApp() + if (app && typeof app.clearAdminSession === 'function') { + app.clearAdminSession() + } else { + auth.clearSession() + } + redirectToLogin() + throw normalizeError('\u767b\u5f55\u5df2\u5931\u6548\uff0c\u8bf7\u91cd\u65b0\u767b\u5f55', 401) + } + + if (isRefreshing) { + return queueRequest(() => request({ + ...options, + _retry: true + })) + } + + isRefreshing = true + try { + await refreshToken() + flushQueue(null) + return await request({ + ...options, + _retry: true + }) + } catch (error) { + flushQueue(error) + const app = getApp() + if (app && typeof app.clearAdminSession === 'function') { + app.clearAdminSession() + } else { + auth.clearSession() + } + redirectToLogin() + throw error + } finally { + isRefreshing = false + } +} + +async function unwrapResponse(response, options) { + idleSession.markActive() + + if (response.statusCode === 401) { + return handleUnauthorized(options) + } + + if (response.statusCode === 403) { + throw normalizeError( + (response.data && response.data.message) || '\u6743\u9650\u4e0d\u8db3', + response.statusCode, + response + ) + } + + if (response.statusCode >= 400) { + throw normalizeError( + (response.data && response.data.message) || '\u7f51\u7edc\u8bf7\u6c42\u5931\u8d25', + response.statusCode, + response + ) + } + + const payload = response.data + if (payload && typeof payload === 'object' && Object.prototype.hasOwnProperty.call(payload, 'code')) { + if (payload.code === 200) { + return payload.data + } + throw normalizeError(payload.message || '\u8bf7\u6c42\u5931\u8d25', payload.code, payload) + } + + return payload +} + +function buildDedupeKey(options, method) { + if (options.skipDedupe) { + return '' + } + if (options.dedupeKey) { + return `${method}:${options.dedupeKey}` + } + if (method === 'GET') { + return `${method}:${options.url}:${buildCanonicalParams(options.params)}` + } + return '' +} + +function isSafeMethod(method) { + return ['GET', 'HEAD', 'OPTIONS'].includes(method) +} + +function buildActionFingerprint(options, method) { + const paramsText = buildCanonicalParams(options.params) + const payloadText = isSafeMethod(method) ? '' : buildJsonPayload(options.data) + return sha256Hex([ + options.url || '', + paramsText, + payloadText + ].join('\n')) +} + +function resolveRepeatMessage(url) { + const path = String(url || '') + if (path.includes('/auth/login')) { + return '\u767b\u5f55\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u63d0\u4ea4' + } + if (path.includes('/auth/switch-shop')) { + return '\u95e8\u5e97\u5207\u6362\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c' + } + if (path.includes('/auth/logout')) { + return '\u9000\u51fa\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c' + } + if (path.includes('/coupon/distribute') || path.includes('/coupon/assign') || path.includes('/order/update-status')) { + return '\u64cd\u4f5c\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u63d0\u4ea4' + } + if (path.includes('/upload')) { + return '\u4e0a\u4f20\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c' + } + if ( + path.includes('/user/create') + || path.includes('/user/update') + || path.includes('/product/create') + || path.includes('/product/update') + || path.includes('/shops/create') + || path.includes('/shops/update') + || path.includes('/tag/create') + || path.includes('/tag/update') + || path.includes('/permission/create') + || path.includes('/permission/update') + || path.includes('/nail-artist/save') + ) { + return '\u4fdd\u5b58\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u63d0\u4ea4' + } + return '\u64cd\u4f5c\u8fdb\u884c\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u70b9\u51fb' +} + +function buildActionGuardConfig(options, method) { + if (options.skipActionGuard || isSafeMethod(method)) { + return null + } + + return { + scope: options.guardScope, + key: options.actionKey || `${method}:${options.url}:${buildActionFingerprint(options, method)}`, + message: options.repeatMessage || resolveRepeatMessage(options.url) + } +} + +function request(options) { + const method = String(options.method || 'GET').toUpperCase() + const dedupeKey = buildDedupeKey(options, method) + if (dedupeKey && inflightRequests[dedupeKey]) { + return inflightRequests[dedupeKey] + } + + const signatureHeaders = buildSignatureHeaders({ + url: options.url, + method, + data: options.data, + params: options.params, + header: options.header + }) + const header = { + 'Content-Type': 'application/json', + ...signatureHeaders, + ...(options.header || {}) + } + const requestOptions = { + ...options, + method, + header + } + const actionGuardConfig = buildActionGuardConfig(options, method) + + const executeRequest = () => new Promise((resolve, reject) => { + wx.request({ + url: buildRequestUrl(options.url, options.params), + method, + timeout: options.timeout || REQUEST_TIMEOUT, + header, + data: method === 'GET' ? undefined : options.data, + success: async response => { + try { + const data = await unwrapResponse(response, requestOptions) + resolve(data) + } catch (error) { + reject(error) + } + }, + fail: error => { + reject(normalizeError(error.errMsg || '\u7f51\u7edc\u5f02\u5e38\uff0c\u8bf7\u7a0d\u540e\u91cd\u8bd5', 0, error)) + } + }) + }) + + const task = (actionGuardConfig + ? actionGuard.run(actionGuardConfig.scope, actionGuardConfig.key, executeRequest, { + message: actionGuardConfig.message + }) + : executeRequest() + ).finally(() => { + if (dedupeKey) { + delete inflightRequests[dedupeKey] + } + }) + + if (dedupeKey) { + inflightRequests[dedupeKey] = task + } + + return task +} + +request.buildSignatureHeaders = buildSignatureHeaders +request.getDeviceIdHeaderName = () => DEVICE_ID_HEADER + +module.exports = request diff --git a/YumiNail-Admin-Program/utils/storage.js b/YumiNail-Admin-Program/utils/storage.js new file mode 100644 index 00000000..6df795d8 --- /dev/null +++ b/YumiNail-Admin-Program/utils/storage.js @@ -0,0 +1,49 @@ +const STORAGE_KEYS = { + ACCESS_TOKEN: 'adminAccessToken', + REFRESH_TOKEN: 'adminRefreshToken', + USER_INFO: 'adminUserInfo', + PERMISSIONS: 'adminPermissions', + CURRENT_SHOP: 'adminCurrentShop', + DEVICE_ID: 'adminMiniDeviceId' +} + +const TEMP_RECORD_PREFIX = 'adminTempRecord:' + +function getStorage(key, defaultValue) { + try { + const value = wx.getStorageSync(key) + return value === '' || value === undefined ? defaultValue : value + } catch (error) { + return defaultValue + } +} + +function setStorage(key, value) { + wx.setStorageSync(key, value) +} + +function removeStorage(key) { + wx.removeStorageSync(key) +} + +function setTempRecord(name, value) { + setStorage(`${TEMP_RECORD_PREFIX}${name}`, value) +} + +function getTempRecord(name, defaultValue) { + return getStorage(`${TEMP_RECORD_PREFIX}${name}`, defaultValue) +} + +function clearTempRecord(name) { + removeStorage(`${TEMP_RECORD_PREFIX}${name}`) +} + +module.exports = { + STORAGE_KEYS, + getStorage, + setStorage, + removeStorage, + setTempRecord, + getTempRecord, + clearTempRecord +} diff --git a/YumiNail-Admin-Program/utils/upload.js b/YumiNail-Admin-Program/utils/upload.js new file mode 100644 index 00000000..12c7023a --- /dev/null +++ b/YumiNail-Admin-Program/utils/upload.js @@ -0,0 +1,198 @@ +const fileApi = require('../api/file') + +function getFileSystemManager() { + return wx.getFileSystemManager() +} + +function getFileInfo(filePath) { + return new Promise((resolve, reject) => { + wx.getFileInfo({ + filePath, + success: resolve, + fail: reject + }) + }) +} + +function readFileBuffer(filePath) { + return new Promise((resolve, reject) => { + getFileSystemManager().readFile({ + filePath, + success: result => resolve(result.data), + fail: reject + }) + }) +} + +function writeChunkFile(filePath, data) { + return new Promise((resolve, reject) => { + getFileSystemManager().writeFile({ + filePath, + data, + encoding: 'binary', + success: resolve, + fail: reject + }) + }) +} + +function removeFile(filePath) { + return new Promise(resolve => { + getFileSystemManager().unlink({ + filePath, + success: resolve, + fail: resolve + }) + }) +} + +function normalizeSelectedFiles(files) { + return (Array.isArray(files) ? files : []).map((item, index) => { + if (typeof item === 'string') { + return { + tempFilePath: item, + fileName: `image-${index + 1}.jpg` + } + } + + return { + tempFilePath: item.tempFilePath || item.path || '', + fileName: item.fileName || item.name || `image-${index + 1}.jpg` + } + }).filter(item => item.tempFilePath) +} + +function createFingerprint(seed) { + let hash = 0 + const text = String(seed || '') + + for (let index = 0; index < text.length; index += 1) { + hash = ((hash << 5) - hash) + text.charCodeAt(index) + hash |= 0 + } + + return `mini-${Math.abs(hash)}` +} + +function resolveContentType(fileName) { + const value = String(fileName || '').toLowerCase() + if (value.endsWith('.png')) { + return 'image/png' + } + if (value.endsWith('.webp')) { + return 'image/webp' + } + if (value.endsWith('.gif')) { + return 'image/gif' + } + return 'image/jpeg' +} + +async function uploadSingleFile(file, scene, onProgress) { + const fileInfo = await getFileInfo(file.tempFilePath) + const buffer = await readFileBuffer(file.tempFilePath) + const contentType = resolveContentType(file.fileName) + const session = await fileApi.initChunkUpload({ + fileName: file.fileName, + fileSize: fileInfo.size, + contentType, + fileFingerprint: createFingerprint(`${file.fileName}|${fileInfo.size}|${file.tempFilePath}`), + scene + }) + + const uploadedChunkSet = new Set(session.uploadedChunks || []) + let uploadedBytes = 0 + const chunkSize = Number(session.chunkSize || 0) + const totalChunks = Number(session.totalChunks || 0) + + if (!chunkSize || !totalChunks) { + throw new Error('上传会话初始化失败') + } + + Array.from(uploadedChunkSet).forEach(chunkIndex => { + const start = chunkIndex * chunkSize + const end = Math.min(start + chunkSize, fileInfo.size) + uploadedBytes += Math.max(end - start, 0) + }) + + onProgress(Math.min((uploadedBytes / Math.max(fileInfo.size, 1)) * 100, 100)) + + for (let chunkIndex = 0; chunkIndex < totalChunks; chunkIndex += 1) { + if (uploadedChunkSet.has(chunkIndex)) { + continue + } + + const start = chunkIndex * chunkSize + const end = Math.min(start + chunkSize, fileInfo.size) + const chunkBuffer = buffer.slice(start, end) + const chunkPath = `${wx.env.USER_DATA_PATH}/${session.uploadId}-${chunkIndex}.part` + + await writeChunkFile(chunkPath, chunkBuffer) + + try { + await fileApi.uploadChunkFile({ + filePath: chunkPath, + uploadId: session.uploadId, + chunkIndex, + totalChunks, + onProgress(progress) { + const loaded = Number(progress && progress.totalBytesSent) || 0 + const currentBytes = Math.min(loaded, end - start) + const percent = ((uploadedBytes + currentBytes) / Math.max(fileInfo.size, 1)) * 100 + onProgress(Math.min(percent, 99.9)) + } + }) + } finally { + await removeFile(chunkPath) + } + + uploadedBytes += (end - start) + onProgress(Math.min((uploadedBytes / Math.max(fileInfo.size, 1)) * 100, 99.9)) + } + + const result = await fileApi.completeChunkUpload(session.uploadId) + onProgress(100) + return result +} + +async function uploadImageFiles(options) { + const files = normalizeSelectedFiles(options && options.files) + const scene = options && options.scene ? options.scene : 'admin-product-image' + const onProgress = typeof options.onProgress === 'function' ? options.onProgress : () => {} + const results = [] + + for (let index = 0; index < files.length; index += 1) { + const basePercent = (index / Math.max(files.length, 1)) * 100 + const filePercentSize = 100 / Math.max(files.length, 1) + + const result = await uploadSingleFile(files[index], scene, percent => { + onProgress(Math.min(basePercent + (percent / 100) * filePercentSize, 100)) + }) + + results.push(result) + } + + onProgress(100) + return results +} + +function chooseImageFiles(options) { + const config = options || {} + + return new Promise((resolve, reject) => { + wx.chooseMedia({ + count: config.count || 9, + mediaType: ['image'], + sourceType: ['album', 'camera'], + success: result => { + resolve(normalizeSelectedFiles(result.tempFiles || [])) + }, + fail: reject + }) + }) +} + +module.exports = { + chooseImageFiles, + uploadImageFiles +} diff --git a/YumiNail-Core/pom.xml b/YumiNail-Core/pom.xml index 996be011..bd9a4d28 100644 --- a/YumiNail-Core/pom.xml +++ b/YumiNail-Core/pom.xml @@ -182,6 +182,12 @@ spring-security-crypto + + + com.github.ben-manes.caffeine + caffeine + + io.minio diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/annotation/OperationGuard.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/annotation/OperationGuard.java new file mode 100644 index 00000000..4ec3b969 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/annotation/OperationGuard.java @@ -0,0 +1,21 @@ +package com.xiaowang.yuminailcore.annotation; + +import com.xiaowang.yuminailcore.support.security.OperationGuardStrategy; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +public @interface OperationGuard { + + String action(); + + OperationGuardStrategy strategy() default OperationGuardStrategy.REJECT_IF_RUNNING; + + int ttlSeconds() default 10; + + String message() default "操作进行中,请勿重复点击"; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/aspect/OperationGuardAspect.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/aspect/OperationGuardAspect.java new file mode 100644 index 00000000..8cd35c6b --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/aspect/OperationGuardAspect.java @@ -0,0 +1,54 @@ +package com.xiaowang.yuminailcore.aspect; + +import com.xiaowang.yuminailcore.annotation.OperationGuard; +import com.xiaowang.yuminailcore.common.Result; +import com.xiaowang.yuminailcore.support.security.OperationGuardService; +import com.xiaowang.yuminailcore.support.security.OperationGuardStrategy; +import lombok.RequiredArgsConstructor; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import javax.servlet.http.HttpServletRequest; +import java.time.Duration; + +@Aspect +@Component +@Order(100) +@RequiredArgsConstructor +public class OperationGuardAspect { + + private final OperationGuardService operationGuardService; + + @Around("@annotation(operationGuard)") + public Object guardOperation(ProceedingJoinPoint joinPoint, OperationGuard operationGuard) throws Throwable { + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + if (attributes == null) { + return Result.error(500, "无法获取请求信息"); + } + + HttpServletRequest request = attributes.getRequest(); + OperationGuardService.GuardHandle handle = operationGuardService.tryAcquire( + request, + operationGuard.action(), + Duration.ofSeconds(Math.max(1, operationGuard.ttlSeconds())) + ); + if (!handle.acquired()) { + if (operationGuard.strategy() == OperationGuardStrategy.NOOP_IF_DUPLICATE) { + return Result.success(); + } + return Result.error(operationGuard.message()); + } + + try { + return joinPoint.proceed(); + } finally { + operationGuardService.release(handle); + } + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/aspect/PermissionAspect.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/aspect/PermissionAspect.java index 94642b1e..efc219fe 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/aspect/PermissionAspect.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/aspect/PermissionAspect.java @@ -13,6 +13,8 @@ import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.reflect.MethodSignature; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import org.springframework.web.context.request.RequestContextHolder; @@ -23,6 +25,7 @@ import java.lang.reflect.Method; @Aspect @Component +@Order(Ordered.HIGHEST_PRECEDENCE) @RequiredArgsConstructor public class PermissionAspect { diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/AppCacheProperties.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/AppCacheProperties.java new file mode 100644 index 00000000..9b7ffc17 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/AppCacheProperties.java @@ -0,0 +1,40 @@ +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.cache") +public class AppCacheProperties { + + private long localMaxSize = 2048; + + private CacheSpec productDetail = new CacheSpec(120, 900); + + private CacheSpec productList = new CacheSpec(60, 300); + + private CacheSpec productSearch = new CacheSpec(60, 300); + + private CacheSpec shop = new CacheSpec(180, 900); + + private CacheSpec tag = new CacheSpec(300, 1200); + + @Data + public static class CacheSpec { + private long localTtlSeconds; + private long redisTtlSeconds; + + public CacheSpec() { + } + + public CacheSpec(long localTtlSeconds, long redisTtlSeconds) { + this.localTtlSeconds = localTtlSeconds; + this.redisTtlSeconds = redisTtlSeconds; + } + } +} 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 060cfc3a..2c238ed6 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 @@ -4,9 +4,13 @@ import com.xiaowang.yuminailcore.entity.UserDO; import com.xiaowang.yuminailcore.mapper.UserMapper; import com.xiaowang.yuminailcore.support.RequestShopContext; import com.xiaowang.yuminailcore.support.UserShopBindingSupport; +import com.xiaowang.yuminailcore.support.security.RequestSignatureService; +import com.xiaowang.yuminailcore.support.security.RequestThrottleService; +import com.xiaowang.yuminailcore.support.security.UserSessionService; import com.xiaowang.yuminailcore.utils.JwtUtil; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; @@ -19,6 +23,9 @@ public class AuthInterceptor implements HandlerInterceptor { private final JwtUtil jwtUtil; private final UserMapper userMapper; private final UserShopBindingSupport userShopBindingSupport; + private final UserSessionService userSessionService; + private final RequestSignatureService requestSignatureService; + private final RequestThrottleService requestThrottleService; private static final String AUTHORIZATION_HEADER = "Authorization"; private static final String BEARER_PREFIX = "Bearer "; @@ -39,9 +46,7 @@ public class AuthInterceptor implements HandlerInterceptor { String token = authHeader.substring(BEARER_PREFIX.length()); if (!jwtUtil.validateToken(token)) { - response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); - response.setContentType("application/json;charset=UTF-8"); - response.getWriter().write("{\"code\":401,\"message\":\"Token无效或已过期\"}"); + writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "Token无效或已过期"); return false; } @@ -53,6 +58,13 @@ public class AuthInterceptor implements HandlerInterceptor { Long userId = jwtUtil.getUserIdFromToken(token); String account = jwtUtil.getAccountFromToken(token); Long currentShopId = jwtUtil.getShopIdFromToken(token); + String sessionId = jwtUtil.getSessionIdFromToken(token); + String jti = jwtUtil.getJtiFromToken(token); + if (!userSessionService.isAccessSessionActive(userId, sessionId, jti)) { + writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "登录态已失效,请重新登录"); + return false; + } + UserDO currentUser = userMapper.selectById(userId); if (currentUser == null || Integer.valueOf(1).equals(currentUser.getIsDelete())) { writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "用户不存在或已失效"); @@ -84,14 +96,48 @@ public class AuthInterceptor implements HandlerInterceptor { return false; } + if (requiresSignature(request)) { + try { + requestSignatureService.validateRequest(request, token, userId); + } catch (RuntimeException exception) { + writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, exception.getMessage()); + return false; + } + } + + if (requiresWriteRateLimit(request)) { + try { + requestThrottleService.checkAuthenticatedWrite(request, userId); + } catch (RuntimeException exception) { + writeJsonResponse(response, 429, exception.getMessage()); + return false; + } + } + request.setAttribute("userId", userId); request.setAttribute("account", account); request.setAttribute("userType", currentUser.getType()); + request.setAttribute("accessToken", token); + request.setAttribute("sessionId", sessionId); + request.setAttribute("tokenJti", jti); request.setAttribute(RequestShopContext.CURRENT_SHOP_ID_ATTRIBUTE, currentShopId); return true; } + private boolean requiresSignature(HttpServletRequest request) { + return requiresWriteRateLimit(request); + } + + private boolean requiresWriteRateLimit(HttpServletRequest request) { + String method = request.getMethod(); + if (!StringUtils.hasText(method)) { + return false; + } + String normalized = method.toUpperCase(); + return !("GET".equals(normalized) || "HEAD".equals(normalized) || "OPTIONS".equals(normalized)); + } + private boolean isAdminPath(String path) { return path.startsWith("/admin/") || path.startsWith("/order/admin/"); } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/JwtProperties.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/JwtProperties.java new file mode 100644 index 00000000..2ec3281d --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/JwtProperties.java @@ -0,0 +1,39 @@ +package com.xiaowang.yuminailcore.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +/** + * JWT 配置。 + */ +@Data +@Configuration +@ConfigurationProperties(prefix = "yuminail.security.jwt") +public class JwtProperties { + + /** + * HS512 密钥,生产环境请通过 Nacos 覆盖。 + */ + private String secret = "yuminail-secret-key-for-jwt-token-generation-2026-must-be-at-least-512-bits-long-for-hs512-algorithm-security-requirements"; + + /** + * Token 发行者。 + */ + private String issuer = "yuminail"; + + /** + * AccessToken 有效期,单位秒。 + */ + private long accessTokenExpirationSeconds = 2 * 60 * 60; + + /** + * RefreshToken 有效期,单位秒。 + */ + private long refreshTokenExpirationSeconds = 7 * 24 * 60 * 60; + + /** + * 时钟偏移容忍,单位秒。 + */ + private long clockSkewSeconds = 30; +} 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 new file mode 100644 index 00000000..1954bb98 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/RateLimitProperties.java @@ -0,0 +1,38 @@ +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.rate-limit") +public class RateLimitProperties { + + private LimitRule login = new LimitRule(10, 60); + + private LimitRule sendCode = new LimitRule(5, 60); + + private LimitRule resetPassword = new LimitRule(5, 600); + + private LimitRule authenticatedWrite = new LimitRule(80, 60); + + private LimitRule orderCreate = new LimitRule(10, 60); + + @Data + public static class LimitRule { + private int limit; + private long windowSeconds; + + public LimitRule() { + } + + public LimitRule(int limit, long windowSeconds) { + this.limit = limit; + this.windowSeconds = windowSeconds; + } + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/RequestSignatureProperties.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/RequestSignatureProperties.java new file mode 100644 index 00000000..1022f003 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/RequestSignatureProperties.java @@ -0,0 +1,29 @@ +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.signature") +public class RequestSignatureProperties { + + /** + * 是否启用签名校验。 + */ + private boolean enabled = true; + + /** + * 时间窗口,单位秒。 + */ + private long windowSeconds = 300; + + /** + * nonce 额外保留时间,单位秒。 + */ + private long nonceRetentionSeconds = 600; +} 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 8a975730..3352914c 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 @@ -1,10 +1,13 @@ package com.xiaowang.yuminailcore.controller; +import com.xiaowang.yuminailcore.annotation.OperationGuard; import com.xiaowang.yuminailcore.common.Result; 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.support.security.RequestThrottleService; +import com.xiaowang.yuminailcore.support.security.OperationGuardStrategy; import com.xiaowang.yuminailcore.utils.AccountValidationUtils; import com.xiaowang.yuminailcore.vo.LoginShopSelectionVO; import com.xiaowang.yuminailcore.vo.LoginResponseVO; @@ -20,9 +23,12 @@ import javax.servlet.http.HttpServletRequest; public class AdminAuthController { private final UserService userService; + private final RequestThrottleService requestThrottleService; @PostMapping("/login") - public Result login(@Valid @RequestBody LoginRequestDTO loginRequestDTO) { + @OperationGuard(action = "admin-login", ttlSeconds = 8, message = "登录处理中,请勿重复提交") + public Result login(HttpServletRequest request, @Valid @RequestBody LoginRequestDTO loginRequestDTO) { + requestThrottleService.checkLogin(request, loginRequestDTO.getAccount()); LoginResponseVO loginResponseVO = userService.adminLogin(loginRequestDTO); return Result.success(loginResponseVO); } @@ -33,14 +39,16 @@ public class AdminAuthController { } @PostMapping("/switch-shop") + @OperationGuard(action = "admin-switch-shop", ttlSeconds = 10, message = "门店切换中,请勿重复操作") public Result switchShop(HttpServletRequest request, @RequestBody SwitchShopRequestDTO switchShopRequestDTO) { Long userId = (Long) request.getAttribute("userId"); - return Result.success(userService.switchAdminShop(userId, switchShopRequestDTO.getShopId())); + return Result.success(userService.switchAdminShop(userId, switchShopRequestDTO.getShopId(), (String) request.getAttribute("sessionId"))); } @PostMapping("/logout") - public Result logout() { - return Result.success(true); + @OperationGuard(action = "admin-logout", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 5) + public Result logout(HttpServletRequest request) { + return Result.success(userService.logout((String) request.getAttribute("sessionId"))); } @PostMapping("/refresh") 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 2735c92f..f68ed184 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 @@ -1,6 +1,7 @@ package com.xiaowang.yuminailcore.controller; import com.xiaowang.yuminailcore.annotation.RequirePermission; +import com.xiaowang.yuminailcore.annotation.OperationGuard; import com.xiaowang.yuminailcore.common.Result; import com.xiaowang.yuminailcore.dto.CouponDTO; import com.xiaowang.yuminailcore.entity.UserDO; @@ -34,6 +35,7 @@ public class AdminCouponController { */ @PostMapping("/create") @RequirePermission("coupon:create") + @OperationGuard(action = "admin-coupon-create", ttlSeconds = 10, message = "保存处理中,请勿重复提交") public Result createCoupon(HttpServletRequest request, @RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); shopId = adminScopeHelper.resolveShopScope(currentUser, shopId != null ? shopId : couponDTO.getShopId()); @@ -46,6 +48,7 @@ public class AdminCouponController { */ @PutMapping("/update/{id}") @RequirePermission("coupon:edit") + @OperationGuard(action = "admin-coupon-update", ttlSeconds = 10, message = "保存处理中,请勿重复提交") public Result updateCoupon(HttpServletRequest request, @PathVariable Long id, @RequestBody CouponDTO couponDTO, @RequestParam(required = false) Long shopId) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); CouponVO couponVO = couponService.getCouponById(id); @@ -64,6 +67,7 @@ public class AdminCouponController { */ @DeleteMapping("/delete/{id}") @RequirePermission("coupon:delete") + @OperationGuard(action = "admin-coupon-delete", ttlSeconds = 10, message = "操作处理中,请勿重复提交") public Result deleteCoupon(HttpServletRequest request, @PathVariable Long id, @RequestParam(required = false) Long shopId) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); CouponVO couponVO = couponService.getCouponById(id); @@ -125,6 +129,7 @@ public class AdminCouponController { */ @PostMapping("/assign") @RequirePermission("coupon:assign") + @OperationGuard(action = "admin-coupon-assign", ttlSeconds = 15, message = "操作处理中,请勿重复提交") public Result assignCouponToUser(HttpServletRequest request, @RequestParam Long userId, @RequestParam Long couponId, @RequestParam(required = false) Long shopId) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); CouponVO couponVO = couponService.getCouponById(couponId); @@ -147,6 +152,7 @@ public class AdminCouponController { */ @PostMapping("/distribute") @RequirePermission("coupon:assign") + @OperationGuard(action = "admin-coupon-distribute", ttlSeconds = 15, message = "操作处理中,请勿重复提交") public Result distributeCoupon(HttpServletRequest request, @RequestParam Long couponId, @RequestParam List userIds, @RequestParam Integer quantity, @RequestParam(required = false) Long shopId) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); CouponVO couponVO = couponService.getCouponById(couponId); 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 0d1b1baa..3de2852d 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 @@ -1,6 +1,7 @@ package com.xiaowang.yuminailcore.controller; import com.xiaowang.yuminailcore.annotation.RequirePermission; +import com.xiaowang.yuminailcore.annotation.OperationGuard; import com.xiaowang.yuminailcore.common.Result; import com.xiaowang.yuminailcore.dto.NailArtistInfoDTO; import com.xiaowang.yuminailcore.entity.UserDO; @@ -75,6 +76,7 @@ public class AdminNailArtistController { @RequirePermission("nail_artist:edit") @PostMapping("/save") + @OperationGuard(action = "admin-nail-artist-save", ttlSeconds = 10, message = "保存处理中,请勿重复提交") 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 74ef3d5b..511fd207 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 @@ -1,6 +1,7 @@ package com.xiaowang.yuminailcore.controller; import com.xiaowang.yuminailcore.annotation.RequirePermission; +import com.xiaowang.yuminailcore.annotation.OperationGuard; import com.xiaowang.yuminailcore.common.Result; import com.xiaowang.yuminailcore.entity.UserDO; import com.xiaowang.yuminailcore.service.OrderService; @@ -81,6 +82,7 @@ public class AdminOrderController { */ @PutMapping("/update-status/{id}") @RequirePermission("order:process") + @OperationGuard(action = "admin-order-update-status", ttlSeconds = 15, message = "操作处理中,请勿重复提交") public Result updateOrderStatus(HttpServletRequest request, @PathVariable Long id, @RequestParam Integer status) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); if (Integer.valueOf(3).equals(currentUser.getType())) { 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 5d412c2e..981b049c 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 @@ -1,6 +1,7 @@ package com.xiaowang.yuminailcore.controller; import com.xiaowang.yuminailcore.annotation.RequirePermission; +import com.xiaowang.yuminailcore.annotation.OperationGuard; import com.xiaowang.yuminailcore.common.Result; import com.xiaowang.yuminailcore.dto.PermissionDTO; import com.xiaowang.yuminailcore.dto.UserPermissionDTO; @@ -26,6 +27,7 @@ public class AdminPermissionController { @PostMapping("/create") @RequirePermission("permission:create") + @OperationGuard(action = "admin-permission-create", ttlSeconds = 10, message = "保存处理中,请勿重复提交") public Result createPermission(HttpServletRequest request, @RequestBody PermissionDTO permissionDTO) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以维护权限定义"); @@ -35,6 +37,7 @@ public class AdminPermissionController { @PutMapping("/update/{id}") @RequirePermission("permission:edit") + @OperationGuard(action = "admin-permission-update", ttlSeconds = 10, message = "保存处理中,请勿重复提交") public Result updatePermission(HttpServletRequest request, @PathVariable Long id, @RequestBody PermissionDTO permissionDTO) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以维护权限定义"); @@ -44,6 +47,7 @@ public class AdminPermissionController { @DeleteMapping("/delete/{id}") @RequirePermission("permission:delete") + @OperationGuard(action = "admin-permission-delete", ttlSeconds = 10, message = "操作处理中,请勿重复提交") public Result deletePermission(HttpServletRequest request, @PathVariable Long id) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以维护权限定义"); @@ -108,6 +112,7 @@ public class AdminPermissionController { @PostMapping("/assign/{userId}") @RequirePermission("permission:assign") + @OperationGuard(action = "admin-permission-assign", ttlSeconds = 15, message = "操作处理中,请勿重复提交") public Result assignPermissions( HttpServletRequest request, @PathVariable Long 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 09e313cd..4e809fd9 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 @@ -1,6 +1,7 @@ package com.xiaowang.yuminailcore.controller; import com.xiaowang.yuminailcore.annotation.RequirePermission; +import com.xiaowang.yuminailcore.annotation.OperationGuard; import com.xiaowang.yuminailcore.common.Result; import com.xiaowang.yuminailcore.dto.ProductDTO; import com.xiaowang.yuminailcore.entity.UserDO; @@ -39,6 +40,7 @@ public class AdminProductController { @PostMapping("/create") @RequirePermission("product:create") + @OperationGuard(action = "admin-product-create", ttlSeconds = 10, message = "保存处理中,请勿重复提交") public Result createProduct(HttpServletRequest request, @RequestBody ProductDTO productDTO) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); productDTO.setShopId(adminScopeHelper.resolveShopScope(currentUser, productDTO.getShopId())); @@ -48,6 +50,7 @@ public class AdminProductController { @PutMapping("/update/{id}") @RequirePermission("product:edit") + @OperationGuard(action = "admin-product-update", ttlSeconds = 10, message = "保存处理中,请勿重复提交") public Result updateProduct(HttpServletRequest request, @PathVariable Long id, @RequestBody ProductDTO productDTO) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); ProductVO productVO = productService.getProductById(id); @@ -63,6 +66,7 @@ public class AdminProductController { @DeleteMapping("/delete/{id}") @RequirePermission("product:delete") + @OperationGuard(action = "admin-product-delete", ttlSeconds = 10, message = "操作处理中,请勿重复提交") public Result deleteProduct(HttpServletRequest request, @PathVariable Long id) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); ProductVO productVO = productService.getProductById(id); 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 27f81938..0fbca040 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 @@ -1,6 +1,7 @@ package com.xiaowang.yuminailcore.controller; import com.xiaowang.yuminailcore.annotation.RequirePermission; +import com.xiaowang.yuminailcore.annotation.OperationGuard; import com.xiaowang.yuminailcore.common.Result; import com.xiaowang.yuminailcore.dto.ShopDTO; import com.xiaowang.yuminailcore.entity.UserDO; @@ -40,6 +41,7 @@ public class AdminShopController { @PostMapping("/create") @RequirePermission("shop:create") + @OperationGuard(action = "admin-shop-create", ttlSeconds = 10, message = "保存处理中,请勿重复提交") public Result createShop(HttpServletRequest request, @RequestBody ShopDTO shopDTO) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以创建店铺"); @@ -49,6 +51,7 @@ public class AdminShopController { @PutMapping("/update/{id}") @RequirePermission("shop:edit") + @OperationGuard(action = "admin-shop-update", ttlSeconds = 10, message = "保存处理中,请勿重复提交") public Result updateShop(HttpServletRequest request, @PathVariable Long id, @RequestBody ShopDTO shopDTO) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); ShopVO shopVO = shopService.getShopById(id); @@ -62,6 +65,7 @@ public class AdminShopController { @DeleteMapping("/delete/{id}") @RequirePermission("shop:delete") + @OperationGuard(action = "admin-shop-delete", ttlSeconds = 10, message = "操作处理中,请勿重复提交") public Result deleteShop(HttpServletRequest request, @PathVariable Long id) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以删除店铺"); @@ -71,6 +75,7 @@ public class AdminShopController { @PutMapping("/status/{id}") @RequirePermission("shop:edit") + @OperationGuard(action = "admin-shop-status", ttlSeconds = 10, message = "操作处理中,请勿重复提交") public Result updateShopStatus(HttpServletRequest request, @PathVariable Long id, @RequestBody StatusRequest statusRequest) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以启停店铺"); 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 2ddaa091..5dfa4835 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 @@ -1,6 +1,7 @@ package com.xiaowang.yuminailcore.controller; import com.xiaowang.yuminailcore.annotation.RequirePermission; +import com.xiaowang.yuminailcore.annotation.OperationGuard; import com.xiaowang.yuminailcore.common.Result; import com.xiaowang.yuminailcore.dto.TagDTO; import com.xiaowang.yuminailcore.entity.UserDO; @@ -29,6 +30,7 @@ public class AdminTagController { */ @PostMapping("/create") @RequirePermission("tag:create") + @OperationGuard(action = "admin-tag-create", ttlSeconds = 10, message = "保存处理中,请勿重复提交") public Result createTag(HttpServletRequest request, @RequestBody TagDTO tagDTO) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); tagDTO.setShopId(adminScopeHelper.resolveShopScope(currentUser, tagDTO.getShopId())); @@ -41,6 +43,7 @@ public class AdminTagController { */ @PutMapping("/update/{id}") @RequirePermission("tag:edit") + @OperationGuard(action = "admin-tag-update", ttlSeconds = 10, message = "保存处理中,请勿重复提交") public Result updateTag(HttpServletRequest request, @PathVariable Long id, @RequestBody TagDTO tagDTO) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); TagVO tagVO = tagService.getTagById(id); @@ -59,6 +62,7 @@ public class AdminTagController { */ @DeleteMapping("/delete/{id}") @RequirePermission("tag:delete") + @OperationGuard(action = "admin-tag-delete", ttlSeconds = 10, message = "操作处理中,请勿重复提交") public Result deleteTag(HttpServletRequest request, @PathVariable Long id) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); TagVO tagVO = tagService.getTagById(id); 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 174bbfff..9f1d720b 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 @@ -1,6 +1,7 @@ package com.xiaowang.yuminailcore.controller; import com.xiaowang.yuminailcore.annotation.RequirePermission; +import com.xiaowang.yuminailcore.annotation.OperationGuard; import com.xiaowang.yuminailcore.common.Result; import com.xiaowang.yuminailcore.dto.AdminUserBalanceChangeDTO; import com.xiaowang.yuminailcore.dto.AdminUserVipOverrideDTO; @@ -49,6 +50,7 @@ public class AdminUserController { @PostMapping("/create") @RequirePermission("user:create") + @OperationGuard(action = "admin-user-create", ttlSeconds = 10, message = "保存处理中,请勿重复提交") public Result createUser(HttpServletRequest request, @Valid @RequestBody UserDTO userDTO) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); adminScopeHelper.ensureAssignableUserType(currentUser, userDTO.getType()); @@ -63,6 +65,7 @@ public class AdminUserController { @PutMapping("/update/{id}") @RequirePermission("user:edit") + @OperationGuard(action = "admin-user-update", ttlSeconds = 10, message = "保存处理中,请勿重复提交") public Result updateUser(HttpServletRequest request, @PathVariable Long id, @Valid @RequestBody UserDTO userDTO) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); UserVO targetUser = userService.getUserById(id); @@ -83,6 +86,7 @@ public class AdminUserController { @PutMapping("/status/{id}") @RequirePermission("user:disable") + @OperationGuard(action = "admin-user-status", ttlSeconds = 10, message = "操作处理中,请勿重复提交") public Result updateUserStatus(HttpServletRequest httpRequest, @PathVariable Long id, @RequestBody StatusRequest request) { UserDO currentUser = adminScopeHelper.getCurrentUser(httpRequest); adminScopeHelper.requirePlatformAdmin(currentUser, "仅系统管理员可以停用用户"); @@ -100,6 +104,7 @@ public class AdminUserController { @PostMapping("/reset-password/{userId}") @RequirePermission("user:reset_password") + @OperationGuard(action = "admin-user-reset-password", ttlSeconds = 10, message = "操作处理中,请勿重复提交") public Result resetPassword(HttpServletRequest request, @PathVariable Long userId) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); UserVO targetUser = userService.getUserById(userId); @@ -114,6 +119,7 @@ public class AdminUserController { @DeleteMapping("/delete/{id}") @RequirePermission("user:delete") + @OperationGuard(action = "admin-user-delete", ttlSeconds = 10, message = "操作处理中,请勿重复提交") public Result deleteUser(HttpServletRequest request, @PathVariable Long id) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); adminScopeHelper.requirePlatformAdmin(currentUser, "仅系统管理员可以删除用户"); @@ -130,6 +136,7 @@ public class AdminUserController { @PutMapping("/unbind/{id}") @RequirePermission("user:unbind") + @OperationGuard(action = "admin-user-unbind", ttlSeconds = 10, message = "操作处理中,请勿重复提交") public Result unbindUser(HttpServletRequest request, @PathVariable Long id) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); UserVO targetUser = userService.getUserById(id); @@ -165,6 +172,7 @@ public class AdminUserController { @PostMapping("/{id}/balance/change") @RequirePermission("user:balance:manage") + @OperationGuard(action = "admin-user-balance-change", ttlSeconds = 15, message = "操作处理中,请勿重复提交") public Result changeUserBalance( HttpServletRequest request, @PathVariable Long id, @@ -178,6 +186,7 @@ public class AdminUserController { @PostMapping("/{id}/vip/override") @RequirePermission("user:vip:manage") + @OperationGuard(action = "admin-user-vip-override", ttlSeconds = 15, message = "操作处理中,请勿重复提交") public Result overrideUserVip( HttpServletRequest request, @PathVariable Long id, @@ -191,6 +200,7 @@ public class AdminUserController { @PostMapping("/{id}/vip/recalculate") @RequirePermission("user:vip:manage") + @OperationGuard(action = "admin-user-vip-recalculate", ttlSeconds = 15, message = "操作处理中,请勿重复提交") public Result recalculateUserVip(HttpServletRequest request, @PathVariable Long id) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); UserVO targetUser = requireAccessibleUser(currentUser, id, "无权重算其他店铺用户 VIP"); 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 b400a12e..f2ffdc25 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 @@ -1,8 +1,10 @@ package com.xiaowang.yuminailcore.controller; +import com.xiaowang.yuminailcore.annotation.OperationGuard; import com.xiaowang.yuminailcore.common.Result; import com.xiaowang.yuminailcore.dto.CartDTO; import com.xiaowang.yuminailcore.service.CartService; +import com.xiaowang.yuminailcore.support.security.OperationGuardStrategy; import com.xiaowang.yuminailcore.vo.CartVO; import org.springframework.web.bind.annotation.*; @@ -18,6 +20,7 @@ public class CartController { private CartService cartService; @PostMapping("/add") + @OperationGuard(action = "cart-add", ttlSeconds = 10, message = "购物车处理中,请勿重复操作") public Result addToCart(@RequestBody CartDTO cartDTO, HttpServletRequest request) { Long userId = (Long) request.getAttribute("userId"); cartService.addToCart(userId, cartDTO); @@ -25,6 +28,7 @@ public class CartController { } @DeleteMapping("/remove/{productId}") + @OperationGuard(action = "cart-remove", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) public Result removeFromCart(@PathVariable Long productId, HttpServletRequest request) { Long userId = (Long) request.getAttribute("userId"); cartService.removeFromCart(userId, productId); @@ -32,6 +36,7 @@ public class CartController { } @PostMapping("/batch-remove") + @OperationGuard(action = "cart-batch-remove", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) public Result batchRemoveFromCart(@RequestBody List cartItemIds, HttpServletRequest request) { Long userId = (Long) request.getAttribute("userId"); cartService.batchRemoveFromCart(userId, cartItemIds); @@ -39,6 +44,7 @@ public class CartController { } @PutMapping("/update") + @OperationGuard(action = "cart-update", ttlSeconds = 10, message = "购物车处理中,请勿重复操作") public Result updateCartQuantity(@RequestBody CartDTO cartDTO, HttpServletRequest request) { Long userId = (Long) request.getAttribute("userId"); cartService.updateCartQuantity(userId, cartDTO); @@ -53,9 +59,10 @@ public class CartController { } @DeleteMapping("/clear") + @OperationGuard(action = "cart-clear", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) public Result clearCart(HttpServletRequest request) { Long userId = (Long) request.getAttribute("userId"); cartService.clearCart(userId); return Result.success(); } -} \ No newline at end of file +} 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 8c0b29af..e7b61b60 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 @@ -52,7 +52,7 @@ public class CouponController { if (couponVO == null) { return Result.success(false); } - adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "鏃犳潈缂栬緫鍏朵粬搴楅摵浼樻儬鍒?"); + adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权编辑其他店铺优惠券"); Long targetShopId = shopId != null ? shopId : (couponDTO.getShopId() != null ? couponDTO.getShopId() : couponVO.getShopId()); shopId = adminScopeHelper.resolveShopScope(currentUser, targetShopId); boolean success = couponService.updateCoupon(id, couponDTO, shopId); @@ -70,7 +70,7 @@ public class CouponController { if (couponVO == null) { return Result.success(false); } - adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "鏃犳潈鍒犻櫎鍏朵粬搴楅摵浼樻儬鍒?"); + adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权删除其他店铺优惠券"); shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId()); boolean success = couponService.deleteCoupon(id, shopId); return Result.success(success); @@ -85,7 +85,7 @@ public class CouponController { UserDO currentUser = adminScopeHelper.getCurrentUser(request); CouponVO couponVO = couponService.getCouponById(id); if (couponVO != null) { - adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "鏃犳潈鏌ョ湅鍏朵粬搴楅摵浼樻儬鍒?"); + adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权查看其他店铺优惠券"); } return Result.success(couponVO); } @@ -113,12 +113,12 @@ public class CouponController { if (couponVO == null) { return Result.success(false); } - adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "鏃犳潈鍙戞斁鍏朵粬搴楅摵浼樻儬鍒?"); + adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权发放其他店铺优惠券"); UserVO targetUser = userService.getUserById(userId); if (targetUser == null) { return Result.success(false); } - adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "鏃犳潈缁欏叾浠栧簵閾虹敤鎴峰彂鏀句紭鎯犲埜"); + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权给其他店铺用户发放优惠券"); shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId()); boolean success = couponService.assignCouponToUser(userId, couponId, shopId); return Result.success(success); @@ -167,13 +167,13 @@ public class CouponController { if (couponVO == null) { return Result.success(false); } - adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "鏃犳潈鍙戞斁鍏朵粬搴楅摵浼樻儬鍒?"); + adminScopeHelper.ensureShopAccessible(currentUser, couponVO.getShopId(), "无权发放其他店铺优惠券"); for (Long userId : userIds) { UserVO targetUser = userService.getUserById(userId); if (targetUser == null) { return Result.success(false); } - adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "鏃犳潈缁欏叾浠栧簵閾虹敤鎴峰彂鏀句紭鎯犲埜"); + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权给其他店铺用户发放优惠券"); } shopId = adminScopeHelper.resolveShopScope(currentUser, couponVO.getShopId()); boolean success = couponService.distributeCoupon(couponId, userIds, quantity, shopId); 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 a7715469..c02fc27b 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 @@ -3,13 +3,17 @@ package com.xiaowang.yuminailcore.controller; import com.xiaowang.yuminailcore.common.Result; import com.xiaowang.yuminailcore.service.MinioService; import com.xiaowang.yuminailcore.service.ObjectStorageFileService; +import com.xiaowang.yuminailcore.support.ObjectStorageUrlSupport; import com.xiaowang.yuminailcore.vo.ObjectStorageFileVO; import lombok.RequiredArgsConstructor; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; /** - * 前台文件控制器 - * 提供前台用户可以访问的文件相关接口 + * 前台文件控制器,提供前台用户可访问的文件相关接口。 */ @RestController @RequestMapping("/file") @@ -18,31 +22,29 @@ public class FrontendFileController { private final ObjectStorageFileService objectStorageFileService; private final MinioService minioService; + private final ObjectStorageUrlSupport objectStorageUrlSupport; /** - * 获取带签名的图片链接(前台用户可访问) + * 获取带签名的图片链接。 * - * @param fileId 文件ID - * @param expiryTimeInMinutes 有效期(分钟),默认60分钟 - * @return 带签名的临时访问链接 + * @param fileId 文件 ID + * @param expiryTimeInMinutes 有效期,默认 60 分钟 + * @return 临时可访问的签名地址 */ @GetMapping("/get-signed-url/{fileId}") - public Result getSignedUrl(@PathVariable Long fileId, @RequestParam(defaultValue = "60") Integer expiryTimeInMinutes) { + public Result getSignedUrl(@PathVariable Long fileId, + @RequestParam(defaultValue = "60") Integer expiryTimeInMinutes) { try { ObjectStorageFileVO fileVO = objectStorageFileService.getObjectStorageFileById(fileId); if (fileVO == null) { return Result.error("文件不存在"); } - - // 从fileUrl中提取objectName - String fileUrl = fileVO.getFileUrl(); - // 提取最后一个/后面的部分作为objectName - int lastSlashIndex = fileUrl.lastIndexOf("/"); - if (lastSlashIndex == -1) { - return Result.error("文件URL格式错误"); + + String objectName = objectStorageUrlSupport.extractObjectName(fileVO.getFileUrl()); + if (objectName == null || objectName.isEmpty()) { + return Result.error("文件 URL 格式错误"); } - String objectName = fileUrl.substring(lastSlashIndex + 1); - + String signedUrl = minioService.getPresignedUrl(objectName, expiryTimeInMinutes); return Result.success(signedUrl); } catch (Exception e) { 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 5b310b19..e5f4b1ac 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 @@ -1,5 +1,6 @@ package com.xiaowang.yuminailcore.controller; +import com.xiaowang.yuminailcore.annotation.OperationGuard; import com.xiaowang.yuminailcore.common.Result; import com.xiaowang.yuminailcore.dto.ChunkUploadCompleteRequestDTO; import com.xiaowang.yuminailcore.dto.ChunkUploadInitRequestDTO; @@ -7,24 +8,31 @@ import com.xiaowang.yuminailcore.dto.ObjectStorageFileDTO; import com.xiaowang.yuminailcore.service.ChunkUploadService; import com.xiaowang.yuminailcore.service.MinioService; 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.vo.ChunkUploadSessionVO; import com.xiaowang.yuminailcore.vo.ObjectStorageFileVO; import lombok.RequiredArgsConstructor; import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import java.io.FileInputStream; import java.util.List; + /** - * 对象存储文件信息表 Controller - * 对应数据库表 t_object_storage_file - * - * @author xiaowang - * @date 2026-02-13 + * 对象存储文件控制器,对应表 t_object_storage_file。 */ @RestController @RequestMapping("/admin/object-storage-file") @@ -35,15 +43,19 @@ public class ObjectStorageFileController { private final ObjectStorageFileService objectStorageFileService; private final MinioService minioService; private final ChunkUploadService chunkUploadService; + private final ObjectStorageUrlSupport objectStorageUrlSupport; private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; @PostMapping("/upload/init") - public Result initChunkUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadInitRequestDTO requestDTO) { + @OperationGuard(action = "admin-upload-init", ttlSeconds = 10, message = "上传处理中,请勿重复操作") + public Result initChunkUpload(HttpServletRequest request, + @Valid @RequestBody ChunkUploadInitRequestDTO requestDTO) { Long userId = (Long) request.getAttribute("userId"); return Result.success(chunkUploadService.initAdminObjectStorageUpload(userId, requestDTO)); } @PostMapping("/upload/chunk") + @OperationGuard(action = "admin-upload-chunk", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 20) public Result uploadChunk(HttpServletRequest request, @RequestParam("uploadId") String uploadId, @RequestParam("chunkIndex") Integer chunkIndex, @@ -55,16 +67,23 @@ public class ObjectStorageFileController { } @PostMapping("/upload/complete") - public Result completeChunkUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadCompleteRequestDTO requestDTO) { + @OperationGuard(action = "admin-upload-complete", ttlSeconds = 30, message = "上传处理中,请勿重复操作") + public Result completeChunkUpload(HttpServletRequest request, + @Valid @RequestBody ChunkUploadCompleteRequestDTO requestDTO) { Long userId = (Long) request.getAttribute("userId"); try (ChunkUploadService.PreparedUploadFile preparedUploadFile = chunkUploadService.prepareAdminObjectStorageFile(userId, requestDTO.getUploadId()); - FileInputStream inputStream = new FileInputStream(preparedUploadFile.getFile())) { + FileInputStream inputStream = new FileInputStream(preparedUploadFile.getFile())) { String originalFilename = preparedUploadFile.getFileName(); String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); String objectName = snowflakeIdGenerator.nextIdString() + fileExtension; - String fileUrl = minioService.uploadStream(inputStream, preparedUploadFile.getFileSize(), preparedUploadFile.getContentType(), objectName); + String fileUrl = minioService.uploadStream( + inputStream, + preparedUploadFile.getFileSize(), + preparedUploadFile.getContentType(), + objectName + ); ObjectStorageFileDTO dto = new ObjectStorageFileDTO(); dto.setFileName(originalFilename); @@ -81,6 +100,7 @@ public class ObjectStorageFileController { } @DeleteMapping("/upload/{uploadId}") + @OperationGuard(action = "admin-upload-cancel", ttlSeconds = 30, message = "上传处理中,请勿重复操作") public Result cancelChunkUpload(HttpServletRequest request, @PathVariable String uploadId) { Long userId = (Long) request.getAttribute("userId"); chunkUploadService.clearAdminObjectStorageUpload(userId, uploadId); @@ -88,29 +108,25 @@ public class ObjectStorageFileController { } /** - * 上传文件 - * - * @param file 文件 - * @return 文件ID和URL + * 上传文件。 */ @PostMapping("/upload") + @OperationGuard(action = "admin-upload-direct", ttlSeconds = 30, message = "上传处理中,请勿重复操作") public Result uploadFile(@RequestParam("file") MultipartFile file) { try { String originalFilename = file.getOriginalFilename(); String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); String objectName = snowflakeIdGenerator.nextIdString() + fileExtension; - + String fileUrl = minioService.uploadFile(file, objectName); - + ObjectStorageFileDTO dto = new ObjectStorageFileDTO(); dto.setFileName(originalFilename); dto.setFileUrl(fileUrl); dto.setStatus(1); - + Long fileId = objectStorageFileService.createObjectStorageFile(dto); - ObjectStorageFileVO fileVO = objectStorageFileService.getObjectStorageFileById(fileId); - - return Result.success(fileVO); + return Result.success(objectStorageFileService.getObjectStorageFileById(fileId)); } catch (Exception e) { e.printStackTrace(); return Result.error("文件上传失败: " + e.getMessage()); @@ -118,29 +134,22 @@ public class ObjectStorageFileController { } /** - * 获取带签名的图片链接 - * - * @param fileId 文件ID - * @param expiryTimeInMinutes 有效期(分钟),默认60分钟 - * @return 带签名的临时访问链接 + * 获取带签名的图片链接。 */ @GetMapping("/get-signed-url/{fileId}") - public Result getSignedUrl(@PathVariable Long fileId, @RequestParam(defaultValue = "60") Integer expiryTimeInMinutes) { + public Result getSignedUrl(@PathVariable Long fileId, + @RequestParam(defaultValue = "60") Integer expiryTimeInMinutes) { try { ObjectStorageFileVO fileVO = objectStorageFileService.getObjectStorageFileById(fileId); if (fileVO == null) { return Result.error("文件不存在"); } - - // 从fileUrl中提取objectName - String fileUrl = fileVO.getFileUrl(); - // 提取最后一个/后面的部分作为objectName - int lastSlashIndex = fileUrl.lastIndexOf("/"); - if (lastSlashIndex == -1) { - return Result.error("文件URL格式错误"); + + String objectName = objectStorageUrlSupport.extractObjectName(fileVO.getFileUrl()); + if (objectName == null || objectName.isEmpty()) { + return Result.error("文件 URL 格式错误"); } - String objectName = fileUrl.substring(lastSlashIndex + 1); - + String signedUrl = minioService.getPresignedUrl(objectName, expiryTimeInMinutes); return Result.success(signedUrl); } catch (Exception e) { @@ -149,72 +158,40 @@ public class ObjectStorageFileController { } } - /** - * 创建文件 - * - * @param objectStorageFileDTO 文件DTO - * @return 文件ID - */ @PostMapping("/create") + @OperationGuard(action = "admin-file-create", ttlSeconds = 10, message = "保存处理中,请勿重复提交") public Result createObjectStorageFile(@RequestBody ObjectStorageFileDTO objectStorageFileDTO) { Long id = objectStorageFileService.createObjectStorageFile(objectStorageFileDTO); return Result.success(id); } - /** - * 更新文件 - * - * @param id 文件ID - * @param objectStorageFileDTO 文件DTO - * @return 是否更新成功 - */ @PutMapping("/update/{id}") - public Result updateObjectStorageFile(@PathVariable Long id, @RequestBody ObjectStorageFileDTO objectStorageFileDTO) { + @OperationGuard(action = "admin-file-update", ttlSeconds = 10, message = "保存处理中,请勿重复提交") + public Result updateObjectStorageFile(@PathVariable Long id, + @RequestBody ObjectStorageFileDTO objectStorageFileDTO) { boolean success = objectStorageFileService.updateObjectStorageFile(id, objectStorageFileDTO); return Result.success(success); } - /** - * 删除文件 - * - * @param id 文件ID - * @return 是否删除成功 - */ @DeleteMapping("/delete/{id}") + @OperationGuard(action = "admin-file-delete", ttlSeconds = 10, message = "操作处理中,请勿重复提交") public Result deleteObjectStorageFile(@PathVariable Long id) { boolean success = objectStorageFileService.deleteObjectStorageFile(id); return Result.success(success); } - /** - * 根据ID查询文件 - * - * @param id 文件ID - * @return 文件VO - */ @GetMapping("/get/{id}") public Result getObjectStorageFileById(@PathVariable Long id) { ObjectStorageFileVO objectStorageFileVO = objectStorageFileService.getObjectStorageFileById(id); return Result.success(objectStorageFileVO); } - /** - * 查询所有文件 - * - * @return 文件VO列表 - */ @GetMapping("/list/all") public Result> listAllObjectStorageFiles() { List objectStorageFileVOs = objectStorageFileService.listAllObjectStorageFiles(); return Result.success(objectStorageFileVOs); } - /** - * 根据状态查询文件 - * - * @param status 文件状态 - * @return 文件VO列表 - */ @GetMapping("/list/status/{status}") public Result> listObjectStorageFilesByStatus(@PathVariable Integer status) { List objectStorageFileVOs = objectStorageFileService.listObjectStorageFilesByStatus(status); 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 129441d2..9795fe42 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 @@ -1,5 +1,6 @@ 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.OrderDTO; @@ -24,6 +25,7 @@ public class OrderController { private UserService userService; @PostMapping("/create") + @OperationGuard(action = "order-create", ttlSeconds = 15, message = "订单正在提交中,请勿重复点击") public Result createOrder(@RequestBody OrderDTO orderDTO, HttpServletRequest request) { Long userId = (Long) request.getAttribute("userId"); OrderVO orderVO = orderService.createOrder(userId, orderDTO); @@ -45,6 +47,7 @@ public class OrderController { } @PutMapping("/cancel/{orderId}") + @OperationGuard(action = "order-cancel", ttlSeconds = 15, message = "操作进行中,请勿重复点击") public Result cancelOrder(@PathVariable Long orderId, HttpServletRequest request) { Long userId = (Long) request.getAttribute("userId"); orderService.cancelOrder(orderId, userId); @@ -77,6 +80,7 @@ public class OrderController { @RequirePermission("order:process") @PutMapping("/admin/process/{orderId}") + @OperationGuard(action = "admin-order-process", ttlSeconds = 15, message = "操作处理中,请勿重复提交") public Result processOrder(@PathVariable Long orderId, @RequestParam Integer status, HttpServletRequest request) { Long userId = (Long) request.getAttribute("userId"); Integer userType = (Integer) request.getAttribute("userType"); @@ -119,6 +123,7 @@ public class OrderController { @RequirePermission("order:process") @PutMapping("/artist/complete/{orderId}") + @OperationGuard(action = "artist-order-complete", ttlSeconds = 15, message = "操作处理中,请勿重复提交") public Result completeArtistOrder(@PathVariable Long orderId, HttpServletRequest request) { Long userId = (Long) request.getAttribute("userId"); Integer userType = (Integer) request.getAttribute("userType"); 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 f511e018..96b27216 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 @@ -128,9 +128,9 @@ public class PermissionController { if (!adminScopeHelper.isPlatformAdmin(currentUser)) { UserDO targetUser = userService.getById(userId); if (targetUser == null) { - throw new RuntimeException("鐩爣鐢ㄦ埛涓嶅瓨鍦?"); + throw new RuntimeException("目标用户不存在"); } - adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "鏃犳潈鏌ョ湅鍏朵粬搴楅摵鐢ㄦ埛鏉冮檺"); + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权查看其他店铺用户权限"); } List permissionVOs = permissionService.listUserPermissions(userId); return Result.success(permissionVOs); @@ -149,9 +149,9 @@ public class PermissionController { if (!adminScopeHelper.isPlatformAdmin(currentUser)) { UserDO targetUser = userService.getById(userPermissionDTO.getUserId()); if (targetUser == null) { - throw new RuntimeException("鐩爣鐢ㄦ埛涓嶅瓨鍦?"); + throw new RuntimeException("目标用户不存在"); } - adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userPermissionDTO.getUserId(), "鏃犳潈缁欏叾浠栧簵閾虹敤鎴峰垎閰嶆潈闄?"); + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userPermissionDTO.getUserId(), "无权给其他店铺用户分配权限"); } Long userId = (Long) request.getAttribute("userId"); boolean success = permissionService.assignPermissions(userPermissionDTO, userId); 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 2093923a..f44a9281 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 @@ -39,7 +39,7 @@ public class ProductController { if (productVO == null) { return Result.success(false); } - adminScopeHelper.ensureShopAccessible(currentUser, productVO.getShopId(), "鏃犳潈缂栬緫鍏朵粬搴楅摵鍟嗗搧"); + adminScopeHelper.ensureShopAccessible(currentUser, productVO.getShopId(), "无权编辑其他店铺商品"); Long targetShopId = productDTO.getShopId() != null ? productDTO.getShopId() : productVO.getShopId(); productDTO.setShopId(adminScopeHelper.resolveShopScope(currentUser, targetShopId)); boolean success = productService.updateProduct(id, productDTO); @@ -54,7 +54,7 @@ public class ProductController { if (productVO == null) { return Result.success(false); } - adminScopeHelper.ensureShopAccessible(currentUser, productVO.getShopId(), "鏃犳潈鍒犻櫎鍏朵粬搴楅摵鍟嗗搧"); + adminScopeHelper.ensureShopAccessible(currentUser, productVO.getShopId(), "无权删除其他店铺商品"); boolean success = productService.deleteProduct(id); return Result.success(success); } @@ -85,8 +85,15 @@ public class ProductController { @GetMapping("/list/search") public Result> searchProducts(@RequestParam("keyword") String keyword) { - // 调用pageProducts方法,设置默认分页参数,只返回列表 - PageResultVO pageResult = productService.pageProducts(1, 100, keyword, null); - return Result.success(pageResult.getList()); + List productVOs = productService.searchProducts(keyword); + return Result.success(productVOs); + } + + @GetMapping("/list/page") + public Result> pagePublicProducts(@RequestParam(defaultValue = "1") Integer page, + @RequestParam(defaultValue = "10") Integer size, + @RequestParam(required = false) String keyword, + @RequestParam(required = false) String tag) { + return Result.success(productService.pagePublicProducts(page, size, keyword, tag)); } } 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 d1b5bef8..fc5edad8 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 @@ -1,7 +1,9 @@ package com.xiaowang.yuminailcore.controller; +import com.xiaowang.yuminailcore.annotation.OperationGuard; import com.xiaowang.yuminailcore.common.Result; import com.xiaowang.yuminailcore.service.ProductLikeService; +import com.xiaowang.yuminailcore.support.security.OperationGuardStrategy; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.*; @@ -26,6 +28,7 @@ public class ProductLikeController { * @return 是否成功 */ @PostMapping("/like/{productId}") + @OperationGuard(action = "product-like", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) public Result likeProduct(@RequestAttribute("userId") Long userId, @PathVariable Long productId) { productLikeService.addLike(userId, productId); return Result.success(true); @@ -39,6 +42,7 @@ public class ProductLikeController { * @return 是否成功 */ @PostMapping("/unlike/{productId}") + @OperationGuard(action = "product-unlike", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) public Result unlikeProduct(@RequestAttribute("userId") Long userId, @PathVariable Long productId) { productLikeService.removeLike(userId, productId); return Result.success(true); 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 59be6d43..81c4dd8f 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 @@ -41,7 +41,7 @@ public class ShopController { if (shopVO == null) { return Result.success(false); } - adminScopeHelper.ensureShopAccessible(currentUser, shopVO.getId(), "鏃犳潈缂栬緫鍏朵粬搴楅摵淇℃伅"); + adminScopeHelper.ensureShopAccessible(currentUser, shopVO.getId(), "无权编辑其他店铺信息"); boolean success = shopService.updateShop(id, shopDTO); return Result.success(success); } 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 3d5886c8..d0ed2f2f 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 @@ -58,7 +58,7 @@ public class TagController { if (tagVO == null) { return Result.success(false); } - adminScopeHelper.ensureShopAccessible(currentUser, tagVO.getShopId(), "鏃犳潈缂栬緫鍏朵粬搴楅摵鏍囩"); + adminScopeHelper.ensureShopAccessible(currentUser, tagVO.getShopId(), "无权编辑其他店铺标签"); Long targetShopId = tagDTO.getShopId() != null ? tagDTO.getShopId() : tagVO.getShopId(); tagDTO.setShopId(adminScopeHelper.resolveShopScope(currentUser, targetShopId)); boolean success = tagService.updateTag(id, tagDTO); @@ -79,7 +79,7 @@ public class TagController { if (tagVO == null) { return Result.success(false); } - adminScopeHelper.ensureShopAccessible(currentUser, tagVO.getShopId(), "鏃犳潈鍒犻櫎鍏朵粬搴楅摵鏍囩"); + adminScopeHelper.ensureShopAccessible(currentUser, tagVO.getShopId(), "无权删除其他店铺标签"); boolean success = tagService.deleteTag(id); return Result.success(success); } @@ -96,7 +96,7 @@ public class TagController { UserDO currentUser = adminScopeHelper.getCurrentUser(request); TagVO tagVO = tagService.getTagById(id); if (tagVO != null) { - adminScopeHelper.ensureShopAccessible(currentUser, tagVO.getShopId(), "鏃犳潈鏌ョ湅鍏朵粬搴楅摵鏍囩"); + adminScopeHelper.ensureShopAccessible(currentUser, tagVO.getShopId(), "无权查看其他店铺标签"); } return Result.success(tagVO); } @@ -139,7 +139,7 @@ public class TagController { UserDO currentUser = adminScopeHelper.getCurrentUser(request); TagVO tagVO = tagService.getTagByTagName(tagName); if (tagVO != null) { - adminScopeHelper.ensureShopAccessible(currentUser, tagVO.getShopId(), "鏃犳潈鏌ョ湅鍏朵粬搴楅摵鏍囩"); + adminScopeHelper.ensureShopAccessible(currentUser, tagVO.getShopId(), "无权查看其他店铺标签"); } return Result.success(tagVO); } 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 88b54396..014fec14 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 @@ -1,6 +1,7 @@ package com.xiaowang.yuminailcore.controller; import com.xiaowang.yuminailcore.annotation.RequirePermission; +import com.xiaowang.yuminailcore.annotation.OperationGuard; import com.xiaowang.yuminailcore.common.Result; import com.xiaowang.yuminailcore.dto.*; import com.xiaowang.yuminailcore.entity.UserDO; @@ -17,7 +18,10 @@ import com.xiaowang.yuminailcore.service.UserService; import com.xiaowang.yuminailcore.service.VerificationCodeService; import com.xiaowang.yuminailcore.service.WechatMiniAuthService; import com.xiaowang.yuminailcore.support.id.TimeOrderedSnowflakeIdGenerator; +import com.xiaowang.yuminailcore.support.ObjectStorageUrlSupport; +import com.xiaowang.yuminailcore.support.security.RequestThrottleService; import com.xiaowang.yuminailcore.utils.AccountValidationUtils; +import com.xiaowang.yuminailcore.support.security.OperationGuardStrategy; import lombok.Data; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.*; @@ -49,6 +53,8 @@ public class UserController { private final AdminScopeHelper adminScopeHelper; private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; private final WechatMiniAuthService wechatMiniAuthService; + private final ObjectStorageUrlSupport objectStorageUrlSupport; + private final RequestThrottleService requestThrottleService; /** * 创建用户 @@ -58,6 +64,7 @@ public class UserController { */ @PostMapping("/create") @RequirePermission("user:create") + @OperationGuard(action = "admin-user-create", ttlSeconds = 10, message = "保存处理中,请勿重复提交") public Result createUser(HttpServletRequest request, @Valid @RequestBody UserDTO userDTO) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); adminScopeHelper.ensureAssignableUserType(currentUser, userDTO.getType()); @@ -79,9 +86,10 @@ public class UserController { */ @PutMapping("/update/{id}") @RequirePermission("user:edit") + @OperationGuard(action = "admin-user-update", ttlSeconds = 10, message = "保存处理中,请勿重复提交") public Result updateUser(HttpServletRequest request, @PathVariable Long id, @Valid @RequestBody UserDTO userDTO) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); - UserVO targetUser = requireAccessibleUser(currentUser, id, "鏃犳潈缂栬緫鍏朵粬搴楅摵鐢ㄦ埛"); + UserVO targetUser = requireAccessibleUser(currentUser, id, "无权编辑其他店铺用户"); if (userDTO.getType() != null) { adminScopeHelper.ensureAssignableUserType(currentUser, userDTO.getType()); } @@ -101,6 +109,7 @@ public class UserController { */ @DeleteMapping("/delete/{id}") @RequirePermission("user:delete") + @OperationGuard(action = "admin-user-delete", ttlSeconds = 10, message = "操作进行中,请勿重复点击") public Result deleteUser(HttpServletRequest request, @PathVariable Long id) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); adminScopeHelper.requirePlatformAdmin(currentUser, "仅系统管理员可以删除用户"); @@ -114,6 +123,7 @@ public class UserController { @PutMapping("/unbind/{id}") @RequirePermission("user:unbind") + @OperationGuard(action = "admin-user-unbind", ttlSeconds = 10, message = "操作进行中,请勿重复点击") public Result unbindUser(HttpServletRequest request, @PathVariable Long id) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); UserVO targetUser = requireAccessibleUser(currentUser, id, "无权解绑其他店铺用户"); @@ -135,7 +145,7 @@ public class UserController { @RequirePermission("user:view") public Result getUserById(HttpServletRequest request, @PathVariable Long id) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); - UserVO userVO = requireAccessibleUser(currentUser, id, "鏃犳潈鏌ョ湅鍏朵粬搴楅摵鐢ㄦ埛"); + UserVO userVO = requireAccessibleUser(currentUser, id, "无权查看其他店铺用户"); return Result.success(userVO); } @@ -199,7 +209,7 @@ public class UserController { UserDO currentUser = adminScopeHelper.getCurrentUser(request); UserVO userVO = userService.getUserByAccount(AccountValidationUtils.requireValidAccount(account)); if (userVO != null) { - adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userVO.getId(), "鏃犳潈鏌ョ湅鍏朵粬搴楅摵鐢ㄦ埛"); + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userVO.getId(), "无权查看其他店铺用户"); } return Result.success(userVO); } @@ -262,7 +272,9 @@ public class UserController { * @return 登录响应VO */ @PostMapping("/login") - public Result login(@Valid @RequestBody LoginRequestDTO loginRequestDTO) { + @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); } @@ -274,30 +286,36 @@ public class UserController { * @return 登录响应VO */ @PostMapping("/phone-login") - public Result phoneLogin(@RequestBody PhoneLoginRequestDTO phoneLoginRequestDTO) { + @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); } @PostMapping("/wechat-mini/auto-login") + @OperationGuard(action = "wechat-mini-auto-login", ttlSeconds = 8, message = "登录处理中,请勿重复提交") 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)); } @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)); } @PostMapping("/switch-shop") + @OperationGuard(action = "user-switch-shop", ttlSeconds = 10, message = "门店切换中,请勿重复操作") public Result switchShop(HttpServletRequest request, @RequestBody SwitchShopRequestDTO switchShopRequestDTO) { Long userId = (Long) request.getAttribute("userId"); - return Result.success(userService.switchShop(userId, switchShopRequestDTO.getShopId())); + return Result.success(userService.switchShop(userId, switchShopRequestDTO.getShopId(), (String) request.getAttribute("sessionId"))); } /** @@ -307,6 +325,7 @@ public class UserController { * @return 是否注册成功 */ @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); @@ -319,7 +338,9 @@ public class UserController { * @return 是否发送成功 */ @PostMapping("/send-verification-code") - public Result sendVerificationCode(@RequestBody SendVerificationCodeRequestDTO sendVerificationCodeRequestDTO) { + @OperationGuard(action = "send-verification-code", ttlSeconds = 8, message = "验证码发送处理中,请稍后再试") + public Result sendVerificationCode(HttpServletRequest request, @RequestBody SendVerificationCodeRequestDTO sendVerificationCodeRequestDTO) { + requestThrottleService.checkSendCode(request, sendVerificationCodeRequestDTO.getPhone()); if (!verificationCodeService.canResend(sendVerificationCodeRequestDTO.getPhone())) { throw new RuntimeException("验证码发送过于频繁,请1分钟后再试"); } @@ -334,7 +355,9 @@ public class UserController { * @return 是否重置成功 */ @PostMapping("/reset-password-by-phone") - public Result resetPasswordByPhone(@RequestBody ResetPasswordRequestDTO resetPasswordRequestDTO) { + @OperationGuard(action = "reset-password-by-phone", ttlSeconds = 8, message = "操作进行中,请勿重复点击") + public Result resetPasswordByPhone(HttpServletRequest request, @RequestBody ResetPasswordRequestDTO resetPasswordRequestDTO) { + requestThrottleService.checkResetPassword(request, resetPasswordRequestDTO.getPhone()); boolean success = userService.resetPasswordByPhone(resetPasswordRequestDTO); return Result.success(success); } @@ -357,8 +380,9 @@ public class UserController { * @return 是否登出成功 */ @PostMapping("/logout") - public Result logout() { - boolean success = userService.logout(); + @OperationGuard(action = "user-logout", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 5) + public Result logout(HttpServletRequest request) { + boolean success = userService.logout((String) request.getAttribute("sessionId")); return Result.success(success); } @@ -381,6 +405,7 @@ public class UserController { * @return 是否更新成功 */ @PutMapping({"/update", "/info"}) + @OperationGuard(action = "user-update-info", ttlSeconds = 10, message = "保存处理中,请勿重复提交") public Result updateCurrentUserInfo(HttpServletRequest request, @Valid @RequestBody UserDTO userDTO) { Long userId = (Long) request.getAttribute("userId"); boolean success = userService.updateCurrentUserInfo(userId, userDTO); @@ -394,6 +419,7 @@ public class UserController { * @return 是否绑定成功 */ @PostMapping("/bind-phone") + @OperationGuard(action = "user-bind-phone", ttlSeconds = 10, message = "保存处理中,请勿重复提交") public Result bindPhone(HttpServletRequest request, @RequestBody BindPhoneRequestDTO bindPhoneRequestDTO) { Long userId = (Long) request.getAttribute("userId"); boolean success = userService.bindPhone(userId, bindPhoneRequestDTO); @@ -407,6 +433,7 @@ public class UserController { * @return 是否绑定成功 */ @PostMapping("/bind-email") + @OperationGuard(action = "user-bind-email", ttlSeconds = 10, message = "保存处理中,请勿重复提交") public Result bindEmail(HttpServletRequest request, @RequestBody BindEmailRequestDTO bindEmailRequestDTO) { Long userId = (Long) request.getAttribute("userId"); boolean success = userService.bindEmail(userId, bindEmailRequestDTO); @@ -420,12 +447,14 @@ public class UserController { * @return 头像URL */ @PostMapping("/upload-avatar/init") + @OperationGuard(action = "user-avatar-upload-init", ttlSeconds = 10, message = "上传处理中,请勿重复操作") public Result initAvatarUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadInitRequestDTO requestDTO) { Long userId = (Long) request.getAttribute("userId"); return Result.success(chunkUploadService.initUserAvatarUpload(userId, requestDTO)); } @PostMapping("/upload-avatar/chunk") + @OperationGuard(action = "user-avatar-upload-chunk", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 20) public Result uploadAvatarChunk(HttpServletRequest request, @RequestParam("uploadId") String uploadId, @RequestParam("chunkIndex") Integer chunkIndex, @@ -437,6 +466,7 @@ public class UserController { } @PostMapping("/upload-avatar/complete") + @OperationGuard(action = "user-avatar-upload-complete", ttlSeconds = 30, message = "上传处理中,请勿重复操作") public Result completeAvatarUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadCompleteRequestDTO requestDTO) { Long userId = (Long) request.getAttribute("userId"); try (ChunkUploadService.PreparedUploadFile preparedUploadFile = @@ -449,7 +479,7 @@ public class UserController { String avatarUrl = minioService.uploadStream(inputStream, preparedUploadFile.getFileSize(), preparedUploadFile.getContentType(), objectName); userService.updateUserAvatar(userId, avatarUrl); chunkUploadService.clearUserAvatarUpload(userId, requestDTO.getUploadId()); - return Result.success(avatarUrl); + return Result.success(objectStorageUrlSupport.toAccessibleUrl(avatarUrl)); } catch (Exception e) { e.printStackTrace(); return Result.error("头像上传失败: " + e.getMessage()); @@ -457,6 +487,7 @@ public class UserController { } @DeleteMapping("/upload-avatar/{uploadId}") + @OperationGuard(action = "user-avatar-upload-cancel", ttlSeconds = 30, message = "上传处理中,请勿重复操作") public Result cancelAvatarUpload(HttpServletRequest request, @PathVariable String uploadId) { Long userId = (Long) request.getAttribute("userId"); chunkUploadService.clearUserAvatarUpload(userId, uploadId); @@ -464,6 +495,7 @@ public class UserController { } @PostMapping("/upload-avatar") + @OperationGuard(action = "user-avatar-upload", ttlSeconds = 30, message = "上传处理中,请勿重复操作") public Result uploadAvatar(HttpServletRequest request, @RequestParam("file") MultipartFile file) { try { Long userId = (Long) request.getAttribute("userId"); @@ -474,7 +506,7 @@ public class UserController { String avatarUrl = minioService.uploadFile(file, objectName); userService.updateUserAvatar(userId, avatarUrl); - return Result.success(avatarUrl); + return Result.success(objectStorageUrlSupport.toAccessibleUrl(avatarUrl)); } catch (Exception e) { e.printStackTrace(); return Result.error("头像上传失败: " + e.getMessage()); @@ -489,9 +521,10 @@ public class UserController { */ @PostMapping("/reset-password/{userId}") @RequirePermission("user:reset_password") + @OperationGuard(action = "admin-user-reset-password", ttlSeconds = 10, message = "操作进行中,请勿重复点击") public Result resetPassword(HttpServletRequest request, @PathVariable Long userId) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); - requireAccessibleUser(currentUser, userId, "鏃犳潈閲嶇疆鍏朵粬搴楅摵鐢ㄦ埛瀵嗙爜"); + requireAccessibleUser(currentUser, userId, "无权重置其他店铺用户密码"); Long currentUserId = (Long) request.getAttribute("userId"); boolean success = userService.resetPassword(userId, currentUserId); return Result.success(success); @@ -505,6 +538,7 @@ public class UserController { * @return 是否更新成功 */ @PutMapping("/password") + @OperationGuard(action = "user-update-password", ttlSeconds = 10, message = "保存处理中,请勿重复提交") public Result updatePassword(HttpServletRequest request, @RequestBody PasswordDTO passwordDTO) { Long userId = (Long) request.getAttribute("userId"); boolean success = userService.updatePassword(userId, passwordDTO.getPassword(), passwordDTO.getVerificationCode()); @@ -519,6 +553,7 @@ public class UserController { * @return 是否修改成功 */ @PutMapping("/phone") + @OperationGuard(action = "user-update-phone", ttlSeconds = 10, message = "保存处理中,请勿重复提交") public Result updatePhone(HttpServletRequest request, @RequestBody UpdatePhoneRequestDTO updatePhoneDTO) { Long userId = (Long) request.getAttribute("userId"); boolean success = userService.updatePhone(userId, updatePhoneDTO); @@ -532,6 +567,7 @@ public class UserController { * @return 是否注销成功 */ @DeleteMapping("/deactivate") + @OperationGuard(action = "user-deactivate", ttlSeconds = 10, message = "操作进行中,请勿重复点击") public Result deactivateAccount(HttpServletRequest request) { Long userId = (Long) request.getAttribute("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 d2fa23f5..00316f83 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 @@ -1,8 +1,10 @@ package com.xiaowang.yuminailcore.controller; +import com.xiaowang.yuminailcore.annotation.OperationGuard; import com.xiaowang.yuminailcore.common.Result; import com.xiaowang.yuminailcore.dto.WishlistDTO; import com.xiaowang.yuminailcore.service.WishlistService; +import com.xiaowang.yuminailcore.support.security.OperationGuardStrategy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @@ -17,6 +19,7 @@ public class WishlistController { private WishlistService wishlistService; @PostMapping("/add") + @OperationGuard(action = "wishlist-add", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) public Result addToWishlist(@RequestBody Map request, @RequestAttribute("userId") Long userId) { Long productId = request.get("productId"); wishlistService.addToWishlist(userId, productId); @@ -24,6 +27,7 @@ public class WishlistController { } @PostMapping("/remove") + @OperationGuard(action = "wishlist-remove", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 10) public Result removeFromWishlist(@RequestBody Map request, @RequestAttribute("userId") Long userId) { Long productId = request.get("productId"); wishlistService.removeFromWishlist(userId, productId); diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/filter/RequestBodyCacheFilter.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/filter/RequestBodyCacheFilter.java new file mode 100644 index 00000000..3b41b556 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/filter/RequestBodyCacheFilter.java @@ -0,0 +1,56 @@ +package com.xiaowang.yuminailcore.filter; + +import com.xiaowang.yuminailcore.support.security.CachedBodyHttpServletRequest; +import com.xiaowang.yuminailcore.support.security.RequestSignatureService; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; +import org.springframework.util.StreamUtils; +import org.springframework.util.StringUtils; +import org.springframework.web.filter.OncePerRequestFilter; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +/** + * 缓存 JSON 请求体,供签名校验复用。 + */ +@Component +@Order(Ordered.HIGHEST_PRECEDENCE) +public class RequestBodyCacheFilter extends OncePerRequestFilter { + + @Override + protected void doFilterInternal(HttpServletRequest request, + HttpServletResponse response, + FilterChain filterChain) throws ServletException, IOException { + if (!shouldWrap(request)) { + filterChain.doFilter(request, response); + return; + } + + byte[] body = StreamUtils.copyToByteArray(request.getInputStream()); + CachedBodyHttpServletRequest wrappedRequest = new CachedBodyHttpServletRequest(request, body); + wrappedRequest.setAttribute(RequestSignatureService.REQUEST_BODY_ATTRIBUTE, body); + filterChain.doFilter(wrappedRequest, response); + } + + private boolean shouldWrap(HttpServletRequest request) { + String method = request.getMethod(); + if (!StringUtils.hasText(method)) { + return false; + } + String normalizedMethod = method.toUpperCase(); + if (!("POST".equals(normalizedMethod) || "PUT".equals(normalizedMethod) || "PATCH".equals(normalizedMethod) || "DELETE".equals(normalizedMethod))) { + return false; + } + String contentType = request.getContentType(); + if (!StringUtils.hasText(contentType)) { + return false; + } + String normalizedType = contentType.toLowerCase(); + return normalizedType.contains("application/json"); + } +} 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 05566087..267a33b8 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 @@ -88,6 +88,14 @@ public interface ProductService extends IService { * @return 商品VO列表 */ List listProductsByTag(String tag); + + /** + * 前台按标题、描述、标签名搜索商品 + * + * @param keyword 搜索关键词 + * @return 商品列表 + */ + List searchProducts(String keyword); /** * 分页查询商品 @@ -98,4 +106,6 @@ public interface ProductService extends IService { * @return 分页结果 */ PageResultVO pageProducts(Integer page, Integer size, String keyword, Long shopId); + + PageResultVO pagePublicProducts(Integer page, Integer size, String keyword, String tag); } 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 8a102be5..a1c79012 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 @@ -51,9 +51,9 @@ public interface UserService extends IService { LoginShopSelectionVO getAdminLoginShopSelection(String account); - LoginResponseVO switchShop(Long userId, Long shopId); + LoginResponseVO switchShop(Long userId, Long shopId, String previousSessionId); - LoginResponseVO switchAdminShop(Long userId, Long shopId); + LoginResponseVO switchAdminShop(Long userId, Long shopId, String previousSessionId); void syncManagedPermissions(Long userId); @@ -61,7 +61,7 @@ public interface UserService extends IService { LoginResponseVO refreshToken(String refreshToken); - boolean logout(); + boolean logout(String sessionId); UserVO getCurrentUserInfo(); 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 ee33b00a..dd6eef1c 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 @@ -11,6 +11,7 @@ import com.xiaowang.yuminailcore.mapper.UserMapper; import com.xiaowang.yuminailcore.service.CartService; import com.xiaowang.yuminailcore.service.TagService; import com.xiaowang.yuminailcore.support.BookableArtistSupport; +import com.xiaowang.yuminailcore.support.ObjectStorageUrlSupport; import com.xiaowang.yuminailcore.support.UserShopBindingSupport; import com.xiaowang.yuminailcore.vo.CartArtistVO; import com.xiaowang.yuminailcore.vo.CartVO; @@ -49,6 +50,9 @@ public class CartServiceImpl implements CartService { @Resource private BookableArtistSupport bookableArtistSupport; + @Resource + private ObjectStorageUrlSupport objectStorageUrlSupport; + @Override @Transactional public void addToCart(Long userId, CartDTO cartDTO) { @@ -239,7 +243,7 @@ public class CartServiceImpl implements CartService { CartArtistVO cartArtistVO = new CartArtistVO(); cartArtistVO.setId(artist.getId()); cartArtistVO.setName(artist.getNickname()); - cartArtistVO.setAvatar(artist.getAvatar()); + cartArtistVO.setAvatar(objectStorageUrlSupport.toAccessibleUrl(artist.getAvatar())); return cartArtistVO; } } 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 d8d1afa2..15c2448e 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 @@ -22,6 +22,7 @@ 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.ObjectStorageUrlSupport; import com.xiaowang.yuminailcore.support.id.TimeOrderedSnowflakeIdGenerator; import com.xiaowang.yuminailcore.support.UserShopBindingSupport; import com.xiaowang.yuminailcore.vo.OrderItemVO; @@ -144,6 +145,9 @@ public class OrderServiceImpl implements OrderService { @Resource private StringRedisTemplate stringRedisTemplate; + @Resource + private ObjectStorageUrlSupport objectStorageUrlSupport; + @Resource private TransactionTemplate transactionTemplate; @@ -536,7 +540,7 @@ public class OrderServiceImpl implements OrderService { UserDO artist = getUserFromCache(item.getArtistId(), userCache); if (artist != null) { itemVO.setArtistName(artist.getNickname()); - itemVO.setArtistAvatar(artist.getAvatar()); + itemVO.setArtistAvatar(objectStorageUrlSupport.toAccessibleUrl(artist.getAvatar())); } } 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 987f5f87..7abe1d88 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 @@ -4,6 +4,8 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.fasterxml.jackson.core.type.TypeReference; +import com.xiaowang.yuminailcore.config.AppCacheProperties; import com.xiaowang.yuminailcore.dto.ProductDTO; import com.xiaowang.yuminailcore.entity.CouponDO; import com.xiaowang.yuminailcore.entity.ProductDO; @@ -17,6 +19,7 @@ import com.xiaowang.yuminailcore.service.ObjectStorageFileService; import com.xiaowang.yuminailcore.service.ProductService; import com.xiaowang.yuminailcore.service.TagService; import com.xiaowang.yuminailcore.support.BookableArtistSupport; +import com.xiaowang.yuminailcore.support.cache.MultiLevelCacheService; import com.xiaowang.yuminailcore.vo.ObjectStorageFileVO; import com.xiaowang.yuminailcore.vo.PageResultVO; import com.xiaowang.yuminailcore.vo.ProductVO; @@ -26,9 +29,11 @@ import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; +import java.time.Duration; import java.util.ArrayList; import java.util.HashSet; import java.util.List; +import java.util.Locale; import java.util.Set; import java.util.stream.Collectors; @@ -42,6 +47,11 @@ import java.util.stream.Collectors; @Service @RequiredArgsConstructor 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; private final ProductMapper productMapper; private final TagService tagService; @@ -50,6 +60,8 @@ public class ProductServiceImpl extends ServiceImpl im private final ShopMapper shopMapper; private final TagMapper tagMapper; private final BookableArtistSupport bookableArtistSupport; + private final MultiLevelCacheService multiLevelCacheService; + private final AppCacheProperties appCacheProperties; @Override public Long createProduct(ProductDTO productDTO) { @@ -69,6 +81,7 @@ public class ProductServiceImpl extends ServiceImpl im productDO.setAvailableCoupons(productDTO.getAvailableCoupons()); productDO.setIsDelete(0); productMapper.insert(productDO); + evictPublicProductCaches(productDO.getId()); return productDO.getId(); } @@ -95,7 +108,11 @@ public class ProductServiceImpl extends ServiceImpl im productDO.setApproximateDuration(productDTO.getApproximateDuration()); productDO.setBookableArtists(bookableArtistSupport.filterValidBookableArtists(productDTO.getShopId(), productDTO.getBookableArtists())); productDO.setAvailableCoupons(productDTO.getAvailableCoupons()); - return productMapper.updateById(productDO) > 0; + boolean updated = productMapper.updateById(productDO) > 0; + if (updated) { + evictPublicProductCaches(id); + } + return updated; } @Override @@ -105,37 +122,67 @@ public class ProductServiceImpl extends ServiceImpl im return false; } productDO.setIsDelete(1); - return productMapper.updateById(productDO) > 0; + boolean deleted = productMapper.updateById(productDO) > 0; + if (deleted) { + evictPublicProductCaches(id); + } + return deleted; } @Override public int incrementLikeCount(Long productId) { - return productMapper.incrementLikeCount(productId); + int updated = productMapper.incrementLikeCount(productId); + if (updated > 0) { + evictPublicProductCaches(productId); + } + return updated; } @Override public int decrementLikeCount(Long productId) { - return productMapper.decrementLikeCount(productId); + int updated = productMapper.decrementLikeCount(productId); + if (updated > 0) { + evictPublicProductCaches(productId); + } + return updated; } @Override public ProductVO getProductById(Long id) { - ProductDO productDO = productMapper.selectById(id); - if (productDO == null || Integer.valueOf(1).equals(productDO.getIsDelete())) { - return null; - } - return convertToVO(productDO); + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getProductDetail(); + return multiLevelCacheService.getOrLoad( + PRODUCT_DETAIL_CACHE_PREFIX + id, + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference() { + }, + () -> { + ProductDO productDO = productMapper.selectById(id); + if (productDO == null || Integer.valueOf(1).equals(productDO.getIsDelete())) { + return null; + } + return convertToVO(productDO); + } + ); } @Override public List listAllProducts() { - List productDOs = productMapper.selectList( - Wrappers.lambdaQuery(ProductDO.class) - .eq(ProductDO::getIsDelete, 0) + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getProductList(); + return multiLevelCacheService.getOrLoad( + PRODUCT_LIST_CACHE_PREFIX + "all", + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference>() { + }, + () -> productMapper.selectList( + Wrappers.lambdaQuery(ProductDO.class) + .eq(ProductDO::getIsDelete, 0) + .orderByDesc(ProductDO::getCreateTime) + ).stream() + .map(this::convertToVO) + .collect(Collectors.toList()) ); - return productDOs.stream() - .map(this::convertToVO) - .collect(Collectors.toList()); } @Override @@ -152,27 +199,33 @@ public class ProductServiceImpl extends ServiceImpl im @Override public List listProductsByTag(String tag) { - List matchedTags = tagMapper.selectList( - Wrappers.lambdaQuery(TagDO.class) - .eq(TagDO::getIsDelete, 0) - .eq(TagDO::getTagName, tag) + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getProductList(); + String normalizedTag = normalizeOptionalKeyword(tag); + return multiLevelCacheService.getOrLoad( + PRODUCT_LIST_CACHE_PREFIX + "tag:" + normalizedTag, + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference>() { + }, + () -> loadProductsByTag(normalizedTag) ); - if (matchedTags.isEmpty()) { - return new java.util.ArrayList<>(); - } + } - Set matchedTagIds = matchedTags.stream() - .map(TagDO::getId) - .map(String::valueOf) - .collect(Collectors.toCollection(HashSet::new)); - List productDOs = productMapper.selectList( - Wrappers.lambdaQuery(ProductDO.class) - .eq(ProductDO::getIsDelete, 0) + @Override + public List searchProducts(String keyword) { + if (!StringUtils.hasText(keyword)) { + return new ArrayList<>(); + } + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getProductSearch(); + String trimmedKeyword = keyword.trim(); + return multiLevelCacheService.getOrLoad( + PRODUCT_SEARCH_CACHE_PREFIX + trimmedKeyword.toLowerCase(Locale.ROOT), + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference>() { + }, + () -> searchFrontProducts(trimmedKeyword) ); - return productDOs.stream() - .filter(productDO -> containsAnyTagId(productDO.getTags(), matchedTagIds)) - .map(this::convertToVO) - .collect(Collectors.toList()); } /** @@ -277,6 +330,29 @@ public class ProductServiceImpl extends ServiceImpl im return result; } + @Override + public PageResultVO pagePublicProducts(Integer page, Integer size, String keyword, String tag) { + int normalizedPage = normalizePage(page); + int normalizedSize = normalizePageSize(size); + String normalizedKeyword = normalizeOptionalKeyword(keyword); + String normalizedTag = normalizeOptionalKeyword(tag); + AppCacheProperties.CacheSpec cacheSpec = StringUtils.hasText(normalizedKeyword) + ? appCacheProperties.getProductSearch() + : appCacheProperties.getProductList(); + String cacheKey = PRODUCT_LIST_CACHE_PREFIX + "page:" + normalizedPage + + ":" + normalizedSize + + ":" + normalizedKeyword.toLowerCase(Locale.ROOT) + + ":" + normalizedTag.toLowerCase(Locale.ROOT); + return multiLevelCacheService.getOrLoad( + cacheKey, + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference>() { + }, + () -> buildPublicProductPage(normalizedPage, normalizedSize, normalizedKeyword, normalizedTag) + ); + } + private void validateBookableArtists(Long shopId, String bookableArtists) { if (!StringUtils.hasText(bookableArtists)) { return; @@ -363,6 +439,25 @@ public class ProductServiceImpl extends ServiceImpl im return count; } + private boolean matchesFrontSearch(ProductDO productDO, String normalizedKeyword, Set matchedTagIds) { + if (containsKeyword(productDO.getTitle(), normalizedKeyword) + || containsKeyword(productDO.getDescription(), normalizedKeyword)) { + return true; + } + return containsAnyTagId(productDO.getTags(), matchedTagIds); + } + + private String normalizeSearchKeyword(String keyword) { + return keyword.trim().toLowerCase(Locale.ROOT); + } + + private boolean containsKeyword(String source, String normalizedKeyword) { + if (!StringUtils.hasText(source) || !StringUtils.hasText(normalizedKeyword)) { + return false; + } + return source.toLowerCase(Locale.ROOT).contains(normalizedKeyword); + } + private boolean containsAnyTagId(String tags, Set targetTagIds) { if (!StringUtils.hasText(tags) || targetTagIds == null || targetTagIds.isEmpty()) { return false; @@ -374,4 +469,121 @@ public class ProductServiceImpl extends ServiceImpl im } return false; } + + private List loadProductsByTag(String tag) { + if (!StringUtils.hasText(tag)) { + return new ArrayList<>(); + } + Set matchedTagIds = findExactTagIds(tag); + if (matchedTagIds.isEmpty()) { + return new ArrayList<>(); + } + return listFrontProductDOs().stream() + .filter(productDO -> containsAnyTagId(productDO.getTags(), matchedTagIds)) + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + private List searchFrontProducts(String keyword) { + String normalizedKeyword = normalizeSearchKeyword(keyword); + Set matchedTagIds = findLikeTagIds(keyword); + return listFrontProductDOs().stream() + .filter(productDO -> matchesFrontSearch(productDO, normalizedKeyword, matchedTagIds)) + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + private PageResultVO buildPublicProductPage(int page, int size, String keyword, String tag) { + if (!StringUtils.hasText(keyword) && !StringUtils.hasText(tag)) { + Page pageParam = new Page<>(page, size); + Page productPage = productMapper.selectPage(pageParam, + Wrappers.lambdaQuery(ProductDO.class) + .eq(ProductDO::getIsDelete, 0) + .orderByDesc(ProductDO::getCreateTime)); + PageResultVO result = new PageResultVO<>(); + result.setList(productPage.getRecords().stream().map(this::convertToVO).collect(Collectors.toList())); + result.setTotal(productPage.getTotal()); + result.setPage(page); + result.setSize(size); + return result; + } + + List source = StringUtils.hasText(keyword) + ? searchFrontProducts(keyword) + : loadProductsByTag(tag); + if (StringUtils.hasText(keyword) && StringUtils.hasText(tag)) { + Set exactTagIds = findExactTagIds(tag); + source = source.stream() + .filter(productVO -> containsAnyTagId(productVO.getTags(), exactTagIds)) + .collect(Collectors.toList()); + } + + int fromIndex = Math.max((page - 1) * size, 0); + int toIndex = Math.min(fromIndex + size, source.size()); + PageResultVO result = new PageResultVO<>(); + result.setList(fromIndex >= source.size() ? List.of() : new ArrayList<>(source.subList(fromIndex, toIndex))); + result.setTotal((long) source.size()); + result.setPage(page); + result.setSize(size); + return result; + } + + private List listFrontProductDOs() { + return productMapper.selectList( + Wrappers.lambdaQuery(ProductDO.class) + .eq(ProductDO::getIsDelete, 0) + .orderByDesc(ProductDO::getCreateTime) + ); + } + + private Set findExactTagIds(String tag) { + if (!StringUtils.hasText(tag)) { + return Set.of(); + } + return tagMapper.selectList( + Wrappers.lambdaQuery(TagDO.class) + .eq(TagDO::getIsDelete, 0) + .eq(TagDO::getTagName, tag) + ).stream() + .map(TagDO::getId) + .map(String::valueOf) + .collect(Collectors.toCollection(HashSet::new)); + } + + private Set findLikeTagIds(String keyword) { + if (!StringUtils.hasText(keyword)) { + return Set.of(); + } + return tagMapper.selectList( + Wrappers.lambdaQuery(TagDO.class) + .eq(TagDO::getIsDelete, 0) + .like(TagDO::getTagName, keyword) + ).stream() + .map(TagDO::getId) + .map(String::valueOf) + .collect(Collectors.toCollection(HashSet::new)); + } + + private int normalizePage(Integer page) { + return page == null || page < 1 ? 1 : page; + } + + private int normalizePageSize(Integer size) { + if (size == null || size < 1) { + return DEFAULT_PUBLIC_PAGE_SIZE; + } + return Math.min(size, MAX_PUBLIC_PAGE_SIZE); + } + + private String normalizeOptionalKeyword(String value) { + return StringUtils.hasText(value) ? value.trim() : ""; + } + + private void evictPublicProductCaches(Long productId) { + if (productId != null) { + multiLevelCacheService.evict(PRODUCT_DETAIL_CACHE_PREFIX + productId); + } + multiLevelCacheService.evictByPrefix(PRODUCT_LIST_CACHE_PREFIX); + multiLevelCacheService.evictByPrefix(PRODUCT_SEARCH_CACHE_PREFIX); + } } 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 bfcd7830..cd58d2e9 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 @@ -4,6 +4,8 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.fasterxml.jackson.core.type.TypeReference; +import com.xiaowang.yuminailcore.config.AppCacheProperties; import com.xiaowang.yuminailcore.dto.ShopDTO; import com.xiaowang.yuminailcore.entity.CouponDO; import com.xiaowang.yuminailcore.entity.CommentDO; @@ -20,6 +22,7 @@ import com.xiaowang.yuminailcore.mapper.UserCouponMapper; import com.xiaowang.yuminailcore.service.CouponService; import com.xiaowang.yuminailcore.service.ShopService; import com.xiaowang.yuminailcore.support.UserShopBindingSupport; +import com.xiaowang.yuminailcore.support.cache.MultiLevelCacheService; import com.xiaowang.yuminailcore.vo.PageResultVO; import com.xiaowang.yuminailcore.vo.ShopVO; import lombok.RequiredArgsConstructor; @@ -27,6 +30,7 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; +import java.time.Duration; import java.util.List; import java.util.stream.Collectors; @@ -40,6 +44,8 @@ import java.util.stream.Collectors; @Service @RequiredArgsConstructor 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:"; private final ShopMapper shopMapper; private final CouponService couponService; @@ -49,6 +55,8 @@ public class ShopServiceImpl extends ServiceImpl implements private final CommentMapper commentMapper; private final UserCouponMapper userCouponMapper; private final UserShopBindingSupport userShopBindingSupport; + private final MultiLevelCacheService multiLevelCacheService; + private final AppCacheProperties appCacheProperties; @Override @Transactional(rollbackFor = Exception.class) @@ -64,6 +72,7 @@ public class ShopServiceImpl extends ServiceImpl implements shopDO.setIsDelete(0); shopMapper.insert(shopDO); couponService.initializeDefaultVipAutoCoupons(shopDO.getId()); + evictShopCaches(shopDO.getId()); return shopDO.getId(); } @@ -82,7 +91,11 @@ public class ShopServiceImpl extends ServiceImpl implements if (shopDTO.getStatus() != null) { shopDO.setStatus(normalizeStatus(shopDTO.getStatus())); } - return shopMapper.updateById(shopDO) > 0; + boolean updated = shopMapper.updateById(shopDO) > 0; + if (updated) { + evictShopCaches(id); + } + return updated; } @Override @@ -124,7 +137,11 @@ public class ShopServiceImpl extends ServiceImpl implements userShopBindingSupport.deleteBindingsByShopId(id); shopDO.setStatus(0); shopDO.setIsDelete(1); - return shopMapper.updateById(shopDO) > 0; + boolean deleted = shopMapper.updateById(shopDO) > 0; + if (deleted) { + evictShopCaches(id); + } + return deleted; } @Override @@ -134,28 +151,50 @@ public class ShopServiceImpl extends ServiceImpl implements return false; } shopDO.setStatus(normalizeStatus(status)); - return shopMapper.updateById(shopDO) > 0; + boolean updated = shopMapper.updateById(shopDO) > 0; + if (updated) { + evictShopCaches(id); + } + return updated; } @Override public ShopVO getShopById(Long id) { - ShopDO shopDO = shopMapper.selectById(id); - if (shopDO == null || Integer.valueOf(1).equals(shopDO.getIsDelete())) { - return null; - } - return convertToVO(shopDO); + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getShop(); + return multiLevelCacheService.getOrLoad( + SHOP_DETAIL_CACHE_PREFIX + id, + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference() { + }, + () -> { + ShopDO shopDO = shopMapper.selectById(id); + if (shopDO == null || Integer.valueOf(1).equals(shopDO.getIsDelete())) { + return null; + } + return convertToVO(shopDO); + } + ); } @Override public List listAllShops() { - List shopDOs = shopMapper.selectList( - Wrappers.lambdaQuery(ShopDO.class) - .eq(ShopDO::getIsDelete, 0) - .eq(ShopDO::getStatus, 1) + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getShop(); + return multiLevelCacheService.getOrLoad( + SHOP_LIST_CACHE_PREFIX + "active", + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference>() { + }, + () -> shopMapper.selectList( + Wrappers.lambdaQuery(ShopDO.class) + .eq(ShopDO::getIsDelete, 0) + .eq(ShopDO::getStatus, 1) + .orderByDesc(ShopDO::getCreateTime) + ).stream() + .map(this::convertToVO) + .collect(Collectors.toList()) ); - return shopDOs.stream() - .map(this::convertToVO) - .collect(Collectors.toList()); } @Override @@ -236,4 +275,11 @@ public class ShopServiceImpl extends ServiceImpl implements private Integer normalizeStatus(Integer status) { return Integer.valueOf(0).equals(status) ? 0 : 1; } + + private void evictShopCaches(Long shopId) { + if (shopId != null) { + multiLevelCacheService.evict(SHOP_DETAIL_CACHE_PREFIX + shopId); + } + multiLevelCacheService.evictByPrefix(SHOP_LIST_CACHE_PREFIX); + } } 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 20b8f0b0..40b79a27 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 @@ -2,18 +2,22 @@ package com.xiaowang.yuminailcore.service.impl; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.fasterxml.jackson.core.type.TypeReference; +import com.xiaowang.yuminailcore.config.AppCacheProperties; import com.xiaowang.yuminailcore.dto.TagDTO; import com.xiaowang.yuminailcore.entity.ShopDO; import com.xiaowang.yuminailcore.entity.TagDO; import com.xiaowang.yuminailcore.mapper.ShopMapper; import com.xiaowang.yuminailcore.mapper.TagMapper; import com.xiaowang.yuminailcore.service.TagService; +import com.xiaowang.yuminailcore.support.cache.MultiLevelCacheService; import com.xiaowang.yuminailcore.vo.TagVO; import lombok.RequiredArgsConstructor; import org.springframework.dao.DuplicateKeyException; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; +import java.time.Duration; import java.util.List; import java.util.stream.Collectors; @@ -27,9 +31,13 @@ import java.util.stream.Collectors; @Service @RequiredArgsConstructor 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:"; private final TagMapper tagMapper; private final ShopMapper shopMapper; + private final MultiLevelCacheService multiLevelCacheService; + private final AppCacheProperties appCacheProperties; @Override public Long createTag(TagDTO tagDTO) { @@ -49,6 +57,7 @@ public class TagServiceImpl extends ServiceImpl implements Tag } catch (DuplicateKeyException exception) { throw buildDuplicateTagException(tagName, shopId, null); } + evictTagCaches(tagDO.getId(), shopId); return tagDO.getId(); } @@ -68,7 +77,11 @@ public class TagServiceImpl extends ServiceImpl implements Tag tagDO.setBorderColor(tagDTO.getBorderColor()); tagDO.setShopId(shopId); try { - return tagMapper.updateById(tagDO) > 0; + boolean updated = tagMapper.updateById(tagDO) > 0; + if (updated) { + evictTagCaches(id, shopId); + } + return updated; } catch (DuplicateKeyException exception) { throw buildDuplicateTagException(tagName, shopId, id); } @@ -81,39 +94,69 @@ public class TagServiceImpl extends ServiceImpl implements Tag return false; } tagDO.setIsDelete(1); - return tagMapper.updateById(tagDO) > 0; + boolean deleted = tagMapper.updateById(tagDO) > 0; + if (deleted) { + evictTagCaches(id, tagDO.getShopId()); + } + return deleted; } @Override public TagVO getTagById(Long id) { - TagDO tagDO = tagMapper.selectById(id); - if (tagDO == null) { - return null; - } - return convertToVO(tagDO); + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getTag(); + return multiLevelCacheService.getOrLoad( + TAG_DETAIL_CACHE_PREFIX + id, + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference() { + }, + () -> { + TagDO tagDO = tagMapper.selectById(id); + if (tagDO == null || Integer.valueOf(1).equals(tagDO.getIsDelete())) { + return null; + } + return convertToVO(tagDO); + } + ); } @Override public List listAllTags() { - List tagDOs = tagMapper.selectList( - Wrappers.lambdaQuery(TagDO.class) - .eq(TagDO::getIsDelete, 0) + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getTag(); + return multiLevelCacheService.getOrLoad( + TAG_LIST_CACHE_PREFIX + "all", + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference>() { + }, + () -> tagMapper.selectList( + Wrappers.lambdaQuery(TagDO.class) + .eq(TagDO::getIsDelete, 0) + .orderByDesc(TagDO::getCreateTime) + ).stream() + .map(this::convertToVO) + .collect(Collectors.toList()) ); - return tagDOs.stream() - .map(this::convertToVO) - .collect(Collectors.toList()); } @Override public List listTagsByShopId(Long shopId) { - List tagDOs = tagMapper.selectList( - Wrappers.lambdaQuery(TagDO.class) - .eq(TagDO::getIsDelete, 0) - .eq(TagDO::getShopId, shopId) + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getTag(); + return multiLevelCacheService.getOrLoad( + TAG_LIST_CACHE_PREFIX + "shop:" + shopId, + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference>() { + }, + () -> tagMapper.selectList( + Wrappers.lambdaQuery(TagDO.class) + .eq(TagDO::getIsDelete, 0) + .eq(TagDO::getShopId, shopId) + .orderByDesc(TagDO::getCreateTime) + ).stream() + .map(this::convertToVO) + .collect(Collectors.toList()) ); - return tagDOs.stream() - .map(this::convertToVO) - .collect(Collectors.toList()); } @Override @@ -194,4 +237,14 @@ public class TagServiceImpl extends ServiceImpl implements Tag ShopDO shopDO = shopMapper.selectById(shopId); return shopDO == null ? null : shopDO.getShopName(); } + + private void evictTagCaches(Long tagId, Long shopId) { + if (tagId != null) { + multiLevelCacheService.evict(TAG_DETAIL_CACHE_PREFIX + tagId); + } + if (shopId != null) { + multiLevelCacheService.evict(TAG_LIST_CACHE_PREFIX + "shop:" + shopId); + } + multiLevelCacheService.evict(TAG_LIST_CACHE_PREFIX + "all"); + } } 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 59294e56..61635ed9 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 @@ -19,6 +19,8 @@ import com.xiaowang.yuminailcore.service.NailArtistInfoService; import com.xiaowang.yuminailcore.service.ShopService; import com.xiaowang.yuminailcore.service.UserService; import com.xiaowang.yuminailcore.service.VerificationCodeService; +import com.xiaowang.yuminailcore.support.ObjectStorageUrlSupport; +import com.xiaowang.yuminailcore.support.security.UserSessionService; import com.xiaowang.yuminailcore.support.id.TimeOrderedSnowflakeIdGenerator; import com.xiaowang.yuminailcore.support.PermissionPolicy; import com.xiaowang.yuminailcore.support.RequestShopContext; @@ -62,6 +64,7 @@ import java.util.stream.Collectors; public class UserServiceImpl extends ServiceImpl implements UserService { private static final String VIP_LEVEL_NORMAL = "普通"; private static final String PHONE_REGEX = "^1[3-9]\\d{9}$"; + private static final String DEFAULT_AVATAR_URL = "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"; private static final String DELETED_PHONE_MARKER = "_deleted_"; private static final String LOGIN_FAIL_KEY_PREFIX = "user:login:failed:"; private static final int MAX_LOGIN_FAILURES = 5; @@ -79,9 +82,11 @@ public class UserServiceImpl extends ServiceImpl implements private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); private final VerificationCodeService verificationCodeService; private final UserShopBindingSupport userShopBindingSupport; + private final ObjectStorageUrlSupport objectStorageUrlSupport; private final StringRedisTemplate redisTemplate; private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; private final WechatMiniBindingMapper wechatMiniBindingMapper; + private final UserSessionService userSessionService; private static Map buildDefaultPermissionSeeds() { Map seeds = new HashMap<>(); @@ -266,8 +271,7 @@ public class UserServiceImpl extends ServiceImpl implements userDO.setIsDelete(0); userDO.setStatus(1); // 设置默认头像 - String defaultAvatar = "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"; - userDO.setAvatar(defaultAvatar); + userDO.setAvatar(DEFAULT_AVATAR_URL); if (Integer.valueOf(0).equals(userDO.getType())) { if (!StringUtils.hasText(userDO.getLevel())) { @@ -382,7 +386,7 @@ public class UserServiceImpl extends ServiceImpl implements if (userDTO.getAvatar().isEmpty()) { userDO.setAvatar(null); } else { - userDO.setAvatar(userDTO.getAvatar()); + userDO.setAvatar(normalizeStoredAvatar(userDTO.getAvatar())); } } if (userDTO.getSignature() != null) { @@ -411,6 +415,9 @@ public class UserServiceImpl extends ServiceImpl implements if (shopBindingChanged) { userShopBindingSupport.syncUserShopBindings(id, validatedShopIds); } + if (userDTO.getPassword() != null) { + userSessionService.revokeAllUserSessions(id); + } syncDefaultPermissions(id, targetUserType); } return updated; @@ -429,6 +436,7 @@ public class UserServiceImpl extends ServiceImpl implements } clearLoginFailureCount(userDO.getAccount()); + userSessionService.revokeAllUserSessions(id); userShopBindingSupport.deleteBindingsByUserId(id); wechatMiniBindingMapper.update( null, @@ -566,8 +574,7 @@ public class UserServiceImpl extends ServiceImpl implements userVO.setNickname(userDO.getNickname()); userVO.setAccount(userDO.getAccount()); userVO.setPhone(userDO.getPhone()); - String defaultAvatar = "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"; - userVO.setAvatar(userDO.getAvatar() != null && !userDO.getAvatar().isEmpty() ? userDO.getAvatar() : defaultAvatar); + userVO.setAvatar(resolveAccessibleAvatar(userDO.getAvatar())); userVO.setSignature(userDO.getSignature()); userVO.setLevel(userDO.getLevel()); userVO.setType(userDO.getType()); @@ -578,6 +585,20 @@ public class UserServiceImpl extends ServiceImpl implements return userVO; } + private String resolveAccessibleAvatar(String avatarUrl) { + if (!StringUtils.hasText(avatarUrl)) { + return DEFAULT_AVATAR_URL; + } + return objectStorageUrlSupport.toAccessibleUrl(avatarUrl); + } + + private String normalizeStoredAvatar(String avatarUrl) { + if (!StringUtils.hasText(avatarUrl)) { + return avatarUrl; + } + return objectStorageUrlSupport.toStoredUrl(avatarUrl); + } + @Override public LoginShopSelectionVO getLoginShopSelectionByAccount(String account) { String normalizedAccount = account == null ? "" : account.trim(); @@ -835,18 +856,18 @@ public class UserServiceImpl extends ServiceImpl implements } @Override - public LoginResponseVO switchShop(Long userId, Long shopId) { + public LoginResponseVO switchShop(Long userId, Long shopId, String previousSessionId) { UserDO userDO = userMapper.selectById(userId); assertUserAvailable(userDO); if (userDO.getType() != null && userDO.getType() >= 2) { throw new RuntimeException("当前账号请使用后台切换店铺"); } Long resolvedShopId = resolveUserLoginShopId(userDO, shopId); - return buildLoginResponse(userDO, resolvedShopId, ENCODED_UNSET_PASSWORD.equals(userDO.getPassword())); + return buildLoginResponse(userDO, resolvedShopId, ENCODED_UNSET_PASSWORD.equals(userDO.getPassword()), previousSessionId); } @Override - public LoginResponseVO switchAdminShop(Long userId, Long shopId) { + public LoginResponseVO switchAdminShop(Long userId, Long shopId, String previousSessionId) { UserDO userDO = userMapper.selectById(userId); assertUserAvailable(userDO); Integer userType = userDO.getType(); @@ -854,7 +875,7 @@ public class UserServiceImpl extends ServiceImpl implements throw new RuntimeException("您没有后台管理权限"); } Long resolvedShopId = resolveAdminLoginShopId(userDO, shopId); - return buildLoginResponse(userDO, resolvedShopId, false); + return buildLoginResponse(userDO, resolvedShopId, false, previousSessionId); } private Long resolveAdminLoginShopId(UserDO userDO, Long requestedShopId) { @@ -966,6 +987,11 @@ public class UserServiceImpl extends ServiceImpl implements Long userId = jwtUtil.getUserIdFromToken(refreshToken); String account = jwtUtil.getAccountFromToken(refreshToken); Long currentShopId = normalizeShopId(jwtUtil.getShopIdFromToken(refreshToken)); + String sessionId = jwtUtil.getSessionIdFromToken(refreshToken); + String refreshJti = jwtUtil.getJtiFromToken(refreshToken); + if (!userSessionService.isRefreshSessionActive(userId, sessionId, refreshJti)) { + throw new RuntimeException("登录态已失效,请重新登录"); + } UserDO userDO = userMapper.selectById(userId); assertUserAvailable(userDO); @@ -974,11 +1000,12 @@ public class UserServiceImpl extends ServiceImpl implements throw new RuntimeException("当前登录店铺已失效,请重新登录"); } - return buildLoginResponse(userDO, currentShopId, ENCODED_UNSET_PASSWORD.equals(userDO.getPassword())); + return buildLoginResponse(userDO, currentShopId, ENCODED_UNSET_PASSWORD.equals(userDO.getPassword()), sessionId); } @Override - public boolean logout() { + public boolean logout(String sessionId) { + userSessionService.revokeSession(sessionId); return true; } @@ -999,7 +1026,7 @@ public class UserServiceImpl extends ServiceImpl implements if (userDTO.getAvatar().isEmpty()) { userDO.setAvatar(null); } else { - userDO.setAvatar(userDTO.getAvatar()); + userDO.setAvatar(normalizeStoredAvatar(userDTO.getAvatar())); } } if (userDTO.getSignature() != null) { @@ -1067,8 +1094,11 @@ public class UserServiceImpl extends ServiceImpl implements targetUser.setPassword(passwordEncoder.encode("888888")); targetUser.setUpdateTime(LocalDateTime.now()); - - return userMapper.updateById(targetUser) > 0; + boolean updated = userMapper.updateById(targetUser) > 0; + if (updated) { + userSessionService.revokeAllUserSessions(targetUserId); + } + return updated; } @Override @@ -1131,6 +1161,8 @@ public class UserServiceImpl extends ServiceImpl implements if (latestUser != null) { clearLoginFailureCount(latestUser.getAccount()); } + } else if (updated) { + userSessionService.revokeAllUserSessions(id); } return updated; } @@ -1197,7 +1229,11 @@ public class UserServiceImpl extends ServiceImpl implements validateVerificationCode(userDO.getPhone(), verificationCode); userDO.setPassword(passwordEncoder.encode(password)); userDO.setUpdateTime(LocalDateTime.now()); - return userMapper.updateById(userDO) > 0; + boolean updated = userMapper.updateById(userDO) > 0; + if (updated) { + userSessionService.revokeAllUserSessions(userId); + } + return updated; } @Override @@ -1248,7 +1284,11 @@ public class UserServiceImpl extends ServiceImpl implements // 更新密码 userDO.setPassword(passwordEncoder.encode(newPassword)); userDO.setUpdateTime(LocalDateTime.now()); - return userMapper.updateById(userDO) > 0; + boolean updated = userMapper.updateById(userDO) > 0; + if (updated) { + userSessionService.revokeAllUserSessions(userDO.getId()); + } + return updated; } private String buildDeletedAccount(UserDO userDO) { @@ -1317,6 +1357,7 @@ public class UserServiceImpl extends ServiceImpl implements .set(UserDO::getStatus, 0) .set(UserDO::getUpdateTime, LocalDateTime.now()) ); + userSessionService.revokeAllUserSessions(userId); } private void clearLoginFailureCount(String account) { @@ -1432,8 +1473,27 @@ public class UserServiceImpl extends ServiceImpl implements } private LoginResponseVO buildLoginResponse(UserDO userDO, Long currentShopId, boolean needSetPassword) { - String accessToken = jwtUtil.generateAccessToken(userDO.getId(), userDO.getAccount(), currentShopId); - String refreshToken = jwtUtil.generateRefreshToken(userDO.getId(), userDO.getAccount(), currentShopId); + return buildLoginResponse(userDO, currentShopId, needSetPassword, null); + } + + 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()) + : userSessionService.issueSession(userDO.getId(), userDO.getAccount(), currentShopId, userDO.getType()); + String accessToken = jwtUtil.generateAccessToken( + userDO.getId(), + userDO.getAccount(), + currentShopId, + sessionIssueResult.sessionId(), + sessionIssueResult.accessJti() + ); + String refreshToken = jwtUtil.generateRefreshToken( + userDO.getId(), + userDO.getAccount(), + currentShopId, + sessionIssueResult.sessionId(), + sessionIssueResult.refreshJti() + ); LoginResponseVO responseVO = new LoginResponseVO(); responseVO.setAccessToken(accessToken); @@ -1462,7 +1522,7 @@ public class UserServiceImpl extends ServiceImpl implements userInfo.setId(userDO.getId()); userInfo.setAccount(userDO.getAccount()); userInfo.setNickname(userDO.getNickname()); - userInfo.setAvatar(userDO.getAvatar()); + userInfo.setAvatar(resolveAccessibleAvatar(userDO.getAvatar())); userInfo.setType(userDO.getType()); userInfo.setShopId(normalizedCurrentShopId); userInfo.setShopName(currentShopName); diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/ObjectStorageUrlSupport.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/ObjectStorageUrlSupport.java new file mode 100644 index 00000000..931739fd --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/ObjectStorageUrlSupport.java @@ -0,0 +1,127 @@ +package com.xiaowang.yuminailcore.support; + +import com.xiaowang.yuminailcore.config.MinioConfig; +import com.xiaowang.yuminailcore.service.MinioService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import java.net.URI; + +/** + * 统一处理对象存储文件地址的提取、签名与归一化,避免把私有桶原始地址直接暴露给前端。 + */ +@Slf4j +@Component +@RequiredArgsConstructor +public class ObjectStorageUrlSupport { + + private static final int DEFAULT_SIGNED_URL_EXPIRE_MINUTES = 60; + + private final MinioService minioService; + private final MinioConfig minioConfig; + + public String toAccessibleUrl(String fileUrl) { + if (!StringUtils.hasText(fileUrl)) { + return fileUrl; + } + String objectName = extractObjectName(fileUrl); + if (!StringUtils.hasText(objectName)) { + return fileUrl; + } + try { + return minioService.getPresignedUrl(objectName, DEFAULT_SIGNED_URL_EXPIRE_MINUTES); + } catch (Exception e) { + log.warn("生成对象存储签名地址失败,回退原地址: {}", fileUrl, e); + return fileUrl; + } + } + + public String toStoredUrl(String fileUrl) { + if (!StringUtils.hasText(fileUrl)) { + return fileUrl; + } + String objectName = extractObjectName(fileUrl); + if (!StringUtils.hasText(objectName)) { + return fileUrl; + } + return minioService.getFileUrl(objectName); + } + + public String extractObjectName(String fileUrl) { + if (!StringUtils.hasText(fileUrl)) { + return ""; + } + + String normalizedUrl = fileUrl.trim(); + if (!normalizedUrl.startsWith("http://") && !normalizedUrl.startsWith("https://")) { + return trimBucketPrefix(stripQuery(normalizedUrl)); + } + + try { + URI fileUri = URI.create(normalizedUrl); + String path = fileUri.getPath(); + if (!StringUtils.hasText(path)) { + return ""; + } + return extractObjectNameFromPath(path); + } catch (Exception e) { + log.warn("解析对象存储文件地址失败: {}", fileUrl, e); + return ""; + } + } + + private String extractObjectNameFromPath(String path) { + String bucketPrefix = "/" + minioConfig.getBucketName() + "/"; + if (path.startsWith(bucketPrefix)) { + return path.substring(bucketPrefix.length()); + } + + String endpointPath = ""; + try { + endpointPath = URI.create(minioConfig.getEndpoint()).getPath(); + } catch (Exception e) { + log.warn("解析 MinIO endpoint 失败: {}", minioConfig.getEndpoint(), e); + } + + if (StringUtils.hasText(endpointPath) && !"/".equals(endpointPath)) { + String normalizedEndpointPath = endpointPath.endsWith("/") + ? endpointPath.substring(0, endpointPath.length() - 1) + : endpointPath; + String prefixedBucketPath = normalizedEndpointPath + bucketPrefix; + if (path.startsWith(prefixedBucketPath)) { + return path.substring(prefixedBucketPath.length()); + } + } + + int bucketIndex = path.indexOf(bucketPrefix); + if (bucketIndex >= 0) { + return path.substring(bucketIndex + bucketPrefix.length()); + } + + return ""; + } + + private String trimBucketPrefix(String rawValue) { + String normalized = stripLeadingSlash(rawValue); + String bucketPrefix = minioConfig.getBucketName() + "/"; + if (normalized.startsWith(bucketPrefix)) { + return normalized.substring(bucketPrefix.length()); + } + return normalized; + } + + private String stripLeadingSlash(String rawValue) { + String normalized = rawValue; + while (normalized.startsWith("/")) { + normalized = normalized.substring(1); + } + return normalized; + } + + private String stripQuery(String rawValue) { + int queryIndex = rawValue.indexOf('?'); + return queryIndex >= 0 ? rawValue.substring(0, queryIndex) : rawValue; + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/cache/MultiLevelCacheService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/cache/MultiLevelCacheService.java new file mode 100644 index 00000000..c6f8b551 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/cache/MultiLevelCacheService.java @@ -0,0 +1,165 @@ +package com.xiaowang.yuminailcore.support.cache; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; +import com.xiaowang.yuminailcore.config.AppCacheProperties; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.stereotype.Component; +import org.springframework.util.CollectionUtils; +import org.springframework.util.StringUtils; + +import java.time.Duration; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; + +/** + * 本地 + Redis 多级缓存。 + */ +@Component +@RequiredArgsConstructor +public class MultiLevelCacheService { + + private static final String NULL_SENTINEL = "__CACHE_NULL__"; + + private final StringRedisTemplate stringRedisTemplate; + private final ObjectMapper objectMapper; + private final AppCacheProperties cacheProperties; + + private Cache localCache; + + private Cache getLocalCache() { + if (localCache == null) { + localCache = Caffeine.newBuilder() + .maximumSize(Math.max(128, cacheProperties.getLocalMaxSize())) + .build(); + } + return localCache; + } + + public T getOrLoad(String key, + Duration localTtl, + Duration redisTtl, + TypeReference typeReference, + Supplier loader) { + CacheLookup lookup = get(key, localTtl, typeReference); + if (lookup.isHit()) { + return lookup.getValue(); + } + + T loaded = loader.get(); + put(key, loaded, localTtl, redisTtl); + return loaded; + } + + public CacheLookup get(String key, Duration localTtl, TypeReference typeReference) { + if (!StringUtils.hasText(key)) { + return CacheLookup.miss(); + } + + LocalCacheEntry localEntry = getLocalCache().getIfPresent(key); + if (localEntry != null) { + if (!localEntry.isExpired()) { + return CacheLookup.hit(readValue(localEntry.getJson(), typeReference)); + } + getLocalCache().invalidate(key); + } + + String json = stringRedisTemplate.opsForValue().get(key); + if (!StringUtils.hasText(json)) { + return CacheLookup.miss(); + } + + putLocal(key, json, localTtl); + return CacheLookup.hit(readValue(json, typeReference)); + } + + public void put(String key, Object value, Duration localTtl, Duration redisTtl) { + if (!StringUtils.hasText(key)) { + return; + } + String json = writeValue(value); + putLocal(key, json, localTtl); + stringRedisTemplate.opsForValue().set(key, json, redisTtl.getSeconds(), TimeUnit.SECONDS); + } + + public void evict(String... keys) { + if (keys == null || keys.length == 0) { + return; + } + for (String key : keys) { + getLocalCache().invalidate(key); + } + stringRedisTemplate.delete(Set.of(keys)); + } + + public void evictByPrefix(String prefix) { + if (!StringUtils.hasText(prefix)) { + return; + } + getLocalCache().asMap().keySet().removeIf(key -> key.startsWith(prefix)); + Set redisKeys = stringRedisTemplate.keys(prefix + "*"); + if (!CollectionUtils.isEmpty(redisKeys)) { + stringRedisTemplate.delete(redisKeys); + } + } + + private void putLocal(String key, String json, Duration localTtl) { + getLocalCache().put(key, new LocalCacheEntry(json, System.currentTimeMillis() + Math.max(1L, localTtl.toMillis()))); + } + + private String writeValue(Object value) { + try { + return value == null ? NULL_SENTINEL : objectMapper.writeValueAsString(value); + } catch (JsonProcessingException exception) { + throw new RuntimeException("缓存序列化失败", exception); + } + } + + private T readValue(String json, TypeReference typeReference) { + if (NULL_SENTINEL.equals(json)) { + return null; + } + try { + return objectMapper.readValue(json, typeReference); + } catch (JsonProcessingException exception) { + throw new RuntimeException("缓存反序列化失败", exception); + } + } + + @Getter + public static final class CacheLookup { + private final boolean hit; + private final T value; + + private CacheLookup(boolean hit, T value) { + this.hit = hit; + this.value = value; + } + + public static CacheLookup hit(T value) { + return new CacheLookup<>(true, value); + } + + public static CacheLookup miss() { + return new CacheLookup<>(false, null); + } + } + + @Getter + @RequiredArgsConstructor + private static final class LocalCacheEntry { + private final String json; + private final long expireAt; + + private boolean isExpired() { + return System.currentTimeMillis() >= expireAt; + } + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/security/CachedBodyHttpServletRequest.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/security/CachedBodyHttpServletRequest.java new file mode 100644 index 00000000..5770ed9b --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/security/CachedBodyHttpServletRequest.java @@ -0,0 +1,59 @@ +package com.xiaowang.yuminailcore.support.security; + +import javax.servlet.ReadListener; +import javax.servlet.ServletInputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; + +/** + * 可重复读取 body 的请求包装。 + */ +public class CachedBodyHttpServletRequest extends HttpServletRequestWrapper { + + private final byte[] cachedBody; + + public CachedBodyHttpServletRequest(HttpServletRequest request, byte[] cachedBody) { + super(request); + this.cachedBody = cachedBody == null ? new byte[0] : cachedBody; + } + + @Override + public ServletInputStream getInputStream() { + ByteArrayInputStream inputStream = new ByteArrayInputStream(cachedBody); + return new ServletInputStream() { + @Override + public boolean isFinished() { + return inputStream.available() == 0; + } + + @Override + public boolean isReady() { + return true; + } + + @Override + public void setReadListener(ReadListener readListener) { + // no-op + } + + @Override + public int read() { + return inputStream.read(); + } + }; + } + + @Override + public BufferedReader getReader() throws IOException { + Charset charset = getCharacterEncoding() == null + ? StandardCharsets.UTF_8 + : Charset.forName(getCharacterEncoding()); + return new BufferedReader(new InputStreamReader(getInputStream(), charset)); + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/security/OperationGuardService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/security/OperationGuardService.java new file mode 100644 index 00000000..1a128e10 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/security/OperationGuardService.java @@ -0,0 +1,296 @@ +package com.xiaowang.yuminailcore.support.security; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.yuminailcore.support.RequestShopContext; +import lombok.RequiredArgsConstructor; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.data.redis.core.script.DefaultRedisScript; +import org.springframework.stereotype.Component; +import org.springframework.util.DigestUtils; +import org.springframework.util.StringUtils; + +import javax.servlet.http.HttpServletRequest; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +import static com.xiaowang.yuminailcore.support.security.RequestSignatureService.REQUEST_BODY_ATTRIBUTE; + +@Component +@RequiredArgsConstructor +public class OperationGuardService { + + private static final DefaultRedisScript RELEASE_LOCK_SCRIPT = new DefaultRedisScript<>(); + + static { + RELEASE_LOCK_SCRIPT.setScriptText( + "if redis.call('get', KEYS[1]) == ARGV[1] then " + + "return redis.call('del', KEYS[1]) " + + "else return 0 end" + ); + RELEASE_LOCK_SCRIPT.setResultType(Long.class); + } + + private static final TypeReference> MAP_TYPE = new TypeReference<>() { + }; + + private final StringRedisTemplate stringRedisTemplate; + private final ObjectMapper objectMapper; + + public GuardHandle tryAcquire(HttpServletRequest request, String action, Duration ttl) { + String key = buildKey(request, action); + String token = UUID.randomUUID().toString(); + Boolean success = stringRedisTemplate.opsForValue().setIfAbsent( + key, + token, + Math.max(1L, ttl == null ? 10L : ttl.getSeconds()), + TimeUnit.SECONDS + ); + return new GuardHandle(key, token, Boolean.TRUE.equals(success)); + } + + public void release(GuardHandle handle) { + if (handle == null || !handle.acquired()) { + return; + } + stringRedisTemplate.execute( + RELEASE_LOCK_SCRIPT, + Collections.singletonList(handle.key()), + handle.token() + ); + } + + public String buildKey(HttpServletRequest request, String action) { + String safeAction = sanitize(action); + String path = request == null ? "-" : sanitize(request.getRequestURI()); + Long userId = request == null ? null : parseLong(request.getAttribute("userId")); + Integer userType = request == null ? null : parseInteger(request.getAttribute("userType")); + Long shopId = request == null ? null : RequestShopContext.getCurrentShopId(request); + + if (isUploadPath(path)) { + return buildUploadKey(request, safeAction, userId); + } + + String fingerprint = buildRequestFingerprint(request, path); + if (userId != null) { + if (isAdminRequest(path, userType)) { + return String.join(":", + "op", + "admin", + String.valueOf(userId), + safeAction, + sanitize(shopId), + fingerprint + ); + } + return String.join(":", + "op", + "user", + String.valueOf(userId), + safeAction, + fingerprint + ); + } + + String subject = resolvePublicSubject(request); + return String.join(":", + "op", + "public", + safeAction, + subject, + sanitize(resolveClientIp(request)), + sanitize(resolveDeviceId(request)) + ); + } + + private String buildUploadKey(HttpServletRequest request, String action, Long userId) { + String uploadId = firstNonBlank( + request == null ? null : request.getParameter("uploadId"), + readBodyField(request, "uploadId") + ); + String chunkIndex = firstNonBlank( + request == null ? null : request.getParameter("chunkIndex"), + readBodyField(request, "chunkIndex") + ); + String suffix = StringUtils.hasText(chunkIndex) + ? sanitize(chunkIndex) + : buildRequestFingerprint(request, request == null ? "-" : request.getRequestURI()); + return String.join(":", + "op", + "upload", + sanitize(userId), + action, + sanitize(uploadId), + suffix + ); + } + + private String buildRequestFingerprint(HttpServletRequest request, String path) { + String canonicalParams = buildCanonicalParams(request == null ? null : request.getParameterMap()); + String bodyHash = buildBodyHash(request); + String raw = String.join("|", + sanitize(path), + sanitize(canonicalParams), + sanitize(bodyHash) + ); + return DigestUtils.md5DigestAsHex(raw.getBytes(StandardCharsets.UTF_8)); + } + + private String resolvePublicSubject(HttpServletRequest request) { + for (String key : new String[]{"account", "phone", "shopId", "productId", "couponId", "userId", "uploadId", "ticket"}) { + String value = firstNonBlank( + request == null ? null : request.getParameter(key), + readBodyField(request, key) + ); + if (StringUtils.hasText(value)) { + return sanitize(value); + } + } + return buildRequestFingerprint(request, request == null ? "-" : request.getRequestURI()); + } + + private String buildBodyHash(HttpServletRequest request) { + if (request == null) { + return "-"; + } + Object cachedBody = request.getAttribute(REQUEST_BODY_ATTRIBUTE); + if (cachedBody instanceof byte[] bytes && bytes.length > 0) { + return DigestUtils.md5DigestAsHex(bytes); + } + return DigestUtils.md5DigestAsHex( + buildCanonicalParams(request.getParameterMap()).getBytes(StandardCharsets.UTF_8) + ); + } + + private String readBodyField(HttpServletRequest request, String fieldName) { + if (request == null || !StringUtils.hasText(fieldName)) { + return null; + } + Object cachedBody = request.getAttribute(REQUEST_BODY_ATTRIBUTE); + if (!(cachedBody instanceof byte[] bytes) || bytes.length == 0) { + return null; + } + try { + Map payload = objectMapper.readValue(bytes, MAP_TYPE); + Object value = payload.get(fieldName); + return value == null ? null : String.valueOf(value); + } catch (Exception ignored) { + return null; + } + } + + private String buildCanonicalParams(Map parameterMap) { + if (parameterMap == null || parameterMap.isEmpty()) { + return ""; + } + Map sorted = new LinkedHashMap<>(); + parameterMap.entrySet().stream() + .sorted(Map.Entry.comparingByKey()) + .forEach(entry -> sorted.put(entry.getKey(), entry.getValue())); + StringBuilder builder = new StringBuilder(); + sorted.forEach((key, values) -> { + if (builder.length() > 0) { + builder.append('&'); + } + builder.append(key) + .append('=') + .append(String.join(",", sortValues(values))); + }); + return builder.toString(); + } + + private String[] sortValues(String[] values) { + String[] copy = values == null ? new String[0] : values.clone(); + Arrays.sort(copy, Comparator.nullsLast(String::compareTo)); + return copy; + } + + private boolean isUploadPath(String path) { + return StringUtils.hasText(path) && path.contains("/upload/"); + } + + private boolean isAdminRequest(String path, Integer userType) { + return (StringUtils.hasText(path) && (path.startsWith("/admin/") || path.startsWith("/order/admin/"))) + || (userType != null && userType >= 2); + } + + 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(); + } + String realIp = request.getHeader("X-Real-IP"); + if (StringUtils.hasText(realIp)) { + return realIp.trim(); + } + return request.getRemoteAddr(); + } + + private String resolveDeviceId(HttpServletRequest request) { + if (request == null) { + return "-"; + } + return request.getHeader(RequestThrottleService.DEVICE_ID_HEADER); + } + + private String sanitize(Object value) { + if (value == null) { + return "-"; + } + String text = String.valueOf(value).trim(); + return text.isEmpty() ? "-" : text.replace(":", "_"); + } + + private String firstNonBlank(String... values) { + if (values == null) { + return null; + } + for (String value : values) { + if (StringUtils.hasText(value)) { + return value.trim(); + } + } + return null; + } + + private Long parseLong(Object value) { + if (value instanceof Number number) { + return number.longValue(); + } + if (value instanceof String text && StringUtils.hasText(text)) { + try { + return Long.parseLong(text.trim()); + } catch (NumberFormatException ignored) { + return null; + } + } + return null; + } + + private Integer parseInteger(Object value) { + if (value instanceof Number number) { + return number.intValue(); + } + if (value instanceof String text && StringUtils.hasText(text)) { + try { + return Integer.parseInt(text.trim()); + } catch (NumberFormatException ignored) { + return null; + } + } + return null; + } + + public record GuardHandle(String key, String token, boolean acquired) { + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/security/OperationGuardStrategy.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/security/OperationGuardStrategy.java new file mode 100644 index 00000000..88eb0ae3 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/security/OperationGuardStrategy.java @@ -0,0 +1,6 @@ +package com.xiaowang.yuminailcore.support.security; + +public enum OperationGuardStrategy { + REJECT_IF_RUNNING, + NOOP_IF_DUPLICATE +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/security/RequestSignatureService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/security/RequestSignatureService.java new file mode 100644 index 00000000..1688c821 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/security/RequestSignatureService.java @@ -0,0 +1,162 @@ +package com.xiaowang.yuminailcore.support.security; + +import com.xiaowang.yuminailcore.config.RequestSignatureProperties; +import lombok.RequiredArgsConstructor; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import javax.servlet.http.HttpServletRequest; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Instant; +import java.util.Arrays; +import java.util.Comparator; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +/** + * 已登录写接口签名校验。 + */ +@Component +@RequiredArgsConstructor +public class RequestSignatureService { + + public static final String REQUEST_BODY_ATTRIBUTE = "cachedRequestBody"; + public static final String HEADER_TIMESTAMP = "X-Timestamp"; + public static final String HEADER_NONCE = "X-Nonce"; + public static final String HEADER_SIGNATURE = "X-Signature"; + public static final String HEADER_SIGNATURE_VERSION = "X-Sign-Version"; + + private static final String SIGNATURE_VERSION = "v1"; + private static final String HMAC_ALGORITHM = "HmacSHA256"; + + private final RequestSignatureProperties properties; + private final StringRedisTemplate stringRedisTemplate; + + public void validateRequest(HttpServletRequest request, String accessToken, Long userId) { + if (!properties.isEnabled() || isSafeMethod(request.getMethod())) { + return; + } + if (!StringUtils.hasText(accessToken)) { + throw new RuntimeException("请求签名缺少登录态"); + } + + String version = request.getHeader(HEADER_SIGNATURE_VERSION); + String timestamp = request.getHeader(HEADER_TIMESTAMP); + String nonce = request.getHeader(HEADER_NONCE); + String signature = request.getHeader(HEADER_SIGNATURE); + + if (!SIGNATURE_VERSION.equals(version)) { + throw new RuntimeException("请求签名版本不正确"); + } + if (!StringUtils.hasText(timestamp) || !StringUtils.hasText(nonce) || !StringUtils.hasText(signature)) { + throw new RuntimeException("请求签名缺失"); + } + + validateTimestamp(timestamp); + registerNonce(userId, nonce); + + String bodyHash = sha256Hex(resolvePayloadBytes(request)); + String canonical = request.getMethod().toUpperCase() + + "\n" + request.getRequestURI() + + "\n" + timestamp + + "\n" + nonce + + "\n" + bodyHash; + String expected = hmacSha256Hex(accessToken, canonical); + if (!MessageDigest.isEqual(expected.getBytes(StandardCharsets.UTF_8), signature.getBytes(StandardCharsets.UTF_8))) { + throw new RuntimeException("请求签名无效"); + } + } + + private void validateTimestamp(String timestamp) { + long requestTimestamp; + try { + requestTimestamp = Long.parseLong(timestamp); + } catch (NumberFormatException exception) { + throw new RuntimeException("请求时间戳不合法"); + } + long now = Instant.now().toEpochMilli(); + long delta = Math.abs(now - requestTimestamp); + if (delta > properties.getWindowSeconds() * 1000L) { + throw new RuntimeException("请求已过期,请重试"); + } + } + + private void registerNonce(Long userId, String nonce) { + String nonceKey = "request:nonce:" + (userId == null ? "anon" : userId) + ":" + nonce; + Boolean success = stringRedisTemplate.opsForValue().setIfAbsent( + nonceKey, + "1", + properties.getNonceRetentionSeconds(), + TimeUnit.SECONDS + ); + if (Boolean.FALSE.equals(success)) { + throw new RuntimeException("请求已失效,请勿重复提交"); + } + } + + private boolean isSafeMethod(String method) { + if (!StringUtils.hasText(method)) { + return true; + } + String normalized = method.toUpperCase(); + return "GET".equals(normalized) || "HEAD".equals(normalized) || "OPTIONS".equals(normalized); + } + + private byte[] resolvePayloadBytes(HttpServletRequest request) { + Object cachedBody = request.getAttribute(REQUEST_BODY_ATTRIBUTE); + if (cachedBody instanceof byte[] bytes && bytes.length > 0) { + return bytes; + } + String canonicalParams = buildCanonicalParams(request.getParameterMap()); + return canonicalParams.getBytes(StandardCharsets.UTF_8); + } + + private String buildCanonicalParams(Map parameterMap) { + if (parameterMap == null || parameterMap.isEmpty()) { + return ""; + } + return parameterMap.entrySet().stream() + .sorted(Map.Entry.comparingByKey()) + .map(entry -> entry.getKey() + "=" + String.join(",", sorted(entry.getValue()))) + .reduce((left, right) -> left + "&" + right) + .orElse(""); + } + + private String[] sorted(String[] values) { + String[] result = values == null ? new String[0] : values.clone(); + Arrays.sort(result, Comparator.nullsLast(String::compareTo)); + return result; + } + + private String sha256Hex(byte[] payload) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + byte[] bytes = digest.digest(payload == null ? new byte[0] : payload); + return toHex(bytes); + } catch (Exception exception) { + throw new RuntimeException("计算请求摘要失败", exception); + } + } + + private String hmacSha256Hex(String secret, String text) { + try { + Mac mac = Mac.getInstance(HMAC_ALGORITHM); + mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), HMAC_ALGORITHM)); + return toHex(mac.doFinal(text.getBytes(StandardCharsets.UTF_8))); + } catch (Exception exception) { + throw new RuntimeException("计算请求签名失败", exception); + } + } + + private String toHex(byte[] bytes) { + StringBuilder builder = new StringBuilder(bytes.length * 2); + for (byte value : bytes) { + builder.append(String.format("%02x", value)); + } + return builder.toString(); + } +} 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 new file mode 100644 index 00000000..8836e70a --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/security/RequestThrottleService.java @@ -0,0 +1,96 @@ +package com.xiaowang.yuminailcore.support.security; + +import com.xiaowang.yuminailcore.config.RateLimitProperties; +import lombok.RequiredArgsConstructor; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.stereotype.Component; +import org.springframework.util.DigestUtils; +import org.springframework.util.StringUtils; + +import javax.servlet.http.HttpServletRequest; +import java.nio.charset.StandardCharsets; +import java.util.concurrent.TimeUnit; + +/** + * 请求限流服务。 + */ +@Component +@RequiredArgsConstructor +public class RequestThrottleService { + + public static final String DEVICE_ID_HEADER = "X-Device-Id"; + + private final StringRedisTemplate stringRedisTemplate; + private final RateLimitProperties rateLimitProperties; + + public void checkLogin(HttpServletRequest request, String account) { + RateLimitProperties.LimitRule rule = rateLimitProperties.getLogin(); + assertAllowed("login", request, sanitize(account), rule, "登录过于频繁,请稍后再试"); + } + + public void checkSendCode(HttpServletRequest request, String phone) { + RateLimitProperties.LimitRule rule = rateLimitProperties.getSendCode(); + assertAllowed("send-code", request, sanitize(phone), rule, "验证码发送过于频繁,请稍后再试"); + } + + public void checkResetPassword(HttpServletRequest request, String phone) { + RateLimitProperties.LimitRule rule = rateLimitProperties.getResetPassword(); + assertAllowed("reset-password", request, sanitize(phone), rule, "密码重置请求过于频繁,请稍后再试"); + } + + public void checkAuthenticatedWrite(HttpServletRequest request, Long userId) { + String path = request.getRequestURI(); + RateLimitProperties.LimitRule rule = rateLimitProperties.getAuthenticatedWrite(); + String message = "操作过于频繁,请稍后再试"; + String category = "write:" + path; + if ("/order/create".equals(path)) { + rule = rateLimitProperties.getOrderCreate(); + message = "下单过于频繁,请稍后再试"; + } + assertAllowed(category, request, userId == null ? "" : String.valueOf(userId), rule, message); + } + + private void assertAllowed(String category, + HttpServletRequest request, + String subject, + RateLimitProperties.LimitRule rule, + String message) { + if (rule == null || rule.getLimit() <= 0 || rule.getWindowSeconds() <= 0) { + return; + } + String raw = String.join("|", + category, + sanitize(resolveClientIp(request)), + sanitize(resolveDeviceId(request)), + sanitize(subject) + ); + String key = "rate:" + DigestUtils.md5DigestAsHex(raw.getBytes(StandardCharsets.UTF_8)); + Long count = stringRedisTemplate.opsForValue().increment(key); + if (count != null && count == 1L) { + stringRedisTemplate.expire(key, rule.getWindowSeconds(), TimeUnit.SECONDS); + } + if (count != null && count > rule.getLimit()) { + throw new RuntimeException(message); + } + } + + private String resolveClientIp(HttpServletRequest request) { + String forwarded = request.getHeader("X-Forwarded-For"); + if (StringUtils.hasText(forwarded)) { + return forwarded.split(",")[0].trim(); + } + String realIp = request.getHeader("X-Real-IP"); + if (StringUtils.hasText(realIp)) { + return realIp.trim(); + } + return request.getRemoteAddr(); + } + + private String resolveDeviceId(HttpServletRequest request) { + return request.getHeader(DEVICE_ID_HEADER); + } + + private String sanitize(String value) { + return StringUtils.hasText(value) ? value.trim() : "-"; + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/security/UserSessionService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/security/UserSessionService.java new file mode 100644 index 00000000..085d7397 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/security/UserSessionService.java @@ -0,0 +1,146 @@ +package com.xiaowang.yuminailcore.support.security; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.yuminailcore.config.JwtProperties; +import com.xiaowang.yuminailcore.support.id.TimeOrderedSnowflakeIdGenerator; +import lombok.Builder; +import lombok.Data; +import lombok.RequiredArgsConstructor; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import java.time.Duration; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +/** + * 基于 Redis 的登录会话状态。 + */ +@Component +@RequiredArgsConstructor +public class UserSessionService { + + private static final String SESSION_KEY_PREFIX = "auth:session:"; + private static final String USER_SESSION_SET_PREFIX = "auth:user:sessions:"; + + private final StringRedisTemplate stringRedisTemplate; + private final ObjectMapper objectMapper; + private final JwtProperties jwtProperties; + private final TimeOrderedSnowflakeIdGenerator idGenerator; + + public SessionIssueResult issueSession(Long userId, String account, Long shopId, Integer userType) { + String sessionId = idGenerator.nextIdString(); + String accessJti = idGenerator.nextIdString(); + String refreshJti = idGenerator.nextIdString(); + SessionState state = SessionState.builder() + .sessionId(sessionId) + .userId(userId) + .account(account) + .shopId(shopId) + .userType(userType) + .accessJti(accessJti) + .refreshJti(refreshJti) + .build(); + save(state); + return new SessionIssueResult(sessionId, accessJti, refreshJti); + } + + public SessionIssueResult rotateSession(String previousSessionId, Long userId, String account, Long shopId, Integer userType) { + revokeSession(previousSessionId); + return issueSession(userId, account, shopId, userType); + } + + public boolean isAccessSessionActive(Long userId, String sessionId, String accessJti) { + SessionState state = getSessionState(sessionId); + return matches(state, userId) && StringUtils.hasText(accessJti) && accessJti.equals(state.getAccessJti()); + } + + public boolean isRefreshSessionActive(Long userId, String sessionId, String refreshJti) { + SessionState state = getSessionState(sessionId); + return matches(state, userId) && StringUtils.hasText(refreshJti) && refreshJti.equals(state.getRefreshJti()); + } + + public void revokeSession(String sessionId) { + if (!StringUtils.hasText(sessionId)) { + return; + } + SessionState state = getSessionState(sessionId); + stringRedisTemplate.delete(buildSessionKey(sessionId)); + if (state != null && state.getUserId() != null) { + stringRedisTemplate.opsForSet().remove(buildUserSessionSetKey(state.getUserId()), sessionId); + } + } + + public void revokeAllUserSessions(Long userId) { + if (userId == null) { + return; + } + String setKey = buildUserSessionSetKey(userId); + Set sessionIds = stringRedisTemplate.opsForSet().members(setKey); + if (sessionIds != null) { + for (String sessionId : sessionIds) { + stringRedisTemplate.delete(buildSessionKey(sessionId)); + } + } + stringRedisTemplate.delete(setKey); + } + + private boolean matches(SessionState state, Long userId) { + return state != null && state.getUserId() != null && state.getUserId().equals(userId); + } + + private void save(SessionState state) { + try { + String sessionKey = buildSessionKey(state.getSessionId()); + String setKey = buildUserSessionSetKey(state.getUserId()); + Duration ttl = Duration.ofSeconds(jwtProperties.getRefreshTokenExpirationSeconds()); + String json = objectMapper.writeValueAsString(state); + stringRedisTemplate.opsForValue().set(sessionKey, json, ttl.getSeconds(), TimeUnit.SECONDS); + stringRedisTemplate.opsForSet().add(setKey, state.getSessionId()); + stringRedisTemplate.expire(setKey, ttl.getSeconds(), TimeUnit.SECONDS); + } catch (JsonProcessingException exception) { + throw new RuntimeException("写入登录会话失败", exception); + } + } + + private SessionState getSessionState(String sessionId) { + if (!StringUtils.hasText(sessionId)) { + return null; + } + String json = stringRedisTemplate.opsForValue().get(buildSessionKey(sessionId)); + if (!StringUtils.hasText(json)) { + return null; + } + try { + return objectMapper.readValue(json, SessionState.class); + } catch (JsonProcessingException exception) { + stringRedisTemplate.delete(buildSessionKey(sessionId)); + return null; + } + } + + private String buildSessionKey(String sessionId) { + return SESSION_KEY_PREFIX + sessionId; + } + + private String buildUserSessionSetKey(Long userId) { + return USER_SESSION_SET_PREFIX + userId; + } + + @Data + @Builder + public static class SessionState { + private String sessionId; + private Long userId; + private String account; + private Long shopId; + private Integer userType; + private String accessJti; + private String refreshJti; + } + + public record SessionIssueResult(String sessionId, String accessJti, String refreshJti) { + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/utils/JwtUtil.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/utils/JwtUtil.java index 1fd6f04a..6b082cc8 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/utils/JwtUtil.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/utils/JwtUtil.java @@ -1,9 +1,11 @@ package com.xiaowang.yuminailcore.utils; +import com.xiaowang.yuminailcore.config.JwtProperties; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.security.Keys; +import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Component; import javax.crypto.SecretKey; @@ -13,38 +15,39 @@ import java.util.HashMap; import java.util.Map; @Component +@RequiredArgsConstructor public class JwtUtil { - private static final String SECRET = "yuminail-secret-key-for-jwt-token-generation-2026-must-be-at-least-512-bits-long-for-hs512-algorithm-security-requirements"; - private static final long ACCESS_TOKEN_EXPIRATION = 2 * 60 * 60 * 1000; - private static final long REFRESH_TOKEN_EXPIRATION = 7 * 24 * 60 * 60 * 1000; + private final JwtProperties jwtProperties; - private final SecretKey key; - - public JwtUtil() { - this.key = Keys.hmacShaKeyFor(SECRET.getBytes(StandardCharsets.UTF_8)); + private SecretKey getKey() { + return Keys.hmacShaKeyFor(jwtProperties.getSecret().getBytes(StandardCharsets.UTF_8)); } - public String generateAccessToken(Long userId, String account, Long currentShopId) { + public String generateAccessToken(Long userId, String account, Long currentShopId, String sessionId, String jti) { Map claims = new HashMap<>(); claims.put("userId", userId); claims.put("account", account); claims.put("type", "access"); + claims.put("sessionId", sessionId); + claims.put("jti", jti); if (currentShopId != null && currentShopId > 0) { claims.put("shopId", currentShopId); } - return createToken(claims, userId.toString(), ACCESS_TOKEN_EXPIRATION); + return createToken(claims, userId.toString(), jwtProperties.getAccessTokenExpirationSeconds() * 1000); } - public String generateRefreshToken(Long userId, String account, Long currentShopId) { + public String generateRefreshToken(Long userId, String account, Long currentShopId, String sessionId, String jti) { Map claims = new HashMap<>(); claims.put("userId", userId); claims.put("account", account); claims.put("type", "refresh"); + claims.put("sessionId", sessionId); + claims.put("jti", jti); if (currentShopId != null && currentShopId > 0) { claims.put("shopId", currentShopId); } - return createToken(claims, userId.toString(), REFRESH_TOKEN_EXPIRATION); + return createToken(claims, userId.toString(), jwtProperties.getRefreshTokenExpirationSeconds() * 1000); } private String createToken(Map claims, String subject, long expiration) { @@ -54,15 +57,18 @@ public class JwtUtil { return Jwts.builder() .setClaims(claims) .setSubject(subject) + .setIssuer(jwtProperties.getIssuer()) .setIssuedAt(now) .setExpiration(expiryDate) - .signWith(key, SignatureAlgorithm.HS512) + .signWith(getKey(), SignatureAlgorithm.HS512) .compact(); } public Claims parseToken(String token) { return Jwts.parserBuilder() - .setSigningKey(key) + .setSigningKey(getKey()) + .setAllowedClockSkewSeconds(jwtProperties.getClockSkewSeconds()) + .requireIssuer(jwtProperties.getIssuer()) .build() .parseClaimsJws(token) .getBody(); @@ -83,6 +89,21 @@ public class JwtUtil { return claims.get("type", String.class); } + public String getSessionIdFromToken(String token) { + Claims claims = parseToken(token); + return claims.get("sessionId", String.class); + } + + public String getJtiFromToken(String token) { + Claims claims = parseToken(token); + return claims.get("jti", String.class); + } + + public String getIssuerFromToken(String token) { + Claims claims = parseToken(token); + return claims.getIssuer(); + } + public Long getShopIdFromToken(String token) { Claims claims = parseToken(token); Object value = claims.get("shopId"); diff --git a/YumiNail-Core/src/main/resources/application.yaml b/YumiNail-Core/src/main/resources/application.yaml index 8701e69b..3e54e0f5 100644 --- a/YumiNail-Core/src/main/resources/application.yaml +++ b/YumiNail-Core/src/main/resources/application.yaml @@ -24,3 +24,48 @@ server: mybatis: configuration: map-underscore-to-camel-case: true + +yuminail: + security: + jwt: + issuer: yuminail + access-token-expiration-seconds: 7200 + refresh-token-expiration-seconds: 604800 + clock-skew-seconds: 30 + signature: + enabled: true + window-seconds: 300 + nonce-retention-seconds: 600 + rate-limit: + login: + limit: 10 + window-seconds: 60 + send-code: + limit: 5 + window-seconds: 60 + reset-password: + limit: 5 + window-seconds: 600 + authenticated-write: + limit: 80 + window-seconds: 60 + order-create: + limit: 10 + window-seconds: 60 + cache: + local-max-size: 2048 + product-detail: + local-ttl-seconds: 120 + redis-ttl-seconds: 900 + product-list: + local-ttl-seconds: 60 + redis-ttl-seconds: 300 + product-search: + local-ttl-seconds: 60 + redis-ttl-seconds: 300 + shop: + local-ttl-seconds: 180 + redis-ttl-seconds: 900 + tag: + local-ttl-seconds: 300 + redis-ttl-seconds: 1200 diff --git a/YumiNail-Core/src/main/resources/log4j2.xml b/YumiNail-Core/src/main/resources/log4j2.xml index ee4f486f..d3aee10b 100644 --- a/YumiNail-Core/src/main/resources/log4j2.xml +++ b/YumiNail-Core/src/main/resources/log4j2.xml @@ -7,6 +7,7 @@ + diff --git a/YumiNail-Gateway/pom.xml b/YumiNail-Gateway/pom.xml index ce0a7d4a..0605f5d9 100644 --- a/YumiNail-Gateway/pom.xml +++ b/YumiNail-Gateway/pom.xml @@ -101,6 +101,24 @@ + + io.jsonwebtoken + jjwt-api + 0.11.5 + + + io.jsonwebtoken + jjwt-impl + 0.11.5 + runtime + + + io.jsonwebtoken + jjwt-jackson + 0.11.5 + runtime + + org.projectlombok diff --git a/YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/config/JwtProperties.java b/YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/config/JwtProperties.java new file mode 100644 index 00000000..90a20d49 --- /dev/null +++ b/YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/config/JwtProperties.java @@ -0,0 +1,20 @@ +package com.xiaowang.yumitailgateway.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +/** + * Gateway JWT 校验配置。 + */ +@Data +@Configuration +@ConfigurationProperties(prefix = "yuminail.security.jwt") +public class JwtProperties { + + private String secret = "yuminail-secret-key-for-jwt-token-generation-2026-must-be-at-least-512-bits-long-for-hs512-algorithm-security-requirements"; + + private String issuer = "yuminail"; + + private long clockSkewSeconds = 30; +} 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 33ed69c2..15ada215 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 @@ -59,6 +59,9 @@ public class AuthGlobalFilter implements GlobalFilter, Ordered { @Autowired private GatewayConfig gatewayConfig; + @Autowired + private GatewayJwtValidator gatewayJwtValidator; + private final AntPathMatcher pathMatcher = new AntPathMatcher(); @Override @@ -70,15 +73,20 @@ public class AuthGlobalFilter implements GlobalFilter, Ordered { return chain.filter(exchange); } - String token = request.getHeaders().getFirst("Authorization"); - if (!StringUtils.hasText(token)) { + String authorization = request.getHeaders().getFirst("Authorization"); + if (!StringUtils.hasText(authorization)) { return unAuthorized(exchange, "未携带Token,拒绝访问"); } - if (!token.startsWith("Bearer ")) { + if (!authorization.startsWith("Bearer ")) { return unAuthorized(exchange, "Token格式错误"); } + String token = authorization.substring("Bearer ".length()); + if (!gatewayJwtValidator.validateAccessToken(token)) { + return unAuthorized(exchange, "Token无效或已过期"); + } + return chain.filter(exchange); } diff --git a/YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/filter/GatewayJwtValidator.java b/YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/filter/GatewayJwtValidator.java new file mode 100644 index 00000000..3f01d229 --- /dev/null +++ b/YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/filter/GatewayJwtValidator.java @@ -0,0 +1,40 @@ +package com.xiaowang.yumitailgateway.filter; + +import com.xiaowang.yumitailgateway.config.JwtProperties; +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.security.Keys; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; + +import javax.crypto.SecretKey; +import java.nio.charset.StandardCharsets; + +/** + * Gateway 侧 JWT 快速校验。 + */ +@Component +@RequiredArgsConstructor +public class GatewayJwtValidator { + + private final JwtProperties jwtProperties; + + public boolean validateAccessToken(String token) { + try { + Claims claims = Jwts.parserBuilder() + .setSigningKey(getKey()) + .setAllowedClockSkewSeconds(jwtProperties.getClockSkewSeconds()) + .requireIssuer(jwtProperties.getIssuer()) + .build() + .parseClaimsJws(token) + .getBody(); + return "access".equals(claims.get("type", String.class)); + } catch (Exception exception) { + return false; + } + } + + private SecretKey getKey() { + return Keys.hmacShaKeyFor(jwtProperties.getSecret().getBytes(StandardCharsets.UTF_8)); + } +} diff --git a/YumiNail-Gateway/src/main/resources/application.yaml b/YumiNail-Gateway/src/main/resources/application.yaml index 356834b5..8f64da4d 100644 --- a/YumiNail-Gateway/src/main/resources/application.yaml +++ b/YumiNail-Gateway/src/main/resources/application.yaml @@ -113,6 +113,10 @@ spring: - RewritePath=/api/(?.*), /${remaining} yuminail: + security: + jwt: + issuer: yuminail + clock-skew-seconds: 30 gateway: whitelist: - /api/user/login diff --git a/YumiNail-Gateway/src/main/resources/log4j2.xml b/YumiNail-Gateway/src/main/resources/log4j2.xml index 131464bb..efea8593 100644 --- a/YumiNail-Gateway/src/main/resources/log4j2.xml +++ b/YumiNail-Gateway/src/main/resources/log4j2.xml @@ -7,6 +7,7 @@ + diff --git a/docs/changes/2026-04-20-小程序前后台防呆与重复提交收口.md b/docs/changes/2026-04-20-小程序前后台防呆与重复提交收口.md new file mode 100644 index 00000000..14c33336 --- /dev/null +++ b/docs/changes/2026-04-20-小程序前后台防呆与重复提交收口.md @@ -0,0 +1,55 @@ +# 小程序前后台防呆与重复提交收口 + +## 本次范围 + +- 用户端小程序 `WeChatProgram` +- 后台管理小程序 `YumiNail-Admin-Program` +- 服务端 `YumiNail-Core` + +## 前端收口 + +- 新增统一动作守卫工具: + - `WeChatProgram/utils/action-guard.js` + - `YumiNail-Admin-Program/utils/action-guard.js` +- 两端请求工具统一接入写请求防重: + - 同一作用域内,相同写动作在前一次完成前不可重复发起 + - GET 继续保留请求去重 + - 写请求统一返回明确中文重复提示 +- 上传链路继续复用同一请求签名与会话校验,不新增前端幂等 token +- 用户端重点页补齐或修正了动作守卫与脚本可用性: + - 作品页 + - 收藏页 + - 个人中心 + - 订单页 + - 作品详情页 +- 本轮同时修复了几处因历史编码污染导致的脚本语法错误,避免真机或开发工具直接报错 + +## 后端收口 + +- 新增 `@OperationGuard` 注解,统一声明写操作防重策略 +- 新增 `OperationGuardService`,基于 Redis 做短时动作锁 +- 新增 `OperationGuardAspect`,在控制器写接口进入实际业务前做统一拦截 +- 支持两类策略: + - `REJECT_IF_RUNNING` + - 重复中的提交直接拒绝 + - `NOOP_IF_DUPLICATE` + - 收藏、点赞、移除、退出等可幂等动作直接按无害重复处理 +- 权限切面执行顺序前置,保证先做身份与权限校验,再进入操作防重 +- 已对前后台主要写接口接入该注解,包括登录、切店、资料更新、购物车、下单、点赞收藏、后台增删改发放等链路 + +## 接口与数据 + +- 不新增 HTTP 路由 +- 不修改现有请求体和响应结构 +- 不新增 SQL +- 不改数据库表 + +## 验证 + +- `YumiNail-Core` 已执行 `mvn -q -DskipTests compile` +- 两套小程序本次改动的公共层与关键页面已执行 `node --check` + +## 备注 + +- 本轮优先落统一基础设施和高频链路收口,页面按钮的显式 loading/disabled 继续优先复用现有页面状态与统一请求守卫 +- 重复点击即使绕过前端直接调用接口,服务端也会继续由 Redis 动作锁和现有鉴权链路兜底