diff --git a/.gitignore b/.gitignore index 51696d7b..9392dd61 100644 --- a/.gitignore +++ b/.gitignore @@ -260,6 +260,11 @@ jspm_packages/ WeChatProgram/utils/config.local.js YumiNail-Admin-Program/utils/config.local.js +# Local release/test artifacts +release-packages/ +.codex-temp-* +*.swp + # Snowpack dependency directory (https://snowpack.dev/) web_modules/ diff --git a/WeChatProgram/assets/images/default-product.png b/WeChatProgram/assets/images/default-product.png new file mode 100644 index 00000000..84c1b545 Binary files /dev/null and b/WeChatProgram/assets/images/default-product.png differ diff --git a/WeChatProgram/assets/images/default-shop.png b/WeChatProgram/assets/images/default-shop.png new file mode 100644 index 00000000..bbcce9f4 Binary files /dev/null and b/WeChatProgram/assets/images/default-shop.png differ diff --git a/WeChatProgram/pages/auth/index.js b/WeChatProgram/pages/auth/index.js index b5057c70..91f4e60d 100644 --- a/WeChatProgram/pages/auth/index.js +++ b/WeChatProgram/pages/auth/index.js @@ -124,14 +124,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({ @@ -752,7 +752,7 @@ Page({ handleWechatMiniUnavailableTap() { wx.showToast({ - title: this.data.wechatMiniDisabledReason || '当前环境暂不支持一键登录', + title: this.data.wechatMiniDisabledReason || '请使用账号密码或验证码登录', icon: 'none' }) }, diff --git a/WeChatProgram/pages/settings/index.js b/WeChatProgram/pages/settings/index.js index a296354b..4615e5f4 100644 --- a/WeChatProgram/pages/settings/index.js +++ b/WeChatProgram/pages/settings/index.js @@ -17,36 +17,6 @@ const { const phoneRegex = /^1[3-9]\d{9}$/ const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@$!%*#?&]{8,}$/ const SETTINGS_DRAFT_KEY = 'user-settings' -const placeholderEntries = [ - { - key: 'notifications', - title: '消息通知' - }, - { - key: 'message-push', - title: '消息推送' - }, - { - key: 'theme', - title: '主题设置' - }, - { - key: 'privacy', - title: '隐私政策' - }, - { - key: 'about', - title: '关于我们' - }, - { - key: 'help', - title: '帮助中心' - }, - { - key: 'clear-cache', - title: '缓存清理' - } -] Page({ data: Object.assign(createKeyboardSafeData({ @@ -64,7 +34,6 @@ Page({ activeSecurityPanel: '', userInfo: null, defaultAvatar: DEFAULT_AVATAR, - placeholderEntries, form: { nickname: '', signature: '' @@ -734,13 +703,6 @@ Page({ } }, - handleComingSoon() { - wx.showToast({ - title: '该功能暂未开放', - icon: 'none' - }) - }, - async handleDeactivateAccount() { if (this.data.deactivating) { return diff --git a/WeChatProgram/pages/settings/index.wxml b/WeChatProgram/pages/settings/index.wxml index a4bbda6b..41466edb 100644 --- a/WeChatProgram/pages/settings/index.wxml +++ b/WeChatProgram/pages/settings/index.wxml @@ -277,17 +277,6 @@ - - 更多功能 - - - - {{item.title}} - - 暂未开放 - - - 退出登录 diff --git a/WeChatProgram/pages/settings/index.wxss b/WeChatProgram/pages/settings/index.wxss index a928cbb4..65aa2191 100644 --- a/WeChatProgram/pages/settings/index.wxss +++ b/WeChatProgram/pages/settings/index.wxss @@ -90,8 +90,7 @@ margin-top: 20rpx; } -.security-card, -.more-card { +.security-card { margin-top: 20rpx; } @@ -195,16 +194,6 @@ flex: 1; } -.placeholder-tag { - flex-shrink: 0; - padding: 12rpx 18rpx; - border-radius: 999rpx; - background: #fdf0f4; - color: #c6597d; - font-size: 22rpx; - font-weight: 700; -} - .danger-row { margin-top: 8rpx; } diff --git a/WeChatProgram/utils/config.js b/WeChatProgram/utils/config.js index 00bbcbb7..086af937 100644 --- a/WeChatProgram/utils/config.js +++ b/WeChatProgram/utils/config.js @@ -121,8 +121,8 @@ module.exports = { signedUrl: 50 * 60 * 1000 }, DEFAULT_AVATAR: 'https://api.dicebear.com/7.x/avataaars/svg?seed=default', - DEFAULT_PRODUCT_IMAGE: 'https://via.placeholder.com/200x200?text=Product', - DEFAULT_SHOP_IMAGE: 'https://via.placeholder.com/200x200?text=Shop', + DEFAULT_PRODUCT_IMAGE: '/assets/images/default-product.png', + DEFAULT_SHOP_IMAGE: '/assets/images/default-shop.png', NO_COUPON_KEY: 'NONE', TAB_PAGES: [ '/pages/home/index', diff --git a/WeChatProgram/utils/request.js b/WeChatProgram/utils/request.js index 46dada16..7f56c183 100644 --- a/WeChatProgram/utils/request.js +++ b/WeChatProgram/utils/request.js @@ -131,10 +131,12 @@ function buildSignatureHeaders(options) { return headers } + const formData = options.formData + const hasFormData = formData && Object.keys(formData).length > 0 const contentType = String((options.header && options.header['Content-Type']) || options.contentType || 'application/json').toLowerCase() - const payload = contentType.includes('application/json') + const payload = contentType.includes('application/json') && !hasFormData ? buildJsonPayload(options.data) - : buildCanonicalParams(options.formData || options.data || options.params) + : buildCanonicalParams(formData || options.data || options.params) const timestamp = String(Date.now()) const nonce = randomNonce() const canonical = [ diff --git a/YumiNail-Admin-Program/utils/request.js b/YumiNail-Admin-Program/utils/request.js index dbb3a6f2..0bdf9b26 100644 --- a/YumiNail-Admin-Program/utils/request.js +++ b/YumiNail-Admin-Program/utils/request.js @@ -26,6 +26,39 @@ function buildRequestUrl(url, params) { return query ? `${target}${target.includes('?') ? '&' : '?'}${query}` : target } +function extractPath(value) { + const target = String(value || '') + if (!target) { + return '' + } + if (/^[a-z][a-z\d+\-.]*:\/\//i.test(target)) { + try { + return new URL(target).pathname + } catch (error) {} + } + return target.split('?')[0] || '' +} + +function toBackendRequestPath(url) { + const path = extractPath(url).replace(/\/+$/, '') || '/' + if (path === '/admin/api') { + return '/admin' + } + if (path.startsWith('/admin/api/')) { + return `/admin/${path.slice('/admin/api/'.length)}` + } + if (path === '/api/admin') { + return '/admin' + } + if (path.startsWith('/api/admin/')) { + return `/admin/${path.slice('/api/admin/'.length)}` + } + if (path === '/admin' || path.startsWith('/admin/')) { + return path + } + return path.startsWith('/') ? `/admin${path}` : `/admin/${path}` +} + function isAuthFreePath(url) { return [ '/auth/login', @@ -124,15 +157,17 @@ function buildSignatureHeaders(options) { return headers } + const formData = options.formData + const hasFormData = formData && Object.keys(formData).length > 0 const contentType = String((options.header && options.header['Content-Type']) || options.contentType || 'application/json').toLowerCase() - const payload = contentType.includes('application/json') + const payload = contentType.includes('application/json') && !hasFormData ? buildJsonPayload(options.data) - : buildCanonicalParams(options.formData || options.data || options.params) + : buildCanonicalParams(formData || options.data || options.params) const timestamp = String(Date.now()) const nonce = randomNonce() const canonical = [ method, - options.url, + toBackendRequestPath(options.url), timestamp, nonce, sha256Hex(payload) 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 index 5d1bd39c..d8879a85 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/AppCacheProperties.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/AppCacheProperties.java @@ -26,6 +26,8 @@ public class AppCacheProperties { private CacheSpec objectStorageFile = new CacheSpec(300, 1800); + private CacheSpec dashboard = new CacheSpec(30, 90); + @Data public static class CacheSpec { private long localTtlSeconds; diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/DashboardController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/DashboardController.java index 27c18631..21df8f19 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/DashboardController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/DashboardController.java @@ -1,8 +1,10 @@ package com.xiaowang.yuminailcore.controller; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.fasterxml.jackson.core.type.TypeReference; import com.xiaowang.yuminailcore.annotation.RequirePermission; import com.xiaowang.yuminailcore.common.Result; +import com.xiaowang.yuminailcore.config.AppCacheProperties; import com.xiaowang.yuminailcore.entity.CommentDO; import com.xiaowang.yuminailcore.entity.OrderDO; import com.xiaowang.yuminailcore.entity.OrderItemDO; @@ -16,6 +18,7 @@ import com.xiaowang.yuminailcore.mapper.ShopMapper; import com.xiaowang.yuminailcore.mapper.UserMapper; import com.xiaowang.yuminailcore.support.AdminScopeHelper; import com.xiaowang.yuminailcore.support.UserShopBindingSupport; +import com.xiaowang.yuminailcore.support.cache.MultiLevelCacheService; import com.xiaowang.yuminailcore.vo.DashboardStatsVO; import com.xiaowang.yuminailcore.vo.HotProductVO; import com.xiaowang.yuminailcore.vo.RecentActivityVO; @@ -24,6 +27,7 @@ import org.springframework.beans.BeanUtils; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; +import java.time.Duration; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; @@ -44,15 +48,30 @@ public class DashboardController { private final OrderItemMapper orderItemMapper; private final AdminScopeHelper adminScopeHelper; private final UserShopBindingSupport userShopBindingSupport; + private final MultiLevelCacheService multiLevelCacheService; + private final AppCacheProperties appCacheProperties; @GetMapping("/stats") @RequirePermission("dashboard:view") public Result getDashboardStats(HttpServletRequest request) { - DashboardStatsVO stats = new DashboardStatsVO(); - UserDO currentUser = adminScopeHelper.getCurrentUser(request); - Long shopIdScope = null; - + Long shopIdScope = resolveShopScope(currentUser); + String cacheScope = currentUser == null ? "anonymous" : (shopIdScope == null ? "admin" : "shop:" + shopIdScope); + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getDashboard(); + DashboardStatsVO stats = multiLevelCacheService.getOrLoad( + "cache:dashboard:stats:" + cacheScope, + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference() { + }, + () -> buildDashboardStats(currentUser, shopIdScope) + ); + return Result.success(stats); + } + + private DashboardStatsVO buildDashboardStats(UserDO currentUser, Long shopIdScope) { + DashboardStatsVO stats = new DashboardStatsVO(); + if (currentUser != null) { // 根据用户类型显示不同的数据 if (currentUser.getType() == 4) { // 管理员 @@ -88,27 +107,29 @@ public class DashboardController { stats.setHotProducts(getHotProducts(shopIdScope)); stats.setRecentActivities(getRecentActivities(shopIdScope)); - return Result.success(stats); + return stats; + } + + private Long resolveShopScope(UserDO currentUser) { + if (currentUser == null || currentUser.getType() == 4) { + return null; + } + return currentUser.getShopId(); } private Long getTodayOrders(Long shopId) { // 获取今天的开始时间 LocalDateTime todayStart = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0); String todayStartStr = todayStart.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); - System.out.println("Today start time: " + todayStartStr); if (shopId != null) { // 非管理员只查询自己店铺的订单,通过订单商品关联到商品,再关联到店铺 java.util.Map result = orderItemMapper.countTodayOrdersByShopId(shopId, todayStartStr); - Long count = result != null && result.get("count") != null ? Long.valueOf(result.get("count").toString()) : 0L; - System.out.println("Shop ID: " + shopId + ", Order count: " + count); - return count; + return result != null && result.get("count") != null ? Long.valueOf(result.get("count").toString()) : 0L; } else { // 管理员查询所有订单 java.util.Map result = orderItemMapper.countTodayOrders(todayStartStr); - Long count = result != null && result.get("count") != null ? Long.valueOf(result.get("count").toString()) : 0L; - System.out.println("Admin order count: " + count); - return count; + return result != null && result.get("count") != null ? Long.valueOf(result.get("count").toString()) : 0L; } } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/HealthController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/HealthController.java index 9f189efe..911fc0b3 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/HealthController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/HealthController.java @@ -1,10 +1,22 @@ package com.xiaowang.yuminailcore.controller; import com.xiaowang.yuminailcore.common.Result; +import lombok.RequiredArgsConstructor; +import org.springframework.cloud.client.ServiceInstance; +import org.springframework.cloud.client.discovery.DiscoveryClient; +import org.springframework.core.env.Environment; +import org.springframework.data.redis.connection.RedisConnection; +import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import javax.sql.DataSource; +import java.sql.Connection; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + /** * 健康检查控制器 * @@ -13,8 +25,14 @@ import org.springframework.web.bind.annotation.RestController; */ @RestController @RequestMapping("/health") +@RequiredArgsConstructor public class HealthController { + private final DataSource dataSource; + private final StringRedisTemplate stringRedisTemplate; + private final DiscoveryClient discoveryClient; + private final Environment environment; + /** * 服务状态检查 */ @@ -22,4 +40,55 @@ public class HealthController { public Result check() { return Result.success("YumiNail-Core is running"); } + + @GetMapping("/diagnostics") + public Result> diagnostics() { + Map diagnostics = new LinkedHashMap<>(); + diagnostics.put("service", environment.getProperty("spring.application.name", "yumi-nail-core")); + diagnostics.put("port", environment.getProperty("server.port", "")); + diagnostics.put("database", checkDatabase()); + diagnostics.put("redis", checkRedis()); + diagnostics.put("discovery", checkDiscovery()); + return Result.success(diagnostics); + } + + private Map checkDatabase() { + Map result = new LinkedHashMap<>(); + try (Connection connection = dataSource.getConnection()) { + result.put("ok", connection.isValid(2)); + result.put("catalog", connection.getCatalog()); + result.put("product", connection.getMetaData().getDatabaseProductName()); + } catch (Exception exception) { + result.put("ok", false); + result.put("error", exception.getClass().getSimpleName()); + } + return result; + } + + private Map checkRedis() { + Map result = new LinkedHashMap<>(); + try (RedisConnection connection = stringRedisTemplate.getConnectionFactory().getConnection()) { + String pong = connection.ping(); + result.put("ok", "PONG".equalsIgnoreCase(pong)); + } catch (Exception exception) { + result.put("ok", false); + result.put("error", exception.getClass().getSimpleName()); + } + return result; + } + + private Map checkDiscovery() { + Map result = new LinkedHashMap<>(); + try { + String serviceName = environment.getProperty("spring.application.name", "yumi-nail-core"); + List instances = discoveryClient.getInstances(serviceName); + result.put("ok", !instances.isEmpty()); + result.put("service", serviceName); + result.put("instanceCount", instances.size()); + } catch (Exception exception) { + result.put("ok", false); + result.put("error", exception.getClass().getSimpleName()); + } + return result; + } } 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 95118b9e..8ab424a6 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 @@ -179,13 +179,23 @@ public class ProductServiceImpl extends ServiceImpl im @Override public List listProductsByShopId(Long shopId) { - List productDOs = productMapper.selectList( - Wrappers.lambdaQuery(ProductDO.class) - .eq(ProductDO::getIsDelete, 0) - .eq(ProductDO::getShopId, shopId) - .orderByDesc(ProductDO::getCreateTime) + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getProductList(); + return multiLevelCacheService.getOrLoad( + PRODUCT_LIST_CACHE_PREFIX + "shop:" + shopId, + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference>() { + }, + () -> { + List productDOs = productMapper.selectList( + Wrappers.lambdaQuery(ProductDO.class) + .eq(ProductDO::getIsDelete, 0) + .eq(ProductDO::getShopId, shopId) + .orderByDesc(ProductDO::getCreateTime) + ); + return toProductVOList(productDOs); + } ); - return toProductVOList(productDOs); } @Override 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 cd58d2e9..50362e93 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 @@ -211,15 +211,26 @@ public class ShopServiceImpl extends ServiceImpl implements @Override public List listShopsByShopName(String shopName) { - List shopDOs = shopMapper.selectList( - Wrappers.lambdaQuery(ShopDO.class) - .eq(ShopDO::getIsDelete, 0) - .eq(ShopDO::getStatus, 1) - .like(ShopDO::getShopName, shopName) + AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getShop(); + String normalizedShopName = StringUtils.hasText(shopName) ? shopName.trim() : ""; + return multiLevelCacheService.getOrLoad( + SHOP_LIST_CACHE_PREFIX + "name:" + normalizedShopName, + Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()), + Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()), + new TypeReference>() { + }, + () -> { + List shopDOs = shopMapper.selectList( + Wrappers.lambdaQuery(ShopDO.class) + .eq(ShopDO::getIsDelete, 0) + .eq(ShopDO::getStatus, 1) + .like(ShopDO::getShopName, normalizedShopName) + ); + return shopDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } ); - return shopDOs.stream() - .map(this::convertToVO) - .collect(Collectors.toList()); } @Override diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/PermissionPolicy.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/PermissionPolicy.java index 5e598465..8c1fcf37 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/PermissionPolicy.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/PermissionPolicy.java @@ -13,14 +13,14 @@ public final class PermissionPolicy { "home:view", "dashboard:view", "user:view", "user:create", "user:edit", "user:disable", "user:unbind", "user:reset_password", "user:delete", - "user:balance:view", - "product:view", + "user:balance:view", "user:balance:manage", "user:vip:manage", + "product:view", "product:create", "product:edit", "product:delete", "product:category:manage", "shop:view", "shop:create", "shop:edit", "shop:delete", "shop:staff:manage", "permission:view", "permission:create", "permission:edit", "permission:delete", "permission:assign", - "tag:view", - "coupon:view", - "order:view", - "nail_artist:view" + "tag:view", "tag:create", "tag:edit", "tag:delete", "tag:assign", + "coupon:view", "coupon:create", "coupon:edit", "coupon:delete", "coupon:assign", + "order:view", "order:process", "order:edit", "order:delete", + "nail_artist:view", "nail_artist:edit" ); private static final List SHOP_MANAGER_DEFAULT_PERMISSION_CODES = List.of( 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 index c6f8b551..629e3647 100644 --- 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 @@ -8,12 +8,18 @@ import com.github.benmanes.caffeine.cache.Caffeine; import com.xiaowang.yuminailcore.config.AppCacheProperties; import lombok.Getter; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.data.redis.connection.RedisConnection; +import org.springframework.data.redis.core.Cursor; +import org.springframework.data.redis.core.ScanOptions; 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.nio.charset.StandardCharsets; +import java.util.LinkedHashSet; import java.util.Optional; import java.util.Set; import java.util.concurrent.TimeUnit; @@ -24,6 +30,7 @@ import java.util.function.Supplier; */ @Component @RequiredArgsConstructor +@Slf4j public class MultiLevelCacheService { private static final String NULL_SENTINEL = "__CACHE_NULL__"; @@ -71,7 +78,7 @@ public class MultiLevelCacheService { getLocalCache().invalidate(key); } - String json = stringRedisTemplate.opsForValue().get(key); + String json = readRedisValue(key); if (!StringUtils.hasText(json)) { return CacheLookup.miss(); } @@ -86,7 +93,7 @@ public class MultiLevelCacheService { } String json = writeValue(value); putLocal(key, json, localTtl); - stringRedisTemplate.opsForValue().set(key, json, redisTtl.getSeconds(), TimeUnit.SECONDS); + writeRedisValue(key, json, redisTtl); } public void evict(String... keys) { @@ -96,7 +103,7 @@ public class MultiLevelCacheService { for (String key : keys) { getLocalCache().invalidate(key); } - stringRedisTemplate.delete(Set.of(keys)); + deleteRedisKeys(Set.of(keys)); } public void evictByPrefix(String prefix) { @@ -104,9 +111,58 @@ public class MultiLevelCacheService { return; } getLocalCache().asMap().keySet().removeIf(key -> key.startsWith(prefix)); - Set redisKeys = stringRedisTemplate.keys(prefix + "*"); + Set redisKeys = scanRedisKeys(prefix + "*"); if (!CollectionUtils.isEmpty(redisKeys)) { - stringRedisTemplate.delete(redisKeys); + deleteRedisKeys(redisKeys); + } + } + + private String readRedisValue(String key) { + try { + return stringRedisTemplate.opsForValue().get(key); + } catch (Exception exception) { + log.warn("Redis cache read failed, key={}", key, exception); + return null; + } + } + + private void writeRedisValue(String key, String json, Duration redisTtl) { + try { + stringRedisTemplate.opsForValue().set(key, json, redisTtl.getSeconds(), TimeUnit.SECONDS); + } catch (Exception exception) { + log.warn("Redis cache write failed, key={}", key, exception); + } + } + + private void deleteRedisKeys(Set keys) { + if (CollectionUtils.isEmpty(keys)) { + return; + } + try { + stringRedisTemplate.delete(keys); + } catch (Exception exception) { + log.warn("Redis cache delete failed, size={}", keys.size(), exception); + } + } + + private Set scanRedisKeys(String pattern) { + Set keys = new LinkedHashSet<>(); + try { + return stringRedisTemplate.execute((RedisConnection connection) -> { + Set matchedKeys = new LinkedHashSet<>(); + try (Cursor cursor = connection.scan(ScanOptions.scanOptions() + .match(pattern) + .count(500) + .build())) { + while (cursor.hasNext()) { + matchedKeys.add(new String(cursor.next(), StandardCharsets.UTF_8)); + } + } + return matchedKeys; + }); + } catch (Exception exception) { + log.warn("Redis cache scan failed, pattern={}", pattern, exception); + return keys; } } diff --git a/YumiNail-Core/src/main/resources/application.yaml b/YumiNail-Core/src/main/resources/application.yaml index 63060904..b94453fa 100644 --- a/YumiNail-Core/src/main/resources/application.yaml +++ b/YumiNail-Core/src/main/resources/application.yaml @@ -1,6 +1,6 @@ spring: datasource: - url: jdbc:mysql://localhost:3306/yumi_nail?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai + url: jdbc:mysql://localhost:3306/nailart?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai servlet: multipart: max-file-size: 5MB @@ -72,6 +72,9 @@ yuminail: object-storage-file: local-ttl-seconds: 300 redis-ttl-seconds: 1800 + dashboard: + local-ttl-seconds: 30 + redis-ttl-seconds: 90 slow-request: enabled: true threshold-ms: 300 diff --git a/YumiNail-Core/src/main/resources/files/YumiNail.sql b/YumiNail-Core/src/main/resources/files/YumiNail.sql index 780a761f..e0ae2f48 100644 --- a/YumiNail-Core/src/main/resources/files/YumiNail.sql +++ b/YumiNail-Core/src/main/resources/files/YumiNail.sql @@ -3,7 +3,8 @@ -- 1. 首次部署空库时,只需要执行本文件即可完成基础建表、结构补丁、权限种子、VIP 规则、admin01 初始化与默认权限分配。 -- 2. 2026-03-20_user_asset_vip_coupon_permission_patch.sql、2026-03-25_user_shop_binding_and_shop_status_patch.sql、 -- 2026-03-20_init_admin_permission_template.sql 仍保留用于已有数据库的增量升级,不再作为空库首选入口。 --- 3. 如果你的数据库名不是 nailart,请先将本文件中的 `use nailart;` 改成实际库名后再执行。 +-- 3. 当前 Nacos datasource.yaml 指向 nailart,本文件默认按该库名初始化;如果你的实际数据库名不同,请先统一 datasource 与下方库名。 +CREATE DATABASE IF NOT EXISTS nailart DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; use nailart; -- auto-generated definition @@ -1192,7 +1193,13 @@ INNER JOIN t_permission p 'user:reset_password', 'user:delete', 'user:balance:view', + 'user:balance:manage', + 'user:vip:manage', 'product:view', + 'product:create', + 'product:edit', + 'product:delete', + 'product:category:manage', 'shop:view', 'shop:create', 'shop:edit', @@ -1204,9 +1211,21 @@ INNER JOIN t_permission p 'permission:delete', 'permission:assign', 'tag:view', + 'tag:create', + 'tag:edit', + 'tag:delete', + 'tag:assign', 'coupon:view', + 'coupon:create', + 'coupon:edit', + 'coupon:delete', + 'coupon:assign', 'order:view', - 'nail_artist:view' + 'order:process', + 'order:edit', + 'order:delete', + 'nail_artist:view', + 'nail_artist:edit' ) WHERE u.is_delete = 0 AND u.type = 4 diff --git a/YumiNail-Frontend/public/assets/images/default-product.png b/YumiNail-Frontend/public/assets/images/default-product.png new file mode 100644 index 00000000..84c1b545 Binary files /dev/null and b/YumiNail-Frontend/public/assets/images/default-product.png differ diff --git a/YumiNail-Frontend/public/assets/images/default-shop.png b/YumiNail-Frontend/public/assets/images/default-shop.png new file mode 100644 index 00000000..bbcce9f4 Binary files /dev/null and b/YumiNail-Frontend/public/assets/images/default-shop.png differ diff --git a/YumiNail-Frontend/src/api/admin.ts b/YumiNail-Frontend/src/api/admin.ts index 9cf39ce7..b27bbcac 100644 --- a/YumiNail-Frontend/src/api/admin.ts +++ b/YumiNail-Frontend/src/api/admin.ts @@ -3,6 +3,7 @@ import { message } from 'ant-design-vue' import { ADMIN_API_BASE_URL } from '../config/api' import type { IdType } from '@/utils/id' import { clearAdminSessionStorage } from '@/utils/admin-session' +import { attachRequestSignature } from '@/utils/request-signature' let lastErrorTime = 0 let lastErrorMessage = '' @@ -43,7 +44,7 @@ const showError = (msg: string) => { } const isAuthFreePath = (url?: string) => { - return Boolean(url?.includes('/auth/login') || url?.includes('/auth/refresh')) + return Boolean(url?.includes('/auth/login') || url?.includes('/auth/login-shops/') || url?.includes('/auth/refresh')) } const handleAdminTokenExpired = () => { @@ -59,9 +60,10 @@ const handleAdminTokenExpired = () => { } adminApi.interceptors.request.use( - config => { + async config => { + let token: string | null = null if (!isAuthFreePath(config.url)) { - let token = localStorage.getItem('adminAccessToken') + token = localStorage.getItem('adminAccessToken') if (!token) { token = sessionStorage.getItem('adminAccessToken') } @@ -69,7 +71,9 @@ adminApi.interceptors.request.use( config.headers.Authorization = `Bearer ${token}` } } - return config + return attachRequestSignature(config, token, { + authFree: isAuthFreePath(config.url) + }) }, error => Promise.reject(error) ) diff --git a/YumiNail-Frontend/src/api/index.ts b/YumiNail-Frontend/src/api/index.ts index 5710c924..d1c241f2 100644 --- a/YumiNail-Frontend/src/api/index.ts +++ b/YumiNail-Frontend/src/api/index.ts @@ -6,6 +6,7 @@ import { message } from 'ant-design-vue' import { API_BASE_URL } from '../config/api' import type { IdType } from '@/utils/id' import { clearAdminSessionStorage } from '@/utils/admin-session' +import { attachRequestSignature } from '@/utils/request-signature' // 防重复提示标志 let lastErrorTime = 0 @@ -47,6 +48,29 @@ const showError = (msg: string) => { } } +const isAuthFreePath = (url?: string) => { + return [ + '/user/login', + '/user/register', + '/user/check/', + '/user/refresh-token', + '/user/send-verification-code', + '/user/phone-login', + '/user/wechat-mini/', + '/user/reset-password-by-phone', + '/product/get/', + '/product/list/', + '/shop/get/', + '/shop/list/public', + '/shop/list/simple', + '/tag/list/all', + '/file/get-signed-url/', + '/admin/auth/login', + '/admin/auth/login-shops/', + '/admin/auth/refresh' + ].some(path => String(url || '').includes(path)) +} + const handleTokenExpired = (isAdmin = false) => { // 清理token和用户信息 if (isAdmin) { @@ -76,7 +100,7 @@ const handleTokenExpired = (isAdmin = false) => { } api.interceptors.request.use( - config => { + async config => { let token = localStorage.getItem('accessToken') if (!token) { token = sessionStorage.getItem('accessToken') @@ -93,7 +117,9 @@ api.interceptors.request.use( if (token) { config.headers.Authorization = `Bearer ${token}` } - return config + return attachRequestSignature(config, token, { + authFree: isAuthFreePath(config.url) + }) }, error => { return Promise.reject(error) diff --git a/YumiNail-Frontend/src/api/product.ts b/YumiNail-Frontend/src/api/product.ts index 502e455e..4affb141 100644 --- a/YumiNail-Frontend/src/api/product.ts +++ b/YumiNail-Frontend/src/api/product.ts @@ -79,11 +79,11 @@ export const productApi = { }, likeProduct: async (productId: IdType): Promise => { - return await api.post(`/product/like/${productId}`) as unknown as boolean + return await api.post(`/product-like/like/${productId}`) as unknown as boolean }, unlikeProduct: async (productId: IdType): Promise => { - return await api.post(`/product/unlike/${productId}`) as unknown as boolean + return await api.post(`/product-like/unlike/${productId}`) as unknown as boolean }, searchProducts: async (keyword: string): Promise => { diff --git a/YumiNail-Frontend/src/components.d.ts b/YumiNail-Frontend/src/components.d.ts index c775981c..512187a1 100644 --- a/YumiNail-Frontend/src/components.d.ts +++ b/YumiNail-Frontend/src/components.d.ts @@ -83,7 +83,6 @@ declare module 'vue' { ElColorPicker: typeof import('element-plus/es')['ElColorPicker'] ElConfigProvider: typeof import('element-plus/es')['ElConfigProvider'] ElIcon: typeof import('element-plus/es')['ElIcon'] - HelloWorld: typeof import('./components/HelloWorld.vue')['default'] RouterLink: typeof import('vue-router')['RouterLink'] RouterView: typeof import('vue-router')['RouterView'] TableEllipsisText: typeof import('./components/TableEllipsisText.vue')['default'] diff --git a/YumiNail-Frontend/src/components/HelloWorld.vue b/YumiNail-Frontend/src/components/HelloWorld.vue deleted file mode 100644 index b58e52b9..00000000 --- a/YumiNail-Frontend/src/components/HelloWorld.vue +++ /dev/null @@ -1,41 +0,0 @@ - - - - - diff --git a/YumiNail-Frontend/src/constants/index.ts b/YumiNail-Frontend/src/constants/index.ts index 62100472..b1b40305 100644 --- a/YumiNail-Frontend/src/constants/index.ts +++ b/YumiNail-Frontend/src/constants/index.ts @@ -1,3 +1,3 @@ export const DEFAULT_AVATAR = 'https://api.dicebear.com/7.x/avataaars/svg?seed=default' -export const DEFAULT_PRODUCT_IMAGE = 'https://via.placeholder.com/200x200?text=Product' -export const DEFAULT_SHOP_IMAGE = 'https://via.placeholder.com/200x200?text=Shop' +export const DEFAULT_PRODUCT_IMAGE = '/assets/images/default-product.png' +export const DEFAULT_SHOP_IMAGE = '/assets/images/default-shop.png' diff --git a/YumiNail-Frontend/src/main.ts b/YumiNail-Frontend/src/main.ts index 1f5d7bda..4971af7c 100644 --- a/YumiNail-Frontend/src/main.ts +++ b/YumiNail-Frontend/src/main.ts @@ -1,8 +1,5 @@ import { createApp } from 'vue' import { createPinia } from 'pinia' -import ElementPlus from 'element-plus' -import 'element-plus/dist/index.css' -import Antd from 'ant-design-vue' import 'ant-design-vue/dist/reset.css' import './styles/admin-mobile.css' import App from './App.vue' @@ -13,7 +10,5 @@ const pinia = createPinia() app.use(pinia) app.use(router) -app.use(ElementPlus) -app.use(Antd) app.mount('#app') diff --git a/YumiNail-Frontend/src/utils/action-loading.ts b/YumiNail-Frontend/src/utils/action-loading.ts index 1fb0dcb7..e0c1f48f 100644 --- a/YumiNail-Frontend/src/utils/action-loading.ts +++ b/YumiNail-Frontend/src/utils/action-loading.ts @@ -1,4 +1,5 @@ import { ElLoading, type LoadingInstance } from 'element-plus' +import 'element-plus/es/components/loading/style/css' export interface GlobalLoadingOptions { text?: string diff --git a/YumiNail-Frontend/src/utils/request-signature.ts b/YumiNail-Frontend/src/utils/request-signature.ts new file mode 100644 index 00000000..5b5dbc78 --- /dev/null +++ b/YumiNail-Frontend/src/utils/request-signature.ts @@ -0,0 +1,236 @@ +import type { InternalAxiosRequestConfig } from 'axios' + +const HEADER_TIMESTAMP = 'X-Timestamp' +const HEADER_NONCE = 'X-Nonce' +const HEADER_SIGNATURE = 'X-Signature' +const HEADER_SIGNATURE_VERSION = 'X-Sign-Version' +const DEVICE_ID_HEADER = 'X-Device-Id' +const DEVICE_ID_STORAGE_KEY = 'yuminail-device-id' +const SIGNATURE_VERSION = 'v1' + +type HeaderContainer = Record & { + set?: (name: string, value: string) => void + get?: (name: string) => unknown +} + +interface RequestSignatureOptions { + authFree?: boolean +} + +function isSafeMethod(method?: string) { + return ['GET', 'HEAD', 'OPTIONS'].includes(String(method || 'GET').toUpperCase()) +} + +function toHex(bytes: ArrayBuffer) { + return Array.from(new Uint8Array(bytes)) + .map(byte => byte.toString(16).padStart(2, '0')) + .join('') +} + +async function sha256Hex(text: string) { + const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text)) + return toHex(digest) +} + +async function hmacSha256Hex(secret: string, message: string) { + const key = await crypto.subtle.importKey( + 'raw', + new TextEncoder().encode(secret), + { name: 'HMAC', hash: 'SHA-256' }, + false, + ['sign'] + ) + const signature = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(message)) + return toHex(signature) +} + +function randomNonce() { + if (typeof crypto.randomUUID === 'function') { + return `${Date.now()}-${crypto.randomUUID()}` + } + return `${Date.now()}-${Math.random().toString(36).slice(2, 12)}` +} + +export function getDeviceId() { + try { + const stored = localStorage.getItem(DEVICE_ID_STORAGE_KEY) + if (stored) { + return stored + } + const next = `web-${randomNonce()}` + localStorage.setItem(DEVICE_ID_STORAGE_KEY, next) + return next + } catch { + return `web-${randomNonce()}` + } +} + +function setHeader(config: InternalAxiosRequestConfig, name: string, value: string) { + const headers = config.headers as HeaderContainer | undefined + if (headers && typeof headers.set === 'function') { + headers.set(name, value) + return + } + config.headers = { + ...(headers || {}), + [name]: value + } as InternalAxiosRequestConfig['headers'] +} + +function getHeader(config: InternalAxiosRequestConfig, name: string) { + const headers = config.headers as HeaderContainer | undefined + if (!headers) { + return '' + } + if (typeof headers.get === 'function') { + const value = headers.get(name) + if (value !== undefined && value !== null) { + return String(value) + } + } + return String(headers[name] || headers[name.toLowerCase()] || '') +} + +function extractPath(value?: string) { + if (!value) { + return '' + } + try { + return new URL(value, window.location.origin).pathname + } catch { + return value.split('?')[0] || '' + } +} + +function joinAxiosPath(baseUrl?: string, requestUrl?: string) { + if (requestUrl && /^[a-z][a-z\d+\-.]*:\/\//i.test(requestUrl)) { + return extractPath(requestUrl) + } + + const basePath = extractPath(baseUrl).replace(/^\/+|\/+$/g, '') + const requestPath = extractPath(requestUrl).replace(/^\/+|\/+$/g, '') + const joined = [basePath, requestPath].filter(Boolean).join('/') + return joined ? `/${joined}` : '/' +} + +function toBackendRequestPath(baseUrl?: string, requestUrl?: string) { + const path = joinAxiosPath(baseUrl, requestUrl) + if (path === '/admin/api') { + return '/admin' + } + if (path.startsWith('/admin/api/')) { + return `/admin/${path.slice('/admin/api/'.length)}` + } + if (path === '/api/admin') { + return '/admin' + } + if (path.startsWith('/api/admin/')) { + return `/admin/${path.slice('/api/admin/'.length)}` + } + if (path === '/api') { + return '/' + } + if (path.startsWith('/api/')) { + return `/${path.slice('/api/'.length)}` + } + return path +} + +function appendParam(target: Record, key: string, value: unknown) { + if (value === undefined || value === null || value === '') { + return + } + if (!target[key]) { + target[key] = [] + } + if (Array.isArray(value)) { + value.forEach(item => appendParam(target, key, item)) + return + } + target[key].push(value) +} + +function collectParams(source: unknown, target: Record) { + if (!source) { + return + } + if (source instanceof URLSearchParams) { + source.forEach((value, key) => appendParam(target, key, value)) + return + } + if (source instanceof FormData) { + source.forEach((value, key) => { + if (!(value instanceof Blob)) { + appendParam(target, key, value) + } + }) + return + } + if (typeof source === 'object') { + Object.entries(source as Record).forEach(([key, value]) => appendParam(target, key, value)) + } +} + +function buildCanonicalParams(...sources: unknown[]) { + const params: Record = {} + sources.forEach(source => collectParams(source, params)) + return Object.keys(params) + .sort() + .map(key => { + const normalized = params[key] + ?.map(value => String(value)) + .sort() + .join(',') || '' + return `${key}=${normalized}` + }) + .join('&') +} + +function buildJsonPayload(data: unknown) { + if (data === undefined || data === null || data === '') { + return '' + } + if (typeof data === 'string') { + return data + } + return JSON.stringify(data) +} + +function resolvePayload(config: InternalAxiosRequestConfig) { + const contentType = getHeader(config, 'Content-Type').toLowerCase() + const jsonPayload = contentType.includes('application/json') ? buildJsonPayload(config.data) : '' + if (jsonPayload) { + return jsonPayload + } + return buildCanonicalParams(config.params, config.data) +} + +export async function attachRequestSignature( + config: InternalAxiosRequestConfig, + accessToken?: string | null, + options: RequestSignatureOptions = {} +) { + setHeader(config, DEVICE_ID_HEADER, getDeviceId()) + + const method = String(config.method || 'GET').toUpperCase() + if (!accessToken || options.authFree || isSafeMethod(method)) { + return config + } + + const timestamp = String(Date.now()) + const nonce = randomNonce() + const payloadHash = await sha256Hex(resolvePayload(config)) + const canonical = [ + method, + toBackendRequestPath(config.baseURL, config.url), + timestamp, + nonce, + payloadHash + ].join('\n') + + setHeader(config, HEADER_TIMESTAMP, timestamp) + setHeader(config, HEADER_NONCE, nonce) + setHeader(config, HEADER_SIGNATURE, await hmacSha256Hex(accessToken, canonical)) + setHeader(config, HEADER_SIGNATURE_VERSION, SIGNATURE_VERSION) + return config +} diff --git a/YumiNail-Frontend/src/views/AuthView.vue b/YumiNail-Frontend/src/views/AuthView.vue index f9d64db7..122c2bb4 100644 --- a/YumiNail-Frontend/src/views/AuthView.vue +++ b/YumiNail-Frontend/src/views/AuthView.vue @@ -290,22 +290,10 @@ @@ -398,7 +386,7 @@ diff --git a/YumiNail-Frontend/src/views/WishlistView.vue b/YumiNail-Frontend/src/views/WishlistView.vue index df514d84..be9e7950 100644 --- a/YumiNail-Frontend/src/views/WishlistView.vue +++ b/YumiNail-Frontend/src/views/WishlistView.vue @@ -52,6 +52,7 @@ import { ref, onMounted, inject } from 'vue' import { ArrowLeft, Delete, StarFilled } from '@element-plus/icons-vue' import { useRouter } from 'vue-router' import { ElMessage } from 'element-plus' +import 'element-plus/es/components/message/style/css' import { wishlistApi, type WishlistItem } from '@/api/wishlist' import { cartApi } from '@/api/cart' import { fileApi } from '@/api/file' diff --git a/YumiNail-Frontend/src/views/admin/AdminLoginView.vue b/YumiNail-Frontend/src/views/admin/AdminLoginView.vue index 4a4aa9a9..593485e3 100644 --- a/YumiNail-Frontend/src/views/admin/AdminLoginView.vue +++ b/YumiNail-Frontend/src/views/admin/AdminLoginView.vue @@ -228,7 +228,7 @@ const loadLoginShops = async (account = formState.account) => { if (isLoginShopPrefetchUnsupported(error)) { applyLoginShopSelection({ allowShoplessLogin: true, - message: '当前环境暂未开放登录前店铺预加载,可直接登录。', + message: '可直接登录;如账号绑定多家门店,登录后可在个人中心切换当前门店。', shops: [] }) } else { diff --git a/YumiNail-Frontend/src/views/admin/DashboardView.vue b/YumiNail-Frontend/src/views/admin/DashboardView.vue index 113bf534..e23375f2 100644 --- a/YumiNail-Frontend/src/views/admin/DashboardView.vue +++ b/YumiNail-Frontend/src/views/admin/DashboardView.vue @@ -153,7 +153,7 @@ const insightItems = computed(() => { if (stats.totalProducts === 0) { items.push({ title: '还没有可售作品', - description: '可以先补充几款基础作品,首页和前台作品页会更完整,也更方便测试完整下单流程。' + description: '先补充基础作品,首页和作品页会更完整,顾客也能更顺畅地下单。' }) } else { items.push({ diff --git a/YumiNail-Frontend/src/views/admin/PermissionsView.vue b/YumiNail-Frontend/src/views/admin/PermissionsView.vue index acd1426a..c03a8beb 100644 --- a/YumiNail-Frontend/src/views/admin/PermissionsView.vue +++ b/YumiNail-Frontend/src/views/admin/PermissionsView.vue @@ -324,7 +324,7 @@ diff --git a/YumiNail-Frontend/src/views/admin/ProductsView.vue b/YumiNail-Frontend/src/views/admin/ProductsView.vue index 84d12904..576cbc21 100644 --- a/YumiNail-Frontend/src/views/admin/ProductsView.vue +++ b/YumiNail-Frontend/src/views/admin/ProductsView.vue @@ -123,7 +123,7 @@
预计时长 - {{ item.approximateDuration || '--' }} 分钟 + {{ formatDuration(item.approximateDuration) }}
互动数据 @@ -550,6 +550,14 @@ const nextRequestToken = (key: keyof typeof requestTokens) => { const isLatestRequestToken = (key: keyof typeof requestTokens, token: number) => requestTokens[key] === token +const formatDuration = (value?: string | number | null) => { + if (value === undefined || value === null || value === '') { + return '--' + } + const text = String(value).trim() + return text.includes('分钟') ? text : `${text}分钟` +} + const viewFormState = reactive({ shopId: undefined, title: '', diff --git a/YumiNail-Frontend/src/views/admin/ShopsView.vue b/YumiNail-Frontend/src/views/admin/ShopsView.vue index 4674b077..8c5096dc 100644 --- a/YumiNail-Frontend/src/views/admin/ShopsView.vue +++ b/YumiNail-Frontend/src/views/admin/ShopsView.vue @@ -338,7 +338,7 @@
diff --git a/YumiNail-Frontend/vite.config.ts b/YumiNail-Frontend/vite.config.ts index c3816a2b..3c6669fe 100644 --- a/YumiNail-Frontend/vite.config.ts +++ b/YumiNail-Frontend/vite.config.ts @@ -63,13 +63,17 @@ export default defineConfig(({ mode }) => { if (!id.includes('node_modules')) { return undefined } - if (id.includes('ant-design-vue')) { + const normalizedId = id.replaceAll('\\', '/') + if (normalizedId.includes('@ant-design/icons-vue')) { + return 'antdv-icons' + } + if (normalizedId.includes('ant-design-vue')) { return 'antdv' } - if (id.includes('element-plus') || id.includes('@element-plus')) { + if (normalizedId.includes('element-plus') || normalizedId.includes('@element-plus')) { return 'element-plus' } - if (id.includes('vue-router') || id.includes('pinia') || id.includes('/vue/')) { + if (normalizedId.includes('vue-router') || normalizedId.includes('pinia') || normalizedId.includes('/vue/')) { return 'vue-core' } return 'vendor' diff --git a/YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/controller/HealthController.java b/YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/controller/HealthController.java new file mode 100644 index 00000000..694c4b0e --- /dev/null +++ b/YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/controller/HealthController.java @@ -0,0 +1,65 @@ +package com.xiaowang.yumitailgateway.controller; + +import lombok.RequiredArgsConstructor; +import org.springframework.cloud.client.ServiceInstance; +import org.springframework.cloud.client.discovery.DiscoveryClient; +import org.springframework.core.env.Environment; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +@RestController +@RequestMapping("/health") +@RequiredArgsConstructor +public class HealthController { + + private final DiscoveryClient discoveryClient; + private final Environment environment; + + @GetMapping("/check") + public Map check() { + Map result = new LinkedHashMap<>(); + result.put("code", 200); + result.put("message", "YumiNail-Gateway is running"); + result.put("data", diagnosticsPayload()); + return result; + } + + @GetMapping("/diagnostics") + public Map diagnostics() { + Map result = new LinkedHashMap<>(); + result.put("code", 200); + result.put("message", "operation successful"); + result.put("data", diagnosticsPayload()); + return result; + } + + private Map diagnosticsPayload() { + Map diagnostics = new LinkedHashMap<>(); + String serviceName = environment.getProperty("spring.application.name", "yuminail-gateway"); + diagnostics.put("service", serviceName); + diagnostics.put("port", environment.getProperty("server.port", "")); + diagnostics.put("gatewayService", discoverySummary(serviceName)); + diagnostics.put("coreService", discoverySummary("yumi-nail-core")); + return diagnostics; + } + + private Map discoverySummary(String serviceName) { + Map result = new LinkedHashMap<>(); + try { + List instances = discoveryClient.getInstances(serviceName); + result.put("ok", !instances.isEmpty()); + result.put("service", serviceName); + result.put("instanceCount", instances.size()); + } catch (Exception exception) { + result.put("ok", false); + result.put("service", serviceName); + result.put("error", exception.getClass().getSimpleName()); + } + return result; + } +} diff --git a/scripts/package-release.ps1 b/scripts/package-release.ps1 new file mode 100644 index 00000000..d0c7a647 --- /dev/null +++ b/scripts/package-release.ps1 @@ -0,0 +1,116 @@ +param( + [switch]$SkipTests, + [string]$MavenPath = "" +) + +$ErrorActionPreference = "Stop" + +$repoRoot = Split-Path -Parent $PSScriptRoot +$timestamp = Get-Date -Format "yyyyMMdd-HHmmss" +$releaseRoot = Join-Path $repoRoot "release-packages" +$releaseDir = Join-Path $releaseRoot $timestamp +$backendDir = Join-Path $releaseDir "backend" +$frontendDir = Join-Path $releaseDir "frontend" +$miniProgramDir = Join-Path $releaseDir "miniprograms" + +function Resolve-Maven { + param([string]$PreferredPath) + + if ($PreferredPath -and (Test-Path $PreferredPath)) { + return $PreferredPath + } + + $fromPath = Get-Command mvn.cmd -ErrorAction SilentlyContinue + if ($fromPath) { + return $fromPath.Source + } + + $fallback = "D:\开发\apache-maven-3.9.9\bin\mvn.cmd" + if (Test-Path $fallback) { + return $fallback + } + + throw "Cannot find mvn.cmd. Pass -MavenPath with an absolute Maven path." +} + +function Invoke-Step { + param( + [string]$Name, + [scriptblock]$Script + ) + + Write-Host "==> $Name" + & $Script +} + +function Copy-Directory { + param( + [string]$Source, + [string]$Destination + ) + + if (!(Test-Path $Source)) { + throw "Missing source directory: $Source" + } + + New-Item -ItemType Directory -Force -Path $Destination | Out-Null + Copy-Item -Path (Join-Path $Source "*") -Destination $Destination -Recurse -Force +} + +$maven = Resolve-Maven $MavenPath +New-Item -ItemType Directory -Force -Path $backendDir, $frontendDir, $miniProgramDir | Out-Null + +$mavenArgs = @("-q", "package") +if ($SkipTests) { + $mavenArgs += "-DskipTests" +} + +Invoke-Step "Build YumiNail-Core" { + Push-Location (Join-Path $repoRoot "YumiNail-Core") + try { & $maven @mavenArgs } finally { Pop-Location } +} + +Invoke-Step "Build YumiNail-Gateway" { + Push-Location (Join-Path $repoRoot "YumiNail-Gateway") + try { & $maven @mavenArgs } finally { Pop-Location } +} + +Invoke-Step "Build YumiNail-Frontend" { + Push-Location (Join-Path $repoRoot "YumiNail-Frontend") + try { + if (!(Test-Path "node_modules")) { + npm ci + } + npm run build + } finally { + Pop-Location + } +} + +Copy-Item (Join-Path $repoRoot "YumiNail-Core\target\YumiNail-Core.jar") (Join-Path $backendDir "YumiNail-Core.jar") -Force +Copy-Item (Join-Path $repoRoot "YumiNail-Gateway\target\YumiNail-Gateway.jar") (Join-Path $backendDir "YumiNail-Gateway.jar") -Force +Copy-Directory (Join-Path $repoRoot "YumiNail-Frontend\dist") (Join-Path $frontendDir "dist") +Copy-Directory (Join-Path $repoRoot "WeChatProgram") (Join-Path $miniProgramDir "WeChatProgram") +Copy-Directory (Join-Path $repoRoot "YumiNail-Admin-Program") (Join-Path $miniProgramDir "YumiNail-Admin-Program") +Copy-Item (Join-Path $repoRoot "YumiNail-Core\src\main\resources\files\YumiNail.sql") (Join-Path $releaseDir "YumiNail.sql") -Force + +$manifest = @( + "# YumiNail Release $timestamp", + "", + "- backend/YumiNail-Core.jar", + "- backend/YumiNail-Gateway.jar", + "- frontend/dist", + "- miniprograms/WeChatProgram", + "- miniprograms/YumiNail-Admin-Program", + "- YumiNail.sql", + "", + "Nacos namespace: YumiNail-Dev", + "Database initialized by: YumiNail.sql" +) +$manifest | Set-Content -Encoding UTF8 (Join-Path $releaseDir "README.md") + +$zipPath = "$releaseDir.zip" +Compress-Archive -Path (Join-Path $releaseDir "*") -DestinationPath $zipPath -Force + +Write-Host "Release folder: $releaseDir" +Write-Host "Release archive: $zipPath"