Author SHA1 Message Date
xiaowang 787545eb04 Merge pull request '同步中文工作流文件名到生产' (#87) from sit into prod
自动发布生产环境 Nacos / publish (push) Failing after 29s
同步中文工作流文件名到生产
2026-10-16 15:01:52 +08:00
xiaowang 2f21b11117 Merge pull request '同步中文工作流文件名' (#86) from dev into sit
自动发布测试环境 Nacos 配置 / publish (push) Successful in 27s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 1s
同步中文工作流文件名
2026-10-16 14:55:32 +08:00
xiaowang 3ad792115c fix(actions): use Chinese workflow filenames
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 1s
自动发布开发环境 Nacos 配置 / publish (push) Successful in 29s
2026-10-16 14:48:49 +08:00
xiaowang ecccda37b1 Merge pull request '更新 Gitea 工作流中文显示名称' (#85) from sit into prod
自动发布生产环境 Nacos / publish (push) Failing after 32s
2026-10-16 14:03:28 +08:00
xiaowang 21986185ab Merge pull request '修复工作流中文名称显示' (#84) from dev into sit
自动发布测试环境 Nacos 配置 / publish (push) Successful in 33s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 5s
2026-10-16 13:50:24 +08:00
xiaowang 3ffa920d1c fix(actions): display workflow names in Chinese
自动发布开发环境 Nacos 配置 / publish (push) Successful in 30s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 1s
2026-10-16 13:44:44 +08:00
xiaowang 7cd44489b7 Merge pull request '同步环境发布工作流修复到生产' (#83) from sit into prod
自动发布生产环境 Nacos / publish (push) Failing after 31s
2026-10-16 13:20:00 +08:00
xiaowang b9cd8caaab Merge pull request '补充所有环境发布记录持久化挂载' (#82) from dev into sit
自动发布测试环境 Nacos 配置 / publish (push) Successful in 28s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 1s
2026-10-16 13:10:49 +08:00
xiaowang 768b7848c5 fix(actions): persist release store for all environments
自动发布开发环境 Nacos 配置 / publish (push) Successful in 29s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 1s
2026-10-16 13:06:54 +08:00
xiaowang 52fc3df992 Merge pull request '修复 SIT 发布记录跨任务持久化' (#81) from dev into sit
自动发布测试环境 Nacos 配置 / publish (push) Successful in 27s
2026-10-16 12:48:23 +08:00
xiaowang 51cf60f242 fix(actions): persist SIT release store across jobs
自动发布开发环境 Nacos 配置 / publish (push) Successful in 29s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 1s
2026-10-16 12:42:41 +08:00
xiaowang b27f1f58b1 补充 Runner 发布记录持久化
自动发布测试环境 Nacos 配置 / publish (push) Failing after 4s
2026-10-16 11:44:35 +08:00
xiaowang eb1a18d7be 补充 Runner 发布记录持久化说明
自动发布开发环境 Nacos 配置 / publish (push) Successful in 34s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 1s
2026-10-16 11:39:00 +08:00
xiaowang 15e4947891 Merge pull request '修复 Gitea 工作流 YAML 解析与 Nacos 发布' (#79) from dev into sit
自动发布测试环境 Nacos 配置 / publish (push) Successful in 31s
2026-10-16 10:56:50 +08:00
xiaowang cbd2efeeb5 修复 Nacos 发布配置路径识别
自动发布开发环境 Nacos 配置 / publish (push) Successful in 34s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 2s
2026-10-16 10:49:36 +08:00
xiaowang af85d6320d 修复 Gitea 工作流 YAML 解析错误
自动发布开发环境 Nacos 配置 / publish (push) Failing after 30s
2026-10-16 10:08:20 +08:00
xiaowang 548b2e496a Merge pull request 'Sit' (#78) from sit into prod
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/78
2026-10-16 09:23:54 +08:00
xiaowang ac3daf4626 Merge pull request '修复工作流触发器解析' (#77) from dev into sit
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 1s
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/77
2026-10-16 09:23:10 +08:00
xiaowang d2a2840fa8 修复工作流触发器解析
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 1s
2026-10-15 18:01:30 +08:00
xiaowang e5b771b599 Merge pull request 'Sit' (#76) from sit into prod
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/76
2026-10-15 17:56:54 +08:00
xiaowang 9a0a33ee51 Merge pull request '修复工作流中文名称解析' (#75) from dev into sit
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 1s
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/75
2026-10-15 17:47:30 +08:00
xiaowang ce810e8ded 修复工作流中文名称解析
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 1s
2026-10-15 17:30:33 +08:00
xiaowang be9f67fd87 Merge pull request 'Sit' (#74) from sit into prod
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/74
2026-10-15 16:28:31 +08:00
xiaowang b1be204220 Merge pull request '修改 10 个工作流名称,统一使用中文环境名称' (#73) from dev into sit
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 1s
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/73
2026-10-15 16:27:34 +08:00
xiaowang 59fe99bec8 修改 10 个工作流名称,统一使用中文环境名称
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 1s
2026-10-15 16:26:24 +08:00
xiaowang 7e5027b17d Merge pull request '重整三环境发布与回退工作流' (#70) from dev into sit
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 1s
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/70
2026-10-15 11:31:11 +08:00
xiaowang ac84f8f206 重整三环境发布与回退工作流
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 1s
2026-10-15 11:26:28 +08:00
xiaowang 697708d754 Merge pull request 'sit微信小程序app-secret补充' (#69) from dev into sit
发布 Nacos 配置 / publish (push) Successful in 30s
Salon SIT 自动发布 / deploy (push) Successful in 5m56s
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/69
2026-10-14 22:40:45 +08:00
xiaowang 28510db233 sit微信小程序app-secret补充
发布 Nacos 配置 / publish (push) Successful in 30s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 3s
2026-10-14 22:31:13 +08:00
xiaowang 2b621a6fe0 Merge pull request 'fix(salon): restore object storage signed URL config' (#68) from dev into sit
发布 Nacos 配置 / publish (push) Successful in 33s
Salon SIT 自动发布 / deploy (push) Failing after 3m56s
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/68
2026-10-14 17:59:43 +08:00
xiaowang 6c7f8aef30 fix(salon): restore object storage signed URL config
发布 Nacos 配置 / publish (push) Successful in 30s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 2s
2026-10-14 17:57:47 +08:00
xiaowang 39fce9da7e Merge pull request '补充MessageHub Token迁移说明' (#67) from dev into sit
发布 Nacos 配置 / publish (push) Successful in 34s
Salon SIT 自动发布 / deploy (push) Failing after 4m54s
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/67
2026-10-14 16:18:04 +08:00
xiaowang 8635eccb06 补充MessageHub Token迁移说明
发布 Nacos 配置 / publish (push) Successful in 34s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 1s
2026-10-14 15:37:00 +08:00
xiaowang 065a5c7fb8 迁移Salon SIT MessageHub Token到Nacos密钥配置 2026-10-14 15:34:28 +08:00
xiaowang a29a468ed3 合并双端初始化SQL并清理版本脚本 2026-10-14 14:57:53 +08:00
xiaowang d6cc82a4bc Merge pull request '统一ArtList与Salon历史命名 整理三环境中间件配置分层' (#66) from dev into sit
发布 Nacos 配置 / publish (push) Successful in 43s
Salon SIT 自动发布 / deploy (push) Failing after 4m38s
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/66
2026-10-14 14:22:39 +08:00
xiaowang c957994006 统一ArtList与Salon历史命名
发布 Nacos 配置 / publish (push) Successful in 44s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 1s
2026-10-14 13:04:10 +08:00
xiaowang fe782b47d5 文档:设计ArtList与Salon命名统一迁移 2026-10-14 11:37:50 +08:00
xiaowang 52ac5d6cea 整理三环境中间件配置分层 2026-10-14 11:20:30 +08:00
xiaowang 4cedbb826d 文档:设计三环境中间件配置分层整理 2026-10-14 10:19:37 +08:00
xiaowang 7eb1f9a62f Merge pull request 'sit中redis密码修改' (#65) from dev into sit
发布 Nacos 配置 / publish (push) Successful in 36s
Salon SIT 自动发布 / deploy (push) Successful in 2m57s
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/65
2026-10-14 09:20:14 +08:00
xiaowang 3cf2fbdcc6 sit中redis密码修改
发布 Nacos 配置 / publish (push) Successful in 27s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 2s
2026-10-14 09:19:27 +08:00
xiaowang 138d3eae57 Merge pull request '功能:优化Salon作品选择与历史补单' (#64) from dev into sit
发布 Nacos 配置 / publish (push) Successful in 34s
Salon SIT 自动发布 / deploy (push) Successful in 3m32s
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/64
2026-10-14 09:15:03 +08:00
xiaowang 261723bc6e 功能:优化Salon作品选择与历史补单
发布 Nacos 配置 / publish (push) Successful in 30s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 1s
2026-10-14 00:47:10 +08:00
xiaowang d6f3652a70 Merge pull request 'Dev合并到sit' (#63) from dev into sit
发布 Nacos 配置 / publish (push) Successful in 31s
Salon SIT 自动发布 / deploy (push) Successful in 3m36s
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/63
2026-10-14 00:27:29 +08:00
xiaowang 4101ab3408 将历史补单字段合并到初始化SQL
发布 Nacos 配置 / publish (push) Successful in 32s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 1s
2026-10-13 14:37:54 +08:00
xiaowang 5145dc44c6 补充历史补单小程序页面 2026-10-13 12:40:21 +08:00
xiaowang bd8d95fcd9 新增历史补单与服务中状态 2026-10-13 12:36:01 +08:00
xiaowang 3ab615ccd4 功能:支持待分配预约与首次排班引导 2026-10-12 23:52:20 +08:00
xiaowang 59608ef57f 文档:设计待分配预约与首次排班引导 2026-10-12 23:15:15 +08:00
xiaowang 3b98e4746a 优化:统一小程序业务引用选择交互 2026-10-12 22:24:24 +08:00
xiaowang fa1fed006e 修复:预约作品弹层滚动穿透 2026-10-12 17:37:51 +08:00
xiaowang 2714bd7201 优化:规划日期快捷新增预约 2026-10-12 17:15:27 +08:00
xiaowang e4aff0803a 功能:增加店长员工审核与登录提醒 2026-10-12 16:45:42 +08:00
xiaowang 247472fcae 优化:资料弹窗使用圆形默认头像 2026-10-12 15:35:19 +08:00
xiaowang 960c042c17 文档:设计资料弹窗默认头像优化 2026-10-12 15:31:00 +08:00
xiaowang 7411414419 修复:同步SIT数据源覆盖凭据
发布 Nacos 配置 / publish (push) Successful in 33s
Salon SIT 自动发布 / deploy (push) Successful in 3m40s
通过 dev → sit 受保护分支晋级发布完整数据源配置。
2026-10-12 11:39:15 +08:00
xiaowang e18c2b06d5 修复:同步SIT数据源覆盖凭据
发布 Nacos 配置 / publish (push) Successful in 29s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 1s
2026-10-12 11:38:01 +08:00
xiaowang 09db9fceaa 修复:更新SIT中间件业务凭据
发布 Nacos 配置 / publish (push) Successful in 36s
Salon SIT 自动发布 / deploy (push) Failing after 3m39s
通过 dev → sit 受保护分支晋级发布 SIT 配置。
2026-10-12 11:16:34 +08:00
xiaowang 66b9e2dc2d 修复:更新SIT中间件业务凭据
发布 Nacos 配置 / publish (push) Successful in 33s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 1s
2026-10-12 11:14:39 +08:00
xiaowang f185ec4ba5 Merge pull request 'Dev' (#60) from dev into sit
发布 Nacos 配置 / publish (push) Successful in 32s
Salon SIT 自动发布 / deploy (push) Failing after 3m3s
Reviewed-on: http://wcy111.top:3000/xiaowang/JayuCloud/pulls/60
2026-10-12 10:53:47 +08:00
xiaowang 7cbfba7cf6 合并:同步sit并解决变更记录冲突
发布 Nacos 配置 / publish (push) Successful in 29s
环境分支晋级检查 / environment-promotion-source (pull_request_target) Successful in 1s
2026-10-12 10:51:28 +08:00
xiaowang 48b25583ee 安全:[skip ci] 固定目标分支晋级检查 2026-10-12 10:35:53 +08:00
xiaowang 63097311ef 安全:[skip ci] 固定目标分支晋级检查 2026-10-12 10:34:55 +08:00
xiaowang ceb210a582 安全:[skip ci] 限制环境晋级来源仓库 2026-10-12 10:31:12 +08:00
xiaowang 126ec43c10 安全:[skip ci] 限制环境晋级来源仓库 2026-10-12 10:30:59 +08:00
xiaowang cbd6e23104 配置:[skip ci] 引导环境分支晋级检查 2026-10-12 10:24:12 +08:00
xiaowang d25f9674c3 配置:[skip ci] 增加环境分支晋级检查 2026-10-12 10:20:58 +08:00
xiaowang 943fa79d16 文档:[skip ci] 设计环境分支保护规则 2026-10-12 10:12:11 +08:00
xiaowang 10a3b6413c 修复:恢复后端Nacos环境变量引导
发布 Nacos 配置 / publish (push) Successful in 30s
2026-10-12 09:45:54 +08:00
xiaowang 4004506b65 文档:设计后端Nacos启动引导修复 2026-10-12 09:34:29 +08:00
xiaowang bd4ed62368 优化:完善快捷登录与微信资料入口 2026-10-12 09:10:47 +08:00
xiaowang f00c753fd6 优化:提升小程序全链路性能 2026-10-11 16:53:02 +08:00
xiaowang 0e7e60fefd 文档:设计小程序全链路性能优化 2026-10-11 16:24:21 +08:00
xiaowang ef5f638e7e 优化:微信资料改为双按钮 2026-10-10 18:04:00 +08:00
xiaowang 89f51440a0 文档:设计微信资料双按钮 2026-10-10 18:02:42 +08:00
xiaowang d57f9b736a 修复:微信头像选择后未生效 2026-10-10 18:01:34 +08:00
xiaowang ff98e89ab7 文档:设计微信头像选择修复方案 2026-10-10 18:00:18 +08:00
xiaowang cd08d3c3b0 优化:个人资料与手机号设置入口 2026-10-10 17:56:44 +08:00
xiaowang 0ceea1578f 文档:设计个人资料与手机号入口优化 2026-10-10 17:53:35 +08:00
xiaowang d3e9404c17 优化:精简个人信息头像卡 2026-10-10 17:40:27 +08:00
xiaowang 7e62fed56d 文档:设计个人信息头像卡精简方案 2026-10-10 17:38:40 +08:00
xiaowang 804c69c296 优化:个人信息改为独立页面 2026-10-10 17:32:26 +08:00
xiaowang 72bfcffc25 文档:设计小程序个人信息独立页面 2026-10-10 17:26:38 +08:00
xiaowang 9148bdb027 优化:我的页面展示账号头像昵称 2026-10-10 17:04:03 +08:00
xiaowang d511070fc7 文档:设计小程序我的页面账号卡 2026-10-10 17:01:46 +08:00
xiaowang d38c5cd4fe 优化:小程序记住登录与启动跳转 2026-10-10 16:41:37 +08:00
xiaowang ae1b568131 文档:制定小程序记住登录体验优化计划 2026-10-10 16:31:43 +08:00
xiaowang 34e6536b0f 文档:设计小程序记住登录体验优化 2026-10-10 16:31:06 +08:00
xiaowang e69498cc15 整理:删除已合并的重复SQL脚本 2026-10-10 16:14:52 +08:00
xiaowang e7de04717a 修复:后台注册审核接口与退出流程 2026-10-10 16:08:46 +08:00
xiaowang 297af45fea 文档:制定后台审核与退出修复计划 2026-10-10 15:36:00 +08:00
xiaowang c4c17a67d4 文档:设计后台审核与退出修复 2026-10-10 15:21:43 +08:00
2215 changed files with 117480 additions and 112902 deletions
+18
View File
@@ -0,0 +1,18 @@
import { createHash } from 'node:crypto';
import { access, readFile } from 'node:fs/promises';
import { join } from 'node:path';
import { envName, latestSuccess, recordsRoot, snapshotRoot } from './release-store.mjs';
const environment = envName(process.env.RELEASE_ENVIRONMENT);
const commitSha = process.env.RELEASE_SHA;
const record = await latestSuccess(environment, 'nacos');
if (!commitSha || record.commitSha !== commitSha || record.status !== 'success') throw new Error(`没有提交 ${commitSha} 对应的成功 Nacos 发布`);
if (!record.activeSnapshotId || !record.snapshotId || !Array.isArray(record.files) || record.files.length === 0 || record.files.some((file) => !file.sha256 || !file.dataId || !file.namespace)) throw new Error('Nacos 发布记录不完整');
const destinations = environment === 'prod' ? ['prod-center1', 'prod-center2'] : [environment];
for (const destination of destinations) for (const file of record.files) {
const path = join(snapshotRoot(environment, record.activeSnapshotId), destination, file.namespace, 'DEFAULT_GROUP', file.dataId);
const content = await readFile(path, 'utf8');
if (createHash('sha256').update(content, 'utf8').digest('hex') !== file.sha256) throw new Error(`Nacos 发布快照摘要不匹配:${destination}/${file.namespace}/${file.dataId}`);
}
await access(join(recordsRoot(environment), 'latest-success-nacos.json'));
console.log(JSON.stringify(record));
+20
View File
@@ -0,0 +1,20 @@
const workflow = process.argv[2];
const ref = process.argv[3] || process.env.GITHUB_REF_NAME;
if (!workflow || !ref) throw new Error('用法:node dispatch-workflow.mjs <workflow.yml> <ref>');
const token = process.env.GITHUB_TOKEN;
if (!token) throw new Error('缺少 GITHUB_TOKEN');
const server = process.env.GITHUB_SERVER_URL || 'http://192.168.5.15:3000';
const repository = process.env.GITHUB_REPOSITORY || 'xiaowang/JayuCloud';
const inputs = Object.fromEntries(Object.entries(process.env).filter(([key]) => key.startsWith('DISPATCH_INPUT_')).map(([key, value]) => [key.slice('DISPATCH_INPUT_'.length).toLowerCase(), value]));
if (process.env.AUTO_ROLLBACK === 'true') inputs.auto_rollback = 'true';
const isNacosRollback = /^(回退dev环境nacos配置|回退sit环境nacos配置|回退prod环境nacos配置)\.yml$/.test(workflow);
if (isNacosRollback && !inputs.snapshot_id && process.env.RELEASE_STORE_ROOT && (process.env.RELEASE_ENVIRONMENT || process.env.NACOS_ENVIRONMENT)) {
try { inputs.snapshot_id = JSON.parse(await (await import('node:fs/promises')).readFile(`${process.env.RELEASE_STORE_ROOT}/records/${process.env.RELEASE_ENVIRONMENT || process.env.NACOS_ENVIRONMENT}/pending-nacos.json`, 'utf8')).snapshotId; } catch {}
}
if (isNacosRollback && process.env.AUTO_ROLLBACK === 'true' && !inputs.snapshot_id) {
console.log('没有待处理的 Nacos 发布快照,无需触发 Nacos 回退');
process.exit(0);
}
const response = await fetch(`${server}/api/v1/repos/${repository}/actions/workflows/${workflow}/dispatches`, { method: 'POST', headers: { Authorization: `token ${token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ ref, inputs }) });
if (!response.ok && response.status !== 204) throw new Error(`触发 ${workflow} 失败:HTTP ${response.status} ${await response.text()}`);
console.log(`已触发 ${workflow} @ ${ref}`);
+68 -122
View File
@@ -1,133 +1,79 @@
import { createHash } from 'node:crypto';
import { readFile, readdir } from 'node:fs/promises';
import { mkdir, readFile, readdir, rm } from 'node:fs/promises';
import { join, relative, sep } from 'node:path';
import { atomicWrite, envName, listYamlFiles, recordsRoot, snapshotRoot, writeJson } from './release-store.mjs';
const repositoryRoot = process.cwd();
const target = requiredNacosTarget('NACOS_ENVIRONMENT');
const environment = envName(process.env.NACOS_ENVIRONMENT);
const group = 'DEFAULT_GROUP';
const configRoot = join(repositoryRoot, 'nacos', 'namespaces', target.environment);
const configFiles = await collectYamlFiles(configRoot);
if (configFiles.length === 0) {
throw new Error(`nacos/namespaces/${target.environment} 下没有可发布的 YAML 配置`);
}
for (const destination of target.destinations) {
await publishDestination(destination, configFiles);
}
async function publishDestination(destination, files) {
const nacosUrls = requiredEnvironment(`${destination.prefix}_URLS`).split(',').map((value) => normalizeNacosBaseUrl(value.trim())).filter(Boolean);
if (nacosUrls.length < destination.verificationNodeCount) {
throw new Error(`${destination.name} 至少需要 ${destination.verificationNodeCount} 个 Nacos 地址用于发布校验`);
}
const username = requiredEnvironment(`${destination.prefix}_USERNAME`);
const password = requiredEnvironment(`${destination.prefix}_PASSWORD`);
const token = await login(nacosUrls[0], username, password);
for (const filePath of files) {
const root = join(repositoryRoot, 'nacos', 'namespaces', destination.environment);
const relativePath = relative(root, filePath).split(sep);
if (relativePath.length !== 3 || relativePath[1] !== group) {
throw new Error(`配置路径必须是 <namespace>/${group}/<dataId>.yaml:${relativePath.join('/')}`);
}
const [namespace, , dataId] = relativePath;
const content = await readFile(filePath, 'utf8');
await publish(nacosUrls[0], token, namespace, group, dataId, content);
await verify(nacosUrls.slice(0, destination.verificationNodeCount), token, namespace, group, dataId, content);
console.log(`已发布并校验 ${destination.name}/${namespace}/${group}/${dataId}`);
const root = process.cwd();
const configRoot = join(root, 'nacos', 'namespaces', environment);
const files = await listYamlFiles(configRoot);
if (!files.length) throw new Error(`没有可发布的 ${environment} YAML 配置`);
const destinations = (environment === 'prod' ? [['NACOS_PROD', 'prod-center1', 2], ['NACOS_DR', 'prod-center2', 1]] : [[environment === 'dev' ? 'NACOS_DEV' : 'NACOS_SIT', environment, 1]]).map(([prefix, id, nodes]) => {
const urls = required(`${prefix}_URLS`).split(',').map(normalize).filter(Boolean);
if (urls.length < nodes) throw new Error(`${prefix} Nacos 地址不足`);
return { prefix, id, urls, token: null, nodes };
});
for (const destination of destinations) destination.token = await login(destination.urls[0], required(`${destination.prefix}_USERNAME`), required(`${destination.prefix}_PASSWORD`));
const groupName = group;
const runId = process.env.GITHUB_RUN_ID || 'manual';
const commitSha = process.env.GITHUB_SHA || 'unknown';
const recordRoot = recordsRoot(environment);
const snapshotId = `${new Date().toISOString().replaceAll(/[:.]/g, '-')}-${runId}`;
const releaseId = `${environment}-${commitSha.slice(0, 12)}-${runId}`;
const snapshot = snapshotRoot(environment, snapshotId);
const activeSnapshotId = `active-${releaseId}`;
const activeSnapshot = snapshotRoot(environment, activeSnapshotId);
await mkdir(snapshot, { recursive: true });
await mkdir(activeSnapshot, { recursive: true });
const entries = [];
for (const file of files) {
const { namespace, dataId } = info(file);
const content = await readFile(file, 'utf8');
const entry = { namespace, dataId, sha256: sha256(content), previousSha256: {}, previousExists: {} };
entries.push(entry);
for (const destination of destinations) {
const response = await fetch(`${destination.urls[0]}/nacos/v1/cs/configs?${new URLSearchParams({ dataId, group: groupName, tenant: namespace, accessToken: destination.token })}`);
if (!response.ok && response.status !== 404) throw new Error(`读取当前 Nacos 配置失败:${destination.prefix}/${namespace}/${dataId} HTTP ${response.status}`);
const oldContent = await response.text();
entry.previousExists[destination.id] = response.status !== 404;
entry.previousSha256[destination.id] = sha256(oldContent);
await atomicWrite(join(snapshot, destination.id, namespace, groupName, dataId), oldContent);
await atomicWrite(join(activeSnapshot, destination.id, namespace, groupName, dataId), content);
}
}
function requiredEnvironment(name) {
const value = process.env[name];
if (!value) {
throw new Error(`缺少环境变量 ${name}`);
}
return value;
}
function normalizeNacosBaseUrl(value) {
return value.replace(/\/+$/, '').replace(/\/nacos$/, '');
}
function requiredNacosTarget(name) {
const value = requiredEnvironment(name);
const destinations = {
dev: [{ name: 'dev', environment: 'dev', prefix: 'NACOS_DEV', verificationNodeCount: 1 }],
sit: [{ name: 'sit', environment: 'sit', prefix: 'NACOS_SIT', verificationNodeCount: 1 }],
'prod-center1': [{ name: 'prod-center1', environment: 'prod', prefix: 'NACOS_PROD', verificationNodeCount: 2 }],
'prod-center2': [{ name: 'prod-center2', environment: 'prod', prefix: 'NACOS_DR', verificationNodeCount: 1 }],
'prod-both': [
{ name: 'prod-center1', environment: 'prod', prefix: 'NACOS_PROD', verificationNodeCount: 2 },
{ name: 'prod-center2', environment: 'prod', prefix: 'NACOS_DR', verificationNodeCount: 1 },
],
}[value];
if (!destinations) {
throw new Error(`不支持的 Nacos 发布目标:${value}`);
}
return { environment: destinations[0].environment, destinations };
}
async function collectYamlFiles(directory) {
const entries = await readdir(directory, { withFileTypes: true });
const files = [];
for (const entry of entries) {
const entryPath = join(directory, entry.name);
if (entry.isDirectory()) {
files.push(...await collectYamlFiles(entryPath));
} else if (entry.isFile() && entry.name.endsWith('.yaml')) {
files.push(entryPath);
await writeJson(join(recordRoot, 'pending-nacos.json'), { environment, snapshotId, activeSnapshotId, commitSha, runId, releaseId, files: entries, createdAt: new Date().toISOString() });
try {
for (const file of files) {
const { namespace, dataId } = info(file);
const content = await readFile(file, 'utf8');
for (const destination of destinations) {
const response = await fetch(`${destination.urls[0]}/nacos/v1/cs/configs?accessToken=${encodeURIComponent(destination.token)}`, { method: 'POST', body: new URLSearchParams({ dataId, group: groupName, tenant: namespace, type: 'yaml', content }) });
const result = await response.text();
if (!response.ok || result.trim() !== 'true') throw new Error(`发布失败:${destination.prefix}/${namespace}/${dataId} HTTP ${response.status}`);
await verify(destination, namespace, dataId, content);
}
}
return files.sort();
const previous = await optionalJson(join(recordRoot, 'latest-success-nacos.json'));
const record = { environment, status: 'success', commitSha, runId, releaseId, snapshotId, activeSnapshotId, previousReleaseId: previous?.releaseId || null, files: entries, publishedAt: new Date().toISOString() };
await writeJson(join(recordRoot, 'latest-success-nacos.json'), record);
await writeJson(join(recordRoot, 'nacos', `${releaseId}.json`), record);
await rm(join(recordRoot, 'pending-nacos.json'), { force: true });
console.log(`已发布并校验 ${environment} Nacos,回退快照 ${snapshotId}`);
} catch (error) {
console.error(error.message);
console.error(`AUTO_ROLLBACK_SNAPSHOT_ID=${snapshotId}`);
throw error;
}
async function login(baseUrl, user, secret) {
const body = new URLSearchParams({ username: user, password: secret });
const response = await fetch(`${baseUrl}/nacos/v1/auth/login`, { method: 'POST', body });
if (!response.ok) {
throw new Error(`Nacos 登录失败:${baseUrl} HTTP ${response.status}`);
}
const payload = await response.json();
if (!payload.accessToken) {
throw new Error(`Nacos 登录响应缺少 accessToken:${baseUrl}`);
}
return payload.accessToken;
}
async function publish(baseUrl, token, namespace, configGroup, dataId, content) {
const body = new URLSearchParams({ dataId, group: configGroup, tenant: namespace, type: 'yaml', content });
const response = await fetch(`${baseUrl}/nacos/v1/cs/configs?accessToken=${encodeURIComponent(token)}`, { method: 'POST', body });
const result = await response.text();
if (!response.ok || result.trim() !== 'true') {
throw new Error(`Nacos 发布失败:${baseUrl}/${namespace}/${dataId} HTTP ${response.status} ${result}`);
}
}
async function verify(baseUrls, token, namespace, configGroup, dataId, expectedContent) {
const expectedHash = sha256(expectedContent);
for (const baseUrl of baseUrls) {
const query = new URLSearchParams({ dataId, group: configGroup, tenant: namespace });
let lastStatus = 0;
let lastContent = '';
for (let attempt = 1; attempt <= 3; attempt += 1) {
const response = await fetch(`${baseUrl}/nacos/v1/cs/configs?${query}&accessToken=${encodeURIComponent(token)}`);
const content = await response.text();
lastStatus = response.status;
lastContent = content;
if (response.ok && sha256(content) === expectedHash) {
break;
}
if (attempt < 3) {
await new Promise((resolve) => setTimeout(resolve, 1000));
}
}
if (lastStatus !== 200 || sha256(lastContent) !== expectedHash) {
throw new Error(`Nacos 配置校验失败:${baseUrl}/${namespace}/${dataId} HTTP ${lastStatus} ${lastContent.slice(0, 200)}`);
}
}
}
function sha256(value) {
return createHash('sha256').update(value, 'utf8').digest('hex');
function required(name) { if (!process.env[name]) throw new Error(`缺少环境变量 ${name}`); return process.env[name]; }
function normalize(value) { return value.replace(/\/+$/, '').replace(/\/nacos$/, ''); }
function sha256(value) { return createHash('sha256').update(value, 'utf8').digest('hex'); }
function info(file) {
const parts = relative(configRoot, file).split(sep);
if (parts.length !== 3 || parts[1] !== group || !parts[0] || !parts[2]) throw new Error(`配置路径无效,必须为 namespace/${group}/dataId:${file}`);
return { namespace: parts[0], dataId: parts[2] };
}
async function optionalJson(path) { try { return JSON.parse(await readFile(path, 'utf8')); } catch { return null; } }
async function login(base, user, password) { const response = await fetch(`${base}/nacos/v1/auth/login`, { method: 'POST', body: new URLSearchParams({ username: user, password }) }); if (!response.ok) throw new Error(`Nacos 登录失败:HTTP ${response.status}`); const result = await response.json(); if (!result.accessToken) throw new Error('Nacos 登录响应缺少 accessToken'); return result.accessToken; }
async function verify(destination, namespace, dataId, expected) { const expectedHash = sha256(expected); for (const base of destination.urls) { let status = 0; let content = ''; for (let attempt = 0; attempt < 3; attempt += 1) { const response = await fetch(`${base}/nacos/v1/cs/configs?${new URLSearchParams({ dataId, group: groupName, tenant: namespace, accessToken: destination.token })}`); status = response.status; content = await response.text(); if (status === 200 && sha256(content) === expectedHash) break; await new Promise((resolve) => setTimeout(resolve, 1000)); } if (status !== 200 || sha256(content) !== expectedHash) throw new Error(`Nacos 校验失败:${destination.prefix}/${base}/${namespace}/${dataId}`); } }
+37
View File
@@ -0,0 +1,37 @@
import { createHash } from 'node:crypto';
import { readFile, readdir } from 'node:fs/promises';
import { join } from 'node:path';
import { envName, latestSuccess, recordsRoot, writeJson } from './release-store.mjs';
const environment = envName(process.env.RELEASE_ENVIRONMENT);
const commitSha = process.env.RELEASE_SHA;
const nacos = await latestSuccess(environment, 'nacos');
const packageDir = process.env.PACKAGE_DIRECTORY;
if (!commitSha || nacos.commitSha !== commitSha || !packageDir) throw new Error('部署记录参数不完整');
if (nacos.status !== 'success' || !nacos.files?.length || !nacos.activeSnapshotId) throw new Error('Nacos 发布已回退或发布记录不完整');
const manifestPath = await findFile(packageDir, 'manifest.json');
const manifest = JSON.parse(await readFile(manifestPath, 'utf8'));
const artifactPaths = {};
for (const [name, fileName] of Object.entries({ core: 'JC-Salon-Core.jar', gateway: 'JC-Salon-Gateway.jar', frontend: 'jc-salon-frontend-dist.tar.gz' })) {
const artifactPath = await findFile(packageDir, fileName);
const sha256 = createHash('sha256').update(await readFile(artifactPath)).digest('hex');
const expected = manifest.artifacts?.find((item) => item.Path?.endsWith(fileName))?.Sha256?.toLowerCase();
if (!expected || expected !== sha256) throw new Error(`发布包摘要不匹配:${fileName}`);
artifactPaths[name] = { path: artifactPath, sha256 };
}
const previous = await optional(join(recordsRoot(environment), 'latest-success-deploy.json'));
const releaseId = `${environment}-${commitSha.slice(0, 12)}-${process.env.GITHUB_RUN_ID || 'manual'}`;
const record = { environment, status: 'success', commitSha, releaseId, nacosReleaseId: nacos.releaseId, snapshotId: nacos.snapshotId, activeSnapshotId: nacos.activeSnapshotId, packageDir, manifestPath, artifacts: artifactPaths, previousReleaseId: previous?.releaseId || null, runId: process.env.GITHUB_RUN_ID || 'manual', deployedAt: new Date().toISOString() };
await writeJson(join(recordsRoot(environment), 'deploy', `${releaseId}.json`), record);
await writeJson(join(recordsRoot(environment), 'latest-success-deploy.json'), record);
console.log(JSON.stringify(record));
async function optional(path) { try { return JSON.parse(await readFile(path, 'utf8')); } catch { return null; } }
async function findFile(root, name) {
for (const entry of await readdir(root, { withFileTypes: true })) {
const path = join(root, entry.name);
if (entry.isDirectory()) { const nested = await optionalFind(path, name); if (nested) return nested; }
else if (entry.name === name) return path;
}
throw new Error(`发布包缺少 ${name}`);
}
async function optionalFind(root, name) { try { return await findFile(root, name); } catch { return null; } }
+10
View File
@@ -0,0 +1,10 @@
import { join } from 'node:path';
import { envName, recordsRoot, readJson, writeJson } from './release-store.mjs';
const environment = envName(process.env.RELEASE_ENVIRONMENT);
const releaseId = process.env.ROLLBACK_RELEASE_ID;
if (!releaseId) throw new Error('缺少 ROLLBACK_RELEASE_ID');
const record = await readJson(join(recordsRoot(environment), 'deploy', `${releaseId}.json`));
if (record.status !== 'success' || !record.packageDir || !record.activeSnapshotId) throw new Error('目标回退版本记录不完整');
await writeJson(join(recordsRoot(environment), 'latest-success-deploy.json'), { ...record, restoredAt: new Date().toISOString() });
console.log(`已将 ${environment} 成功版本指针更新到 ${releaseId}`);
+62
View File
@@ -0,0 +1,62 @@
import { mkdir, readFile, readdir, rename, writeFile } from 'node:fs/promises';
import { dirname, join, resolve } from 'node:path';
export const storeRoot = process.env.RELEASE_STORE_ROOT || '/salon-release';
export function envName(value = process.env.NACOS_ENVIRONMENT) {
if (!['dev', 'sit', 'prod'].includes(value)) throw new Error(`不支持的环境:${value}`);
return value;
}
export function environmentRoot(environment = envName()) {
return join(storeRoot, environment);
}
export function snapshotRoot(environment = envName(), snapshotId) {
return join(storeRoot, 'nacos-snapshots', environment, snapshotId);
}
export function recordsRoot(environment = envName()) {
return join(storeRoot, 'records', environment);
}
export async function atomicWrite(path, content) {
await mkdir(dirname(path), { recursive: true });
const temp = `${path}.tmp-${process.pid}-${Date.now()}`;
await writeFile(temp, content, 'utf8');
await rename(temp, path);
}
export async function readJson(path) {
return JSON.parse(await readFile(path, 'utf8'));
}
export async function writeJson(path, value) {
await atomicWrite(path, `${JSON.stringify(value, null, 2)}\n`);
}
export async function latestSuccess(environment = envName(), kind = 'nacos') {
const path = join(recordsRoot(environment), `latest-success-${kind}.json`);
return readJson(path);
}
export async function releaseRecord(environment, kind, releaseId) {
return readJson(join(recordsRoot(environment), kind, `${releaseId}.json`));
}
export async function listYamlFiles(root) {
const result = [];
for (const entry of await readdir(root, { withFileTypes: true })) {
const path = join(root, entry.name);
if (entry.isDirectory()) result.push(...await listYamlFiles(path));
else if (entry.isFile() && entry.name.endsWith('.yaml')) result.push(path);
}
return result.sort();
}
export function safeRelative(root, path) {
const value = resolve(path);
const base = resolve(root);
if (!value.startsWith(`${base}/`) && !value.startsWith(`${base}\\`)) throw new Error(`路径越界:${path}`);
return value.slice(base.length + 1).replaceAll('\\', '/');
}
+67
View File
@@ -0,0 +1,67 @@
import { createHash } from 'node:crypto';
import { readFile, readdir, rm } from 'node:fs/promises';
import { join } from 'node:path';
import { envName, recordsRoot, snapshotRoot, writeJson } from './release-store.mjs';
const environment = envName(process.env.NACOS_ENVIRONMENT);
const group = 'DEFAULT_GROUP';
const destinations = environment === 'prod' ? [['NACOS_PROD', 'prod-center1'], ['NACOS_DR', 'prod-center2']] : [[environment === 'dev' ? 'NACOS_DEV' : 'NACOS_SIT', environment]];
const targets = [];
for (const [prefix, id] of destinations) {
const urls = required(`${prefix}_URLS`).split(',').map(normalize).filter(Boolean);
if (!urls.length) throw new Error(`${prefix}_URLS 为空`);
targets.push({ prefix, id, urls, token: await login(urls[0], required(`${prefix}_USERNAME`), required(`${prefix}_PASSWORD`)) });
}
const root = recordsRoot(environment);
const pending = await optional(join(root, 'pending-nacos.json'));
const latest = await optional(join(root, 'latest-success-nacos.json'));
let selected = process.env.NACOS_RELEASE_ID
? await optional(join(root, 'nacos', `${process.env.NACOS_RELEASE_ID}.json`))
: null;
if (process.env.NACOS_RELEASE_ID && !selected) throw new Error(`找不到 Nacos 发布记录:${process.env.NACOS_RELEASE_ID}`);
if (!process.env.NACOS_SNAPSHOT_ID && !pending && !selected && latest?.previousReleaseId) selected = await optional(join(root, 'nacos', `${latest.previousReleaseId}.json`));
const snapshotId = process.env.NACOS_SNAPSHOT_ID || (selected ? selected.activeSnapshotId : pending?.snapshotId || latest?.snapshotId);
if (!snapshotId) throw new Error(`没有 ${environment} Nacos 回退快照`);
if (!selected && !pending) selected = await findSnapshotRecord(join(root, 'nacos'), snapshotId);
const snapshot = snapshotRoot(environment, snapshotId);
const entries = selected?.files || pending?.files || latest?.files || [];
const selectedIsActive = selected?.activeSnapshotId === snapshotId;
if (!entries.length) throw new Error('回退记录缺少配置清单');
for (const target of targets) {
for (const entry of entries) {
for (const base of target.urls) {
const exists = selectedIsActive || entry.previousExists?.[target.id] !== false;
const path = join(snapshot, target.id, entry.namespace, group, entry.dataId);
const content = exists ? await readFile(path, 'utf8') : '';
const expectedHash = selectedIsActive ? entry.sha256 : entry.previousSha256?.[target.id];
if (exists && (!expectedHash || sha256(content) !== expectedHash)) throw new Error(`回退快照摘要不匹配:${target.id}/${entry.namespace}/${entry.dataId}`);
const query = new URLSearchParams({ dataId: entry.dataId, group, tenant: entry.namespace, accessToken: target.token });
const response = exists
? await fetch(`${base}/nacos/v1/cs/configs?accessToken=${encodeURIComponent(target.token)}`, { method: 'POST', body: new URLSearchParams({ dataId: entry.dataId, group, tenant: entry.namespace, type: 'yaml', content }) })
: await fetch(`${base}/nacos/v1/cs/configs?${query}`, { method: 'DELETE' });
if (!response.ok || (exists && (await response.text()).trim() !== 'true')) throw new Error(`回退失败:${target.id}/${entry.namespace}/${entry.dataId}`);
const check = await fetch(`${base}/nacos/v1/cs/configs?${new URLSearchParams({ dataId: entry.dataId, group, tenant: entry.namespace, accessToken: target.token })}`);
const actual = await check.text();
if (exists ? (!check.ok || sha256(actual) !== sha256(content)) : check.status !== 404) throw new Error(`回退摘要校验失败:${target.id}/${entry.namespace}/${entry.dataId}`);
}
}
}
await writeJson(join(root, 'last-rollback.json'), { environment, snapshotId, source: process.env.AUTO_ROLLBACK === 'true' ? 'automatic' : 'manual', rollbackAt: new Date().toISOString() });
if (selectedIsActive && selected) await writeJson(join(root, 'latest-success-nacos.json'), selected);
await rm(join(root, 'pending-nacos.json'), { force: true });
console.log(`已回退 ${environment} Nacos:${snapshotId}`);
function required(name) { if (!process.env[name]) throw new Error(`缺少环境变量 ${name}`); return process.env[name]; }
function normalize(value) { return value.replace(/\/+$/, '').replace(/\/nacos$/, ''); }
function sha256(value) { return createHash('sha256').update(value, 'utf8').digest('hex'); }
async function optional(path) { try { return JSON.parse(await readFile(path, 'utf8')); } catch { return null; } }
async function findSnapshotRecord(directory, id) {
try {
for (const file of await readdir(directory)) {
if (!file.endsWith('.json')) continue;
const record = await optional(join(directory, file));
if (record?.snapshotId === id || record?.activeSnapshotId === id) return record;
}
} catch {}
return null;
}
async function login(base, user, password) { const response = await fetch(`${base}/nacos/v1/auth/login`, { method: 'POST', body: new URLSearchParams({ username: user, password }) }); if (!response.ok) throw new Error(`Nacos 登录失败:HTTP ${response.status}`); const result = await response.json(); if (!result.accessToken) throw new Error('Nacos 登录响应缺少 accessToken'); return result.accessToken; }
@@ -0,0 +1,87 @@
name: 生产环境回退上一个版本
"on":
workflow_dispatch:
inputs:
auto_rollback:
description: 是否由自动失败流程触发
required: false
type: boolean
concurrency:
group: release-prod
cancel-in-progress: false
jobs:
rollback:
runs-on: jayucloud
container:
options: >-
-v /opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release
env:
GITHUB_SERVER_URL: http://192.168.5.15:3000
RELEASE_ENVIRONMENT: prod
RELEASE_STORE_ROOT: /salon-release
NACOS_ENVIRONMENT: prod
AUTO_ROLLBACK: ${{ inputs.auto_rollback }}
WEB_TARGET_HOST: 10.66.0.3
WEB_TARGET_PORT: 22
WEB_TARGET_USER: root
WEB_REMOTE_DIR: /opt/jc-salon-frontend
SALON_PROD_SSH_PASSWORD: ${{ secrets.SALON_PROD_SSH_PASSWORD }}
NACOS_PROD_URLS: ${{ secrets.NACOS_PROD_URLS }}
NACOS_PROD_USERNAME: ${{ secrets.NACOS_PROD_USERNAME }}
NACOS_PROD_PASSWORD: ${{ secrets.NACOS_PROD_PASSWORD }}
NACOS_DR_URLS: ${{ secrets.NACOS_DR_URLS }}
NACOS_DR_USERNAME: ${{ secrets.NACOS_DR_USERNAME }}
NACOS_DR_PASSWORD: ${{ secrets.NACOS_DR_PASSWORD }}
steps:
- name: 检出回退脚本
shell: bash
env:
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
git init .
git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git"
git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$GITHUB_SHA"
git checkout --detach "$GITHUB_SHA"
- name: 读取上一成功版本
shell: bash
run: |
set -euo pipefail
current=/salon-release/records/prod/latest-success-deploy.json
test -f "$current"
node - <<'NODE' >> "$GITHUB_ENV"
const fs = require('fs');
const latest = JSON.parse(fs.readFileSync('/salon-release/records/prod/latest-success-deploy.json'));
const id = process.env.AUTO_ROLLBACK === 'true' ? latest.releaseId : latest.previousReleaseId;
if (!id) throw new Error('没有可回退的 PROD 成功版本');
const target = JSON.parse(fs.readFileSync(`/salon-release/records/prod/deploy/${id}.json`));
console.log(`PACKAGE_DIRECTORY=${target.packageDir}`);
console.log(`ROLLBACK_SNAPSHOT_ID=${target.activeSnapshotId}`);
console.log(`ROLLBACK_RELEASE_ID=${target.releaseId}`);
console.log(`NACOS_RELEASE_ID=${target.nacosReleaseId}`);
NODE
- name: 安装 SSH 密码工具
shell: bash
run: apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends sshpass
- name: 写入 PROD 目标清单
shell: bash
run: |
mkdir -p "$RUNNER_TEMP/salon-prod"
printf '[{"Name":"core01-01","Host":"192.168.10.24","Port":22,"User":"root","Environment":"prod"},{"Name":"core01-02","Host":"192.168.10.25","Port":22,"User":"root","Environment":"prod"},{"Name":"core01-03","Host":"192.168.20.16","Port":22,"User":"root","Environment":"prod"},{"Name":"gateway01-01","Host":"192.168.10.26","Port":22,"User":"root","Environment":"prod"},{"Name":"gateway01-02","Host":"192.168.10.27","Port":22,"User":"root","Environment":"prod"},{"Name":"gateway01-03","Host":"192.168.20.18","Port":22,"User":"root","Environment":"prod"},{"Name":"salon-web","Host":"%s","Port":%s,"User":"%s","Environment":"prod"}]\n' "$WEB_TARGET_HOST" "$WEB_TARGET_PORT" "$WEB_TARGET_USER" > "$RUNNER_TEMP/salon-prod/servers.json"
- name: 恢复 PROD Nacos
shell: bash
env:
NACOS_SNAPSHOT_ID: ${{ env.ROLLBACK_SNAPSHOT_ID }}
NACOS_RELEASE_ID: ${{ env.NACOS_RELEASE_ID }}
AUTO_ROLLBACK: 'true'
NACOS_ROLLBACK_INVALIDATE: 'true'
run: node .gitea/scripts/rollback-nacos.mjs
- name: 恢复 PROD 应用
shell: pwsh
run: ./docs/scripts/deploy-jayucloud-salon-production.ps1 -Deploy -SkipDatabaseInit -RequireSystemd -PackageDirectory "$env:PACKAGE_DIRECTORY" -ServerInfoJsonPath "$env:RUNNER_TEMP/salon-prod/servers.json" -SshPassword "$env:SALON_PROD_SSH_PASSWORD" -CoreRemoteAppDir /opt/jc-salon-core -GatewayRemoteAppDir /opt/jc-salon-gateway -CorePattern '^core01-' -GatewayPattern '^gateway01-' -CoreServiceName jc-salon-core -GatewayServiceName jc-salon-gateway -WebTargetName salon-web -WebRemoteDir "$env:WEB_REMOTE_DIR" -PublicBaseUrl https://salon.yunail.art
- name: 记录回退后的成功版本
shell: bash
run: node .gitea/scripts/record-rollback.mjs
-59
View File
@@ -1,59 +0,0 @@
name: 发布 Nacos 配置
on:
push:
branches:
- dev
- sit
workflow_dispatch:
inputs:
environment:
description: 发布目标
required: true
type: choice
options:
- dev
- sit
- prod-center1
- prod-center2
- prod-both
jobs:
publish:
runs-on: jayucloud
env:
GITHUB_SERVER_URL: http://192.168.5.15:3000
steps:
- name: 从内网 Gitea 检出配置源
shell: bash
env:
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
test -n "$GITEA_TOKEN"
git init .
git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git"
git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$GITHUB_SHA"
git checkout --detach "$GITHUB_SHA"
- name: 检查 Node.js 运行时
shell: bash
run: |
set -euo pipefail
node_version="$(node --version)"
[[ "$node_version" == v20.* ]]
- name: 发布并校验配置
env:
NACOS_ENVIRONMENT: ${{ inputs.environment || github.ref_name }}
NACOS_PROD_URLS: ${{ secrets.NACOS_PROD_URLS }}
NACOS_PROD_USERNAME: ${{ secrets.NACOS_PROD_USERNAME }}
NACOS_PROD_PASSWORD: ${{ secrets.NACOS_PROD_PASSWORD }}
NACOS_DR_URLS: ${{ secrets.NACOS_DR_URLS }}
NACOS_DR_USERNAME: ${{ secrets.NACOS_DR_USERNAME }}
NACOS_DR_PASSWORD: ${{ secrets.NACOS_DR_PASSWORD }}
NACOS_SIT_URLS: ${{ secrets.NACOS_SIT_URLS }}
NACOS_SIT_USERNAME: ${{ secrets.NACOS_SIT_USERNAME }}
NACOS_SIT_PASSWORD: ${{ secrets.NACOS_SIT_PASSWORD }}
NACOS_DEV_URLS: ${{ secrets.NACOS_DEV_URLS }}
NACOS_DEV_USERNAME: ${{ secrets.NACOS_DEV_USERNAME }}
NACOS_DEV_PASSWORD: ${{ secrets.NACOS_DEV_PASSWORD }}
run: node .gitea/scripts/publish-nacos.mjs
-123
View File
@@ -1,123 +0,0 @@
name: Salon 生产发布
on:
workflow_dispatch:
inputs:
prepare_run_id:
description: 自动准备工作流的运行 ID
required: true
type: string
release_sha:
description: prod 合并提交 SHA
required: true
type: string
jobs:
deploy:
runs-on: jayucloud
env:
GITHUB_SERVER_URL: http://192.168.5.15:3000
WEB_TARGET_HOST: 10.66.0.3
WEB_TARGET_PORT: 22
WEB_TARGET_USER: root
WEB_REMOTE_DIR: /opt/jc-salon-frontend
SALON_PROD_SSH_PASSWORD: ${{ secrets.SALON_PROD_SSH_PASSWORD }}
steps:
- name: 从内网 Gitea 检出发布脚本
shell: bash
env:
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
CHECKOUT_SHA: ${{ inputs.release_sha }}
run: |
set -euo pipefail
test -n "$GITEA_TOKEN"
test -n "$CHECKOUT_SHA"
git init .
git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git"
git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$CHECKOUT_SHA"
git checkout --detach "$CHECKOUT_SHA"
- name: 检查发布工具链
shell: bash
run: |
set -euo pipefail
java_version="$(java -version 2>&1)"
[[ "$java_version" == *'17.'* ]]
node_version="$(node --version)"
[[ "$node_version" == v20.* ]]
pwsh --version
- name: 准备 SSH 密码登录工具
shell: bash
run: |
set -euo pipefail
if ! command -v sshpass >/dev/null 2>&1; then
apt-get update
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends sshpass
fi
sshpass -V >/dev/null 2>&1
- name: 读取已审核发布包
shell: bash
env:
RELEASE_SHA: ${{ inputs.release_sha }}
run: |
set -euo pipefail
test -n "$RELEASE_SHA"
shared_dir="/salon-release/$RELEASE_SHA"
test -d "$shared_dir"
test -f "$shared_dir/.manifest.sha256"
(cd "$shared_dir" && sha256sum -c .manifest.sha256)
mkdir -p artifacts/release
cp -a "$shared_dir/." artifacts/release/
test -f artifacts/release/manifest.json
test -f artifacts/release/backend/JC-Salon-Core.jar
test -f artifacts/release/backend/JC-Salon-Gateway.jar
- name: 发布并校验 Salon 生产 Nacos
shell: bash
env:
NACOS_ENVIRONMENT: prod-both
NACOS_PROD_URLS: ${{ secrets.NACOS_PROD_URLS }}
NACOS_PROD_USERNAME: ${{ secrets.NACOS_PROD_USERNAME }}
NACOS_PROD_PASSWORD: ${{ secrets.NACOS_PROD_PASSWORD }}
NACOS_DR_URLS: ${{ secrets.NACOS_DR_URLS }}
NACOS_DR_USERNAME: ${{ secrets.NACOS_DR_USERNAME }}
NACOS_DR_PASSWORD: ${{ secrets.NACOS_DR_PASSWORD }}
run: node .gitea/scripts/publish-nacos.mjs
- name: 写入临时 SSH 配置和目标清单
shell: bash
env:
SALON_PROD_SSH_PASSWORD: ${{ secrets.SALON_PROD_SSH_PASSWORD }}
run: |
set -euo pipefail
test -n "$SALON_PROD_SSH_PASSWORD"
test -n "$WEB_TARGET_HOST"
test -n "$WEB_TARGET_PORT"
test -n "$WEB_TARGET_USER"
test -n "$WEB_REMOTE_DIR"
mkdir -p "$RUNNER_TEMP/salon-prod"
cat > "$RUNNER_TEMP/salon-prod/servers.json" <<JSON
[
{"Name":"core01-01","Host":"192.168.10.24","Port":22,"User":"root","Purpose":"Salon Core","Environment":"prod"},
{"Name":"core01-02","Host":"192.168.10.25","Port":22,"User":"root","Purpose":"Salon Core","Environment":"prod"},
{"Name":"core01-03","Host":"192.168.20.16","Port":22,"User":"root","Purpose":"Salon Core","Environment":"prod"},
{"Name":"gateway01-01","Host":"192.168.10.26","Port":22,"User":"root","Purpose":"Salon Gateway","Environment":"prod"},
{"Name":"gateway01-02","Host":"192.168.10.27","Port":22,"User":"root","Purpose":"Salon Gateway","Environment":"prod"},
{"Name":"gateway01-03","Host":"192.168.20.18","Port":22,"User":"root","Purpose":"Salon Gateway","Environment":"prod"},
{"Name":"salon-web","Host":"${WEB_TARGET_HOST}","Port":${WEB_TARGET_PORT},"User":"${WEB_TARGET_USER}","Purpose":"Salon NGINX","Environment":"prod"}
]
JSON
- name: 人工确认后执行生产发布
shell: pwsh
env:
SALON_PROD_SSH_PASSWORD: ${{ secrets.SALON_PROD_SSH_PASSWORD }}
SERVER_INFO_JSON: ${{ runner.temp }}/salon-prod/servers.json
run: >-
./docs/scripts/deploy-jayucloud-salon-production.ps1
-Deploy
-SkipDatabaseInit
-RequireSystemd
-PackageDirectory "artifacts/release"
-ServerInfoJsonPath "$env:SERVER_INFO_JSON"
-SshPassword "$env:SALON_PROD_SSH_PASSWORD"
-CorePattern "^core01-"
-GatewayPattern "^gateway01-"
-WebTargetName salon-web
-WebRemoteDir "$env:WEB_REMOTE_DIR"
-80
View File
@@ -1,80 +0,0 @@
name: Salon 生产发布准备
on:
pull_request:
types:
- closed
branches:
- prod
jobs:
prepare:
if: >-
github.event.pull_request.merged == true &&
github.event.pull_request.base.ref == 'prod' &&
github.event.pull_request.head.ref == 'sit'
runs-on: jayucloud
env:
GITHUB_REF_NAME: prod
GITHUB_SERVER_URL: http://192.168.5.15:3000
steps:
- name: 从内网 Gitea 检出合并提交
shell: bash
env:
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
CHECKOUT_SHA: ${{ github.event.pull_request.merge_commit_sha }}
run: |
set -euo pipefail
test -n "$GITEA_TOKEN"
test -n "$CHECKOUT_SHA"
git init .
git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git"
git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$CHECKOUT_SHA"
git checkout --detach "$CHECKOUT_SHA"
- name: 检查构建工具链
shell: bash
run: |
set -euo pipefail
java -version 2>&1 | grep -q '17\.'
node --version | grep -q '^v20\.'
mvn --version > "$RUNNER_TEMP/maven-version.txt"
grep -q 'Java version: 17\.' "$RUNNER_TEMP/maven-version.txt"
pwsh --version
- name: 构建 Salon 发布包
shell: pwsh
run: >-
./docs/scripts/deploy-jayucloud-salon-production.ps1
-PackageOnly
-SkipTests
-SkipDatabaseInit
- name: 保存发布包到共享目录
shell: bash
env:
RELEASE_SHA: ${{ github.event.pull_request.merge_commit_sha }}
run: |
set -euo pipefail
test -n "$RELEASE_SHA"
shared_dir="/salon-release/$RELEASE_SHA"
rm -rf "$shared_dir"
mkdir -p "$shared_dir"
cp -a artifacts/release/. "$shared_dir/"
test -f "$shared_dir/manifest.json"
(cd "$shared_dir" && sha256sum manifest.json > .manifest.sha256)
- name: 输出部署参数
shell: bash
env:
RELEASE_SHA: ${{ github.event.pull_request.merge_commit_sha }}
run: |
{
echo "## Salon 生产部署参数"
echo ""
echo "**prepare_run_id**: \`${{ github.run_id }}\`"
echo ""
echo "**release_sha**: \`$RELEASE_SHA\`"
echo ""
echo "**共享目录**: \`/salon-release/$RELEASE_SHA\`"
} >> "$GITHUB_STEP_SUMMARY"
echo "prepare_run_id=${{ github.run_id }}"
echo "release_sha=$RELEASE_SHA"
echo "artifact_name=salon-prod-$RELEASE_SHA"
-115
View File
@@ -1,115 +0,0 @@
name: Salon SIT 自动发布
on:
push:
branches:
- sit
workflow_dispatch:
jobs:
deploy:
runs-on: jayucloud
env:
GITHUB_SERVER_URL: http://192.168.5.15:3000
WEB_TARGET_HOST: 10.66.0.3
WEB_TARGET_PORT: 22
WEB_TARGET_USER: root
SALON_PROD_SSH_PASSWORD: ${{ secrets.SALON_PROD_SSH_PASSWORD }}
MESSAGEHUB_ACCESS_TOKEN: ${{ secrets.MESSAGEHUB_SIT_ACCESS_TOKEN }}
WEB_REMOTE_DIR: /opt/jc-salon-frontend-sit
steps:
- name: 从内网 Gitea 检出代码
shell: bash
env:
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
test -n "$GITEA_TOKEN"
git init .
git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git"
git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$GITHUB_SHA"
git checkout --detach "$GITHUB_SHA"
- name: 检查发布工具链
shell: bash
run: |
set -euo pipefail
java_version="$(java -version 2>&1)"
[[ "$java_version" == *'17.'* ]]
node_version="$(node --version)"
[[ "$node_version" == v20.* ]]
mvn_version="$(mvn --version 2>&1)"
[[ "$mvn_version" == *'Java version: 17.'* ]]
pwsh --version
- name: 构建 Salon SIT 发布包
shell: pwsh
env:
VITE_API_BASE_URL: https://sit.yunail.art/api
VITE_ADMIN_API_BASE_URL: https://sit.yunail.art/admin/api
run: >-
./docs/scripts/deploy-jayucloud-salon-production.ps1
-PackageOnly
-SkipTests
-SkipDatabaseInit
- name: 准备 SSH 密码登录工具
shell: bash
run: |
set -euo pipefail
if ! command -v sshpass >/dev/null 2>&1; then
apt-get update
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends sshpass
fi
sshpass -V >/dev/null 2>&1
- name: 写入 SIT SSH 配置和目标清单
shell: bash
env:
SALON_PROD_SSH_PASSWORD: ${{ secrets.SALON_PROD_SSH_PASSWORD }}
run: |
set -euo pipefail
test -n "$SALON_PROD_SSH_PASSWORD"
test -n "$WEB_TARGET_HOST"
test -n "$WEB_TARGET_PORT"
test -n "$WEB_TARGET_USER"
mkdir -p "$RUNNER_TEMP/salon-sit"
cat > "$RUNNER_TEMP/salon-sit/servers.json" <<JSON
[
{"Name":"sit-app01","Host":"192.168.10.15","Port":22,"User":"root","Purpose":"Salon SIT Core/Gateway","Environment":"sit"},
{"Name":"salon-web-sit","Host":"${WEB_TARGET_HOST}","Port":${WEB_TARGET_PORT},"User":"${WEB_TARGET_USER}","Purpose":"Salon SIT NGINX","Environment":"sit"}
]
JSON
- name: 写入 MessageHub 运行时 Token
shell: bash
env:
SALON_PROD_SSH_PASSWORD: ${{ secrets.SALON_PROD_SSH_PASSWORD }}
MESSAGEHUB_ACCESS_TOKEN: ${{ secrets.MESSAGEHUB_SIT_ACCESS_TOKEN }}
run: |
set -euo pipefail
test -n "$SALON_PROD_SSH_PASSWORD"
test -n "$MESSAGEHUB_ACCESS_TOKEN"
printf 'MESSAGEHUB_ACCESS_TOKEN=%s\n' "$MESSAGEHUB_ACCESS_TOKEN" |
SSHPASS="$SALON_PROD_SSH_PASSWORD" sshpass -e ssh -o StrictHostKeyChecking=no -p 22 root@192.168.10.15 \
'install -d -m 700 /etc/sysconfig /etc/systemd/system/jc-salon-core-sit.service.d; install -m 600 /dev/stdin /etc/sysconfig/jc-salon-messagehub; printf "[Service]\\nEnvironmentFile=/etc/sysconfig/jc-salon-messagehub\\n" | install -m 644 /dev/stdin /etc/systemd/system/jc-salon-core-sit.service.d/messagehub.conf; systemctl daemon-reload'
- name: 自动发布 Salon SIT
shell: pwsh
env:
SALON_PROD_SSH_PASSWORD: ${{ secrets.SALON_PROD_SSH_PASSWORD }}
SERVER_INFO_JSON: ${{ runner.temp }}/salon-sit/servers.json
run: >-
./docs/scripts/deploy-jayucloud-salon-production.ps1
-Deploy
-SkipDatabaseInit
-AllowSitTarget
-RequireSystemd
-PackageDirectory "artifacts/release"
-ServerInfoJsonPath "$env:SERVER_INFO_JSON"
-SshPassword "$env:SALON_PROD_SSH_PASSWORD"
-CoreRemoteAppDir "/opt/jc-salon-core-sit"
-GatewayRemoteAppDir "/opt/jc-salon-gateway-sit"
-CorePattern "^sit-app01$"
-GatewayPattern "^sit-app01$"
-CoreServiceName "jc-salon-core-sit"
-GatewayServiceName "jc-salon-gateway-sit"
-CoreHealthPort 181
-GatewayHealthPort 180
-WebTargetName "salon-web-sit"
-WebRemoteDir "$env:WEB_REMOTE_DIR"
-PublicBaseUrl "https://sit.yunail.art"
@@ -0,0 +1,78 @@
name: 测试环境回退上一个版本
"on":
workflow_dispatch:
inputs:
auto_rollback:
description: 是否由自动失败流程触发
required: false
type: boolean
concurrency:
group: release-sit
cancel-in-progress: false
jobs:
rollback:
runs-on: jayucloud
container:
options: >-
-v /opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release
env:
GITHUB_SERVER_URL: http://192.168.5.15:3000
RELEASE_ENVIRONMENT: sit
RELEASE_STORE_ROOT: /salon-release
NACOS_ENVIRONMENT: sit
AUTO_ROLLBACK: ${{ inputs.auto_rollback }}
WEB_TARGET_HOST: 10.66.0.3
WEB_TARGET_PORT: 22
WEB_TARGET_USER: root
WEB_REMOTE_DIR: /opt/jc-salon-frontend-sit
SALON_PROD_SSH_PASSWORD: ${{ secrets.SALON_PROD_SSH_PASSWORD }}
NACOS_SIT_URLS: ${{ secrets.NACOS_SIT_URLS }}
NACOS_SIT_USERNAME: ${{ secrets.NACOS_SIT_USERNAME }}
NACOS_SIT_PASSWORD: ${{ secrets.NACOS_SIT_PASSWORD }}
steps:
- name: 检出回退脚本
shell: bash
env:
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITHUB_SERVER_URL: http://192.168.5.15:3000
run: |
git init .
git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git"
git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$GITHUB_SHA"
git checkout --detach "$GITHUB_SHA"
- name: 读取最近成功版本
shell: bash
run: |
set -euo pipefail
test -f /salon-release/records/sit/latest-success-deploy.json
node - <<'NODE' >> "$GITHUB_ENV"
const fs = require('fs');
const latest = JSON.parse(fs.readFileSync('/salon-release/records/sit/latest-success-deploy.json'));
const id = process.env.AUTO_ROLLBACK === 'true' ? latest.releaseId : latest.previousReleaseId;
if (!id) throw new Error('没有可回退的 SIT 成功版本');
const target = JSON.parse(fs.readFileSync(`/salon-release/records/sit/deploy/${id}.json`));
console.log(`PACKAGE_DIRECTORY=${target.packageDir}`);
console.log(`ROLLBACK_SNAPSHOT_ID=${target.activeSnapshotId}`);
console.log(`ROLLBACK_RELEASE_ID=${target.releaseId}`);
console.log(`NACOS_RELEASE_ID=${target.nacosReleaseId}`);
NODE
- name: 安装 SSH 密码工具
shell: bash
run: apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends sshpass
- name: 恢复 SIT Nacos
shell: bash
env:
NACOS_SNAPSHOT_ID: ${{ env.ROLLBACK_SNAPSHOT_ID }}
NACOS_RELEASE_ID: ${{ env.NACOS_RELEASE_ID }}
AUTO_ROLLBACK: 'true'
NACOS_ROLLBACK_INVALIDATE: 'true'
run: node .gitea/scripts/rollback-nacos.mjs
- name: 执行 SIT 应用回退
shell: pwsh
run: ./docs/scripts/deploy-jayucloud-salon-production.ps1 -Deploy -SkipDatabaseInit -AllowSitTarget -RequireSystemd -PackageDirectory "$env:PACKAGE_DIRECTORY" -SshPassword "$env:SALON_PROD_SSH_PASSWORD" -CoreRemoteAppDir /opt/jc-salon-core-sit -GatewayRemoteAppDir /opt/jc-salon-gateway-sit -CorePattern '^sit-app01$' -GatewayPattern '^sit-app01$' -CoreServiceName jc-salon-core-sit -GatewayServiceName jc-salon-gateway-sit -CoreHealthPort 181 -GatewayHealthPort 180 -WebTargetName salon-web-sit -WebRemoteDir "$env:WEB_REMOTE_DIR" -PublicBaseUrl https://sit.yunail.art
- name: 记录回退后的成功版本
shell: bash
run: node .gitea/scripts/record-rollback.mjs
@@ -0,0 +1,46 @@
name: 回退开发环境 Nacos 配置
"on":
workflow_dispatch:
inputs:
snapshot_id:
description: 可选快照 ID,留空使用待回退快照
required: false
type: string
auto_rollback:
description: 是否由自动失败流程触发
required: false
type: boolean
concurrency:
group: release-dev
cancel-in-progress: false
jobs:
rollback:
runs-on: jayucloud
container:
options: >-
-v /opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release
env:
NACOS_ENVIRONMENT: dev
RELEASE_STORE_ROOT: /salon-release
NACOS_SNAPSHOT_ID: ${{ inputs.snapshot_id }}
NACOS_DEV_URLS: ${{ secrets.NACOS_DEV_URLS }}
NACOS_DEV_USERNAME: ${{ secrets.NACOS_DEV_USERNAME }}
NACOS_DEV_PASSWORD: ${{ secrets.NACOS_DEV_PASSWORD }}
AUTO_ROLLBACK: ${{ inputs.auto_rollback }}
steps:
- name: 检出回退脚本
shell: bash
env:
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITHUB_SERVER_URL: http://192.168.5.15:3000
run: |
git init .
git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git"
git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$GITHUB_SHA"
git checkout --detach "$GITHUB_SHA"
- name: 恢复并校验 Nacos
shell: bash
run: AUTO_ROLLBACK=${AUTO_ROLLBACK:-false} node .gitea/scripts/rollback-nacos.mjs
@@ -0,0 +1,57 @@
name: 回退生产环境 Nacos 配置
"on":
workflow_dispatch:
inputs:
snapshot_id:
description: 可选快照 ID,留空使用待回退快照
required: false
type: string
auto_rollback:
description: 是否由自动失败流程触发
required: false
type: boolean
concurrency:
group: release-prod
cancel-in-progress: false
jobs:
rollback:
runs-on: jayucloud
container:
options: >-
-v /opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release
env:
NACOS_ENVIRONMENT: prod
RELEASE_STORE_ROOT: /salon-release
NACOS_SNAPSHOT_ID: ${{ inputs.snapshot_id }}
NACOS_PROD_URLS: ${{ secrets.NACOS_PROD_URLS }}
NACOS_PROD_USERNAME: ${{ secrets.NACOS_PROD_USERNAME }}
NACOS_PROD_PASSWORD: ${{ secrets.NACOS_PROD_PASSWORD }}
NACOS_DR_URLS: ${{ secrets.NACOS_DR_URLS }}
NACOS_DR_USERNAME: ${{ secrets.NACOS_DR_USERNAME }}
NACOS_DR_PASSWORD: ${{ secrets.NACOS_DR_PASSWORD }}
AUTO_ROLLBACK: ${{ inputs.auto_rollback }}
GITHUB_SERVER_URL: http://192.168.5.15:3000
steps:
- name: 检出回退脚本
shell: bash
env:
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITHUB_SERVER_URL: http://192.168.5.15:3000
run: |
git init .
git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git"
git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$GITHUB_SHA"
git checkout --detach "$GITHUB_SHA"
- name: 恢复并校验 Nacos
shell: bash
run: AUTO_ROLLBACK=${AUTO_ROLLBACK:-false} node .gitea/scripts/rollback-nacos.mjs
- name: 触发 PROD 应用恢复
if: inputs.auto_rollback == true
shell: bash
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
AUTO_ROLLBACK: 'true'
run: node .gitea/scripts/dispatch-workflow.mjs prod环境回退上一个版本.yml refs/heads/prod
@@ -0,0 +1,54 @@
name: 回退测试环境 Nacos 配置
"on":
workflow_dispatch:
inputs:
snapshot_id:
description: 可选快照 ID,留空使用待回退快照
required: false
type: string
auto_rollback:
description: 是否由自动失败流程触发
required: false
type: boolean
concurrency:
group: release-sit
cancel-in-progress: false
jobs:
rollback:
runs-on: jayucloud
container:
options: >-
-v /opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release
env:
NACOS_ENVIRONMENT: sit
RELEASE_STORE_ROOT: /salon-release
NACOS_SNAPSHOT_ID: ${{ inputs.snapshot_id }}
NACOS_SIT_URLS: ${{ secrets.NACOS_SIT_URLS }}
NACOS_SIT_USERNAME: ${{ secrets.NACOS_SIT_USERNAME }}
NACOS_SIT_PASSWORD: ${{ secrets.NACOS_SIT_PASSWORD }}
AUTO_ROLLBACK: ${{ inputs.auto_rollback }}
GITHUB_SERVER_URL: http://192.168.5.15:3000
steps:
- name: 检出回退脚本
shell: bash
env:
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITHUB_SERVER_URL: http://192.168.5.15:3000
run: |
git init .
git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git"
git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$GITHUB_SHA"
git checkout --detach "$GITHUB_SHA"
- name: 恢复并校验 Nacos
shell: bash
run: AUTO_ROLLBACK=${AUTO_ROLLBACK:-false} node .gitea/scripts/rollback-nacos.mjs
- name: 触发 SIT 应用恢复
if: inputs.auto_rollback == true
shell: bash
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
AUTO_ROLLBACK: 'true'
run: node .gitea/scripts/dispatch-workflow.mjs sit环境回退上一个版本.yml refs/heads/sit
@@ -0,0 +1,43 @@
name: 环境分支晋级检查
on:
pull_request_target:
branches:
- sit
- prod
jobs:
validate-source:
name: environment-promotion-source
runs-on: jayucloud
steps:
- name: 校验环境分支晋级链路
shell: bash
env:
TARGET_BRANCH: ${{ gitea.base_ref }}
SOURCE_BRANCH: ${{ gitea.head_ref }}
SOURCE_REPOSITORY: ${{ gitea.event.pull_request.head.repo.full_name }}
TARGET_REPOSITORY: ${{ gitea.repository }}
run: |
set -euo pipefail
test -n "$TARGET_BRANCH"
test -n "$SOURCE_BRANCH"
test -n "$SOURCE_REPOSITORY"
test -n "$TARGET_REPOSITORY"
if [[ "$SOURCE_REPOSITORY" != "$TARGET_REPOSITORY" ]]; then
echo "拒绝跨仓库环境晋级:$SOURCE_REPOSITORY -> $TARGET_REPOSITORY"
exit 1
fi
case "$TARGET_BRANCH:$SOURCE_BRANCH" in
sit:dev|prod:sit)
echo "允许环境晋级:$SOURCE_BRANCH -> $TARGET_BRANCH"
;;
*)
echo "拒绝环境晋级:$SOURCE_BRANCH -> $TARGET_BRANCH"
echo "允许链路仅为 dev -> sit -> prod"
exit 1
;;
esac
@@ -0,0 +1,44 @@
name: 自动发布开发环境 Nacos 配置
"on":
push:
branches: [dev]
concurrency:
group: release-dev
cancel-in-progress: false
jobs:
publish:
runs-on: jayucloud
container:
options: >-
-v /opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release
env:
GITHUB_SERVER_URL: http://192.168.5.15:3000
NACOS_ENVIRONMENT: dev
RELEASE_STORE_ROOT: /salon-release
RELEASE_ENVIRONMENT: dev
NACOS_DEV_URLS: ${{ secrets.NACOS_DEV_URLS }}
NACOS_DEV_USERNAME: ${{ secrets.NACOS_DEV_USERNAME }}
NACOS_DEV_PASSWORD: ${{ secrets.NACOS_DEV_PASSWORD }}
steps:
- name: 检出提交
shell: bash
env:
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
test -n "$GITEA_TOKEN"
git init .
git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git"
git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$GITHUB_SHA"
git checkout --detach "$GITHUB_SHA"
- name: 发布并校验 Nacos
shell: bash
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
trap 'AUTO_ROLLBACK=true RELEASE_ENVIRONMENT=dev node .gitea/scripts/dispatch-workflow.mjs rollback-dev-nacos.yml refs/heads/dev || true' ERR
node .gitea/scripts/publish-nacos.mjs
@@ -0,0 +1,52 @@
name: 自动发布生产环境 Nacos
"on":
push:
branches: [prod]
concurrency:
group: release-prod
cancel-in-progress: false
jobs:
publish:
runs-on: jayucloud
container:
options: >-
-v /opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release
env:
GITHUB_SERVER_URL: http://192.168.5.15:3000
NACOS_ENVIRONMENT: prod
RELEASE_STORE_ROOT: /salon-release
RELEASE_ENVIRONMENT: prod
NACOS_PROD_URLS: ${{ secrets.NACOS_PROD_URLS }}
NACOS_PROD_USERNAME: ${{ secrets.NACOS_PROD_USERNAME }}
NACOS_PROD_PASSWORD: ${{ secrets.NACOS_PROD_PASSWORD }}
NACOS_DR_URLS: ${{ secrets.NACOS_DR_URLS }}
NACOS_DR_USERNAME: ${{ secrets.NACOS_DR_USERNAME }}
NACOS_DR_PASSWORD: ${{ secrets.NACOS_DR_PASSWORD }}
steps:
- name: 检出提交
shell: bash
env:
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
git init .
git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git"
git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$GITHUB_SHA"
git checkout --detach "$GITHUB_SHA"
- name: 发布并校验 Nacos
shell: bash
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
trap 'AUTO_ROLLBACK=true RELEASE_ENVIRONMENT=prod node .gitea/scripts/dispatch-workflow.mjs 回退prod环境nacos配置.yml refs/heads/prod || true' ERR
node .gitea/scripts/publish-nacos.mjs
- name: 触发生产部署
shell: bash
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
DISPATCH_INPUT_RELEASE_SHA: ${{ github.sha }}
run: node .gitea/scripts/dispatch-workflow.mjs 自动部署prod环境.yml refs/heads/prod
@@ -0,0 +1,49 @@
name: 自动发布测试环境 Nacos 配置
"on":
push:
branches: [sit]
concurrency:
group: release-sit
cancel-in-progress: false
jobs:
publish:
runs-on: jayucloud
container:
options: >-
-v /opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release
env:
GITHUB_SERVER_URL: http://192.168.5.15:3000
NACOS_ENVIRONMENT: sit
RELEASE_STORE_ROOT: /salon-release
RELEASE_ENVIRONMENT: sit
NACOS_SIT_URLS: ${{ secrets.NACOS_SIT_URLS }}
NACOS_SIT_USERNAME: ${{ secrets.NACOS_SIT_USERNAME }}
NACOS_SIT_PASSWORD: ${{ secrets.NACOS_SIT_PASSWORD }}
steps:
- name: 检出提交
shell: bash
env:
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
git init .
git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git"
git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$GITHUB_SHA"
git checkout --detach "$GITHUB_SHA"
- name: 发布并校验 Nacos
shell: bash
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
trap 'AUTO_ROLLBACK=true RELEASE_ENVIRONMENT=sit node .gitea/scripts/dispatch-workflow.mjs 回退sit环境nacos配置.yml refs/heads/sit || true' ERR
node .gitea/scripts/publish-nacos.mjs
- name: 触发 SIT 部署
shell: bash
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
DISPATCH_INPUT_RELEASE_SHA: ${{ github.sha }}
run: node .gitea/scripts/dispatch-workflow.mjs 自动部署sit环境.yml refs/heads/sit
@@ -0,0 +1,85 @@
name: 自动部署生产环境
"on":
workflow_dispatch:
inputs:
release_sha:
description: 已成功发布 PROD Nacos 的提交 SHA
required: true
type: string
concurrency:
group: release-prod
cancel-in-progress: false
jobs:
deploy:
runs-on: jayucloud
container:
options: >-
-v /opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release
env:
GITHUB_SERVER_URL: http://192.168.5.15:3000
RELEASE_ENVIRONMENT: prod
RELEASE_SHA: ${{ inputs.release_sha || github.sha }}
RELEASE_STORE_ROOT: /salon-release
WEB_TARGET_HOST: 10.66.0.3
WEB_TARGET_PORT: 22
WEB_TARGET_USER: root
WEB_REMOTE_DIR: /opt/jc-salon-frontend
SALON_PROD_SSH_PASSWORD: ${{ secrets.SALON_PROD_SSH_PASSWORD }}
NACOS_PROD_URLS: ${{ secrets.NACOS_PROD_URLS }}
NACOS_PROD_USERNAME: ${{ secrets.NACOS_PROD_USERNAME }}
NACOS_PROD_PASSWORD: ${{ secrets.NACOS_PROD_PASSWORD }}
NACOS_DR_URLS: ${{ secrets.NACOS_DR_URLS }}
NACOS_DR_USERNAME: ${{ secrets.NACOS_DR_USERNAME }}
NACOS_DR_PASSWORD: ${{ secrets.NACOS_DR_PASSWORD }}
steps:
- name: 检出发布提交
shell: bash
env:
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
git init .
git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git"
git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$RELEASE_SHA"
git checkout --detach "$RELEASE_SHA"
- name: 校验 PROD Nacos 发布记录
shell: bash
run: node .gitea/scripts/assert-nacos-release.mjs
- name: 构建并固化 PROD 发布包
shell: pwsh
env:
VITE_API_BASE_URL: https://salon.yunail.art/api
VITE_ADMIN_API_BASE_URL: https://salon.yunail.art/admin/api
run: ./docs/scripts/deploy-jayucloud-salon-production.ps1 -PackageOnly -SkipTests -SkipDatabaseInit
- name: 保存发布包
shell: bash
run: |
set -euo pipefail
package_dir="/salon-release/packages/prod/${RELEASE_SHA}-${GITHUB_RUN_ID}"
mkdir -p "$package_dir"
cp -a artifacts/release/. "$package_dir/"
echo "PACKAGE_DIRECTORY=$package_dir" >> "$GITHUB_ENV"
- name: 安装 SSH 密码工具
shell: bash
run: apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends sshpass
- name: 写入 PROD 目标清单
shell: bash
run: |
mkdir -p "$RUNNER_TEMP/salon-prod"
printf '[{"Name":"core01-01","Host":"192.168.10.24","Port":22,"User":"root","Environment":"prod"},{"Name":"core01-02","Host":"192.168.10.25","Port":22,"User":"root","Environment":"prod"},{"Name":"core01-03","Host":"192.168.20.16","Port":22,"User":"root","Environment":"prod"},{"Name":"gateway01-01","Host":"192.168.10.26","Port":22,"User":"root","Environment":"prod"},{"Name":"gateway01-02","Host":"192.168.10.27","Port":22,"User":"root","Environment":"prod"},{"Name":"gateway01-03","Host":"192.168.20.18","Port":22,"User":"root","Environment":"prod"},{"Name":"salon-web","Host":"%s","Port":%s,"User":"%s","Environment":"prod"}]\n' "$WEB_TARGET_HOST" "$WEB_TARGET_PORT" "$WEB_TARGET_USER" > "$RUNNER_TEMP/salon-prod/servers.json"
- name: 执行 PROD 部署
shell: pwsh
run: ./docs/scripts/deploy-jayucloud-salon-production.ps1 -Deploy -SkipDatabaseInit -RequireSystemd -PackageDirectory "$env:PACKAGE_DIRECTORY" -ServerInfoJsonPath "$env:RUNNER_TEMP/salon-prod/servers.json" -SshPassword "$env:SALON_PROD_SSH_PASSWORD" -CoreRemoteAppDir /opt/jc-salon-core -GatewayRemoteAppDir /opt/jc-salon-gateway -CorePattern '^core01-' -GatewayPattern '^gateway01-' -CoreServiceName jc-salon-core -GatewayServiceName jc-salon-gateway -WebTargetName salon-web -WebRemoteDir "$env:WEB_REMOTE_DIR" -PublicBaseUrl https://salon.yunail.art
- name: 记录成功部署
shell: bash
run: node .gitea/scripts/record-deploy.mjs
- name: 部署失败自动回退
if: failure()
shell: bash
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
AUTO_ROLLBACK: 'true'
run: node .gitea/scripts/dispatch-workflow.mjs prod环境回退上一个版本.yml refs/heads/prod
@@ -0,0 +1,82 @@
name: 自动部署测试环境
"on":
workflow_dispatch:
inputs:
release_sha:
description: 已成功发布 SIT Nacos 的提交 SHA
required: true
type: string
concurrency:
group: release-sit
cancel-in-progress: false
jobs:
deploy:
runs-on: jayucloud
container:
options: >-
-v /opt/software/panel/apps/gitea/act_runner/salon-release:/salon-release
env:
GITHUB_SERVER_URL: http://192.168.5.15:3000
RELEASE_ENVIRONMENT: sit
RELEASE_SHA: ${{ inputs.release_sha || github.sha }}
RELEASE_STORE_ROOT: /salon-release
WEB_TARGET_HOST: 10.66.0.3
WEB_TARGET_PORT: 22
WEB_TARGET_USER: root
WEB_REMOTE_DIR: /opt/jc-salon-frontend-sit
SALON_PROD_SSH_PASSWORD: ${{ secrets.SALON_PROD_SSH_PASSWORD }}
NACOS_SIT_URLS: ${{ secrets.NACOS_SIT_URLS }}
NACOS_SIT_USERNAME: ${{ secrets.NACOS_SIT_USERNAME }}
NACOS_SIT_PASSWORD: ${{ secrets.NACOS_SIT_PASSWORD }}
steps:
- name: 检出发布提交
shell: bash
env:
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
git init .
git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git"
git -c http.extraheader="Authorization: token $GITEA_TOKEN" fetch --no-tags --depth=1 origin "$RELEASE_SHA"
git checkout --detach "$RELEASE_SHA"
- name: 校验 SIT Nacos 发布记录
shell: bash
run: node .gitea/scripts/assert-nacos-release.mjs
- name: 构建 SIT 发布包
shell: pwsh
env:
VITE_API_BASE_URL: https://sit.yunail.art/api
VITE_ADMIN_API_BASE_URL: https://sit.yunail.art/admin/api
run: ./docs/scripts/deploy-jayucloud-salon-production.ps1 -PackageOnly -SkipTests -SkipDatabaseInit
- name: 持久化已校验发布包
shell: bash
run: |
set -euo pipefail
package_dir="/salon-release/packages/sit/${RELEASE_SHA}-${GITHUB_RUN_ID}"
mkdir -p "$package_dir"
cp -a artifacts/release/. "$package_dir/"
echo "PACKAGE_DIRECTORY=$package_dir" >> "$GITHUB_ENV"
- name: 安装 SSH 密码工具
shell: bash
run: apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends sshpass
- name: 写入 SIT 目标清单
shell: bash
run: |
mkdir -p "$RUNNER_TEMP/salon-sit"
printf '[{"Name":"sit-app01","Host":"192.168.10.15","Port":22,"User":"root","Purpose":"Salon SIT Core/Gateway","Environment":"sit"},{"Name":"salon-web-sit","Host":"%s","Port":%s,"User":"%s","Purpose":"Salon SIT NGINX","Environment":"sit"}]\n' "$WEB_TARGET_HOST" "$WEB_TARGET_PORT" "$WEB_TARGET_USER" > "$RUNNER_TEMP/salon-sit/servers.json"
- name: 执行 SIT 部署
shell: pwsh
run: ./docs/scripts/deploy-jayucloud-salon-production.ps1 -Deploy -SkipDatabaseInit -AllowSitTarget -RequireSystemd -PackageDirectory "$env:PACKAGE_DIRECTORY" -ServerInfoJsonPath "$env:RUNNER_TEMP/salon-sit/servers.json" -SshPassword "$env:SALON_PROD_SSH_PASSWORD" -CoreRemoteAppDir /opt/jc-salon-core-sit -GatewayRemoteAppDir /opt/jc-salon-gateway-sit -CorePattern '^sit-app01$' -GatewayPattern '^sit-app01$' -CoreServiceName jc-salon-core-sit -GatewayServiceName jc-salon-gateway-sit -CoreHealthPort 181 -GatewayHealthPort 180 -WebTargetName salon-web-sit -WebRemoteDir "$env:WEB_REMOTE_DIR" -PublicBaseUrl https://sit.yunail.art
- name: 记录成功部署
shell: bash
run: node .gitea/scripts/record-deploy.mjs
- name: 部署失败自动回退
if: failure()
shell: bash
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
AUTO_ROLLBACK: 'true'
run: node .gitea/scripts/dispatch-workflow.mjs sit环境回退上一个版本.yml refs/heads/sit
+1 -1
View File
@@ -268,7 +268,7 @@ jspm_packages/
# Mini program local overrides
WeChatProgram/utils/config.local.js
FingertipDesigner-Admin-Program/utils/config.local.js
JayuCloudArtList-Admin-Program/utils/config.local.js
FM-Wechat-Fronted/utils/config.local.js
# 本地敏感服务器信息
+2 -2
View File
@@ -45,10 +45,10 @@ This project is indexed by GitNexus as **JayuCloud** (22596 symbols, 47343 relat
## Project Workflow Rules
- 每次任务中发现的问题、原因和处理方式都需要记录下来,并在后续相关任务中回顾,避免重复发生。
- 后端修改如果涉及 SQL,不要修改初始化 SQL;必须新增版本变更 SQL。
- 后端修改如果涉及 SQL,默认新增版本变更 SQL;只有负责人明确要求重整初始化基线时,才将已存在的变更合并到初始化 SQL。
- 版本变更 SQL 文件名必须使用中文,体现功能和日期,并且 SQL 内容必须是完整可执行脚本。
- 如果修改涉及配置,必须提供说明文档;说明文档同样按 SQL 文件命名规则使用中文命名、体现功能和日期,并放在 `scripts/` 目录下。
- 当前代码、脚本、配置、SQL 和文档已固定为 `0.0.1` 基线;`scripts/sql/init/FingertipDesigner.sql` 从该版本起冻结为仅空库首次初始化使用,后续 SQL、脚本和配置都必须通过版本迭代文件新增或调整。
- 当前代码、脚本、配置、SQL 和文档已固定为 `0.0.1` 基线;两个端侧初始化 SQL 仅作为空库首次初始化入口,后续 SQL 变更默认使用版本迭代文件,负责人明确要求整合基线时除外。
- 后续涉及脚本、配置、SQL 的任务,必须优先阅读 `scripts/0.0.1版本基线与后续迭代规则_20260628.md`,并在任务记录中写明新增或调整的版本化文件。
- 每次修改代码或者完成任务后,必须整理本次任务相关改动并创建 git 提交;提交信息必须使用中文。
@@ -1,25 +0,0 @@
package com.xiaowang.jacyucloudsalon.core;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableDiscoveryClient
@EnableScheduling
@SpringBootApplication
/**
* Purpose: FingertipDesignerCoreApplication supports FingertipDesignerCoreApplication.java by holding or executing the fingertip designer core application business role.
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
*/
public class FingertipDesignerCoreApplication {
/**
* Purpose: main supports FingertipDesignerCoreApplication.java by holding or executing the main business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public static void main(String[] args) {
SpringApplication.run(FingertipDesignerCoreApplication.class, args);
}
}
@@ -1,25 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.annotation;
import com.xiaowang.jacyucloudsalon.core.support.security.OperationGuardStrategy;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
/**
* Purpose: OperationGuard supports OperationGuard.java by holding or executing the operation guard business role.
* Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state.
*/
public @interface OperationGuard {
String action();
OperationGuardStrategy strategy() default OperationGuardStrategy.REJECT_IF_RUNNING;
int ttlSeconds() default 10;
String message() default "操作进行中,请勿重复点击";
}
@@ -1,19 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
/**
* Purpose: RequirePermission supports RequirePermission.java by holding or executing the require permission business role.
* Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state.
*/
public @interface RequirePermission {
String value() default "";
int requireUserType() default -1;
}
@@ -1,65 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.aspect;
import com.xiaowang.jacyucloudsalon.core.annotation.OperationGuard;
import com.xiaowang.jacyucloudsalon.core.common.Result;
import com.xiaowang.jacyucloudsalon.core.support.security.OperationGuardService;
import com.xiaowang.jacyucloudsalon.core.support.security.OperationGuardStrategy;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.time.Duration;
@Aspect
@Component
@Order(100)
@RequiredArgsConstructor
/**
* Purpose: OperationGuardAspect supports OperationGuardAspect.java by holding or executing the operation guard aspect business role.
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
*/
public class OperationGuardAspect {
/**
* Purpose: operationGuardService supports OperationGuardAspect.java by holding or executing the operation guard service business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private final OperationGuardService operationGuardService;
@Around("@annotation(operationGuard)")
/**
* Purpose: guardOperation supports OperationGuardAspect.java by holding or executing the guard operation business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public Object guardOperation(ProceedingJoinPoint joinPoint, OperationGuard operationGuard) throws Throwable {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (attributes == null) {
return Result.error(500, "无法获取请求信息");
}
HttpServletRequest request = attributes.getRequest();
OperationGuardService.GuardHandle handle = operationGuardService.tryAcquire(
request,
operationGuard.action(),
Duration.ofSeconds(Math.max(1, operationGuard.ttlSeconds()))
);
if (!handle.acquired()) {
if (operationGuard.strategy() == OperationGuardStrategy.NOOP_IF_DUPLICATE) {
return Result.success();
}
return Result.error(409, operationGuard.message());
}
try {
return joinPoint.proceed();
} finally {
operationGuardService.release(handle);
}
}
}
@@ -1,147 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.aspect;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xiaowang.jacyucloudsalon.core.annotation.RequirePermission;
import com.xiaowang.jacyucloudsalon.core.common.Result;
import com.xiaowang.jacyucloudsalon.core.modules.security.entity.PermissionDO;
import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO;
import com.xiaowang.jacyucloudsalon.core.modules.security.mapper.PermissionMapper;
import com.xiaowang.jacyucloudsalon.core.modules.user.mapper.UserMapper;
import com.xiaowang.jacyucloudsalon.core.modules.security.service.PermissionService;
import com.xiaowang.jacyucloudsalon.core.modules.security.support.PermissionCatalog;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
@Aspect
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
@RequiredArgsConstructor
/**
* Purpose: PermissionAspect supports PermissionAspect.java by holding or executing the permission aspect business role.
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
*/
public class PermissionAspect {
/**
* Purpose: permissionService supports PermissionAspect.java by holding or executing the permission service business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private final PermissionService permissionService;
/**
* Purpose: permissionMapper supports PermissionAspect.java by holding or executing the permission mapper business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private final PermissionMapper permissionMapper;
/**
* Purpose: userMapper supports PermissionAspect.java by holding or executing the user mapper business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private final UserMapper userMapper;
@Around("@annotation(com.xiaowang.jacyucloudsalon.core.annotation.RequirePermission)")
/**
* Purpose: checkPermission supports PermissionAspect.java by holding or executing the check permission business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public Object checkPermission(ProceedingJoinPoint joinPoint) throws Throwable {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (attributes == null) {
return Result.error(403, "无法获取请求信息");
}
HttpServletRequest request = attributes.getRequest();
Long userId = (Long) request.getAttribute("userId");
if (userId == null) {
return Result.error(401, "未登录");
}
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
RequirePermission requirePermission = method.getAnnotation(RequirePermission.class);
if (requirePermission == null) {
return joinPoint.proceed();
}
UserDO userDO = userMapper.selectById(userId);
if (userDO == null) {
return Result.error(404, "用户不存在");
}
String permissionCode = requirePermission.value();
Long currentShopId = parseShopId(request.getAttribute("currentShopId"));
if (Integer.valueOf(4).equals(userDO.getType())
&& currentShopId == null
&& StringUtils.hasText(permissionCode)
&& !PermissionCatalog.isAllowedForPlatformOverview(permissionCode)) {
return Result.error(403, "平台总览模式下仅允许查看店铺业务数据,请勿进行编辑操作");
}
if (Integer.valueOf(4).equals(userDO.getType())
&& currentShopId == null
&& StringUtils.hasText(permissionCode)
&& PermissionCatalog.isAllowedForPlatformOverview(permissionCode)) {
return joinPoint.proceed();
}
boolean hasPermission = !StringUtils.hasText(permissionCode)
|| permissionService.hasPermission(userId, permissionCode);
if (!hasPermission) {
return Result.error(403, buildPermissionDeniedMessage(permissionCode));
}
return joinPoint.proceed();
}
/**
* Purpose: buildPermissionDeniedMessage supports PermissionAspect.java by holding or executing the build permission denied message business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private String buildPermissionDeniedMessage(String permissionCode) {
if (!StringUtils.hasText(permissionCode)) {
return "权限不足";
}
PermissionDO permissionDO = permissionMapper.selectOne(
Wrappers.lambdaQuery(PermissionDO.class)
.eq(PermissionDO::getPermissionCode, permissionCode)
.eq(PermissionDO::getIsDelete, 0)
.last("limit 1")
);
if (permissionDO != null && StringUtils.hasText(permissionDO.getPermissionName())) {
return "权限不足:缺少权限(" + permissionDO.getPermissionName() + " / " + permissionCode + ")";
}
return "权限不足:缺少权限代码 " + permissionCode;
}
/**
* Purpose: parseShopId supports PermissionAspect.java by holding or executing the parse shop id business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private Long parseShopId(Object value) {
if (value instanceof Number number) {
long shopId = number.longValue();
return shopId > 0 ? shopId : null;
}
if (value instanceof String text && StringUtils.hasText(text)) {
try {
long shopId = Long.parseLong(text.trim());
return shopId > 0 ? shopId : null;
} catch (NumberFormatException ignored) {
return null;
}
}
return null;
}
}
@@ -1,39 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.common;
/**
* 业务异常。
*/
public class BusinessException extends RuntimeException {
/**
* Purpose: code supports BusinessException.java by holding or executing the code business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private final Integer code;
public BusinessException(String message) {
this(500, message);
}
public BusinessException(Integer code, String message) {
super(message);
this.code = code;
}
public BusinessException(String message, Throwable cause) {
this(500, message, cause);
}
public BusinessException(Integer code, String message, Throwable cause) {
super(message, cause);
this.code = code;
}
/**
* Purpose: getCode supports BusinessException.java by holding or executing the get code business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public Integer getCode() {
return code;
}
}
@@ -1,155 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.common;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartException;
import javax.validation.ConstraintViolationException;
/**
* 全局异常处理器。
*/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
* Purpose: MAX_UPLOAD_SIZE_BYTES supports GlobalExceptionHandler.java by holding or executing the max upload size bytes business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private static final long MAX_UPLOAD_SIZE_BYTES = 5L * 1024 * 1024;
@ExceptionHandler(MethodArgumentNotValidException.class)
/**
* Purpose: handleMethodArgumentNotValidException supports GlobalExceptionHandler.java by holding or executing the handle method argument not valid exception business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public Result<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
String message = e.getBindingResult().getAllErrors().stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.findFirst()
.orElse("请求参数不合法");
return Result.error(message);
}
@ExceptionHandler(BindException.class)
/**
* Purpose: handleBindException supports GlobalExceptionHandler.java by holding or executing the handle bind exception business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public Result<Void> handleBindException(BindException e) {
String message = e.getBindingResult().getAllErrors().stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.findFirst()
.orElse("请求参数不合法");
return Result.error(message);
}
@ExceptionHandler(ConstraintViolationException.class)
/**
* Purpose: handleConstraintViolationException supports GlobalExceptionHandler.java by holding or executing the handle constraint violation exception business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public Result<Void> handleConstraintViolationException(ConstraintViolationException e) {
String message = e.getConstraintViolations().stream()
.map(violation -> violation.getMessage())
.findFirst()
.orElse("请求参数不合法");
return Result.error(message);
}
@ExceptionHandler(MaxUploadSizeExceededException.class)
/**
* Purpose: handleMaxUploadSizeExceededException supports GlobalExceptionHandler.java by holding or executing the handle max upload size exceeded exception business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public Result<Void> handleMaxUploadSizeExceededException(MaxUploadSizeExceededException e) {
log.warn("上传文件超过限制: {}", e.getMessage());
return Result.error(buildUploadLimitMessage());
}
@ExceptionHandler(MultipartException.class)
/**
* Purpose: handleMultipartException supports GlobalExceptionHandler.java by holding or executing the handle multipart exception business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public Result<Void> handleMultipartException(MultipartException e) {
log.warn("文件上传请求异常: {}", e.getMessage());
return Result.error(buildUploadLimitMessage());
}
@ExceptionHandler(IllegalStateException.class)
/**
* Purpose: handleIllegalStateException supports GlobalExceptionHandler.java by holding or executing the handle illegal state exception business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public Result<Void> handleIllegalStateException(IllegalStateException e) {
if (isUploadLimitException(e)) {
log.warn("上传文件超过限制: {}", e.getMessage());
return Result.error(buildUploadLimitMessage());
}
log.error("非法状态异常", e);
return Result.error(e.getMessage());
}
@ExceptionHandler(BusinessException.class)
/**
* Purpose: handleBusinessException supports GlobalExceptionHandler.java by holding or executing the handle business exception business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public Result<Void> handleBusinessException(BusinessException e) {
log.warn("业务异常: {}", e.getMessage());
return Result.error(e.getCode(), e.getMessage());
}
@ExceptionHandler(RuntimeException.class)
/**
* Purpose: handleRuntimeException supports GlobalExceptionHandler.java by holding or executing the handle runtime exception business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public Result<Void> handleRuntimeException(RuntimeException e) {
log.error("运行时异常", e);
return Result.error(e.getMessage());
}
@ExceptionHandler(Exception.class)
/**
* Purpose: handleException supports GlobalExceptionHandler.java by holding or executing the handle exception business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public Result<Void> handleException(Exception e) {
log.error("系统异常", e);
return Result.error("系统繁忙,请稍后再试");
}
/**
* Purpose: buildUploadLimitMessage supports GlobalExceptionHandler.java by holding or executing the build upload limit message business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private String buildUploadLimitMessage() {
return "上传文件不能超过 " + (MAX_UPLOAD_SIZE_BYTES / 1024 / 1024) + "MB";
}
/**
* Purpose: isUploadLimitException supports GlobalExceptionHandler.java by holding or executing the is upload limit exception business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private boolean isUploadLimitException(Throwable throwable) {
Throwable current = throwable;
while (current != null) {
String message = current.getMessage();
if (message != null && (message.contains("maximum permitted size")
|| message.contains("FileSizeLimitExceededException")
|| message.contains("exceeds its maximum permitted size"))) {
return true;
}
current = current.getCause();
}
return false;
}
}
@@ -1,68 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.common;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* 统一响应结果类
*
* @param <T> 数据类型
* @author xiaowang
* @date 2026-02-12
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result<T> implements Serializable {
/**
* Purpose: code supports Result.java by holding or executing the code business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Integer code;
/**
* Purpose: message supports Result.java by holding or executing the message business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private String message;
/**
* Purpose: data supports Result.java by holding or executing the data business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private T data;
/**
* Purpose: success supports Result.java by holding or executing the success business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public static <T> Result<T> success() {
return new Result<>(200, "操作成功", null);
}
/**
* Purpose: success supports Result.java by holding or executing the success business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public static <T> Result<T> success(T data) {
return new Result<>(200, "操作成功", data);
}
/**
* Purpose: error supports Result.java by holding or executing the error business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public static <T> Result<T> error(String message) {
return new Result<>(500, message, null);
}
/**
* Purpose: error supports Result.java by holding or executing the error business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public static <T> Result<T> error(Integer code, String message) {
return new Result<>(code, message, null);
}
}
@@ -1,16 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.common.dto;
import java.util.Map;
/**
* Purpose: AgreementAwareRequest supports AgreementAwareRequest.java by holding or executing the agreement aware request business role.
* Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state.
*/
public interface AgreementAwareRequest {
Boolean getAgreementAccepted();
Map<String, String> getAgreementVersions();
String getClientType();
}
@@ -1,38 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.common.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 实体类基类
* 提取公共字段,方便后续实体类扩展
*
* @author xiaowang
* @date 2026-02-12
*/
@Data
public abstract class BaseEntity {
/**
* 主键ID
*/
@TableId(type = IdType.ASSIGN_ID)
private Long id;
/**
* 创建时间
*/
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
* 更新时间
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
}
@@ -1,29 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.common.vo;
import lombok.Data;
import java.util.List;
@Data
/**
* PageResultVO is a response VO. Services build it and controllers return it to the frontend.
* Field and parameter names are kept consistent with the frontend/API payload to make tracing easier.
*/
public class PageResultVO<T> {
/**
* Field `list` (List<T>): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private List<T> list;
/**
* Field `total` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long total;
/**
* Field `page` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Integer page;
/**
* Field `size` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Integer size;
}
@@ -1,60 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* 多级缓存配置。
*/
@Data
@Configuration
@ConfigurationProperties(prefix = "fingertip-designer.cache")
public class AppCacheProperties {
/**
* Purpose: localMaxSize supports AppCacheProperties.java by holding or executing the local max size business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private long localMaxSize = 2048;
private CacheSpec productDetail = new CacheSpec(120, 900);
private CacheSpec productList = new CacheSpec(60, 300);
private CacheSpec productSearch = new CacheSpec(60, 300);
private CacheSpec shop = new CacheSpec(180, 900);
private CacheSpec tag = new CacheSpec(300, 1200);
private CacheSpec objectStorageFile = new CacheSpec(300, 1800);
private CacheSpec dashboard = new CacheSpec(30, 90);
@Data
/**
* Purpose: CacheSpec supports AppCacheProperties.java by holding or executing the cache spec business role.
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
*/
public static class CacheSpec {
/**
* Purpose: localTtlSeconds supports AppCacheProperties.java by holding or executing the local ttl seconds business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private long localTtlSeconds;
/**
* Purpose: redisTtlSeconds supports AppCacheProperties.java by holding or executing the redis ttl seconds business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private long redisTtlSeconds;
public CacheSpec() {
}
public CacheSpec(long localTtlSeconds, long redisTtlSeconds) {
this.localTtlSeconds = localTtlSeconds;
this.redisTtlSeconds = redisTtlSeconds;
}
}
}
@@ -1,230 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.config;
import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO;
import com.xiaowang.jacyucloudsalon.core.modules.user.mapper.UserMapper;
import com.xiaowang.jacyucloudsalon.core.support.RequestShopContext;
import com.xiaowang.jacyucloudsalon.core.modules.shop.support.UserShopBindingSupport;
import com.xiaowang.jacyucloudsalon.core.support.security.RequestSignatureService;
import com.xiaowang.jacyucloudsalon.core.support.security.RequestThrottleService;
import com.xiaowang.jacyucloudsalon.core.support.security.UserSessionService;
import com.xiaowang.jacyucloudsalon.core.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
@RequiredArgsConstructor
/**
* Purpose: AuthInterceptor supports AuthInterceptor.java by holding or executing the auth interceptor business role.
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
*/
public class AuthInterceptor implements HandlerInterceptor {
/**
* Purpose: jwtUtil supports AuthInterceptor.java by holding or executing the jwt util business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private final JwtUtil jwtUtil;
/**
* Purpose: userMapper supports AuthInterceptor.java by holding or executing the user mapper business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private final UserMapper userMapper;
/**
* Purpose: userShopBindingSupport supports AuthInterceptor.java by holding or executing the user shop binding support business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private final UserShopBindingSupport userShopBindingSupport;
/**
* Purpose: userSessionService supports AuthInterceptor.java by holding or executing the user session service business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private final UserSessionService userSessionService;
/**
* Purpose: requestSignatureService supports AuthInterceptor.java by holding or executing the request signature service business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private final RequestSignatureService requestSignatureService;
/**
* Purpose: requestThrottleService supports AuthInterceptor.java by holding or executing the request throttle service business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private final RequestThrottleService requestThrottleService;
/**
* Purpose: AUTHORIZATION_HEADER supports AuthInterceptor.java by holding or executing the authorization header business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private static final String AUTHORIZATION_HEADER = "Authorization";
/**
* Purpose: BEARER_PREFIX supports AuthInterceptor.java by holding or executing the bearer prefix business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private static final String BEARER_PREFIX = "Bearer ";
@Override
/**
* Purpose: preHandle supports AuthInterceptor.java by holding or executing the pre handle business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String path = request.getRequestURI();
String authHeader = request.getHeader(AUTHORIZATION_HEADER);
if (authHeader == null || !authHeader.startsWith(BEARER_PREFIX)) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write("{\"code\":401,\"message\":\"未提供认证Token\"}");
return false;
}
String token = authHeader.substring(BEARER_PREFIX.length());
if (!jwtUtil.validateToken(token)) {
writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "Token无效或已过期");
return false;
}
if (!jwtUtil.isAccessToken(token)) {
writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "Token类型错误");
return false;
}
Long userId = jwtUtil.getUserIdFromToken(token);
String account = jwtUtil.getAccountFromToken(token);
Long currentShopId = jwtUtil.getShopIdFromToken(token);
String sessionId = jwtUtil.getSessionIdFromToken(token);
String jti = jwtUtil.getJtiFromToken(token);
if (!userSessionService.isAccessSessionActive(userId, sessionId, jti)) {
writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "登录态已失效,请重新登录");
return false;
}
UserDO currentUser = userMapper.selectById(userId);
if (currentUser == null || Integer.valueOf(1).equals(currentUser.getIsDelete())) {
writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "用户不存在或已失效");
return false;
}
if (currentUser.getStatus() != null && !Integer.valueOf(1).equals(currentUser.getStatus())) {
writeJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, "账号已被禁用");
return false;
}
boolean adminPath = isAdminPath(path);
if (adminPath && (currentUser.getType() == null || currentUser.getType() < 2)) {
writeJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, "无后台访问权限");
return false;
}
boolean canAccessShop = userShopBindingSupport.canUserAccessShop(
userId,
currentShopId,
adminPath,
currentUser.getType()
);
if (!canAccessShop) {
String message = currentShopId == null || currentShopId <= 0
? "当前登录未选择可用店铺,请重新登录"
: (userShopBindingSupport.isShopEnabledIgnoringAuthorization(currentShopId)
&& userShopBindingSupport.isShopAuthorizationExpired(currentShopId)
? "店铺已被冻结"
: "当前登录店铺已停用或账号已失去该店铺访问权限");
writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, message);
return false;
}
if (adminPath
&& !Integer.valueOf(4).equals(currentUser.getType())
&& userShopBindingSupport.isShopAuthorizationExpired(currentShopId)
&& !isExpiredAdminAllowedPath(path)) {
writeJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, "授权已到期,请联系管理员");
return false;
}
if (requiresSignature(request)) {
try {
requestSignatureService.validateRequest(request, token, userId);
} catch (RuntimeException exception) {
writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, exception.getMessage());
return false;
}
}
if (requiresWriteRateLimit(request)) {
try {
requestThrottleService.checkAuthenticatedWrite(request, userId);
} catch (RuntimeException exception) {
writeJsonResponse(response, 429, exception.getMessage());
return false;
}
}
request.setAttribute("userId", userId);
request.setAttribute("account", account);
request.setAttribute("userType", currentUser.getType());
request.setAttribute("accessToken", token);
request.setAttribute("sessionId", sessionId);
request.setAttribute("tokenJti", jti);
request.setAttribute(RequestShopContext.CURRENT_SHOP_ID_ATTRIBUTE, currentShopId);
return true;
}
/**
* Purpose: requiresSignature supports AuthInterceptor.java by holding or executing the requires signature business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private boolean requiresSignature(HttpServletRequest request) {
return requiresWriteRateLimit(request);
}
/**
* Purpose: requiresWriteRateLimit supports AuthInterceptor.java by holding or executing the requires write rate limit business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private boolean requiresWriteRateLimit(HttpServletRequest request) {
String method = request.getMethod();
if (!StringUtils.hasText(method)) {
return false;
}
String normalized = method.toUpperCase();
return !("GET".equals(normalized) || "HEAD".equals(normalized) || "OPTIONS".equals(normalized));
}
/**
* Purpose: isAdminPath supports AuthInterceptor.java by holding or executing the is admin path business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private boolean isAdminPath(String path) {
return path.startsWith("/admin/") || path.startsWith("/order/admin/");
}
/**
* Purpose: isExpiredAdminAllowedPath supports AuthInterceptor.java by holding or executing the is expired admin allowed path business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private boolean isExpiredAdminAllowedPath(String path) {
return path.startsWith("/admin/auth/")
|| path.equals("/admin/user/info")
|| path.equals("/permission/list/user/current")
|| path.equals("/api/permission/list/user/current")
|| path.startsWith("/admin/planning/")
|| path.startsWith("/admin/shops/");
}
/**
* Purpose: writeJsonResponse supports AuthInterceptor.java by holding or executing the write json response business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private void writeJsonResponse(HttpServletResponse response, int status, String message) throws Exception {
response.setStatus(status);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write("{\"code\":" + status + ",\"message\":\"" + message + "\"}");
}
}
@@ -1,24 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* 平台品牌文案配置。
*/
@Data
@Configuration
@ConfigurationProperties(prefix = "fingertip-designer.brand")
public class BrandProperties {
/**
* 短信模板中的平台名称。
*/
private String messageTemplateName = "FingertipDesigner";
/**
* 管理师注册店铺的默认描述。
*/
private String managerRegisterShopDescription = "甲屿店务注册店铺";
}
@@ -1,54 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.config;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import java.util.concurrent.TimeUnit;
@Configuration
/**
* Purpose: HttpClientConfig supports HttpClientConfig.java by holding or executing the http client config business role.
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
*/
public class HttpClientConfig {
@Bean
/**
* Purpose: poolingHttpClientConnectionManager supports HttpClientConfig.java by holding or executing the pooling http client connection manager business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public PoolingHttpClientConnectionManager poolingHttpClientConnectionManager(HttpClientProperties properties) {
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
connectionManager.setMaxTotal(properties.getMaxTotalConnections());
connectionManager.setDefaultMaxPerRoute(properties.getMaxConnectionsPerRoute());
return connectionManager;
}
@Bean
public RestTemplate restTemplate(HttpClientProperties properties,
PoolingHttpClientConnectionManager connectionManager) {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(properties.getConnectTimeoutMs())
.setSocketTimeout(properties.getReadTimeoutMs())
.setConnectionRequestTimeout(properties.getConnectionRequestTimeoutMs())
.build();
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(connectionManager)
.setDefaultRequestConfig(requestConfig)
.disableCookieManagement()
.evictIdleConnections(30, TimeUnit.SECONDS)
.build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
requestFactory.setConnectTimeout(properties.getConnectTimeoutMs());
requestFactory.setReadTimeout(properties.getReadTimeoutMs());
requestFactory.setConnectionRequestTimeout(properties.getConnectionRequestTimeoutMs());
return new RestTemplate(requestFactory);
}
}
@@ -1,45 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Data
@Configuration
@ConfigurationProperties(prefix = "fingertip-designer.http-client")
/**
* Purpose: HttpClientProperties supports HttpClientProperties.java by holding or executing the http client properties business role.
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
*/
public class HttpClientProperties {
/**
* Purpose: connectTimeoutMs supports HttpClientProperties.java by holding or executing the connect timeout ms business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private int connectTimeoutMs = 3000;
/**
* Purpose: readTimeoutMs supports HttpClientProperties.java by holding or executing the read timeout ms business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private int readTimeoutMs = 5000;
/**
* Purpose: connectionRequestTimeoutMs supports HttpClientProperties.java by holding or executing the connection request timeout ms business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private int connectionRequestTimeoutMs = 1000;
/**
* Purpose: maxTotalConnections supports HttpClientProperties.java by holding or executing the max total connections business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private int maxTotalConnections = 200;
/**
* Purpose: maxConnectionsPerRoute supports HttpClientProperties.java by holding or executing the max connections per route business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private int maxConnectionsPerRoute = 50;
}
@@ -1,64 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.config;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.time.LocalDateTime;
import java.io.IOException;
import java.time.format.DateTimeFormatter;
@Configuration
/**
* Purpose: JacksonConfig supports JacksonConfig.java by holding or executing the jackson config business role.
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
*/
public class JacksonConfig {
@Bean
/**
* Purpose: longToStringJacksonCustomizer supports JacksonConfig.java by holding or executing the long to string jackson customizer business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public Jackson2ObjectMapperBuilderCustomizer longToStringJacksonCustomizer() {
return builder -> {
// Snowflake IDs are serialized as strings so the web and mini program do not lose precision.
builder.serializerByType(Long.class, ToStringSerializer.instance);
builder.serializerByType(Long.TYPE, ToStringSerializer.instance);
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addDeserializer(LocalDateTime.class, new FlexibleLocalDateTimeDeserializer());
builder.modules(javaTimeModule);
};
}
/**
* Purpose: FlexibleLocalDateTimeDeserializer supports JacksonConfig.java by holding or executing the flexible local date time deserializer business role.
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
*/
private static class FlexibleLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
private static final DateTimeFormatter SPACE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
@Override
/**
* Purpose: deserialize supports JacksonConfig.java by holding or executing the deserialize business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public LocalDateTime deserialize(JsonParser parser, DeserializationContext context) throws IOException {
String value = parser.getValueAsString();
if (value == null || value.trim().isEmpty()) {
return null;
}
String normalized = value.trim();
if (normalized.contains("T")) {
return LocalDateTime.parse(normalized);
}
return LocalDateTime.parse(normalized, SPACE_FORMATTER);
}
}
}
@@ -1,44 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* JWT 配置。
*/
@Data
@Configuration
@ConfigurationProperties(prefix = "fingertip-designer.security.jwt")
public class JwtProperties {
/**
* HS512 密钥,生产环境请通过 Nacos 覆盖。
*/
private String secret = "fingertip-designer-secret-key-for-jwt-token-generation-2026-must-be-at-least-512-bits-long-for-hs512-algorithm-security-requirements";
/**
* Token 发行者。
*/
private String issuer = "fingertip-designer";
/**
* AccessToken 有效期,单位秒。
*/
private long accessTokenExpirationSeconds = 2 * 60 * 60;
/**
* 记住登录 AccessToken 有效期,单位秒。
*/
private long rememberMeAccessTokenExpirationSeconds = 7 * 24 * 60 * 60;
/**
* RefreshToken 有效期,单位秒。
*/
private long refreshTokenExpirationSeconds = 7 * 24 * 60 * 60;
/**
* 时钟偏移容忍,单位秒。
*/
private long clockSkewSeconds = 30;
}
@@ -1,33 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Data
@Configuration
@ConfigurationProperties(prefix = "fingertip-designer.security.login-lock")
/**
* Purpose: LoginLockProperties supports LoginLockProperties.java by holding or executing the login lock properties business role.
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
*/
public class LoginLockProperties {
/**
* Purpose: maxFailures supports LoginLockProperties.java by holding or executing the max failures business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private int maxFailures = 5;
/**
* Purpose: windowSeconds supports LoginLockProperties.java by holding or executing the window seconds business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private long windowSeconds = 600;
/**
* Purpose: lockSeconds supports LoginLockProperties.java by holding or executing the lock seconds business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private long lockSeconds = 900;
}
@@ -1,87 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.xiaowang.jacyucloudsalon.core.support.id.TimeOrderedSnowflakeIdGenerator;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* MyBatis-Plus配置类
* 配置分页、乐观锁和防止全表更新等插件
*
* @author xiaowang
* @date 2026-02-12
*/
@Configuration
@MapperScan({
"com.xiaowang.fingertipdesigner.core.modules.artist.mapper",
"com.xiaowang.fingertipdesigner.core.modules.auth.mapper",
"com.xiaowang.fingertipdesigner.core.modules.content.mapper",
"com.xiaowang.fingertipdesigner.core.modules.file.mapper",
"com.xiaowang.fingertipdesigner.core.modules.integration.mapper",
"com.xiaowang.fingertipdesigner.core.modules.inventory.mapper",
"com.xiaowang.fingertipdesigner.core.modules.marketing.mapper",
"com.xiaowang.fingertipdesigner.core.modules.message.mapper",
"com.xiaowang.fingertipdesigner.core.modules.order.mapper",
"com.xiaowang.fingertipdesigner.core.modules.payment.mapper",
"com.xiaowang.fingertipdesigner.core.modules.planning.mapper",
"com.xiaowang.fingertipdesigner.core.modules.product.mapper",
"com.xiaowang.fingertipdesigner.core.modules.security.mapper",
"com.xiaowang.fingertipdesigner.core.modules.shop.mapper",
"com.xiaowang.fingertipdesigner.core.modules.system.mapper",
"com.xiaowang.fingertipdesigner.core.modules.user.mapper"
})
public class MyBatisPlusConfig {
/**
* 配置MyBatis-Plus插件
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// 1. 分页插件
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
// 2. 乐观锁插件
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
// 3. 防止全表更新与删除插件
interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
return interceptor;
}
@Bean
/**
* Purpose: identifierGenerator supports MyBatisPlusConfig.java by holding or executing the identifier generator business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public IdentifierGenerator identifierGenerator(TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator) {
return new IdentifierGenerator() {
@Override
/**
* Purpose: nextId supports MyBatisPlusConfig.java by holding or executing the next id business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public Number nextId(Object entity) {
return snowflakeIdGenerator.nextId();
}
@Override
/**
* Purpose: nextUUID supports MyBatisPlusConfig.java by holding or executing the next uuid business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public String nextUUID(Object entity) {
return snowflakeIdGenerator.nextIdString();
}
};
}
}
@@ -1,41 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.config;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
/**
* MyBatis-Plus 自动填充配置
* 用于自动填充实体类中的创建时间、更新时间等字段
*
* @author xiaowang
* @date 2026-02-12
*/
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
/**
* Purpose: insertFill supports MyMetaObjectHandler.java by holding or executing the insert fill business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public void insertFill(MetaObject metaObject) {
log.info("start insert fill ....");
this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
}
@Override
/**
* Purpose: updateFill supports MyMetaObjectHandler.java by holding or executing the update fill business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public void updateFill(MetaObject metaObject) {
log.info("start update fill ....");
this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
}
}
@@ -1,50 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;
@Data
@Component
@Validated
@ConfigurationProperties(prefix = "object-storage")
public class ObjectStorageProperties {
@NotEmpty
private List<String> providerOrder = Arrays.asList("MINIO", "QINIU_KODO", "ALIYUN_OSS");
@NotEmpty
private List<String> replicaRequiredProviders = Arrays.asList("MINIO", "QINIU_KODO", "ALIYUN_OSS");
private String primaryProvider;
private String backupProvider;
@NotNull
@Min(1)
private Integer signedUrlExpireMinutes;
@NotBlank
private String backupQueueName;
@NotBlank
private String backupExchangeName;
@NotBlank
private String backupRoutingKey;
@NotNull
@Min(1)
private Integer backupRetryBatchLimit;
@NotBlank
private String backupRetryCron;
}
@@ -1,59 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.config;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@RequiredArgsConstructor
public class RabbitMQConfig {
public static final String EXAMPLE_QUEUE = "fingertip-designer.example.queue";
public static final String EXAMPLE_EXCHANGE = "fingertip-designer.example.exchange";
public static final String EXAMPLE_ROUTING_KEY = "fingertip-designer.example.routing.key";
private final ObjectStorageProperties objectStorageProperties;
@Bean
public MessageConverter jsonMessageConverter() {
return new Jackson2JsonMessageConverter();
}
@Bean
public Queue exampleQueue() {
return new Queue(EXAMPLE_QUEUE, true);
}
@Bean
public DirectExchange exampleExchange() {
return new DirectExchange(EXAMPLE_EXCHANGE);
}
@Bean
public Binding exampleBinding() {
return BindingBuilder.bind(exampleQueue()).to(exampleExchange()).with(EXAMPLE_ROUTING_KEY);
}
@Bean
public Queue objectStorageBackupQueue() {
return new Queue(objectStorageProperties.getBackupQueueName(), true);
}
@Bean
public DirectExchange objectStorageBackupExchange() {
return new DirectExchange(objectStorageProperties.getBackupExchangeName(), true, false);
}
@Bean
public Binding objectStorageBackupBinding() {
return BindingBuilder.bind(objectStorageBackupQueue())
.to(objectStorageBackupExchange())
.with(objectStorageProperties.getBackupRoutingKey());
}
}
@@ -1,56 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* 限流配置。
*/
@Data
@Configuration
@ConfigurationProperties(prefix = "fingertip-designer.security.rate-limit")
public class RateLimitProperties {
private LimitRule login = new LimitRule(10, 60);
private LimitRule register = new LimitRule(5, 300);
private LimitRule sendCode = new LimitRule(5, 60);
private LimitRule resetPassword = new LimitRule(5, 600);
private LimitRule wechatMiniLogin = new LimitRule(10, 60);
private LimitRule agreementRead = new LimitRule(60, 60);
private LimitRule authenticatedWrite = new LimitRule(80, 60);
private LimitRule orderCreate = new LimitRule(10, 60);
@Data
/**
* Purpose: LimitRule supports RateLimitProperties.java by holding or executing the limit rule business role.
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
*/
public static class LimitRule {
/**
* Purpose: limit supports RateLimitProperties.java by holding or executing the limit business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private int limit;
/**
* Purpose: windowSeconds supports RateLimitProperties.java by holding or executing the window seconds business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private long windowSeconds;
public LimitRule() {
}
public LimitRule(int limit, long windowSeconds) {
this.limit = limit;
this.windowSeconds = windowSeconds;
}
}
}
@@ -1,56 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* Redis配置类
*
* @author xiaowang
* @date 2026-02-12
*/
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
@Bean
/**
* Purpose: redisTemplate supports RedisConfig.java by holding or executing the redis template business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
// 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key采用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
// hash的key也采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
// value序列化方式采用jackson
template.setValueSerializer(jackson2JsonRedisSerializer);
// hash的value序列化方式采用jackson
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
@@ -1,29 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* 请求签名配置。
*/
@Data
@Configuration
@ConfigurationProperties(prefix = "fingertip-designer.security.signature")
public class RequestSignatureProperties {
/**
* 是否启用签名校验。
*/
private boolean enabled = true;
/**
* 时间窗口,单位秒。
*/
private long windowSeconds = 300;
/**
* nonce 额外保留时间,单位秒。
*/
private long nonceRetentionSeconds = 600;
}
@@ -1,34 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.config;
import org.springframework.stereotype.Component;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
/**
* Purpose: SecurityHeadersFilter supports SecurityHeadersFilter.java by holding or executing the security headers filter business role.
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
*/
public class SecurityHeadersFilter implements Filter {
@Override
/**
* Purpose: doFilter supports SecurityHeadersFilter.java by holding or executing the do filter business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if (response instanceof HttpServletResponse httpResponse) {
httpResponse.setHeader("X-Content-Type-Options", "nosniff");
httpResponse.setHeader("X-Frame-Options", "DENY");
httpResponse.setHeader("Referrer-Policy", "strict-origin-when-cross-origin");
httpResponse.setHeader("Content-Security-Policy", "default-src 'self'; img-src 'self' data: blob: http: https:; style-src 'self' 'unsafe-inline'; script-src 'self'; connect-src 'self' http: https:");
}
chain.doFilter(request, response);
}
}
@@ -1,33 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Data
@Configuration
@ConfigurationProperties(prefix = "fingertip-designer.slow-request")
/**
* Purpose: SlowRequestLogProperties supports SlowRequestLogProperties.java by holding or executing the slow request log properties business role.
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
*/
public class SlowRequestLogProperties {
/**
* Purpose: enabled supports SlowRequestLogProperties.java by holding or executing the enabled business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private boolean enabled = true;
/**
* Purpose: thresholdMs supports SlowRequestLogProperties.java by holding or executing the threshold ms business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private long thresholdMs = 300;
/**
* Purpose: logResponseHeaderRequestId supports SlowRequestLogProperties.java by holding or executing the log response header request id business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private boolean logResponseHeaderRequestId = true;
}
@@ -1,172 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
@Component
/**
* Purpose: SlowRequestLoggingInterceptor supports SlowRequestLoggingInterceptor.java by holding or executing the slow request logging interceptor business role.
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
*/
public class SlowRequestLoggingInterceptor implements HandlerInterceptor {
/**
* Purpose: REQUEST_ID_HEADER supports SlowRequestLoggingInterceptor.java by holding or executing the request id header business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
public static final String REQUEST_ID_HEADER = "X-Request-Id";
private static final String START_TIME_ATTRIBUTE = SlowRequestLoggingInterceptor.class.getName() + ".startTime";
private static final Logger SLOW_REQUEST_LOGGER = LoggerFactory.getLogger("core-slow");
/**
* Purpose: properties supports SlowRequestLoggingInterceptor.java by holding or executing the properties business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private final SlowRequestLogProperties properties;
public SlowRequestLoggingInterceptor(SlowRequestLogProperties properties) {
this.properties = properties;
}
@Override
/**
* Purpose: preHandle supports SlowRequestLoggingInterceptor.java by holding or executing the pre handle business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
String requestId = resolveRequestId(request);
request.setAttribute(REQUEST_ID_HEADER, requestId);
if (properties.isLogResponseHeaderRequestId()) {
response.setHeader(REQUEST_ID_HEADER, requestId);
}
if (properties.isEnabled()) {
request.setAttribute(START_TIME_ATTRIBUTE, System.nanoTime());
}
return true;
}
@Override
/**
* Purpose: afterCompletion supports SlowRequestLoggingInterceptor.java by holding or executing the after completion business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) {
if (!properties.isEnabled()) {
return;
}
Object startTimeValue = request.getAttribute(START_TIME_ATTRIBUTE);
if (!(startTimeValue instanceof Long)) {
return;
}
long durationMs = Math.max(0L, (System.nanoTime() - (Long) startTimeValue) / 1_000_000L);
if (durationMs < properties.getThresholdMs()) {
return;
}
String requestId = (String) request.getAttribute(REQUEST_ID_HEADER);
String bestMatchingPattern = toStringValue(request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE));
String controllerMethod = resolveControllerMethod(handler);
String exceptionClass = ex == null ? "" : ex.getClass().getSimpleName();
SLOW_REQUEST_LOGGER.warn(
"requestId={} method={} uri={} query={} bestMatchingPattern={} controllerMethod={} status={} durationMs={} userId={} userType={} shopId={} clientIp={} contentLength={} exceptionClass={}",
sanitize(requestId),
request.getMethod(),
request.getRequestURI(),
sanitize(request.getQueryString()),
sanitize(bestMatchingPattern),
sanitize(controllerMethod),
response.getStatus(),
durationMs,
castLong(request.getAttribute("userId")),
castInteger(request.getAttribute("userType")),
castLong(request.getAttribute("currentShopId")),
resolveClientIp(request),
request.getContentLengthLong(),
sanitize(exceptionClass)
);
}
/**
* Purpose: resolveRequestId supports SlowRequestLoggingInterceptor.java by holding or executing the resolve request id business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private String resolveRequestId(HttpServletRequest request) {
String requestId = request.getHeader(REQUEST_ID_HEADER);
return StringUtils.hasText(requestId) ? requestId.trim() : UUID.randomUUID().toString().replace("-", "");
}
/**
* Purpose: resolveControllerMethod supports SlowRequestLoggingInterceptor.java by holding or executing the resolve controller method business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private String resolveControllerMethod(Object handler) {
if (handler instanceof HandlerMethod handlerMethod) {
return handlerMethod.getBeanType().getSimpleName() + "#" + handlerMethod.getMethod().getName();
}
return "";
}
/**
* Purpose: resolveClientIp supports SlowRequestLoggingInterceptor.java by holding or executing the resolve client ip business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private String resolveClientIp(HttpServletRequest request) {
String forwarded = request.getHeader("X-Forwarded-For");
if (StringUtils.hasText(forwarded)) {
return forwarded.split(",")[0].trim();
}
String realIp = request.getHeader("X-Real-IP");
if (StringUtils.hasText(realIp)) {
return realIp.trim();
}
return request.getRemoteAddr();
}
/**
* Purpose: sanitize supports SlowRequestLoggingInterceptor.java by holding or executing the sanitize business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private String sanitize(String value) {
if (!StringUtils.hasText(value)) {
return "";
}
return value.replace('\n', '_').replace('\r', '_');
}
/**
* Purpose: toStringValue supports SlowRequestLoggingInterceptor.java by holding or executing the to string value business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private String toStringValue(Object value) {
return value == null ? "" : value.toString();
}
/**
* Purpose: castLong supports SlowRequestLoggingInterceptor.java by holding or executing the cast long business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private Long castLong(Object value) {
return value instanceof Long ? (Long) value : null;
}
/**
* Purpose: castInteger supports SlowRequestLoggingInterceptor.java by holding or executing the cast integer business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private Integer castInteger(Object value) {
return value instanceof Integer ? (Integer) value : null;
}
}
@@ -1,33 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import java.util.ArrayList;
import java.util.List;
@Data
@Configuration
@ConfigurationProperties(prefix = "fingertip-designer.security.upload")
/**
* Purpose: UploadSecurityProperties supports UploadSecurityProperties.java by holding or executing the upload security properties business role.
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
*/
public class UploadSecurityProperties {
/**
* Purpose: maxSize supports UploadSecurityProperties.java by holding or executing the max size business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private long maxSize = 10 * 1024 * 1024;
private long maxTotalSize = 500L * 1024 * 1024;
private List<String> allowedMimeTypes = new ArrayList<>(List.of(
"image/jpeg",
"image/png",
"image/webp",
"image/gif"
));
}
@@ -1,75 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.config;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@RequiredArgsConstructor
/**
* Purpose: WebMvcConfig supports WebMvcConfig.java by holding or executing the web mvc config business role.
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
*/
public class WebMvcConfig implements WebMvcConfigurer {
/**
* Purpose: authInterceptor supports WebMvcConfig.java by holding or executing the auth interceptor business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private final AuthInterceptor authInterceptor;
/**
* Purpose: slowRequestLoggingInterceptor supports WebMvcConfig.java by holding or executing the slow request logging interceptor business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private final SlowRequestLoggingInterceptor slowRequestLoggingInterceptor;
@Override
/**
* Purpose: addInterceptors supports WebMvcConfig.java by holding or executing the add interceptors business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(slowRequestLoggingInterceptor)
.addPathPatterns("/**")
.order(-100);
registry.addInterceptor(authInterceptor)
.addPathPatterns("/**")
.order(0)
.excludePathPatterns(
"/user/login",
"/user/register",
"/user/check/**",
"/user/refresh-token",
"/user/send-verification-code",
"/user/phone-login",
"/user/wechat-mini/**",
"/user/reset-password-by-phone",
"/legal-agreement/current",
"/legal-agreement/current/**",
"/api/legal-agreement/current",
"/api/legal-agreement/current/**",
"/product/get/**",
"/product/list/**",
"/comment/list/product/**",
"/api/comment/list/product/**",
"/nail-artist/profile/**",
"/nail-artist/*/availability",
"/nail-artist/*/reviews",
"/shop/get/**",
"/shop/trust-profile/**",
"/shop/list",
"/shop/list/public",
"/shop/list/simple",
"/tag/list/all",
"/tag/list/filter-options",
"/file/get-signed-url/**",
"/admin/auth/login",
"/admin/auth/login-shops/**",
"/admin/auth/refresh",
"/error",
"/health/**"
);
}
}
@@ -1,40 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* 微信小程序登录配置。
*/
@Data
@Configuration
@ConfigurationProperties(prefix = "fingertip-designer.wechat.mini")
public class WechatMiniProperties {
/**
* Purpose: appId supports WechatMiniProperties.java by holding or executing the app id business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private String appId;
/**
* Purpose: appSecret supports WechatMiniProperties.java by holding or executing the app secret business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private String appSecret;
/**
* Purpose: code2sessionUrl supports WechatMiniProperties.java by holding or executing the code2session url business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private String code2sessionUrl = "https://api.weixin.qq.com/sns/jscode2session";
/**
* Purpose: phoneNumberUrl supports WechatMiniProperties.java by holding or executing the phone number url business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private String phoneNumberUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber";
/**
* Purpose: accessTokenBufferSeconds supports WechatMiniProperties.java by holding or executing the access token buffer seconds business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Integer accessTokenBufferSeconds = 60;
}
@@ -1,60 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.filter;
import com.xiaowang.jacyucloudsalon.core.support.security.CachedBodyHttpServletRequest;
import com.xiaowang.jacyucloudsalon.core.support.security.RequestSignatureService;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 缓存 JSON 请求体,供签名校验复用。
*/
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class RequestBodyCacheFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
if (!shouldWrap(request)) {
filterChain.doFilter(request, response);
return;
}
byte[] body = StreamUtils.copyToByteArray(request.getInputStream());
CachedBodyHttpServletRequest wrappedRequest = new CachedBodyHttpServletRequest(request, body);
wrappedRequest.setAttribute(RequestSignatureService.REQUEST_BODY_ATTRIBUTE, body);
filterChain.doFilter(wrappedRequest, response);
}
/**
* Purpose: shouldWrap supports RequestBodyCacheFilter.java by holding or executing the should wrap business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private boolean shouldWrap(HttpServletRequest request) {
String method = request.getMethod();
if (!StringUtils.hasText(method)) {
return false;
}
String normalizedMethod = method.toUpperCase();
if (!("POST".equals(normalizedMethod) || "PUT".equals(normalizedMethod) || "PATCH".equals(normalizedMethod) || "DELETE".equals(normalizedMethod))) {
return false;
}
String contentType = request.getContentType();
if (!StringUtils.hasText(contentType)) {
return false;
}
String normalizedType = contentType.toLowerCase();
return normalizedType.contains("application/json");
}
}
@@ -1,450 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.analytics.controller.front;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.xiaowang.jacyucloudsalon.core.annotation.RequirePermission;
import com.xiaowang.jacyucloudsalon.core.common.Result;
import com.xiaowang.jacyucloudsalon.core.config.AppCacheProperties;
import com.xiaowang.jacyucloudsalon.core.modules.content.entity.CommentDO;
import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderDO;
import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderItemDO;
import com.xiaowang.jacyucloudsalon.core.modules.product.entity.ProductDO;
import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO;
import com.xiaowang.jacyucloudsalon.core.modules.content.mapper.CommentMapper;
import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.OrderItemMapper;
import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.OrderMapper;
import com.xiaowang.jacyucloudsalon.core.modules.product.mapper.ProductMapper;
import com.xiaowang.jacyucloudsalon.core.modules.shop.mapper.ShopMapper;
import com.xiaowang.jacyucloudsalon.core.modules.user.mapper.UserMapper;
import com.xiaowang.jacyucloudsalon.core.modules.analytics.service.OperationsAnalyticsService;
import com.xiaowang.jacyucloudsalon.core.modules.security.support.AdminScopeHelper;
import com.xiaowang.jacyucloudsalon.core.modules.order.support.OrderStatus;
import com.xiaowang.jacyucloudsalon.core.modules.shop.support.UserShopBindingSupport;
import com.xiaowang.jacyucloudsalon.core.support.cache.MultiLevelCacheService;
import com.xiaowang.jacyucloudsalon.core.modules.analytics.vo.DashboardStatsVO;
import com.xiaowang.jacyucloudsalon.core.modules.product.vo.HotProductVO;
import com.xiaowang.jacyucloudsalon.core.modules.analytics.vo.OperationsAnalyticsVO;
import com.xiaowang.jacyucloudsalon.core.modules.analytics.vo.RecentActivityVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/admin/dashboard")
@RequiredArgsConstructor
/**
* DashboardController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called.
* Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class.
*/
public class DashboardController {
/**
* Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final UserMapper userMapper;
/**
* Variable `productMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final ProductMapper productMapper;
/**
* Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final ShopMapper shopMapper;
/**
* Variable `commentMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final CommentMapper commentMapper;
/**
* Variable `orderMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final OrderMapper orderMapper;
/**
* Variable `orderItemMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final OrderItemMapper orderItemMapper;
/**
* Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final AdminScopeHelper adminScopeHelper;
/**
* Variable `userShopBindingSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final UserShopBindingSupport userShopBindingSupport;
/**
* Variable `multiLevelCacheService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final MultiLevelCacheService multiLevelCacheService;
/**
* Variable `appCacheProperties`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final AppCacheProperties appCacheProperties;
private final OperationsAnalyticsService operationsAnalyticsService;
@GetMapping("/stats")
@RequirePermission("dashboard:view")
/**
* Load data by the supplied parameter.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param request parameter `request` supplied by the caller
* @return Result<DashboardStatsVO> result consumed by the caller or returned to the frontend
*/
public Result<DashboardStatsVO> getDashboardStats(HttpServletRequest request) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
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);
}
@GetMapping("/analytics")
@RequirePermission("analytics:view")
public Result<OperationsAnalyticsVO> getAnalytics(HttpServletRequest request) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
Long shopIdScope = resolveShopScope(currentUser);
Long artistScope = currentUser != null && Integer.valueOf(3).equals(currentUser.getType()) ? currentUser.getId() : null;
return Result.success(operationsAnalyticsService.getDashboardAnalytics(shopIdScope, artistScope));
}
/**
* Run business method `buildDashboardStats`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param currentUser parameter `currentUser` supplied by the caller
* @param shopIdScope parameter `shopIdScope` supplied by the caller
* @return private DashboardStatsVO result consumed by the caller or returned to the frontend
*/
private DashboardStatsVO buildDashboardStats(UserDO currentUser, Long shopIdScope) {
DashboardStatsVO stats = new DashboardStatsVO();
Long artistScope = currentUser != null && Integer.valueOf(3).equals(currentUser.getType()) ? currentUser.getId() : null;
if (currentUser != null) {
// 根据用户类型显示不同的数据
if (currentUser.getType() == 4) { // 管理员
stats.setTotalUsers(userMapper.selectCount(null));
stats.setTotalProducts(productMapper.selectCount(null));
stats.setTotalShops(shopMapper.selectCount(null));
stats.setTodayOrders(getTodayOrders(null));
stats.setTotalCustomers(countUsers(null, 0, null, null));
stats.setTotalArtists(countUsers(null, 3, null, null));
} else { // 店长或美甲师
Long shopId = currentUser.getShopId();
if (shopId != null) {
shopIdScope = shopId;
// 只显示当前店铺的数据
stats.setTotalUsers(userShopBindingSupport.countUsersByShopId(shopId, false));
stats.setTotalProducts(productMapper.selectCount(new LambdaQueryWrapper<ProductDO>().eq(ProductDO::getShopId, shopId)));
stats.setTotalShops(0L); // 非管理员不显示店铺数量
stats.setTodayOrders(getTodayOrders(shopId));
stats.setTotalCustomers(countUsers(shopId, 0, null, null));
stats.setTotalArtists(countUsers(shopId, 3, null, null));
} else {
// 没有店铺ID的情况
stats.setTotalUsers(0L);
stats.setTotalProducts(0L);
stats.setTotalShops(0L);
stats.setTodayOrders(0L);
stats.setTotalCustomers(0L);
stats.setTotalArtists(0L);
}
}
} else {
// 无法获取用户信息的情况
stats.setTotalUsers(0L);
stats.setTotalProducts(0L);
stats.setTotalShops(0L);
stats.setTodayOrders(0L);
stats.setTotalCustomers(0L);
stats.setTotalArtists(0L);
}
LocalDateTime todayStart = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0);
LocalDateTime weekStart = todayStart.minusDays(6);
stats.setTotalOrderAmount(sumOrderAmount(shopIdScope, artistScope, null, null));
stats.setTodayOrderAmount(sumOrderAmount(shopIdScope, artistScope, todayStart, null));
stats.setWeekOrderAmount(sumOrderAmount(shopIdScope, artistScope, weekStart, null));
stats.setNewCustomersToday(countUsers(shopIdScope, 0, todayStart, null));
stats.setNewCustomers7Days(countUsers(shopIdScope, 0, weekStart, null));
stats.setNewOrders7Days(countOrders(shopIdScope, artistScope, null, weekStart, null));
long priceConfirmingOrders = countOrders(shopIdScope, artistScope, OrderStatus.PRICE_CONFIRMING.getCode(), null, null);
long pendingServiceOrders = countOrders(shopIdScope, artistScope, OrderStatus.PENDING_SERVICE.getCode(), null, null);
stats.setPendingOrders(priceConfirmingOrders + pendingServiceOrders);
stats.setCompletedOrders(countOrders(shopIdScope, artistScope, OrderStatus.COMPLETED.getCode(), null, null));
stats.setHotProducts(getHotProducts(shopIdScope));
stats.setRecentActivities(getRecentActivities(shopIdScope));
return stats;
}
/**
* Run business method `resolveShopScope`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param currentUser parameter `currentUser` supplied by the caller
* @return private Long result consumed by the caller or returned to the frontend
*/
private Long resolveShopScope(UserDO currentUser) {
if (currentUser == null || currentUser.getType() == 4) {
return null;
}
return currentUser.getShopId();
}
/**
* Purpose: countUsers supports DashboardController.java by holding or executing the count users business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private Long countUsers(Long shopId, Integer type, LocalDateTime from, LocalDateTime to) {
LambdaQueryWrapper<UserDO> wrapper = new LambdaQueryWrapper<>();
if (type != null) {
wrapper.eq(UserDO::getType, type);
}
if (from != null) {
wrapper.ge(UserDO::getCreateTime, from);
}
if (to != null) {
wrapper.le(UserDO::getCreateTime, to);
}
if (shopId != null) {
List<Long> userIds = userShopBindingSupport.listUserIdsByShopId(shopId, false);
if (userIds.isEmpty()) {
return 0L;
}
wrapper.in(UserDO::getId, userIds);
}
return userMapper.selectCount(wrapper);
}
/**
* Purpose: countOrders supports DashboardController.java by holding or executing the count orders business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private Long countOrders(Long shopId, Long artistId, Integer status, LocalDateTime from, LocalDateTime to) {
return (long) listScopedOrders(shopId, artistId, status, from, to).size();
}
/**
* Purpose: sumOrderAmount supports DashboardController.java by holding or executing the sum order amount business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private BigDecimal sumOrderAmount(Long shopId, Long artistId, LocalDateTime from, LocalDateTime to) {
return listScopedOrders(shopId, artistId, null, from, to).stream()
.map(order -> order.getActualAmount() != null ? order.getActualAmount() : order.getTotalAmount())
.filter(amount -> amount != null)
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
/**
* Purpose: listScopedOrders supports DashboardController.java by holding or executing the list scoped orders business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private List<OrderDO> listScopedOrders(Long shopId, Long artistId, Integer status, LocalDateTime from, LocalDateTime to) {
LambdaQueryWrapper<OrderDO> wrapper = new LambdaQueryWrapper<>();
if (shopId != null) {
wrapper.eq(OrderDO::getShopId, shopId);
}
if (status != null) {
wrapper.eq(OrderDO::getStatus, status);
}
if (from != null) {
wrapper.ge(OrderDO::getCreateTime, from);
}
if (to != null) {
wrapper.le(OrderDO::getCreateTime, to);
}
if (artistId != null) {
Set<Long> orderIds = listOrderIdsByArtist(artistId);
if (orderIds.isEmpty()) {
return Collections.emptyList();
}
wrapper.in(OrderDO::getId, orderIds);
}
return orderMapper.selectList(wrapper);
}
/**
* Purpose: listOrderIdsByArtist supports DashboardController.java by holding or executing the list order ids by artist business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private Set<Long> listOrderIdsByArtist(Long artistId) {
List<OrderItemDO> items = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItemDO>()
.select(OrderItemDO::getOrderId)
.eq(OrderItemDO::getArtistId, artistId));
return items.stream()
.map(OrderItemDO::getOrderId)
.filter(id -> id != null)
.collect(Collectors.toCollection(HashSet::new));
}
/**
* Load data by the supplied parameter.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param shopId parameter `shopId` supplied by the caller
* @return private Long result consumed by the caller or returned to the frontend
*/
private Long getTodayOrders(Long shopId) {
// 获取今天的开始时间
LocalDateTime todayStart = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0);
String todayStartStr = todayStart.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
if (shopId != null) {
// 非管理员只查询自己店铺的订单,通过订单商品关联到商品,再关联到店铺
java.util.Map<String, Object> result = orderItemMapper.countTodayOrdersByShopId(shopId, todayStartStr);
return result != null && result.get("count") != null ? Long.valueOf(result.get("count").toString()) : 0L;
} else {
// 管理员查询所有订单
java.util.Map<String, Object> result = orderItemMapper.countTodayOrders(todayStartStr);
return result != null && result.get("count") != null ? Long.valueOf(result.get("count").toString()) : 0L;
}
}
/**
* Load data by the supplied parameter.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param shopId parameter `shopId` supplied by the caller
* @return private List<HotProductVO> result consumed by the caller or returned to the frontend
*/
private List<HotProductVO> getHotProducts(Long shopId) {
// 通过订单商品表统计每个商品的订单数量,按订单数量排序
// 使用SQL查询获取商品及其订单数量
List<Map<String, Object>> productOrderCounts = orderItemMapper.selectMaps(
new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<OrderItemDO>()
.select("product_id, COUNT(*) as order_count")
.groupBy("product_id")
.orderByDesc("order_count")
.last("LIMIT 5")
);
List<HotProductVO> hotProducts = new ArrayList<>();
// 遍历查询结果,获取商品详情
for (Map<String, Object> map : productOrderCounts) {
Long productId = Long.valueOf(map.get("product_id").toString());
ProductDO product = productMapper.selectById(productId);
if (product != null && (shopId == null || shopId.equals(product.getShopId()))) {
HotProductVO vo = new HotProductVO();
BeanUtils.copyProperties(product, vo);
vo.setLikeCount(product.getLikeCount() != null ? product.getLikeCount() : 0);
hotProducts.add(vo);
}
}
// 如果按订单数量查询没有结果,使用点赞数作为备选
if (hotProducts.isEmpty()) {
LambdaQueryWrapper<ProductDO> wrapper = new LambdaQueryWrapper<>();
if (shopId != null) {
wrapper.eq(ProductDO::getShopId, shopId);
}
wrapper.orderByDesc(ProductDO::getLikeCount)
.last("LIMIT 5");
List<ProductDO> products = productMapper.selectList(wrapper);
hotProducts = products.stream().map(product -> {
HotProductVO vo = new HotProductVO();
BeanUtils.copyProperties(product, vo);
vo.setLikeCount(product.getLikeCount() != null ? product.getLikeCount() : 0);
return vo;
}).collect(Collectors.toList());
}
return hotProducts;
}
/**
* Load data by the supplied parameter.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param shopId parameter `shopId` supplied by the caller
* @return private List<RecentActivityVO> result consumed by the caller or returned to the frontend
*/
private List<RecentActivityVO> getRecentActivities(Long shopId) {
List<RecentActivityVO> activities = new ArrayList<>();
LambdaQueryWrapper<UserDO> userWrapper = new LambdaQueryWrapper<>();
if (shopId != null) {
List<Long> userIds = userShopBindingSupport.listUserIdsByShopId(shopId, false);
if (userIds.isEmpty()) {
userWrapper.eq(UserDO::getId, -1L);
} else {
userWrapper.in(UserDO::getId, userIds);
}
}
userWrapper.orderByDesc(UserDO::getCreateTime)
.last("LIMIT 3");
List<UserDO> recentUsers = userMapper.selectList(userWrapper);
for (UserDO user : recentUsers) {
RecentActivityVO vo = new RecentActivityVO();
vo.setId(user.getId());
vo.setType("user");
vo.setTitle("新用户注册");
vo.setDescription("用户\"" + user.getNickname() + "\"注册成功");
vo.setTime(user.getCreateTime());
vo.setColor("");
activities.add(vo);
}
LambdaQueryWrapper<ProductDO> productWrapper = new LambdaQueryWrapper<>();
if (shopId != null) {
productWrapper.eq(ProductDO::getShopId, shopId);
}
productWrapper.orderByDesc(ProductDO::getCreateTime)
.last("LIMIT 2");
List<ProductDO> recentProducts = productMapper.selectList(productWrapper);
for (ProductDO product : recentProducts) {
RecentActivityVO vo = new RecentActivityVO();
vo.setId(product.getId());
vo.setType("product");
vo.setTitle("新品上架");
vo.setDescription("新品\"" + product.getTitle() + "\"已上架");
vo.setTime(product.getCreateTime());
vo.setColor("blue");
activities.add(vo);
}
LambdaQueryWrapper<CommentDO> commentWrapper = new LambdaQueryWrapper<>();
if (shopId != null) {
commentWrapper.eq(CommentDO::getShopId, shopId);
}
commentWrapper.orderByDesc(CommentDO::getCreateTime)
.last("LIMIT 2");
List<CommentDO> recentComments = commentMapper.selectList(commentWrapper);
for (CommentDO comment : recentComments) {
RecentActivityVO vo = new RecentActivityVO();
vo.setId(comment.getId());
vo.setType("comment");
vo.setTitle("用户评论");
String content = comment.getCommentContent();
if (content != null && content.length() > 20) {
content = content.substring(0, 20) + "...";
}
vo.setDescription(content != null ? content : "用户发表了评论");
vo.setTime(comment.getCreateTime());
vo.setColor("green");
activities.add(vo);
}
activities.sort((a, b) -> b.getTime().compareTo(a.getTime()));
return activities.stream().limit(5).collect(Collectors.toList());
}
}
@@ -1,7 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.analytics.service;
import com.xiaowang.jacyucloudsalon.core.modules.analytics.vo.OperationsAnalyticsVO;
public interface OperationsAnalyticsService {
OperationsAnalyticsVO getDashboardAnalytics(Long shopId, Long artistId);
}
@@ -1,7 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.analytics.service;
import com.xiaowang.jacyucloudsalon.core.modules.analytics.vo.StoreWorkbenchVO;
public interface WorkbenchService {
StoreWorkbenchVO getWorkbench(Long shopId, Long artistId);
}
@@ -1,66 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.analytics.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderDO;
import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderItemDO;
import com.xiaowang.jacyucloudsalon.core.modules.product.entity.ProductDO;
import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserGrowthRecordDO;
import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.OrderItemMapper;
import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.OrderMapper;
import com.xiaowang.jacyucloudsalon.core.modules.product.mapper.ProductMapper;
import com.xiaowang.jacyucloudsalon.core.modules.user.mapper.UserGrowthRecordMapper;
import com.xiaowang.jacyucloudsalon.core.modules.analytics.service.OperationsAnalyticsService;
import com.xiaowang.jacyucloudsalon.core.modules.analytics.vo.OperationsAnalyticsVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Service
@RequiredArgsConstructor
public class OperationsAnalyticsServiceImpl implements OperationsAnalyticsService {
private final OrderMapper orderMapper;
private final OrderItemMapper orderItemMapper;
private final ProductMapper productMapper;
private final UserGrowthRecordMapper userGrowthRecordMapper;
@Override
public OperationsAnalyticsVO getDashboardAnalytics(Long shopId, Long artistId) {
List<OrderDO> orders = orderMapper.selectList(new LambdaQueryWrapper<OrderDO>()
.eq(shopId != null, OrderDO::getShopId, shopId)
.eq(OrderDO::getIsDelete, 0));
if (artistId != null) {
Set<Long> orderIds = new HashSet<>();
orderItemMapper.selectList(new LambdaQueryWrapper<OrderItemDO>()
.eq(OrderItemDO::getArtistId, artistId)
.eq(OrderItemDO::getIsDelete, 0))
.forEach(item -> orderIds.add(item.getOrderId()));
orders = orders.stream().filter(order -> orderIds.contains(order.getId())).toList();
}
OperationsAnalyticsVO vo = new OperationsAnalyticsVO();
vo.setViewCount(productMapper.selectList(new LambdaQueryWrapper<ProductDO>()
.eq(shopId != null, ProductDO::getShopId, shopId)
.eq(ProductDO::getIsDelete, 0))
.stream().map(ProductDO::getLikeCount).filter(v -> v != null).mapToLong(Integer::longValue).sum());
vo.setFavoriteCount(productMapper.selectList(new LambdaQueryWrapper<ProductDO>()
.eq(shopId != null, ProductDO::getShopId, shopId)
.eq(ProductDO::getIsDelete, 0))
.stream().map(ProductDO::getCollectCount).filter(v -> v != null).mapToLong(Integer::longValue).sum());
vo.setCartCount(0L);
vo.setOrderCount((long) orders.size());
vo.setPaidOrderCount(orders.stream().filter(order -> "PAID".equals(order.getPaymentStatus())).count());
vo.setCompletedOrderCount(orders.stream().filter(order -> Integer.valueOf(2).equals(order.getStatus())).count());
vo.setReviewCount(userGrowthRecordMapper.selectCount(new LambdaQueryWrapper<UserGrowthRecordDO>()
.eq(UserGrowthRecordDO::getSourceType, "REVIEW")));
vo.setRebookCount(userGrowthRecordMapper.selectCount(new LambdaQueryWrapper<UserGrowthRecordDO>()
.eq(UserGrowthRecordDO::getSourceType, "REBOOK")));
vo.setTotalAmount(orders.stream()
.map(order -> order.getActualAmount() == null ? BigDecimal.ZERO : order.getActualAmount())
.reduce(BigDecimal.ZERO, BigDecimal::add));
return vo;
}
}
@@ -1,145 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.analytics.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaowang.jacyucloudsalon.core.modules.order.entity.AfterSaleDO;
import com.xiaowang.jacyucloudsalon.core.modules.artist.entity.ArtistScheduleDO;
import com.xiaowang.jacyucloudsalon.core.modules.inventory.entity.InventoryItemDO;
import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderArtistChangeRequestDO;
import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderDO;
import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderItemDO;
import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.AfterSaleMapper;
import com.xiaowang.jacyucloudsalon.core.modules.artist.mapper.ArtistScheduleMapper;
import com.xiaowang.jacyucloudsalon.core.modules.inventory.mapper.InventoryItemMapper;
import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.OrderArtistChangeRequestMapper;
import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.OrderArtistReviewMapper;
import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.OrderItemMapper;
import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.OrderMapper;
import com.xiaowang.jacyucloudsalon.core.modules.analytics.service.WorkbenchService;
import com.xiaowang.jacyucloudsalon.core.modules.order.support.OrderStatus;
import com.xiaowang.jacyucloudsalon.core.modules.analytics.vo.StoreWorkbenchVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Service
@RequiredArgsConstructor
public class WorkbenchServiceImpl implements WorkbenchService {
private final OrderMapper orderMapper;
private final OrderItemMapper orderItemMapper;
private final AfterSaleMapper afterSaleMapper;
private final OrderArtistChangeRequestMapper orderArtistChangeRequestMapper;
private final InventoryItemMapper inventoryItemMapper;
private final ArtistScheduleMapper artistScheduleMapper;
private final OrderArtistReviewMapper orderArtistReviewMapper;
@Override
public StoreWorkbenchVO getWorkbench(Long shopId, Long artistId) {
LocalDateTime todayStart = LocalDate.now().atStartOfDay();
LocalDateTime tomorrowStart = todayStart.plusDays(1);
List<OrderDO> orders = scopedOrders(shopId, artistId);
StoreWorkbenchVO vo = new StoreWorkbenchVO();
vo.setTodayOrderCount(orders.stream().filter(order -> between(order.getCreateTime(), todayStart, tomorrowStart)).count());
vo.setPendingOrderCount(orders.stream().filter(this::isActionableOrder).count());
vo.setPendingAfterSaleCount(countAfterSales(shopId));
vo.setPendingArtistChangeCount(countArtistChanges(shopId, artistId));
vo.setLowStockItemCount(countLowStock(shopId));
vo.setScheduleReminderCount(countMissingSchedules(shopId, artistId, todayStart.toLocalDate()));
vo.setTodayServiceCount(countTodayServices(artistId, todayStart, tomorrowStart));
vo.setCompletedServiceCount(orders.stream().filter(order -> Integer.valueOf(2).equals(order.getStatus())).count());
vo.setServiceAmount(orders.stream()
.map(order -> order.getActualAmount() == null ? BigDecimal.ZERO : order.getActualAmount())
.reduce(BigDecimal.ZERO, BigDecimal::add));
vo.setAverageRating(resolveRating(artistId));
return vo;
}
private boolean isActionableOrder(OrderDO order) {
if (order == null || order.getStatus() == null) {
return false;
}
return Integer.valueOf(OrderStatus.PRICE_CONFIRMING.getCode()).equals(order.getStatus())
|| Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(order.getStatus());
}
private List<OrderDO> scopedOrders(Long shopId, Long artistId) {
List<OrderDO> orders = orderMapper.selectList(new LambdaQueryWrapper<OrderDO>()
.eq(shopId != null, OrderDO::getShopId, shopId)
.eq(OrderDO::getIsDelete, 0));
if (artistId == null) {
return orders;
}
Set<Long> orderIds = new HashSet<>();
orderItemMapper.selectList(new LambdaQueryWrapper<OrderItemDO>()
.eq(OrderItemDO::getArtistId, artistId)
.eq(OrderItemDO::getIsDelete, 0))
.forEach(item -> orderIds.add(item.getOrderId()));
return orders.stream().filter(order -> orderIds.contains(order.getId())).toList();
}
private long countAfterSales(Long shopId) {
return afterSaleMapper.selectCount(new LambdaQueryWrapper<AfterSaleDO>()
.eq(shopId != null, AfterSaleDO::getShopId, shopId)
.eq(AfterSaleDO::getStatus, "PENDING")
.eq(AfterSaleDO::getIsDelete, 0));
}
private long countArtistChanges(Long shopId, Long artistId) {
return orderArtistChangeRequestMapper.selectCount(new LambdaQueryWrapper<OrderArtistChangeRequestDO>()
.eq(shopId != null, OrderArtistChangeRequestDO::getShopId, shopId)
.eq(artistId != null, OrderArtistChangeRequestDO::getRequesterId, artistId)
.eq(OrderArtistChangeRequestDO::getStatus, "PENDING")
.eq(OrderArtistChangeRequestDO::getIsDelete, 0));
}
private long countLowStock(Long shopId) {
return inventoryItemMapper.selectList(new LambdaQueryWrapper<InventoryItemDO>()
.eq(shopId != null, InventoryItemDO::getShopId, shopId)
.eq(InventoryItemDO::getIsDelete, 0))
.stream()
.filter(item -> item.getStockQuantity() != null
&& item.getWarningThreshold() != null
&& item.getStockQuantity().compareTo(item.getWarningThreshold()) <= 0)
.count();
}
private long countMissingSchedules(Long shopId, Long artistId, LocalDate today) {
return artistScheduleMapper.selectCount(new LambdaQueryWrapper<ArtistScheduleDO>()
.eq(shopId != null, ArtistScheduleDO::getShopId, shopId)
.eq(artistId != null, ArtistScheduleDO::getArtistId, artistId)
.ge(ArtistScheduleDO::getWorkDate, today)
.lt(ArtistScheduleDO::getWorkDate, today.plusDays(3))
.eq(ArtistScheduleDO::getIsDelete, 0));
}
private long countTodayServices(Long artistId, LocalDateTime todayStart, LocalDateTime tomorrowStart) {
if (artistId == null) {
return 0L;
}
return orderItemMapper.selectList(new LambdaQueryWrapper<OrderItemDO>()
.eq(OrderItemDO::getArtistId, artistId)
.ge(OrderItemDO::getAppointmentTime, todayStart)
.lt(OrderItemDO::getAppointmentTime, tomorrowStart)
.eq(OrderItemDO::getIsDelete, 0))
.size();
}
private BigDecimal resolveRating(Long artistId) {
if (artistId == null) {
return BigDecimal.ZERO.setScale(1, RoundingMode.HALF_UP);
}
BigDecimal rating = orderArtistReviewMapper.selectAverageSubmittedRatingByArtistId(artistId);
return (rating == null ? BigDecimal.ZERO : rating).setScale(1, RoundingMode.HALF_UP);
}
private boolean between(LocalDateTime value, LocalDateTime start, LocalDateTime end) {
return value != null && !value.isBefore(start) && value.isBefore(end);
}
}
@@ -1,89 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.analytics.vo;
import lombok.Data;
import java.math.BigDecimal;
import java.util.List;
import com.xiaowang.jacyucloudsalon.core.modules.product.vo.HotProductVO;
@Data
/**
* DashboardStatsVO is a response VO. Services build it and controllers return it to the frontend.
* Field and parameter names are kept consistent with the frontend/API payload to make tracing easier.
*/
public class DashboardStatsVO {
/**
* Field `totalUsers` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long totalUsers;
/**
* Field `totalProducts` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long totalProducts;
/**
* Field `totalShops` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long totalShops;
/**
* Field `todayOrders` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long todayOrders;
/**
* Purpose: totalOrderAmount supports DashboardStatsVO.java by holding or executing the total order amount business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private BigDecimal totalOrderAmount;
/**
* Purpose: todayOrderAmount supports DashboardStatsVO.java by holding or executing the today order amount business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private BigDecimal todayOrderAmount;
/**
* Purpose: weekOrderAmount supports DashboardStatsVO.java by holding or executing the week order amount business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private BigDecimal weekOrderAmount;
/**
* Purpose: totalCustomers supports DashboardStatsVO.java by holding or executing the total customers business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Long totalCustomers;
/**
* Purpose: totalArtists supports DashboardStatsVO.java by holding or executing the total artists business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Long totalArtists;
/**
* Purpose: newCustomersToday supports DashboardStatsVO.java by holding or executing the new customers today business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Long newCustomersToday;
/**
* Purpose: newCustomers7Days supports DashboardStatsVO.java by holding or executing the new customers7 days business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Long newCustomers7Days;
/**
* Purpose: newOrders7Days supports DashboardStatsVO.java by holding or executing the new orders7 days business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Long newOrders7Days;
/**
* Purpose: pendingOrders supports DashboardStatsVO.java by holding or executing the pending orders business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Long pendingOrders;
/**
* Purpose: completedOrders supports DashboardStatsVO.java by holding or executing the completed orders business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Long completedOrders;
/**
* Field `hotProducts` (List<HotProductVO>): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private List<HotProductVO> hotProducts;
/**
* Field `recentActivities` (List<RecentActivityVO>): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private List<RecentActivityVO> recentActivities;
}
@@ -1,18 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.analytics.vo;
import lombok.Data;
import java.math.BigDecimal;
@Data
public class OperationsAnalyticsVO {
private Long viewCount;
private Long favoriteCount;
private Long cartCount;
private Long orderCount;
private Long paidOrderCount;
private Long completedOrderCount;
private Long reviewCount;
private Long rebookCount;
private BigDecimal totalAmount;
}
@@ -1,37 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.analytics.vo;
import lombok.Data;
import java.time.LocalDateTime;
@Data
/**
* RecentActivityVO is a response VO. Services build it and controllers return it to the frontend.
* Field and parameter names are kept consistent with the frontend/API payload to make tracing easier.
*/
public class RecentActivityVO {
/**
* Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long id;
/**
* Field `type` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String type;
/**
* Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String title;
/**
* Field `description` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String description;
/**
* Field `time` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private LocalDateTime time;
/**
* Field `color` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String color;
}
@@ -1,19 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.analytics.vo;
import lombok.Data;
import java.math.BigDecimal;
@Data
public class StoreWorkbenchVO {
private Long todayOrderCount;
private Long pendingOrderCount;
private Long pendingAfterSaleCount;
private Long pendingArtistChangeCount;
private Long lowStockItemCount;
private Long scheduleReminderCount;
private Long todayServiceCount;
private Long completedServiceCount;
private BigDecimal serviceAmount;
private BigDecimal averageRating;
}
@@ -1,68 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.artist.controller.front;
import com.xiaowang.jacyucloudsalon.core.common.Result;
import com.xiaowang.jacyucloudsalon.core.modules.artist.dto.NailArtistInfoDTO;
import com.xiaowang.jacyucloudsalon.core.modules.artist.service.NailArtistInfoService;
import com.xiaowang.jacyucloudsalon.core.modules.artist.vo.NailArtistAvailabilityVO;
import com.xiaowang.jacyucloudsalon.core.modules.artist.vo.NailArtistProfileVO;
import com.xiaowang.jacyucloudsalon.core.modules.artist.vo.NailArtistReviewVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* 美甲师信息Controller(前台)
*/
@RestController
@RequestMapping("/nail-artist")
public class NailArtistController {
@Autowired
/**
* Purpose: nailArtistInfoService supports NailArtistController.java by holding or executing the nail artist info service business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private NailArtistInfoService nailArtistInfoService;
/**
* 获取所有可用的美甲师信息(前台使用)
*/
@GetMapping("/list")
public Result<List<NailArtistInfoDTO>> getAllAvailableNailArtists() {
List<NailArtistInfoDTO> nailArtistInfoDTOList = nailArtistInfoService.getAllAvailableNailArtists();
return Result.success(nailArtistInfoDTOList);
}
@GetMapping("/list/shop/{shopId}")
public Result<List<NailArtistInfoDTO>> listByShopId(@PathVariable Long shopId) {
return Result.success(nailArtistInfoService.getByShopId(shopId));
}
/**
* 根据用户ID获取美甲师信息(前台使用)
*/
@GetMapping("/get/{userId}")
public Result<NailArtistInfoDTO> getNailArtistInfo(@PathVariable Long userId) {
NailArtistInfoDTO nailArtistInfoDTO = nailArtistInfoService.getByUserId(userId);
return Result.success(nailArtistInfoDTO);
}
@GetMapping("/profile/{artistId}")
public Result<NailArtistProfileVO> getPublicProfile(@PathVariable Long artistId) {
return Result.success(nailArtistInfoService.getPublicProfile(artistId));
}
@GetMapping("/{artistId}/availability")
public Result<List<NailArtistAvailabilityVO>> getAvailability(@PathVariable Long artistId) {
return Result.success(nailArtistInfoService.getAvailability(artistId));
}
@GetMapping("/{artistId}/reviews")
public Result<List<NailArtistReviewVO>> listPublicReviews(@PathVariable Long artistId) {
return Result.success(nailArtistInfoService.listPublicReviews(artistId));
}
}
@@ -1,19 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.artist.dto;
import lombok.Data;
import java.time.LocalDate;
import java.time.LocalTime;
@Data
public class ArtistScheduleDTO {
private Long shopId;
private Long artistId;
private LocalDate workDate;
private LocalTime startTime;
private LocalTime endTime;
private Integer slotMinutes;
private Integer capacity;
private Integer status;
private String remark;
}
@@ -1,17 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.artist.dto;
import lombok.Data;
import java.time.LocalDate;
import java.time.LocalTime;
@Data
public class ArtistScheduleExceptionDTO {
private Long shopId;
private Long artistId;
private LocalDate workDate;
private String exceptionType;
private LocalTime startTime;
private LocalTime endTime;
private String remark;
}
@@ -1,18 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.artist.dto;
import lombok.Data;
import java.time.LocalTime;
import java.util.List;
@Data
public class ArtistScheduleRuleDTO {
private Long shopId;
private Long artistId;
private String presetType;
private List<Integer> workDays;
private LocalTime startTime;
private LocalTime endTime;
private Integer status;
private String remark;
}
@@ -1,117 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.artist.dto;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalTime;
/**
* 美甲师信息DTO
*/
@Data
public class NailArtistInfoDTO {
/**
* 主键ID
*/
@JsonSerialize(using = ToStringSerializer.class)
private Long id;
/**
* 关联用户表主键(美甲师用户)
*/
@JsonSerialize(using = ToStringSerializer.class)
private Long userId;
/**
* 身份
*/
private String identity;
/**
* 从业年限
*/
private Integer experience;
/**
* 技能标签ID集合,多个ID以逗号分隔
*/
private String skills;
/**
* 评分
*/
private BigDecimal rating;
/**
* 状态:1-营业中,0-休息中
*/
private Integer status;
/**
* Field `participateProduction` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Integer participateProduction;
/**
* Field `workStartTime` (LocalTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private LocalTime workStartTime;
/**
* Field `workEndTime` (LocalTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private LocalTime workEndTime;
/**
* Field `userType` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Integer userType;
/**
* Field `userTypeName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String userTypeName;
/**
* 作品集商品ID集合,多个ID以逗号分隔
*/
private String portfolio;
/**
* 美甲师姓名(从用户表获取)
*/
private String nickname;
/**
* 所属店铺ID
*/
@JsonSerialize(using = ToStringSerializer.class)
private Long shopId;
/**
* 店铺名称
*/
private String shopName;
/**
* 用户签名
*/
private String signature;
/**
* 头像访问地址
*/
private String avatar;
/**
* 排班模式摘要
*/
private String scheduleModeSummary;
/**
* 排班时间摘要
*/
private String scheduleTimeSummary;
}
@@ -1,38 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.artist.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.time.LocalDate;
import java.time.LocalTime;
import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity;
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("t_artist_schedule")
public class ArtistScheduleDO extends BaseEntity {
@TableField("shop_id")
private Long shopId;
@TableField("artist_id")
private Long artistId;
@TableField("work_date")
private LocalDate workDate;
@TableField("start_time")
private LocalTime startTime;
@TableField("end_time")
private LocalTime endTime;
@TableField("slot_minutes")
private Integer slotMinutes;
@TableField("capacity")
private Integer capacity;
@TableField("status")
private Integer status;
@TableField("remark")
private String remark;
@TableField("is_delete")
@TableLogic
private Integer isDelete;
}
@@ -1,38 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.artist.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.time.LocalDate;
import java.time.LocalTime;
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("t_artist_schedule_exception")
public class ArtistScheduleExceptionDO extends BaseEntity {
@TableField("shop_id")
private Long shopId;
@TableField("artist_id")
private Long artistId;
@TableField("work_date")
private LocalDate workDate;
@TableField("exception_type")
private String exceptionType;
@TableField("start_time")
private LocalTime startTime;
@TableField("end_time")
private LocalTime endTime;
@TableField("slot_minutes")
private Integer slotMinutes;
@TableField("capacity")
private Integer capacity;
@TableField("remark")
private String remark;
@TableField("is_delete")
@TableLogic
private Integer isDelete;
}
@@ -1,39 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.artist.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.time.LocalTime;
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("t_artist_schedule_rule")
public class ArtistScheduleRuleDO extends BaseEntity {
@TableField("shop_id")
private Long shopId;
@TableField("artist_id")
private Long artistId;
@TableField("preset_type")
private String presetType;
@TableField("work_days")
private String workDays;
@TableField("start_time")
private LocalTime startTime;
@TableField("end_time")
private LocalTime endTime;
@TableField("slot_minutes")
private Integer slotMinutes;
@TableField("capacity")
private Integer capacity;
@TableField("status")
private Integer status;
@TableField("remark")
private String remark;
@TableField("is_delete")
@TableLogic
private Integer isDelete;
}
@@ -1,79 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.artist.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.math.BigDecimal;
import java.time.LocalTime;
import com.xiaowang.jacyucloudsalon.core.common.entity.BaseEntity;
/**
* 美甲师信息实体类
*/
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("t_nail_artist_info")
public class NailArtistInfoDO extends BaseEntity {
/**
* 关联用户表主键(美甲师用户)
*/
private Long userId;
/**
* 身份
*/
private String identity;
/**
* 从业年限
*/
private Integer experience;
/**
* 技能标签ID集合,多个ID以逗号分隔
*/
private String skills;
/**
* 评分
*/
private BigDecimal rating;
/**
* 状态:1-营业中,0-休息中
*/
private Integer status;
@TableField("participate_production")
/**
* Field `participateProduction` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Integer participateProduction;
@TableField("work_start_time")
/**
* Field `workStartTime` (LocalTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private LocalTime workStartTime;
@TableField("work_end_time")
/**
* Field `workEndTime` (LocalTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private LocalTime workEndTime;
/**
* 作品集商品ID集合,多个ID以逗号分隔
*/
private String portfolio;
/**
* 逻辑删除:0-未删,1-已删
*/
@TableField("is_delete")
@TableLogic
private Integer isDelete;
}
@@ -1,9 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.artist.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xiaowang.jacyucloudsalon.core.modules.artist.entity.ArtistScheduleExceptionDO;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface ArtistScheduleExceptionMapper extends BaseMapper<ArtistScheduleExceptionDO> {
}
@@ -1,47 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.artist.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xiaowang.jacyucloudsalon.core.modules.artist.entity.ArtistScheduleDO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.time.LocalDate;
import java.time.LocalTime;
@Mapper
public interface ArtistScheduleMapper extends BaseMapper<ArtistScheduleDO> {
@Select("SELECT * FROM t_artist_schedule WHERE shop_id = #{shopId} AND artist_id = #{artistId} " +
"AND work_date = #{workDate} AND start_time <= #{startTime} AND end_time >= #{endTime} " +
"AND is_delete = 0 ORDER BY CASE WHEN status = 1 THEN 0 ELSE 1 END, start_time ASC LIMIT 1 FOR UPDATE")
ArtistScheduleDO selectCoveringSchedule(@Param("shopId") Long shopId,
@Param("artistId") Long artistId,
@Param("workDate") LocalDate workDate,
@Param("startTime") LocalTime startTime,
@Param("endTime") LocalTime endTime);
@Select("SELECT * FROM t_artist_schedule WHERE shop_id = #{shopId} AND artist_id = #{artistId} " +
"AND work_date = #{workDate} AND is_delete = 0 ORDER BY start_time ASC LIMIT 1 FOR UPDATE")
ArtistScheduleDO selectDayScheduleForUpdate(@Param("shopId") Long shopId,
@Param("artistId") Long artistId,
@Param("workDate") LocalDate workDate);
@Select("SELECT * FROM t_artist_schedule WHERE shop_id = #{shopId} AND artist_id = #{artistId} " +
"AND work_date = #{workDate} AND start_time = #{startTime} AND is_delete = 0 LIMIT 1 FOR UPDATE")
ArtistScheduleDO selectSlotScheduleForUpdate(@Param("shopId") Long shopId,
@Param("artistId") Long artistId,
@Param("workDate") LocalDate workDate,
@Param("startTime") LocalTime startTime);
@Update("UPDATE t_artist_schedule SET start_time = #{startTime}, end_time = #{endTime}, " +
"slot_minutes = #{slotMinutes}, capacity = #{capacity}, status = #{status}, remark = #{remark}, " +
"update_time = NOW() WHERE id = #{id} AND is_delete = 0")
int updateGeneratedSchedule(@Param("id") Long id,
@Param("startTime") LocalTime startTime,
@Param("endTime") LocalTime endTime,
@Param("slotMinutes") Integer slotMinutes,
@Param("capacity") Integer capacity,
@Param("status") Integer status,
@Param("remark") String remark);
}
@@ -1,9 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.artist.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xiaowang.jacyucloudsalon.core.modules.artist.entity.ArtistScheduleRuleDO;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface ArtistScheduleRuleMapper extends BaseMapper<ArtistScheduleRuleDO> {
}
@@ -1,12 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.artist.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xiaowang.jacyucloudsalon.core.modules.artist.entity.NailArtistInfoDO;
import org.apache.ibatis.annotations.Mapper;
/**
* 美甲师信息Mapper
*/
@Mapper
public interface NailArtistInfoMapper extends BaseMapper<NailArtistInfoDO> {
}
@@ -1,24 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.artist.service;
import com.xiaowang.jacyucloudsalon.core.modules.artist.dto.ArtistScheduleDTO;
import com.xiaowang.jacyucloudsalon.core.modules.artist.dto.ArtistScheduleExceptionDTO;
import com.xiaowang.jacyucloudsalon.core.modules.artist.dto.ArtistScheduleRuleDTO;
import com.xiaowang.jacyucloudsalon.core.modules.artist.vo.ArtistScheduleExceptionVO;
import com.xiaowang.jacyucloudsalon.core.modules.artist.vo.ArtistScheduleRuleSettingVO;
import com.xiaowang.jacyucloudsalon.core.modules.artist.vo.ArtistScheduleRuleVO;
import com.xiaowang.jacyucloudsalon.core.modules.artist.vo.ArtistScheduleVO;
import java.time.LocalDate;
import java.util.List;
public interface ArtistScheduleService {
ArtistScheduleVO saveSchedule(ArtistScheduleDTO dto);
List<ArtistScheduleVO> listSchedules(Long shopId, Long artistId, LocalDate startDate, LocalDate endDate);
ArtistScheduleRuleSettingVO getRuleSetting(Long shopId, Long artistId);
ArtistScheduleRuleVO saveRule(ArtistScheduleRuleDTO dto);
ArtistScheduleExceptionVO saveException(ArtistScheduleExceptionDTO dto);
}
@@ -1,54 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.artist.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.xiaowang.jacyucloudsalon.core.modules.artist.dto.NailArtistInfoDTO;
import com.xiaowang.jacyucloudsalon.core.modules.artist.entity.NailArtistInfoDO;
import com.xiaowang.jacyucloudsalon.core.modules.artist.vo.NailArtistAvailabilityVO;
import com.xiaowang.jacyucloudsalon.core.modules.artist.vo.NailArtistProfileVO;
import com.xiaowang.jacyucloudsalon.core.modules.artist.vo.NailArtistReviewVO;
import java.util.List;
/**
* 美甲师信息服务
*/
public interface NailArtistInfoService extends IService<NailArtistInfoDO> {
/**
* 根据用户ID获取美甲师信息
* @param userId 用户ID
* @return 美甲师信息
*/
NailArtistInfoDTO getByUserId(Long userId);
/**
* 获取所有美甲师信息
* @return 美甲师信息列表
*/
List<NailArtistInfoDTO> getAllNailArtists();
/**
* 根据店铺ID获取美甲师信息
* @param shopId 店铺ID
* @return 美甲师信息列表
*/
List<NailArtistInfoDTO> getByShopId(Long shopId);
/**
* 保存或更新美甲师信息
* @param nailArtistInfoDTO 美甲师信息DTO
* @return 保存后的美甲师信息
*/
NailArtistInfoDTO saveOrUpdateNailArtistInfo(NailArtistInfoDTO nailArtistInfoDTO);
/**
* 获取所有可用的美甲师信息(前台使用)
* @return 美甲师信息列表
*/
List<NailArtistInfoDTO> getAllAvailableNailArtists();
NailArtistProfileVO getPublicProfile(Long artistId);
List<NailArtistAvailabilityVO> getAvailability(Long artistId);
List<NailArtistReviewVO> listPublicReviews(Long artistId);
}
@@ -1,423 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.artist.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaowang.jacyucloudsalon.core.modules.artist.dto.ArtistScheduleDTO;
import com.xiaowang.jacyucloudsalon.core.modules.artist.dto.ArtistScheduleExceptionDTO;
import com.xiaowang.jacyucloudsalon.core.modules.artist.dto.ArtistScheduleRuleDTO;
import com.xiaowang.jacyucloudsalon.core.modules.artist.entity.ArtistScheduleExceptionDO;
import com.xiaowang.jacyucloudsalon.core.modules.artist.entity.ArtistScheduleDO;
import com.xiaowang.jacyucloudsalon.core.modules.artist.entity.ArtistScheduleRuleDO;
import com.xiaowang.jacyucloudsalon.core.modules.artist.mapper.ArtistScheduleExceptionMapper;
import com.xiaowang.jacyucloudsalon.core.modules.artist.mapper.ArtistScheduleMapper;
import com.xiaowang.jacyucloudsalon.core.modules.artist.mapper.ArtistScheduleRuleMapper;
import com.xiaowang.jacyucloudsalon.core.modules.artist.service.ArtistScheduleService;
import com.xiaowang.jacyucloudsalon.core.modules.artist.vo.ArtistScheduleExceptionVO;
import com.xiaowang.jacyucloudsalon.core.modules.artist.vo.ArtistScheduleRuleSettingVO;
import com.xiaowang.jacyucloudsalon.core.modules.artist.vo.ArtistScheduleRuleVO;
import com.xiaowang.jacyucloudsalon.core.modules.artist.vo.ArtistScheduleVO;
import com.xiaowang.jacyucloudsalon.core.modules.planning.mapper.AppointmentReservationMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
public class ArtistScheduleServiceImpl implements ArtistScheduleService {
private static final int GENERATED_DAYS = 60;
private static final int DEFAULT_SLOT_MINUTES = 60;
private static final int DEFAULT_CAPACITY = 1;
private static final String PRESET_SINGLE_REST = "SINGLE_REST";
private static final String PRESET_DOUBLE_REST = "DOUBLE_REST";
private static final String PRESET_NINE_TO_FIVE = "NINE_TO_FIVE";
private static final String PRESET_LATE_SHIFT = "LATE_SHIFT";
private static final String PRESET_CUSTOM = "CUSTOM";
private static final String EXCEPTION_REST = "REST";
private static final String EXCEPTION_EXTRA_WORK = "EXTRA_WORK";
private static final String EXCEPTION_CHANGE_SHIFT = "CHANGE_SHIFT";
private final ArtistScheduleMapper artistScheduleMapper;
private final ArtistScheduleRuleMapper ruleMapper;
private final ArtistScheduleExceptionMapper exceptionMapper;
private final AppointmentReservationMapper reservationMapper;
@Override
@Transactional
public ArtistScheduleVO saveSchedule(ArtistScheduleDTO dto) {
if (dto == null || dto.getShopId() == null || dto.getArtistId() == null || dto.getWorkDate() == null
|| dto.getStartTime() == null || dto.getEndTime() == null) {
throw new RuntimeException("排班信息不完整");
}
ArtistScheduleDO schedule = new ArtistScheduleDO();
BeanUtils.copyProperties(dto, schedule);
schedule.setSlotMinutes(dto.getSlotMinutes() == null ? 60 : dto.getSlotMinutes());
schedule.setCapacity(dto.getCapacity() == null || dto.getCapacity() < 1 ? 1 : dto.getCapacity());
schedule.setStatus(dto.getStatus() == null ? 1 : dto.getStatus());
schedule.setIsDelete(0);
ArtistScheduleDO existing = artistScheduleMapper.selectSlotScheduleForUpdate(dto.getShopId(), dto.getArtistId(), dto.getWorkDate(), dto.getStartTime());
if (existing == null) {
artistScheduleMapper.insert(schedule);
} else {
schedule.setId(existing.getId());
artistScheduleMapper.updateGeneratedSchedule(existing.getId(), schedule.getStartTime(), schedule.getEndTime(),
schedule.getSlotMinutes(), schedule.getCapacity(), schedule.getStatus(), schedule.getRemark());
}
return toVO(schedule);
}
@Override
public List<ArtistScheduleVO> listSchedules(Long shopId, Long artistId, LocalDate startDate, LocalDate endDate) {
LambdaQueryWrapper<ArtistScheduleDO> wrapper = new LambdaQueryWrapper<ArtistScheduleDO>()
.eq(ArtistScheduleDO::getIsDelete, 0)
.orderByAsc(ArtistScheduleDO::getWorkDate)
.orderByAsc(ArtistScheduleDO::getStartTime);
if (shopId != null) {
wrapper.eq(ArtistScheduleDO::getShopId, shopId);
}
if (artistId != null) {
wrapper.eq(ArtistScheduleDO::getArtistId, artistId);
}
if (startDate != null) {
wrapper.ge(ArtistScheduleDO::getWorkDate, startDate);
}
if (endDate != null) {
wrapper.le(ArtistScheduleDO::getWorkDate, endDate);
}
return artistScheduleMapper.selectList(wrapper).stream().map(this::toVO).toList();
}
private ArtistScheduleVO toVO(ArtistScheduleDO schedule) {
ArtistScheduleVO vo = new ArtistScheduleVO();
BeanUtils.copyProperties(schedule, vo);
return vo;
}
@Override
public ArtistScheduleRuleSettingVO getRuleSetting(Long shopId, Long artistId) {
if (shopId == null || artistId == null) {
throw new RuntimeException("排班规则查询参数不完整");
}
ArtistScheduleRuleSettingVO setting = new ArtistScheduleRuleSettingVO();
ArtistScheduleRuleDO rule = selectRule(shopId, artistId);
setting.setRule(rule == null ? defaultRuleVO(shopId, artistId) : toRuleVO(rule));
setting.setExceptions(listExceptions(shopId, artistId, LocalDate.now(), LocalDate.now().plusDays(GENERATED_DAYS - 1L))
.stream()
.map(this::toExceptionVO)
.toList());
return setting;
}
@Override
@Transactional
public ArtistScheduleRuleVO saveRule(ArtistScheduleRuleDTO dto) {
ArtistScheduleRuleDO normalized = normalizeRule(dto);
ArtistScheduleRuleDO existing = selectRule(normalized.getShopId(), normalized.getArtistId());
if (existing == null) {
ruleMapper.insert(normalized);
} else {
normalized.setId(existing.getId());
ruleMapper.updateById(normalized);
}
refreshGeneratedSchedules(normalized);
return toRuleVO(normalized);
}
@Override
@Transactional
public ArtistScheduleExceptionVO saveException(ArtistScheduleExceptionDTO dto) {
ArtistScheduleExceptionDO normalized = normalizeException(dto);
ArtistScheduleRuleDO rule = selectRule(normalized.getShopId(), normalized.getArtistId());
if (rule == null) {
rule = defaultRule(normalized.getShopId(), normalized.getArtistId());
}
ArtistScheduleExceptionDO existing = selectException(normalized.getShopId(), normalized.getArtistId(), normalized.getWorkDate());
if (existing == null) {
exceptionMapper.insert(normalized);
} else {
normalized.setId(existing.getId());
exceptionMapper.updateById(normalized);
}
refreshScheduleForDate(rule, normalized, normalized.getWorkDate());
return toExceptionVO(normalized);
}
private ArtistScheduleRuleDO normalizeRule(ArtistScheduleRuleDTO dto) {
if (dto == null || dto.getShopId() == null || dto.getArtistId() == null) {
throw new RuntimeException("排班规则信息不完整");
}
String presetType = normalizePresetType(dto.getPresetType());
LocalTime startTime = dto.getStartTime() == null ? presetStartTime(presetType) : dto.getStartTime();
LocalTime endTime = dto.getEndTime() == null ? presetEndTime(presetType) : dto.getEndTime();
validateTimeRange(startTime, endTime);
ArtistScheduleRuleDO rule = new ArtistScheduleRuleDO();
rule.setShopId(dto.getShopId());
rule.setArtistId(dto.getArtistId());
rule.setPresetType(presetType);
rule.setWorkDays(encodeWorkDays(resolveWorkDays(dto.getWorkDays(), presetType)));
rule.setStartTime(startTime);
rule.setEndTime(endTime);
rule.setSlotMinutes(DEFAULT_SLOT_MINUTES);
rule.setCapacity(DEFAULT_CAPACITY);
rule.setStatus(dto.getStatus() == null ? 1 : dto.getStatus());
rule.setRemark(trimText(dto.getRemark()));
rule.setIsDelete(0);
return rule;
}
private ArtistScheduleExceptionDO normalizeException(ArtistScheduleExceptionDTO dto) {
if (dto == null || dto.getShopId() == null || dto.getArtistId() == null || dto.getWorkDate() == null) {
throw new RuntimeException("排班例外信息不完整");
}
String exceptionType = normalizeExceptionType(dto.getExceptionType());
LocalTime startTime = dto.getStartTime();
LocalTime endTime = dto.getEndTime();
if (!EXCEPTION_REST.equals(exceptionType)) {
if (startTime == null || endTime == null) {
throw new RuntimeException("临时上班或改班必须填写开始和结束时间");
}
validateTimeRange(startTime, endTime);
}
ArtistScheduleExceptionDO exception = new ArtistScheduleExceptionDO();
exception.setShopId(dto.getShopId());
exception.setArtistId(dto.getArtistId());
exception.setWorkDate(dto.getWorkDate());
exception.setExceptionType(exceptionType);
exception.setStartTime(startTime);
exception.setEndTime(endTime);
exception.setSlotMinutes(DEFAULT_SLOT_MINUTES);
exception.setCapacity(DEFAULT_CAPACITY);
exception.setRemark(trimText(dto.getRemark()));
exception.setIsDelete(0);
return exception;
}
private ArtistScheduleRuleDO selectRule(Long shopId, Long artistId) {
return ruleMapper.selectOne(new LambdaQueryWrapper<ArtistScheduleRuleDO>()
.eq(ArtistScheduleRuleDO::getShopId, shopId)
.eq(ArtistScheduleRuleDO::getArtistId, artistId)
.eq(ArtistScheduleRuleDO::getIsDelete, 0)
.last("LIMIT 1"));
}
private ArtistScheduleExceptionDO selectException(Long shopId, Long artistId, LocalDate workDate) {
return exceptionMapper.selectOne(new LambdaQueryWrapper<ArtistScheduleExceptionDO>()
.eq(ArtistScheduleExceptionDO::getShopId, shopId)
.eq(ArtistScheduleExceptionDO::getArtistId, artistId)
.eq(ArtistScheduleExceptionDO::getWorkDate, workDate)
.eq(ArtistScheduleExceptionDO::getIsDelete, 0)
.last("LIMIT 1"));
}
private List<ArtistScheduleExceptionDO> listExceptions(Long shopId, Long artistId, LocalDate start, LocalDate end) {
return exceptionMapper.selectList(new LambdaQueryWrapper<ArtistScheduleExceptionDO>()
.eq(ArtistScheduleExceptionDO::getShopId, shopId)
.eq(ArtistScheduleExceptionDO::getArtistId, artistId)
.eq(ArtistScheduleExceptionDO::getIsDelete, 0)
.between(ArtistScheduleExceptionDO::getWorkDate, start, end)
.orderByAsc(ArtistScheduleExceptionDO::getWorkDate));
}
private void refreshGeneratedSchedules(ArtistScheduleRuleDO rule) {
LocalDate start = LocalDate.now();
LocalDate end = start.plusDays(GENERATED_DAYS - 1L);
Map<LocalDate, ArtistScheduleExceptionDO> exceptionByDate = listExceptions(rule.getShopId(), rule.getArtistId(), start, end)
.stream()
.collect(Collectors.toMap(ArtistScheduleExceptionDO::getWorkDate, Function.identity(), (a, b) -> a));
LocalDate cursor = start;
while (!cursor.isAfter(end)) {
refreshScheduleForDate(rule, exceptionByDate.get(cursor), cursor);
cursor = cursor.plusDays(1L);
}
}
private void refreshScheduleForDate(ArtistScheduleRuleDO rule, ArtistScheduleExceptionDO exception, LocalDate workDate) {
GeneratedSchedule generated = resolveGeneratedSchedule(rule, exception, workDate);
if (!generated.working()) {
assertNoActiveReservations(rule.getShopId(), rule.getArtistId(), workDate);
upsertGeneratedSchedule(rule, workDate, rule.getStartTime(), rule.getEndTime(), rule.getSlotMinutes(), rule.getCapacity(), 0, generated.remark());
return;
}
assertNoReservationsOutsideSchedule(rule.getShopId(), rule.getArtistId(), workDate, generated.startTime(), generated.endTime());
upsertGeneratedSchedule(rule, workDate, generated.startTime(), generated.endTime(), generated.slotMinutes(), generated.capacity(), 1, generated.remark());
}
private GeneratedSchedule resolveGeneratedSchedule(ArtistScheduleRuleDO rule, ArtistScheduleExceptionDO exception, LocalDate workDate) {
if (exception != null) {
if (EXCEPTION_REST.equals(exception.getExceptionType())) {
return new GeneratedSchedule(false, rule.getStartTime(), rule.getEndTime(), rule.getSlotMinutes(), rule.getCapacity(), exceptionRemark(exception));
}
if (EXCEPTION_EXTRA_WORK.equals(exception.getExceptionType()) || EXCEPTION_CHANGE_SHIFT.equals(exception.getExceptionType())) {
return new GeneratedSchedule(true, exception.getStartTime(), exception.getEndTime(), exception.getSlotMinutes(), exception.getCapacity(), exceptionRemark(exception));
}
}
boolean workingDay = Integer.valueOf(1).equals(rule.getStatus()) && decodeWorkDays(rule.getWorkDays()).contains(workDate.getDayOfWeek().getValue());
return new GeneratedSchedule(workingDay, rule.getStartTime(), rule.getEndTime(), rule.getSlotMinutes(), rule.getCapacity(), "规则生成排班");
}
private void upsertGeneratedSchedule(ArtistScheduleRuleDO rule, LocalDate workDate, LocalTime startTime, LocalTime endTime,
Integer slotMinutes, Integer capacity, Integer status, String remark) {
ArtistScheduleDO schedule = artistScheduleMapper.selectDayScheduleForUpdate(rule.getShopId(), rule.getArtistId(), workDate);
if (schedule == null) {
schedule = new ArtistScheduleDO();
schedule.setShopId(rule.getShopId());
schedule.setArtistId(rule.getArtistId());
schedule.setWorkDate(workDate);
schedule.setStartTime(startTime);
schedule.setEndTime(endTime);
schedule.setSlotMinutes(slotMinutes);
schedule.setCapacity(capacity);
schedule.setStatus(status);
schedule.setRemark(remark);
schedule.setIsDelete(0);
artistScheduleMapper.insert(schedule);
return;
}
artistScheduleMapper.updateGeneratedSchedule(schedule.getId(), startTime, endTime, slotMinutes, capacity, status, remark);
}
private void assertNoActiveReservations(Long shopId, Long artistId, LocalDate workDate) {
int count = reservationMapper.countActiveByArtistAndDateForUpdate(shopId, artistId, workDate);
if (count > 0) {
throw new RuntimeException("该日期已有预约,不能设置为休假:" + workDate + ",预约数:" + count);
}
}
private void assertNoReservationsOutsideSchedule(Long shopId, Long artistId, LocalDate workDate, LocalTime startTime, LocalTime endTime) {
int count = reservationMapper.countActiveOutsideScheduleForUpdate(shopId, artistId, workDate, startTime, endTime);
if (count > 0) {
throw new RuntimeException("该日期已有预约超出新的排班时间:" + workDate + ",冲突预约数:" + count);
}
}
private ArtistScheduleRuleVO defaultRuleVO(Long shopId, Long artistId) {
return toRuleVO(defaultRule(shopId, artistId));
}
private ArtistScheduleRuleDO defaultRule(Long shopId, Long artistId) {
ArtistScheduleRuleDO rule = new ArtistScheduleRuleDO();
rule.setShopId(shopId);
rule.setArtistId(artistId);
rule.setPresetType(PRESET_DOUBLE_REST);
rule.setWorkDays(encodeWorkDays(List.of(1, 2, 3, 4, 5)));
rule.setStartTime(LocalTime.of(9, 0));
rule.setEndTime(LocalTime.of(17, 0));
rule.setSlotMinutes(DEFAULT_SLOT_MINUTES);
rule.setCapacity(DEFAULT_CAPACITY);
rule.setStatus(1);
rule.setIsDelete(0);
return rule;
}
private ArtistScheduleRuleVO toRuleVO(ArtistScheduleRuleDO rule) {
ArtistScheduleRuleVO vo = new ArtistScheduleRuleVO();
BeanUtils.copyProperties(rule, vo);
vo.setWorkDays(decodeWorkDays(rule.getWorkDays()));
return vo;
}
private ArtistScheduleExceptionVO toExceptionVO(ArtistScheduleExceptionDO exception) {
ArtistScheduleExceptionVO vo = new ArtistScheduleExceptionVO();
BeanUtils.copyProperties(exception, vo);
return vo;
}
private String normalizePresetType(String presetType) {
String value = trimText(presetType);
if (value == null || value.isBlank()) {
return PRESET_CUSTOM;
}
return value;
}
private String normalizeExceptionType(String exceptionType) {
String value = trimText(exceptionType);
if (EXCEPTION_REST.equals(value) || EXCEPTION_EXTRA_WORK.equals(value) || EXCEPTION_CHANGE_SHIFT.equals(value)) {
return value;
}
throw new RuntimeException("不支持的排班例外类型:" + value);
}
private List<Integer> resolveWorkDays(List<Integer> inputWorkDays, String presetType) {
List<Integer> presetDays = switch (presetType) {
case PRESET_DOUBLE_REST, PRESET_NINE_TO_FIVE -> List.of(1, 2, 3, 4, 5);
case PRESET_SINGLE_REST, PRESET_LATE_SHIFT -> List.of(1, 2, 3, 4, 5, 6);
default -> inputWorkDays;
};
Set<Integer> normalized = new LinkedHashSet<>();
for (Integer day : presetDays == null ? List.<Integer>of() : presetDays) {
if (day != null && day >= DayOfWeek.MONDAY.getValue() && day <= DayOfWeek.SUNDAY.getValue()) {
normalized.add(day);
}
}
if (normalized.isEmpty()) {
throw new RuntimeException("请至少选择一个工作日");
}
return normalized.stream().sorted().toList();
}
private String encodeWorkDays(List<Integer> workDays) {
return workDays.stream()
.sorted()
.map(String::valueOf)
.collect(Collectors.joining(","));
}
private List<Integer> decodeWorkDays(String workDays) {
if (workDays == null || workDays.isBlank()) {
return new ArrayList<>();
}
return List.of(workDays.split(",")).stream()
.map(String::trim)
.filter(value -> !value.isBlank())
.map(Integer::valueOf)
.sorted()
.toList();
}
private LocalTime presetStartTime(String presetType) {
if (PRESET_NINE_TO_FIVE.equals(presetType)) {
return LocalTime.of(9, 0);
}
return LocalTime.of(10, 0);
}
private LocalTime presetEndTime(String presetType) {
if (PRESET_NINE_TO_FIVE.equals(presetType)) {
return LocalTime.of(17, 0);
}
return LocalTime.of(22, 0);
}
private void validateTimeRange(LocalTime startTime, LocalTime endTime) {
if (startTime == null || endTime == null || !startTime.isBefore(endTime)) {
throw new RuntimeException("排班开始时间必须早于结束时间");
}
}
private String trimText(String value) {
return value == null ? null : value.trim();
}
private String exceptionRemark(ArtistScheduleExceptionDO exception) {
if (exception.getRemark() != null && !exception.getRemark().isBlank()) {
return exception.getRemark();
}
return "例外排班:" + exception.getExceptionType();
}
private record GeneratedSchedule(boolean working, LocalTime startTime, LocalTime endTime, Integer slotMinutes,
Integer capacity, String remark) {
}
}
@@ -1,831 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.artist.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaowang.jacyucloudsalon.core.modules.artist.dto.NailArtistInfoDTO;
import com.xiaowang.jacyucloudsalon.core.modules.artist.entity.ArtistScheduleDO;
import com.xiaowang.jacyucloudsalon.core.modules.artist.entity.ArtistScheduleRuleDO;
import com.xiaowang.jacyucloudsalon.core.modules.artist.entity.NailArtistInfoDO;
import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderArtistReviewDO;
import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderDO;
import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderItemDO;
import com.xiaowang.jacyucloudsalon.core.modules.product.entity.ProductDO;
import com.xiaowang.jacyucloudsalon.core.modules.shop.entity.ShopDO;
import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO;
import com.xiaowang.jacyucloudsalon.core.modules.artist.mapper.NailArtistInfoMapper;
import com.xiaowang.jacyucloudsalon.core.modules.planning.mapper.AppointmentReservationMapper;
import com.xiaowang.jacyucloudsalon.core.modules.artist.mapper.ArtistScheduleMapper;
import com.xiaowang.jacyucloudsalon.core.modules.artist.mapper.ArtistScheduleRuleMapper;
import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.OrderArtistReviewMapper;
import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.OrderItemMapper;
import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.OrderMapper;
import com.xiaowang.jacyucloudsalon.core.modules.product.mapper.ProductMapper;
import com.xiaowang.jacyucloudsalon.core.modules.shop.mapper.ShopMapper;
import com.xiaowang.jacyucloudsalon.core.modules.user.mapper.UserMapper;
import com.xiaowang.jacyucloudsalon.core.modules.artist.service.NailArtistInfoService;
import com.xiaowang.jacyucloudsalon.core.modules.file.service.ObjectStorageFileService;
import com.xiaowang.jacyucloudsalon.core.modules.file.support.ObjectStorageUrlSupport;
import com.xiaowang.jacyucloudsalon.core.modules.shop.support.UserShopBindingSupport;
import com.xiaowang.jacyucloudsalon.core.modules.artist.vo.NailArtistAvailabilityVO;
import com.xiaowang.jacyucloudsalon.core.modules.artist.vo.NailArtistProfileVO;
import com.xiaowang.jacyucloudsalon.core.modules.artist.vo.NailArtistReviewVO;
import com.xiaowang.jacyucloudsalon.core.modules.artist.vo.NailArtistWorkVO;
import com.xiaowang.jacyucloudsalon.core.modules.file.vo.ObjectStorageFileVO;
import com.xiaowang.jacyucloudsalon.core.modules.shop.vo.ShopSimpleVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
@Service
/**
* NailArtistInfoServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects.
* Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class.
*/
public class NailArtistInfoServiceImpl extends ServiceImpl<NailArtistInfoMapper, NailArtistInfoDO> implements NailArtistInfoService {
private static final int REVIEW_STATUS_SUBMITTED = 1;
private static final int ORDER_STATUS_COMPLETED = 2;
private static final int AVAILABILITY_DAYS = 7;
private static final int SLOT_MINUTES = 60;
private static final int MAX_AVAILABILITY_SLOTS = 16;
private static final DateTimeFormatter DATE_TEXT_FORMATTER = DateTimeFormatter.ISO_LOCAL_DATE;
private static final DateTimeFormatter TIME_TEXT_FORMATTER = DateTimeFormatter.ofPattern("HH:mm");
private static final String PRESET_DOUBLE_REST = "DOUBLE_REST";
private static final String PRESET_SINGLE_REST = "SINGLE_REST";
@Autowired
/**
* Purpose: userMapper supports NailArtistInfoServiceImpl.java by holding or executing the user mapper business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private UserMapper userMapper;
@Autowired
/**
* Purpose: shopMapper supports NailArtistInfoServiceImpl.java by holding or executing the shop mapper business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private ShopMapper shopMapper;
@Autowired
/**
* Purpose: userShopBindingSupport supports NailArtistInfoServiceImpl.java by holding or executing the user shop binding support business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private UserShopBindingSupport userShopBindingSupport;
@Autowired
private ProductMapper productMapper;
@Autowired
private OrderMapper orderMapper;
@Autowired
private OrderItemMapper orderItemMapper;
@Autowired
private OrderArtistReviewMapper orderArtistReviewMapper;
@Autowired
private ObjectStorageFileService objectStorageFileService;
@Autowired
private ObjectStorageUrlSupport objectStorageUrlSupport;
@Autowired(required = false)
private ArtistScheduleMapper artistScheduleMapper;
@Autowired(required = false)
private ArtistScheduleRuleMapper artistScheduleRuleMapper;
@Autowired(required = false)
private AppointmentReservationMapper appointmentReservationMapper;
@Override
/**
* Load data by the supplied parameter.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param userId parameter `userId` supplied by the caller
* @return NailArtistInfoDTO result consumed by the caller or returned to the frontend
*/
public NailArtistInfoDTO getByUserId(Long userId) {
NailArtistInfoDO info = getOne(new LambdaQueryWrapper<NailArtistInfoDO>()
.eq(NailArtistInfoDO::getUserId, userId)
.eq(NailArtistInfoDO::getIsDelete, 0)
.last("LIMIT 1"));
return info == null ? null : convertToDTO(info);
}
@Override
/**
* Load data by the supplied parameter.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @return List<NailArtistInfoDTO> result consumed by the caller or returned to the frontend
*/
public List<NailArtistInfoDTO> getAllNailArtists() {
List<NailArtistInfoDTO> result = new ArrayList<>();
List<NailArtistInfoDO> records = list(new LambdaQueryWrapper<NailArtistInfoDO>()
.eq(NailArtistInfoDO::getIsDelete, 0));
for (NailArtistInfoDO record : records) {
NailArtistInfoDTO dto = convertToDTO(record);
if (isVisibleServiceUser(dto)) {
result.add(dto);
}
}
enrichScheduleSummaries(result, null);
return result;
}
@Override
/**
* Load data by the supplied parameter.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param shopId parameter `shopId` supplied by the caller
* @return List<NailArtistInfoDTO> result consumed by the caller or returned to the frontend
*/
public List<NailArtistInfoDTO> getByShopId(Long shopId) {
List<Long> serviceUserIds = userShopBindingSupport.listUserIdsByShopId(shopId, true);
if (serviceUserIds.isEmpty()) {
return new ArrayList<>();
}
List<UserDO> users = userMapper.selectList(new LambdaQueryWrapper<UserDO>()
.in(UserDO::getId, serviceUserIds)
.eq(UserDO::getType, 3)
.eq(UserDO::getStatus, 1)
.eq(UserDO::getIsDelete, 0)
.orderByAsc(UserDO::getCreateTime)
.orderByAsc(UserDO::getId));
List<NailArtistInfoDTO> result = new ArrayList<>();
ShopDO shop = shopMapper.selectById(shopId);
for (UserDO user : users) {
NailArtistInfoDTO dto = getByUserId(user.getId());
if (dto == null) {
dto = buildFallbackArtistInfo(user);
}
dto.setShopId(shopId);
dto.setShopName(shop == null ? null : shop.getShopName());
result.add(dto);
}
enrichScheduleSummaries(result, shopId);
return result;
}
@Override
/**
* Save submitted data.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param dto parameter `dto` supplied by the caller
* @return NailArtistInfoDTO result consumed by the caller or returned to the frontend
*/
public NailArtistInfoDTO saveOrUpdateNailArtistInfo(NailArtistInfoDTO dto) {
NailArtistInfoDO entity = new NailArtistInfoDO();
BeanUtils.copyProperties(dto, entity);
NailArtistInfoDO existing = getOne(new LambdaQueryWrapper<NailArtistInfoDO>()
.eq(NailArtistInfoDO::getUserId, dto.getUserId())
.eq(NailArtistInfoDO::getIsDelete, 0)
.last("LIMIT 1"));
if (existing != null) {
entity.setId(existing.getId());
}
if (entity.getStatus() == null) {
entity.setStatus(1);
}
if (entity.getParticipateProduction() == null) {
UserDO user = userMapper.selectById(dto.getUserId());
entity.setParticipateProduction(user != null && Integer.valueOf(3).equals(user.getType()) ? 1 : 0);
}
/**
* Save submitted data.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param entity parameter `entity` supplied by the caller
* @return result consumed by the caller or returned to the frontend
*/
saveOrUpdate(entity);
/**
* Run business method `convertToDTO`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param entity parameter `entity` supplied by the caller
* @return return result consumed by the caller or returned to the frontend
*/
return convertToDTO(entity);
}
@Override
/**
* Load data by the supplied parameter.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @return List<NailArtistInfoDTO> result consumed by the caller or returned to the frontend
*/
public List<NailArtistInfoDTO> getAllAvailableNailArtists() {
List<NailArtistInfoDTO> result = new ArrayList<>();
List<NailArtistInfoDO> records = list(new LambdaQueryWrapper<NailArtistInfoDO>()
.eq(NailArtistInfoDO::getStatus, 1)
.eq(NailArtistInfoDO::getIsDelete, 0));
for (NailArtistInfoDO record : records) {
NailArtistInfoDTO dto = convertToDTO(record);
if (isBookableServiceUser(dto)) {
result.add(dto);
}
}
return result;
}
@Override
public NailArtistProfileVO getPublicProfile(Long artistId) {
NailArtistInfoDTO artistInfo = loadPublicArtistInfo(artistId);
UserDO artist = userMapper.selectById(artistId);
if (artist == null || isDeleted(artist.getIsDelete())) {
throw new RuntimeException("美甲师信息不存在");
}
List<OrderItemDO> servedItems = loadArtistOrderItems(artistId, true);
List<NailArtistReviewVO> reviews = listPublicReviews(artistId);
NailArtistProfileVO profile = new NailArtistProfileVO();
profile.setArtistId(artistId);
profile.setArtistName(resolveArtistName(artistInfo, artist));
profile.setAvatar(artist.getAvatar());
profile.setIdentity(artistInfo.getIdentity());
profile.setSignature(artistInfo.getSignature());
profile.setExperience(artistInfo.getExperience());
profile.setStatus(artistInfo.getStatus());
profile.setShopId(artistInfo.getShopId());
profile.setShopName(artistInfo.getShopName());
profile.setRating(resolvePublicRating(artistId, artistInfo));
profile.setServiceCount(countServiceQuantity(servedItems));
profile.setWorkStartTime(artistInfo.getWorkStartTime());
profile.setWorkEndTime(artistInfo.getWorkEndTime());
profile.setStyleTags(parseTextTokens(artistInfo.getSkills()));
profile.setWorks(buildWorks(artistInfo.getPortfolio(), servedItems, 24));
profile.setReviews(reviews.stream().limit(3).collect(Collectors.toList()));
profile.setAvailability(getAvailability(artistId).stream().limit(8).collect(Collectors.toList()));
return profile;
}
@Override
public List<NailArtistAvailabilityVO> getAvailability(Long artistId) {
NailArtistInfoDTO artistInfo = loadPublicArtistInfo(artistId);
if (!Integer.valueOf(1).equals(artistInfo.getStatus())) {
return new ArrayList<>();
}
List<NailArtistAvailabilityVO> scheduleSlots = buildScheduleAvailabilitySlots(artistId, artistInfo);
if (!scheduleSlots.isEmpty()) {
return scheduleSlots;
}
LocalTime workStart = artistInfo.getWorkStartTime() == null ? LocalTime.of(10, 0) : artistInfo.getWorkStartTime();
LocalTime workEnd = artistInfo.getWorkEndTime() == null ? LocalTime.of(20, 0) : artistInfo.getWorkEndTime();
if (!workEnd.isAfter(workStart)) {
workStart = LocalTime.of(10, 0);
workEnd = LocalTime.of(20, 0);
}
LocalDate today = LocalDate.now();
LocalDateTime rangeStart = today.atStartOfDay();
LocalDateTime rangeEnd = today.plusDays(AVAILABILITY_DAYS + 1L).atStartOfDay();
Set<LocalDateTime> bookedStarts = loadBookedSlotStarts(artistId, rangeStart, rangeEnd);
LocalDateTime now = LocalDateTime.now();
List<NailArtistAvailabilityVO> slots = new ArrayList<>();
for (int dayOffset = 0; dayOffset < AVAILABILITY_DAYS && slots.size() < MAX_AVAILABILITY_SLOTS; dayOffset++) {
LocalDate date = today.plusDays(dayOffset);
LocalTime cursor = workStart;
while (!cursor.plusMinutes(SLOT_MINUTES).isAfter(workEnd) && slots.size() < MAX_AVAILABILITY_SLOTS) {
LocalDateTime slotStart = date.atTime(cursor);
LocalDateTime slotEnd = slotStart.plusMinutes(SLOT_MINUTES);
if (slotStart.isAfter(now.plusMinutes(30)) && !bookedStarts.contains(truncateToMinute(slotStart))) {
slots.add(buildAvailabilitySlot(slotStart, slotEnd));
}
cursor = cursor.plusMinutes(SLOT_MINUTES);
}
}
return slots;
}
private List<NailArtistAvailabilityVO> buildScheduleAvailabilitySlots(Long artistId, NailArtistInfoDTO artistInfo) {
if (artistScheduleMapper == null || artistInfo.getShopId() == null) {
return new ArrayList<>();
}
LocalDate today = LocalDate.now();
List<ArtistScheduleDO> schedules = artistScheduleMapper.selectList(new LambdaQueryWrapper<ArtistScheduleDO>()
.eq(ArtistScheduleDO::getShopId, artistInfo.getShopId())
.eq(ArtistScheduleDO::getArtistId, artistId)
.eq(ArtistScheduleDO::getStatus, 1)
.eq(ArtistScheduleDO::getIsDelete, 0)
.ge(ArtistScheduleDO::getWorkDate, today)
.lt(ArtistScheduleDO::getWorkDate, today.plusDays(AVAILABILITY_DAYS))
.orderByAsc(ArtistScheduleDO::getWorkDate)
.orderByAsc(ArtistScheduleDO::getStartTime));
if (schedules == null || schedules.isEmpty()) {
return new ArrayList<>();
}
LocalDateTime minStart = LocalDateTime.now().plusMinutes(30);
List<NailArtistAvailabilityVO> slots = new ArrayList<>();
for (ArtistScheduleDO schedule : schedules) {
int slotMinutes = schedule.getSlotMinutes() == null || schedule.getSlotMinutes() < 15 ? SLOT_MINUTES : schedule.getSlotMinutes();
int capacity = schedule.getCapacity() == null || schedule.getCapacity() < 1 ? 1 : schedule.getCapacity();
LocalTime cursor = schedule.getStartTime();
while (cursor != null && schedule.getEndTime() != null
&& !cursor.plusMinutes(slotMinutes).isAfter(schedule.getEndTime())
&& slots.size() < MAX_AVAILABILITY_SLOTS) {
LocalDateTime slotStart = schedule.getWorkDate().atTime(cursor);
LocalDateTime slotEnd = slotStart.plusMinutes(slotMinutes);
int used = appointmentReservationMapper == null ? 0
: appointmentReservationMapper.countOverlappingActive(artistId, slotStart, slotEnd);
if (slotStart.isAfter(minStart) && used < capacity) {
slots.add(buildAvailabilitySlot(slotStart, slotEnd));
}
cursor = cursor.plusMinutes(slotMinutes);
}
if (slots.size() >= MAX_AVAILABILITY_SLOTS) {
break;
}
}
return slots;
}
@Override
public List<NailArtistReviewVO> listPublicReviews(Long artistId) {
if (artistId == null) {
return new ArrayList<>();
}
List<OrderArtistReviewDO> reviews = orderArtistReviewMapper.selectList(new LambdaQueryWrapper<OrderArtistReviewDO>()
.eq(OrderArtistReviewDO::getArtistId, artistId)
.eq(OrderArtistReviewDO::getStatus, REVIEW_STATUS_SUBMITTED)
.eq(OrderArtistReviewDO::getIsDelete, 0)
.orderByDesc(OrderArtistReviewDO::getSubmittedAt)
.orderByDesc(OrderArtistReviewDO::getId));
if (reviews == null || reviews.isEmpty()) {
return new ArrayList<>();
}
List<OrderArtistReviewDO> limitedReviews = reviews.stream().limit(20).collect(Collectors.toList());
Map<Long, UserDO> customerMap = loadUsers(limitedReviews.stream()
.map(OrderArtistReviewDO::getCustomerId)
.collect(Collectors.toCollection(LinkedHashSet::new)));
Map<Long, ProductDO> productMap = loadProducts(limitedReviews.stream()
.map(OrderArtistReviewDO::getProductId)
.collect(Collectors.toCollection(LinkedHashSet::new)));
Set<Long> imageIds = new LinkedHashSet<>();
for (OrderArtistReviewDO review : limitedReviews) {
imageIds.addAll(parseLongTokens(review.getImageFileIds()));
}
Map<Long, ObjectStorageFileVO> fileMap = loadFiles(imageIds);
List<NailArtistReviewVO> result = new ArrayList<>();
for (OrderArtistReviewDO review : limitedReviews) {
result.add(buildReviewVO(review, customerMap, productMap, fileMap));
}
return result;
}
/**
* Run business method `convertToDTO`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param entity parameter `entity` supplied by the caller
* @return private NailArtistInfoDTO result consumed by the caller or returned to the frontend
*/
private NailArtistInfoDTO convertToDTO(NailArtistInfoDO entity) {
NailArtistInfoDTO dto = new NailArtistInfoDTO();
BeanUtils.copyProperties(entity, dto);
UserDO user = userMapper.selectById(entity.getUserId());
if (user != null) {
dto.setNickname(user.getNickname());
dto.setSignature(user.getSignature());
dto.setAvatar(resolveAccessibleAvatar(user.getAvatar()));
dto.setUserType(user.getType());
dto.setUserTypeName(resolveUserTypeName(user.getType()));
if (dto.getParticipateProduction() == null) {
dto.setParticipateProduction(Integer.valueOf(3).equals(user.getType()) ? 1 : 0);
}
List<ShopSimpleVO> shopOptions = userShopBindingSupport.listShopOptionsByUserId(user.getId(), true, true);
if (!shopOptions.isEmpty()) {
ShopSimpleVO primaryShop = shopOptions.get(0);
dto.setShopId(primaryShop.getId());
dto.setShopName(primaryShop.getShopName());
} else if (user.getShopId() != null && user.getShopId() > 0) {
ShopDO shop = shopMapper.selectById(user.getShopId());
if (shop != null) {
dto.setShopId(shop.getId());
dto.setShopName(shop.getShopName());
}
}
}
return dto;
}
private NailArtistInfoDTO buildFallbackArtistInfo(UserDO user) {
NailArtistInfoDTO dto = new NailArtistInfoDTO();
dto.setUserId(user.getId());
dto.setNickname(user.getNickname());
dto.setSignature(user.getSignature());
dto.setAvatar(resolveAccessibleAvatar(user.getAvatar()));
dto.setUserType(user.getType());
dto.setUserTypeName(resolveUserTypeName(user.getType()));
dto.setIdentity("美甲师");
dto.setStatus(1);
dto.setParticipateProduction(1);
dto.setShopId(user.getShopId());
List<ShopSimpleVO> shopOptions = userShopBindingSupport.listShopOptionsByUserId(user.getId(), true, true);
if (!shopOptions.isEmpty()) {
ShopSimpleVO primaryShop = shopOptions.get(0);
dto.setShopId(primaryShop.getId());
dto.setShopName(primaryShop.getShopName());
} else if (user.getShopId() != null && user.getShopId() > 0) {
ShopDO shop = shopMapper.selectById(user.getShopId());
if (shop != null) {
dto.setShopId(shop.getId());
dto.setShopName(shop.getShopName());
}
}
return dto;
}
private void enrichScheduleSummaries(List<NailArtistInfoDTO> artists, Long shopId) {
if (artistScheduleRuleMapper == null || artists == null || artists.isEmpty()) {
return;
}
Set<Long> artistIds = artists.stream()
.map(NailArtistInfoDTO::getUserId)
.filter(userId -> userId != null && userId > 0)
.collect(Collectors.toCollection(LinkedHashSet::new));
if (artistIds.isEmpty()) {
return;
}
LambdaQueryWrapper<ArtistScheduleRuleDO> wrapper = new LambdaQueryWrapper<ArtistScheduleRuleDO>()
.in(ArtistScheduleRuleDO::getArtistId, artistIds)
.eq(ArtistScheduleRuleDO::getIsDelete, 0);
if (shopId != null && shopId > 0) {
wrapper.eq(ArtistScheduleRuleDO::getShopId, shopId);
}
Map<Long, ArtistScheduleRuleDO> ruleByArtistId = artistScheduleRuleMapper.selectList(wrapper).stream()
.collect(Collectors.toMap(ArtistScheduleRuleDO::getArtistId, rule -> rule, (left, right) -> left));
artists.forEach(artist -> applyScheduleSummary(artist, ruleByArtistId.get(artist.getUserId())));
}
private void applyScheduleSummary(NailArtistInfoDTO artist, ArtistScheduleRuleDO rule) {
if (artist == null) {
return;
}
if (rule == null || !Integer.valueOf(1).equals(rule.getStatus())) {
artist.setScheduleModeSummary("未设置");
artist.setScheduleTimeSummary("");
return;
}
artist.setScheduleModeSummary(resolveScheduleModeSummary(rule.getPresetType()));
artist.setScheduleTimeSummary(formatScheduleTimeSummary(rule.getStartTime(), rule.getEndTime()));
}
private String resolveScheduleModeSummary(String presetType) {
if (PRESET_DOUBLE_REST.equals(presetType)) {
return "双休";
}
if (PRESET_SINGLE_REST.equals(presetType)) {
return "单休";
}
return "自定义";
}
private String formatScheduleTimeSummary(LocalTime startTime, LocalTime endTime) {
if (startTime == null || endTime == null) {
return "";
}
return TIME_TEXT_FORMATTER.format(startTime) + "-" + TIME_TEXT_FORMATTER.format(endTime);
}
private String resolveAccessibleAvatar(String avatar) {
if (!StringUtils.hasText(avatar)) {
return null;
}
String accessibleUrl = objectStorageUrlSupport.toAccessibleUrl(avatar);
return StringUtils.hasText(accessibleUrl) ? accessibleUrl : avatar;
}
/**
* Run business method `isVisibleServiceUser`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param dto parameter `dto` supplied by the caller
* @return private boolean result consumed by the caller or returned to the frontend
*/
private boolean isVisibleServiceUser(NailArtistInfoDTO dto) {
if (dto == null || dto.getUserType() == null) {
return false;
}
return Integer.valueOf(3).equals(dto.getUserType())
|| Integer.valueOf(2).equals(dto.getUserType());
}
/**
* Run business method `isBookableServiceUser`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param dto parameter `dto` supplied by the caller
* @return private boolean result consumed by the caller or returned to the frontend
*/
private boolean isBookableServiceUser(NailArtistInfoDTO dto) {
return isVisibleServiceUser(dto) && Integer.valueOf(1).equals(dto.getStatus());
}
/**
* Run business method `resolveUserTypeName`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param type parameter `type` supplied by the caller
* @return private String result consumed by the caller or returned to the frontend
*/
private String resolveUserTypeName(Integer type) {
if (Integer.valueOf(2).equals(type)) {
return "店长";
}
if (Integer.valueOf(3).equals(type)) {
return "美甲师";
}
return "用户";
}
private NailArtistInfoDTO loadPublicArtistInfo(Long artistId) {
if (artistId == null) {
throw new RuntimeException("美甲师信息不存在");
}
NailArtistInfoDTO artistInfo = getByUserId(artistId);
if (artistInfo != null && isVisibleServiceUser(artistInfo)) {
return artistInfo;
}
UserDO artist = userMapper.selectById(artistId);
if (artist == null
|| isDeleted(artist.getIsDelete())
|| !Integer.valueOf(3).equals(artist.getType())
|| !Integer.valueOf(1).equals(artist.getStatus())) {
throw new RuntimeException("美甲师信息不存在");
}
return buildFallbackArtistInfo(artist);
}
private BigDecimal resolvePublicRating(Long artistId, NailArtistInfoDTO artistInfo) {
BigDecimal averageRating = orderArtistReviewMapper.selectAverageSubmittedRatingByArtistId(artistId);
BigDecimal rating = averageRating == null ? artistInfo.getRating() : averageRating;
if (rating == null) {
return BigDecimal.ZERO.setScale(1, RoundingMode.HALF_UP);
}
return rating.setScale(1, RoundingMode.HALF_UP);
}
private List<OrderItemDO> loadArtistOrderItems(Long artistId, boolean completedOnly) {
List<OrderDO> orders = orderMapper.selectByArtistId(artistId);
if (orders == null || orders.isEmpty()) {
return new ArrayList<>();
}
Set<Long> allowedOrderIds = orders.stream()
.filter(order -> !isDeleted(order.getIsDelete()))
.filter(order -> !completedOnly || Integer.valueOf(ORDER_STATUS_COMPLETED).equals(order.getStatus()))
.map(OrderDO::getId)
.collect(Collectors.toCollection(LinkedHashSet::new));
if (allowedOrderIds.isEmpty()) {
return new ArrayList<>();
}
List<OrderItemDO> items = new ArrayList<>();
for (Long orderId : allowedOrderIds) {
List<OrderItemDO> orderItems = orderItemMapper.selectByOrderId(orderId);
if (orderItems == null) {
continue;
}
for (OrderItemDO item : orderItems) {
if (item != null
&& artistId.equals(item.getArtistId())
&& !isDeleted(item.getIsDelete())) {
items.add(item);
}
}
}
return items;
}
private long countServiceQuantity(List<OrderItemDO> items) {
if (items == null || items.isEmpty()) {
return 0L;
}
long count = 0L;
for (OrderItemDO item : items) {
if (item == null) {
continue;
}
count += item.getQuantity() == null || item.getQuantity() < 1 ? 1L : item.getQuantity();
}
return count;
}
private List<NailArtistWorkVO> buildWorks(String portfolio, List<OrderItemDO> servedItems, int limit) {
LinkedHashSet<Long> productIds = new LinkedHashSet<>(parseLongTokens(portfolio));
if (servedItems != null) {
servedItems.stream()
.sorted(Comparator.comparing(OrderItemDO::getCreateTime, Comparator.nullsLast(Comparator.reverseOrder())))
.map(OrderItemDO::getProductId)
.filter(productId -> productId != null && productId > 0)
.forEach(productIds::add);
}
if (productIds.isEmpty()) {
return new ArrayList<>();
}
List<Long> limitedIds = productIds.stream().limit(Math.max(limit, 1)).collect(Collectors.toList());
Map<Long, ProductDO> productMap = loadProducts(new LinkedHashSet<>(limitedIds));
Set<Long> fileIds = new LinkedHashSet<>();
for (ProductDO product : productMap.values()) {
fileIds.addAll(parseLongTokens(product.getImageFileIds()));
}
Map<Long, ObjectStorageFileVO> fileMap = loadFiles(fileIds);
List<NailArtistWorkVO> works = new ArrayList<>();
for (Long productId : limitedIds) {
ProductDO product = productMap.get(productId);
if (product == null || isDeleted(product.getIsDelete()) || !isFrontVisible(product)) {
continue;
}
works.add(buildWorkVO(product, fileMap));
}
return works;
}
private NailArtistWorkVO buildWorkVO(ProductDO product, Map<Long, ObjectStorageFileVO> fileMap) {
NailArtistWorkVO work = new NailArtistWorkVO();
work.setId(product.getId());
work.setTitle(product.getTitle());
work.setDescription(product.getDescription());
work.setPrice(product.getPrice());
work.setTags(parseTextTokens(product.getTags()));
work.setLikeCount(product.getLikeCount());
work.setCollectCount(product.getCollectCount());
List<String> imageUrls = resolveImageUrls(parseLongTokens(product.getImageFileIds()), fileMap);
work.setImageUrls(imageUrls);
work.setCoverImageUrl(imageUrls.isEmpty() ? null : imageUrls.get(0));
return work;
}
private NailArtistReviewVO buildReviewVO(OrderArtistReviewDO review,
Map<Long, UserDO> customerMap,
Map<Long, ProductDO> productMap,
Map<Long, ObjectStorageFileVO> fileMap) {
NailArtistReviewVO vo = new NailArtistReviewVO();
vo.setId(review.getId());
vo.setArtistId(review.getArtistId());
vo.setCustomerId(review.getCustomerId());
UserDO customer = customerMap.get(review.getCustomerId());
vo.setCustomerName(customer == null || !StringUtils.hasText(customer.getNickname()) ? "匿名用户" : customer.getNickname());
vo.setCustomerAvatar(customer == null ? null : customer.getAvatar());
vo.setProductId(review.getProductId());
ProductDO product = productMap.get(review.getProductId());
vo.setProductTitle(product == null ? null : product.getTitle());
vo.setRating(review.getRatingScore());
vo.setContent(review.getContent());
List<Long> imageFileIds = parseLongTokens(review.getImageFileIds());
vo.setImageFileIds(imageFileIds);
vo.setImageUrls(resolveImageUrls(imageFileIds, fileMap));
vo.setSubmittedAt(review.getSubmittedAt());
return vo;
}
private Set<LocalDateTime> loadBookedSlotStarts(Long artistId, LocalDateTime rangeStart, LocalDateTime rangeEnd) {
List<OrderItemDO> bookedItems = orderItemMapper.selectArtistCalendarItems(artistId, rangeStart, rangeEnd);
if (bookedItems == null || bookedItems.isEmpty()) {
return new HashSet<>();
}
return bookedItems.stream()
.map(OrderItemDO::getAppointmentTime)
.filter(appointmentTime -> appointmentTime != null)
.map(this::truncateToMinute)
.collect(Collectors.toSet());
}
private NailArtistAvailabilityVO buildAvailabilitySlot(LocalDateTime startTime, LocalDateTime endTime) {
NailArtistAvailabilityVO slot = new NailArtistAvailabilityVO();
slot.setStartTime(startTime);
slot.setEndTime(endTime);
slot.setDateText(DATE_TEXT_FORMATTER.format(startTime.toLocalDate()));
slot.setTimeText(TIME_TEXT_FORMATTER.format(startTime.toLocalTime()));
slot.setAvailable(true);
return slot;
}
private Map<Long, ProductDO> loadProducts(Set<Long> productIds) {
if (productIds == null || productIds.isEmpty()) {
return new HashMap<>();
}
List<ProductDO> products = productMapper.selectBatchIds(productIds);
if (products == null || products.isEmpty()) {
return new HashMap<>();
}
return products.stream()
.filter(product -> product != null && product.getId() != null && !isDeleted(product.getIsDelete()) && isFrontVisible(product))
.collect(Collectors.toMap(ProductDO::getId, product -> product, (left, right) -> left, HashMap::new));
}
private Map<Long, UserDO> loadUsers(Set<Long> userIds) {
if (userIds == null || userIds.isEmpty()) {
return new HashMap<>();
}
List<UserDO> users = userMapper.selectBatchIds(new ArrayList<>(userIds));
if (users == null || users.isEmpty()) {
return new HashMap<>();
}
return users.stream()
.filter(user -> user != null && user.getId() != null)
.collect(Collectors.toMap(UserDO::getId, user -> user, (left, right) -> left, HashMap::new));
}
private Map<Long, ObjectStorageFileVO> loadFiles(Set<Long> fileIds) {
if (fileIds == null || fileIds.isEmpty()) {
return new HashMap<>();
}
Map<Long, ObjectStorageFileVO> files = objectStorageFileService.getObjectStorageFileMapByIds(fileIds);
return files == null ? new HashMap<>() : files;
}
private List<String> resolveImageUrls(List<Long> fileIds, Map<Long, ObjectStorageFileVO> fileMap) {
if (fileIds == null || fileIds.isEmpty() || fileMap == null || fileMap.isEmpty()) {
return new ArrayList<>();
}
List<String> urls = new ArrayList<>();
for (Long fileId : fileIds) {
ObjectStorageFileVO file = fileMap.get(fileId);
if (file != null && StringUtils.hasText(file.getFileUrl())) {
urls.add(objectStorageUrlSupport.toAccessibleUrl(file));
}
}
return urls;
}
private List<Long> parseLongTokens(String raw) {
if (!StringUtils.hasText(raw)) {
return new ArrayList<>();
}
LinkedHashSet<Long> ids = new LinkedHashSet<>();
for (String token : raw.split("[,;,;\\s]+")) {
if (!StringUtils.hasText(token)) {
continue;
}
try {
ids.add(Long.parseLong(token.trim()));
} catch (NumberFormatException ignored) {
// Some legacy fields store tag names instead of ids.
}
}
return new ArrayList<>(ids);
}
private List<String> parseTextTokens(String raw) {
if (!StringUtils.hasText(raw)) {
return new ArrayList<>();
}
LinkedHashSet<String> tokens = new LinkedHashSet<>();
for (String token : raw.split("[,;,;、\\s]+")) {
if (StringUtils.hasText(token)) {
tokens.add(token.trim());
}
}
return new ArrayList<>(tokens);
}
private String resolveArtistName(NailArtistInfoDTO artistInfo, UserDO artist) {
if (artistInfo != null && StringUtils.hasText(artistInfo.getNickname())) {
return artistInfo.getNickname();
}
if (artist != null && StringUtils.hasText(artist.getNickname())) {
return artist.getNickname();
}
return "美甲师";
}
private boolean isDeleted(Integer isDelete) {
return Integer.valueOf(1).equals(isDelete);
}
private boolean isFrontVisible(ProductDO product) {
return product != null && Integer.valueOf(1).equals(product.getFrontVisible());
}
private LocalDateTime truncateToMinute(LocalDateTime value) {
return value == null ? null : value.withSecond(0).withNano(0);
}
}
@@ -1,116 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.artist.support;
import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO;
import com.xiaowang.jacyucloudsalon.core.modules.artist.entity.NailArtistInfoDO;
import com.xiaowang.jacyucloudsalon.core.modules.artist.mapper.NailArtistInfoMapper;
import com.xiaowang.jacyucloudsalon.core.modules.user.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.stream.Collectors;
import com.xiaowang.jacyucloudsalon.core.modules.shop.support.UserShopBindingSupport;
@Component
@RequiredArgsConstructor
/**
* Purpose: BookableArtistSupport supports BookableArtistSupport.java by holding or executing the bookable artist support business role.
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
*/
public class BookableArtistSupport {
/**
* Purpose: userMapper supports BookableArtistSupport.java by holding or executing the user mapper business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private final UserMapper userMapper;
/**
* Purpose: nailArtistInfoMapper supports BookableArtistSupport.java by holding or executing the nail artist info mapper business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private final NailArtistInfoMapper nailArtistInfoMapper;
/**
* Purpose: userShopBindingSupport supports BookableArtistSupport.java by holding or executing the user shop binding support business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private final UserShopBindingSupport userShopBindingSupport;
/**
* Purpose: isValidBookableArtist supports BookableArtistSupport.java by holding or executing the is valid bookable artist business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public boolean isValidBookableArtist(Long shopId, Long artistId) {
if (artistId == null || artistId <= 0) {
return false;
}
UserDO artist = userMapper.selectById(artistId);
if (artist == null || Integer.valueOf(1).equals(artist.getIsDelete())) {
return false;
}
if (!isBookableServiceUser(artist)) {
return false;
}
if (!Integer.valueOf(1).equals(artist.getStatus())) {
return false;
}
return shopId == null || shopId <= 0 || userShopBindingSupport.isUserAccessibleInShop(artistId, shopId);
}
/**
* Purpose: isBookableServiceUser supports BookableArtistSupport.java by holding or executing the is bookable service user business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public boolean isBookableServiceUser(UserDO user) {
if (user == null || Integer.valueOf(1).equals(user.getIsDelete()) || !Integer.valueOf(1).equals(user.getStatus())) {
return false;
}
if (Integer.valueOf(3).equals(user.getType())) {
return true;
}
if (!Integer.valueOf(2).equals(user.getType())) {
return false;
}
NailArtistInfoDO info = nailArtistInfoMapper.selectOne(
new LambdaQueryWrapper<NailArtistInfoDO>()
.eq(NailArtistInfoDO::getUserId, user.getId())
.eq(NailArtistInfoDO::getIsDelete, 0)
.last("LIMIT 1")
);
return info != null
&& Integer.valueOf(1).equals(info.getStatus())
&& Integer.valueOf(1).equals(info.getParticipateProduction());
}
/**
* Purpose: filterValidBookableArtists supports BookableArtistSupport.java by holding or executing the filter valid bookable artists business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public String filterValidBookableArtists(Long shopId, String rawBookableArtists) {
if (!StringUtils.hasText(rawBookableArtists)) {
return "";
}
Set<Long> validArtistIds = new LinkedHashSet<>();
for (String artistIdText : rawBookableArtists.split(",")) {
if (!StringUtils.hasText(artistIdText)) {
continue;
}
try {
Long artistId = Long.parseLong(artistIdText.trim());
if (isValidBookableArtist(shopId, artistId)) {
validArtistIds.add(artistId);
}
} catch (NumberFormatException ignored) {
// Ignore invalid configured IDs and only expose currently valid artists.
}
}
return validArtistIds.stream()
.map(String::valueOf)
.collect(Collectors.joining(","));
}
}
@@ -1,90 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.artist.vo;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDateTime;
@Data
/**
* ArtistCalendarAppointmentVO is a response VO. Services build it and controllers return it to the frontend.
* Field and parameter names are kept consistent with the frontend/API payload to make tracing easier.
*/
public class ArtistCalendarAppointmentVO {
/**
* Field `orderId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long orderId;
/**
* Field `orderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String orderNo;
/**
* Field `totalAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private BigDecimal totalAmount;
/**
* Field `actualAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private BigDecimal actualAmount;
/**
* Field `orderStatus` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Integer orderStatus;
/**
* Field `orderStatusText` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String orderStatusText;
/**
* Field `orderItemId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long orderItemId;
/**
* Field `productId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long productId;
/**
* Field `productTitle` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String productTitle;
/**
* Field `artistId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long artistId;
/**
* Field `artistName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String artistName;
/**
* Field `customerNickname` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String customerNickname;
/**
* Field `customerPhoneMasked` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String customerPhoneMasked;
/**
* Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long shopId;
/**
* Field `shopName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String shopName;
/**
* Field `appointmentStartTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private LocalDateTime appointmentStartTime;
/**
* Field `appointmentEndTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private LocalDateTime appointmentEndTime;
/**
* Field `quantity` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Integer quantity;
/**
* Field `durationMinutes` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long durationMinutes;
}
@@ -1,20 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.artist.vo;
import lombok.Data;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
@Data
public class ArtistScheduleExceptionVO {
private Long id;
private Long shopId;
private Long artistId;
private LocalDate workDate;
private String exceptionType;
private LocalTime startTime;
private LocalTime endTime;
private String remark;
private LocalDateTime createTime;
}
@@ -1,11 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.artist.vo;
import lombok.Data;
import java.util.List;
@Data
public class ArtistScheduleRuleSettingVO {
private ArtistScheduleRuleVO rule;
private List<ArtistScheduleExceptionVO> exceptions;
}
@@ -1,21 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.artist.vo;
import lombok.Data;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
@Data
public class ArtistScheduleRuleVO {
private Long id;
private Long shopId;
private Long artistId;
private String presetType;
private List<Integer> workDays;
private LocalTime startTime;
private LocalTime endTime;
private Integer status;
private String remark;
private LocalDateTime createTime;
}
@@ -1,22 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.artist.vo;
import lombok.Data;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
@Data
public class ArtistScheduleVO {
private Long id;
private Long shopId;
private Long artistId;
private LocalDate workDate;
private LocalTime startTime;
private LocalTime endTime;
private Integer slotMinutes;
private Integer capacity;
private Integer status;
private String remark;
private LocalDateTime createTime;
}
@@ -1,14 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.artist.vo;
import lombok.Data;
import java.time.LocalDateTime;
@Data
public class NailArtistAvailabilityVO {
private LocalDateTime startTime;
private LocalDateTime endTime;
private String dateText;
private String timeText;
private Boolean available;
}
@@ -1,33 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.artist.vo;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
@Data
public class NailArtistProfileVO {
@JsonSerialize(using = ToStringSerializer.class)
private Long artistId;
private String artistName;
private String avatar;
private String identity;
private String signature;
private Integer experience;
private Integer status;
@JsonSerialize(using = ToStringSerializer.class)
private Long shopId;
private String shopName;
private BigDecimal rating;
private Long serviceCount;
private LocalTime workStartTime;
private LocalTime workEndTime;
private List<String> styleTags = new ArrayList<>();
private List<NailArtistWorkVO> works = new ArrayList<>();
private List<NailArtistReviewVO> reviews = new ArrayList<>();
private List<NailArtistAvailabilityVO> availability = new ArrayList<>();
}
@@ -1,30 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.artist.vo;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
@Data
public class NailArtistReviewVO {
@JsonSerialize(using = ToStringSerializer.class)
private Long id;
@JsonSerialize(using = ToStringSerializer.class)
private Long artistId;
@JsonSerialize(using = ToStringSerializer.class)
private Long customerId;
private String customerName;
private String customerAvatar;
@JsonSerialize(using = ToStringSerializer.class)
private Long productId;
private String productTitle;
private BigDecimal rating;
private String content;
private List<Long> imageFileIds = new ArrayList<>();
private List<String> imageUrls = new ArrayList<>();
private LocalDateTime submittedAt;
}
@@ -1,23 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.artist.vo;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import lombok.Data;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
@Data
public class NailArtistWorkVO {
@JsonSerialize(using = ToStringSerializer.class)
private Long id;
private String title;
private String description;
private BigDecimal price;
private String coverImageUrl;
private List<String> imageUrls = new ArrayList<>();
private List<String> tags = new ArrayList<>();
private Integer likeCount;
private Integer collectCount;
}
@@ -1,111 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.auth.controller.front;
import com.xiaowang.jacyucloudsalon.core.common.Result;
import com.xiaowang.jacyucloudsalon.core.modules.auth.dto.LoginIdentityDTO;
import com.xiaowang.jacyucloudsalon.core.modules.auth.vo.LoginIdentityVO;
import com.xiaowang.jacyucloudsalon.core.modules.auth.service.LoginIdentityService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 用户登录标识信息表 Controller
* 对应数据库表 t_login_identity
*
* @author xiaowang
* @date 2026-02-13
*/
@RestController
@RequestMapping({"/login-identity", "/api/login-identity"})
@RequiredArgsConstructor
public class LoginIdentityController {
/**
* Variable `loginIdentityService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final LoginIdentityService loginIdentityService;
/**
* 创建登录标识
*
* @param loginIdentityDTO 登录标识DTO
* @return 登录标识ID
*/
@PostMapping("/create")
public Result<Long> createLoginIdentity(@RequestBody LoginIdentityDTO loginIdentityDTO) {
Long id = loginIdentityService.createLoginIdentity(loginIdentityDTO);
return Result.success(id);
}
/**
* 更新登录标识
*
* @param id 登录标识ID
* @param loginIdentityDTO 登录标识DTO
* @return 是否更新成功
*/
@PutMapping("/update/{id}")
public Result<Boolean> updateLoginIdentity(@PathVariable Long id, @RequestBody LoginIdentityDTO loginIdentityDTO) {
boolean success = loginIdentityService.updateLoginIdentity(id, loginIdentityDTO);
return Result.success(success);
}
/**
* 删除登录标识
*
* @param id 登录标识ID
* @return 是否删除成功
*/
@DeleteMapping("/delete/{id}")
public Result<Boolean> deleteLoginIdentity(@PathVariable Long id) {
boolean success = loginIdentityService.deleteLoginIdentity(id);
return Result.success(success);
}
/**
* 根据ID查询登录标识
*
* @param id 登录标识ID
* @return 登录标识VO
*/
@GetMapping("/get/{id}")
public Result<LoginIdentityVO> getLoginIdentityById(@PathVariable Long id) {
LoginIdentityVO loginIdentityVO = loginIdentityService.getLoginIdentityById(id);
return Result.success(loginIdentityVO);
}
/**
* 查询所有登录标识
*
* @return 登录标识VO列表
*/
@GetMapping("/list/all")
public Result<List<LoginIdentityVO>> listAllLoginIdentities() {
List<LoginIdentityVO> loginIdentityVOs = loginIdentityService.listAllLoginIdentities();
return Result.success(loginIdentityVOs);
}
/**
* 根据用户ID查询登录标识
*
* @param userId 用户ID
* @return 登录标识VO列表
*/
@GetMapping("/list/user/{userId}")
public Result<List<LoginIdentityVO>> listLoginIdentitiesByUserId(@PathVariable Long userId) {
List<LoginIdentityVO> loginIdentityVOs = loginIdentityService.listLoginIdentitiesByUserId(userId);
return Result.success(loginIdentityVOs);
}
/**
* 根据登录方式查询登录标识
*
* @param loginMethod 登录方式
* @return 登录标识VO列表
*/
@GetMapping("/list/loginMethod/{loginMethod}")
public Result<List<LoginIdentityVO>> listLoginIdentitiesByLoginMethod(@PathVariable String loginMethod) {
List<LoginIdentityVO> loginIdentityVOs = loginIdentityService.listLoginIdentitiesByLoginMethod(loginMethod);
return Result.success(loginIdentityVOs);
}
}
@@ -1,24 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.auth.dto;
import lombok.Data;
/**
* 绑定邮箱请求 DTO
* 用于用户绑定邮箱账号
*
* @author xiaowang
* @date 2026-03-12
*/
@Data
public class BindEmailRequestDTO {
/**
* 邮箱地址
*/
private String email;
/**
* 验证码
*/
private String code;
}
@@ -1,26 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.auth.dto;
import com.fasterxml.jackson.annotation.JsonAlias;
import lombok.Data;
/**
* 绑定手机号请求 DTO
* 用于用户绑定手机号
*
* @author xiaowang
* @date 2026-03-12
*/
@Data
public class BindPhoneRequestDTO {
/**
* 手机号
*/
private String phone;
/**
* 验证码
*/
@JsonAlias("code")
private String verificationCode;
}
@@ -1,41 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.auth.dto;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 用户登录标识信息表 DTO
* 用于登录标识信息的传输
*
* @author xiaowang
* @date 2026-02-13
*/
@Data
public class LoginIdentityDTO {
/**
* 关联用户表主键
*/
private Long userId;
/**
* 登录方式(0-手机号、1-账号、2-邮箱)
*/
private String loginMethod;
/**
* 前端输入的具体值(如手机号、账号、邮箱)
*/
private String inputValue;
/**
* 输入时间
*/
private LocalDateTime inputTime;
/**
* 状态:1-有效,0-无效
*/
private Integer status;
}
@@ -1,62 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.auth.dto;
import com.xiaowang.jacyucloudsalon.core.utils.AccountValidationUtils;
import lombok.Getter;
import lombok.Setter;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import java.util.Map;
import com.xiaowang.jacyucloudsalon.core.common.dto.AgreementAwareRequest;
/**
* 登录请求 DTO
* 用于用户账号密码登录
*
* @author xiaowang
* @date 2026-02-14
*/
@Getter
@Setter
public class LoginRequestDTO implements AgreementAwareRequest {
/**
* 账号
*/
@NotBlank(message = "账号不能为空")
@Pattern(regexp = AccountValidationUtils.ACCOUNT_REGEX, message = "账号只能包含字母和数字")
private String account;
/**
* 密码
*/
private String password;
/**
* 记住我标志
*/
private Boolean rememberMe;
/**
* 店铺ID
*/
private Long shopId;
/**
* Purpose: agreementAccepted supports LoginRequestDTO.java by holding or executing the agreement accepted business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Boolean agreementAccepted;
/**
* Purpose: agreementVersions supports LoginRequestDTO.java by holding or executing the agreement versions business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Map<String, String> agreementVersions;
/**
* Purpose: clientType supports LoginRequestDTO.java by holding or executing the client type business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private String clientType;
}
@@ -1,59 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.auth.dto;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import java.util.Map;
import com.xiaowang.jacyucloudsalon.core.common.dto.AgreementAwareRequest;
/**
* 手机号验证码登录请求 DTO
*
* @author xiaowang
* @date 2026-03-03
*/
@Data
public class PhoneLoginRequestDTO implements AgreementAwareRequest {
@NotBlank(message = "手机号不能为空")
@Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确")
/**
* Field `phone` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String phone;
@NotBlank(message = "验证码不能为空")
@Pattern(regexp = "^\\d{6}$", message = "验证码必须是6位数字")
/**
* Field `verificationCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String verificationCode;
/**
* Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long shopId;
/**
* 记住登录标志
*/
private Boolean rememberMe;
/**
* Purpose: agreementAccepted supports PhoneLoginRequestDTO.java by holding or executing the agreement accepted business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Boolean agreementAccepted;
/**
* Purpose: agreementVersions supports PhoneLoginRequestDTO.java by holding or executing the agreement versions business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Map<String, String> agreementVersions;
/**
* Purpose: clientType supports PhoneLoginRequestDTO.java by holding or executing the client type business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private String clientType;
}
@@ -1,19 +0,0 @@
package com.xiaowang.jacyucloudsalon.core.modules.auth.dto;
import lombok.Data;
/**
* 刷新Token请求 DTO
* 用于刷新访问令牌
*
* @author xiaowang
* @date 2026-02-14
*/
@Data
public class RefreshTokenRequestDTO {
/**
* 刷新令牌
*/
private String refreshToken;
}

Some files were not shown because too many files have changed in this diff Show More