功能:完善 YumiNail 全栈修复与打包

This commit is contained in:
xiaowang
2026-05-15 21:10:41 +08:00
parent 3d0a859980
commit 1f05e0ab44
42 changed files with 768 additions and 316 deletions
+5
View File
@@ -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/
Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

+3 -3
View File
@@ -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'
})
},
-38
View File
@@ -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
-11
View File
@@ -277,17 +277,6 @@
</view>
</view>
<view class="page-card settings-card more-card">
<view class="section-title">更多功能</view>
<view wx:for="{{placeholderEntries}}" wx:key="key" class="setting-row" bindtap="handleComingSoon">
<view class="setting-main">
<view class="setting-name">{{item.title}}</view>
</view>
<view class="placeholder-tag">暂未开放</view>
</view>
</view>
<view class="logout-btn" bindtap="handleLogout">退出登录</view>
</block>
</view>
+1 -12
View File
@@ -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;
}
+2 -2
View File
@@ -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',
+4 -2
View File
@@ -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 = [
+38 -3
View File
@@ -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)
@@ -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;
@@ -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<DashboardStatsVO> 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<DashboardStatsVO>() {
},
() -> 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<String, Object> 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<String, Object> 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;
}
}
@@ -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<String> check() {
return Result.success("YumiNail-Core is running");
}
@GetMapping("/diagnostics")
public Result<Map<String, Object>> diagnostics() {
Map<String, Object> 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<String, Object> checkDatabase() {
Map<String, Object> 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<String, Object> checkRedis() {
Map<String, Object> 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<String, Object> checkDiscovery() {
Map<String, Object> result = new LinkedHashMap<>();
try {
String serviceName = environment.getProperty("spring.application.name", "yumi-nail-core");
List<ServiceInstance> 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;
}
}
@@ -179,13 +179,23 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
@Override
public List<ProductVO> listProductsByShopId(Long shopId) {
List<ProductDO> 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<ProductVO>>() {
},
() -> {
List<ProductDO> 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
@@ -211,15 +211,26 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopDO> implements
@Override
public List<ShopVO> listShopsByShopName(String shopName) {
List<ShopDO> 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<ShopVO>>() {
},
() -> {
List<ShopDO> 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
@@ -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<String> SHOP_MANAGER_DEFAULT_PERMISSION_CODES = List.of(
@@ -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<String> redisKeys = stringRedisTemplate.keys(prefix + "*");
Set<String> 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<String> 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<String> scanRedisKeys(String pattern) {
Set<String> keys = new LinkedHashSet<>();
try {
return stringRedisTemplate.execute((RedisConnection connection) -> {
Set<String> matchedKeys = new LinkedHashSet<>();
try (Cursor<byte[]> 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;
}
}
@@ -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
@@ -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
Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

+8 -4
View File
@@ -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)
)
+28 -2
View File
@@ -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)
+2 -2
View File
@@ -79,11 +79,11 @@ export const productApi = {
},
likeProduct: async (productId: IdType): Promise<boolean> => {
return await api.post<boolean>(`/product/like/${productId}`) as unknown as boolean
return await api.post<boolean>(`/product-like/like/${productId}`) as unknown as boolean
},
unlikeProduct: async (productId: IdType): Promise<boolean> => {
return await api.post<boolean>(`/product/unlike/${productId}`) as unknown as boolean
return await api.post<boolean>(`/product-like/unlike/${productId}`) as unknown as boolean
},
searchProducts: async (keyword: string): Promise<ProductVO[]> => {
-1
View File
@@ -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']
@@ -1,41 +0,0 @@
<script setup lang="ts">
import { ref } from 'vue'
defineProps<{ msg: string }>()
const count = ref(0)
</script>
<template>
<h1>{{ msg }}</h1>
<div class="card">
<button type="button" @click="count++">count is {{ count }}</button>
<p>
Edit
<code>components/HelloWorld.vue</code> to test HMR
</p>
</div>
<p>
Check out
<a href="https://vuejs.org/guide/quick-start.html#local" target="_blank"
>create-vue</a
>, the official Vue + Vite starter
</p>
<p>
Learn more about IDE Support for Vue in the
<a
href="https://vuejs.org/guide/scaling-up/tooling.html#ide-support"
target="_blank"
>Vue Docs Scaling up Guide</a
>.
</p>
<p class="read-the-docs">Click on the Vite and Vue logos to learn more</p>
</template>
<style scoped>
.read-the-docs {
color: #888;
}
</style>
+2 -2
View File
@@ -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'
-5
View File
@@ -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')
@@ -1,4 +1,5 @@
import { ElLoading, type LoadingInstance } from 'element-plus'
import 'element-plus/es/components/loading/style/css'
export interface GlobalLoadingOptions {
text?: string
@@ -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<string, unknown> & {
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<string, unknown[]>, 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<string, unknown[]>) {
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<string, unknown>).forEach(([key, value]) => appendParam(target, key, value))
}
}
function buildCanonicalParams(...sources: unknown[]) {
const params: Record<string, unknown[]> = {}
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
}
+4 -24
View File
@@ -290,22 +290,10 @@
<div class="social-login">
<div class="divider">
<span>其他登录方式</span>
<span>微信手机号登录</span>
</div>
<div class="social-hint">
网页端暂未开放第三方登录,微信手机号一键登录仅支持小程序。
</div>
<div class="social-buttons">
<a-button shape="circle" size="large" class="social-circle-btn" @click="handleWeChatLogin">
<WechatOutlined />
</a-button>
<a-button shape="circle" size="large" class="social-circle-btn" @click="handleQQLogin">
<QqOutlined />
</a-button>
</div>
<div class="social-button-captions">
<span>微信登录(仅小程序)</span>
<span>QQ 登录(暂未开放)</span>
微信手机号授权登录请在小程序中使用;网页端可使用账号密码或验证码登录。
</div>
</div>
@@ -398,7 +386,7 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { InfoCircleOutlined, LockOutlined, QqOutlined, UserOutlined, WechatOutlined } from '@ant-design/icons-vue'
import { InfoCircleOutlined, LockOutlined, UserOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import type { Rule } from 'ant-design-vue/es/form'
import { authApi } from '@/api/auth'
@@ -454,7 +442,7 @@ let loginPhoneShopCheckTimer: number | undefined
const phoneRegex = /^1[3-9]\d{9}$/
const verificationCodeRegex = /^\d{6}$/
const loginShopUnsupportedMessage = '当前环境暂未开放登录前门店预加载,可直接登录;如账号绑定多家门店,登录后可在个人中心切换当前门店。'
const loginShopUnsupportedMessage = '可直接登录;如账号绑定多家门店,登录后可在个人中心切换当前门店。'
const loginShopPlaceholder = computed(() => {
if (allowLoginShopless.value) {
return '当前暂无启用店铺,可直接登录'
@@ -926,14 +914,6 @@ const handleResetPassword = async () => {
}
}
const handleWeChatLogin = () => {
message.info('网页端暂未开放微信登录,请使用账号密码、验证码登录,或前往小程序使用微信手机号一键登录')
}
const handleQQLogin = () => {
message.info('网页端暂未开放 QQ 登录,敬请期待')
}
const handleRegisterAccountBlur = async () => {
if (activeTab.value !== 'register' || !formData.account.trim()) {
registerAccountStatus.value = null
@@ -193,10 +193,8 @@
import { computed, onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import {
BellOutlined,
CreditCardOutlined,
HeartOutlined,
QuestionCircleOutlined,
RightOutlined,
SettingOutlined,
ShopOutlined,
@@ -307,46 +305,6 @@ const shopSwitchTip = computed(() => {
return '当前暂无可用门店'
})
const menuItems = [
{
key: 'orders',
title: '我的订单',
desc: '查看预约状态、取消订单',
icon: ShoppingOutlined,
bgColor: '#e6f7ff'
},
{
key: 'wishlist',
title: '我的收藏',
desc: '快速回到喜欢的作品',
icon: HeartOutlined,
bgColor: '#fff1f0'
},
{
key: 'coupons',
title: '我的优惠券',
desc: '查看可用优惠和 VIP 折扣',
icon: CreditCardOutlined,
bgColor: '#fff7e6'
},
{
key: 'notifications',
title: '消息通知',
desc: '消息中心功能开发中',
icon: BellOutlined,
bgColor: '#f9f0ff'
},
{
key: 'help',
title: '帮助与支持',
desc: '常见问题功能开发中',
icon: QuestionCircleOutlined,
bgColor: '#eef9ff'
}
]
void menuItems
const coreMenuItems = [
{
key: 'orders',
@@ -595,10 +553,6 @@ const handleMenuClick = (key: string) => {
router.push('/coupons')
} else if (key === 'settings') {
router.push('/settings')
} else if (key === 'notifications') {
message.info('消息通知功能开发中')
} else if (key === 'help') {
message.info('帮助中心功能开发中')
}
}
+1 -70
View File
@@ -49,23 +49,13 @@
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import {
BellOutlined,
ClearOutlined,
InfoCircleOutlined,
LeftOutlined,
LockOutlined,
MessageOutlined,
QuestionCircleOutlined,
RightOutlined,
SafetyOutlined,
SoundOutlined
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
const router = useRouter()
const comingSoonDesc = '暂未开放,敬请期待'
const settingsSections = ref([
{
type: 'title',
@@ -74,69 +64,12 @@ const settingsSections = ref([
{
key: 'account',
title: '账号设置',
desc: '修改密码、绑定手机号、管理账号安全项',
desc: '管理手机号、登录密码和账号安全',
icon: LockOutlined,
bgColor: '#e6f7ff'
},
{
type: 'title',
title: '更多功能'
},
{
key: 'notifications',
title: '消息通知',
desc: comingSoonDesc,
icon: BellOutlined,
bgColor: '#f6ffed'
},
{
key: 'message-push',
title: '消息推送',
desc: comingSoonDesc,
icon: MessageOutlined,
bgColor: '#fffbe6'
},
{
key: 'theme',
title: '主题设置',
desc: comingSoonDesc,
icon: SoundOutlined,
bgColor: '#f9f0ff'
},
{
key: 'clear-cache',
title: '缓存清理',
desc: comingSoonDesc,
icon: ClearOutlined,
bgColor: '#fff2e8'
},
{
key: 'privacy',
title: '隐私政策',
desc: comingSoonDesc,
icon: SafetyOutlined,
bgColor: '#e6f7ff'
},
{
key: 'about',
title: '关于我们',
desc: comingSoonDesc,
icon: InfoCircleOutlined,
bgColor: '#f6ffed'
},
{
key: 'help',
title: '帮助中心',
desc: comingSoonDesc,
icon: QuestionCircleOutlined,
bgColor: '#eef9ff'
}
])
const showComingSoon = () => {
message.info('该功能暂未开放,敬请期待')
}
const handleBackClick = () => {
router.back()
}
@@ -146,8 +79,6 @@ const handleSettingClick = (key: string) => {
router.push('/settings/account')
return
}
showComingSoon()
}
</script>
@@ -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'
@@ -228,7 +228,7 @@ const loadLoginShops = async (account = formState.account) => {
if (isLoginShopPrefetchUnsupported(error)) {
applyLoginShopSelection({
allowShoplessLogin: true,
message: '当前环境暂未开放登录前店铺预加载,可直接登录。',
message: '可直接登录;如账号绑定多家门店,登录后可在个人中心切换当前门店。',
shops: []
})
} else {
@@ -153,7 +153,7 @@ const insightItems = computed(() => {
if (stats.totalProducts === 0) {
items.push({
title: '还没有可售作品',
description: '可以先补充几款基础作品,首页和前台作品页会更完整,也更方便测试完整下单流程。'
description: '先补充基础作品,首页和作品页会更完整,顾客也能更顺畅地下单。'
})
} else {
items.push({
@@ -324,7 +324,7 @@
<AdminMobileFab
:visible="isMobile && activeTab === 'permissions' && hasPermission('permission:create') && !permissionModalVisible"
label="鏂板鏉冮檺"
label="新增权限"
@click="showAddPermissionModal"
/>
</div>
@@ -123,7 +123,7 @@
<div class="admin-mobile-card__rows">
<div class="admin-mobile-card__row">
<span>预计时长</span>
<strong>{{ item.approximateDuration || '--' }} 分钟</strong>
<strong>{{ formatDuration(item.approximateDuration) }}</strong>
</div>
<div class="admin-mobile-card__row">
<span>互动数据</span>
@@ -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: '',
@@ -338,7 +338,7 @@
<AdminMobileFab
:visible="isMobile && hasPermission('shop:create') && !modalVisible && !viewModalVisible"
label="鏂板搴楅摵"
label="新增店铺"
@click="showAddModal"
/>
</div>
+7 -3
View File
@@ -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'
@@ -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<String, Object> check() {
Map<String, Object> result = new LinkedHashMap<>();
result.put("code", 200);
result.put("message", "YumiNail-Gateway is running");
result.put("data", diagnosticsPayload());
return result;
}
@GetMapping("/diagnostics")
public Map<String, Object> diagnostics() {
Map<String, Object> result = new LinkedHashMap<>();
result.put("code", 200);
result.put("message", "operation successful");
result.put("data", diagnosticsPayload());
return result;
}
private Map<String, Object> diagnosticsPayload() {
Map<String, Object> 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<String, Object> discoverySummary(String serviceName) {
Map<String, Object> result = new LinkedHashMap<>();
try {
List<ServiceInstance> 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;
}
}
+116
View File
@@ -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"