diff --git a/AGENTS.md b/AGENTS.md index 5ddf5e08..804dbe6b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,7 +1,7 @@ # GitNexus — Code Intelligence -This project is indexed by GitNexus as **xiaowang** (17628 symbols, 35093 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. +This project is indexed by GitNexus as **xiaowang** (17889 symbols, 35678 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. > If any GitNexus tool warns the index is stale, run `npx gitnexus analyze` in terminal first. @@ -29,6 +29,17 @@ This project is indexed by GitNexus as **xiaowang** (17628 symbols, 35093 relati | `gitnexus://repo/xiaowang/processes` | All execution flows | | `gitnexus://repo/xiaowang/process/{name}` | Step-by-step execution trace | +## CLI + +| Task | Read this skill file | +|------|---------------------| +| Understand architecture / "How does X work?" | `.claude/skills/gitnexus/gitnexus-exploring/SKILL.md` | +| Blast radius / "What breaks if I change X?" | `.claude/skills/gitnexus/gitnexus-impact-analysis/SKILL.md` | +| Trace bugs / "Why is X failing?" | `.claude/skills/gitnexus/gitnexus-debugging/SKILL.md` | +| Rename / extract / split / refactor | `.claude/skills/gitnexus/gitnexus-refactoring/SKILL.md` | +| Tools, resources, schema reference | `.claude/skills/gitnexus/gitnexus-guide/SKILL.md` | +| Index, status, clean, wiki CLI commands | `.claude/skills/gitnexus/gitnexus-cli/SKILL.md` | + ## Browser MCP Preference diff --git a/CLAUDE.md b/CLAUDE.md index f98cfaf5..ae3f2cdf 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,7 +1,7 @@ # GitNexus — Code Intelligence -This project is indexed by GitNexus as **xiaowang** (17628 symbols, 35093 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. +This project is indexed by GitNexus as **xiaowang** (17889 symbols, 35678 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. > If any GitNexus tool warns the index is stale, run `npx gitnexus analyze` in terminal first. @@ -29,4 +29,15 @@ This project is indexed by GitNexus as **xiaowang** (17628 symbols, 35093 relati | `gitnexus://repo/xiaowang/processes` | All execution flows | | `gitnexus://repo/xiaowang/process/{name}` | Step-by-step execution trace | +## CLI + +| Task | Read this skill file | +|------|---------------------| +| Understand architecture / "How does X work?" | `.claude/skills/gitnexus/gitnexus-exploring/SKILL.md` | +| Blast radius / "What breaks if I change X?" | `.claude/skills/gitnexus/gitnexus-impact-analysis/SKILL.md` | +| Trace bugs / "Why is X failing?" | `.claude/skills/gitnexus/gitnexus-debugging/SKILL.md` | +| Rename / extract / split / refactor | `.claude/skills/gitnexus/gitnexus-refactoring/SKILL.md` | +| Tools, resources, schema reference | `.claude/skills/gitnexus/gitnexus-guide/SKILL.md` | +| Index, status, clean, wiki CLI commands | `.claude/skills/gitnexus/gitnexus-cli/SKILL.md` | + diff --git a/FingertipManager-Program/app.wxss b/FingertipManager-Program/app.wxss index 9402c400..6ed1a987 100644 --- a/FingertipManager-Program/app.wxss +++ b/FingertipManager-Program/app.wxss @@ -255,3 +255,25 @@ button::after { color: #a39b91; text-align: center; } + +.error-card { + display: flex; + flex-direction: column; + gap: 12rpx; + margin: 18rpx 0; + padding: 22rpx; + border-color: rgba(191, 111, 104, 0.22); + background: #fff8f6; +} + +.error-title { + color: #7f4540; + font-size: 26rpx; + font-weight: 800; +} + +.error-desc { + color: #9b6a62; + font-size: 24rpx; + line-height: 1.45; +} diff --git a/FingertipManager-Program/pages/appointment-detail/index.js b/FingertipManager-Program/pages/appointment-detail/index.js index 10ad3fda..f7432241 100644 --- a/FingertipManager-Program/pages/appointment-detail/index.js +++ b/FingertipManager-Program/pages/appointment-detail/index.js @@ -1,4 +1,5 @@ const planningApi = require('../../api/planning') +const config = require('../../utils/config') const mock = require('../../utils/mock') Page({ @@ -6,21 +7,34 @@ Page({ id: '', appointment: {}, avatarText: '', - timeText: '' + timeText: '', + loadError: false, + errorMessage: '' }, - onLoad(options) { + onLoad(options = {}) { this.setData({ id: options.id || '' }) this.loadDetail() }, async loadDetail() { + this.setData({ loadError: false, errorMessage: '' }) try { const appointment = await planningApi.appointment(this.data.id) this.applyAppointment(appointment) } catch (error) { - const demo = mock.buildCalendar(new Date()).appointments[0] - this.applyAppointment(demo) + if (config.USE_DEV_MOCK_DATA) { + const demo = mock.buildCalendar(new Date()).appointments[0] + this.applyAppointment(demo) + } else { + this.setData({ + appointment: {}, + avatarText: '', + timeText: '', + loadError: true, + errorMessage: error.message || '预约详情加载失败,请检查服务连接后重试' + }) + } } }, @@ -28,11 +42,17 @@ Page({ this.setData({ appointment, avatarText: String(appointment.customerName || '客').slice(0, 1), - timeText: `${(appointment.startTime || '').slice(0, 16)} - ${(appointment.endTime || '').slice(11, 16)}` + timeText: `${(appointment.startTime || '').slice(0, 16)} - ${(appointment.endTime || '').slice(11, 16)}`, + loadError: false, + errorMessage: '' }) }, async updateStatus(status) { + if (!this.data.appointment.orderId) { + wx.showToast({ title: '预约数据未加载', icon: 'none' }) + return + } try { await planningApi.updateStatus(this.data.appointment.orderId, status) wx.showToast({ title: '已更新' }) diff --git a/FingertipManager-Program/pages/appointment-detail/index.wxml b/FingertipManager-Program/pages/appointment-detail/index.wxml index b1725e46..29731ce5 100644 --- a/FingertipManager-Program/pages/appointment-detail/index.wxml +++ b/FingertipManager-Program/pages/appointment-detail/index.wxml @@ -1,46 +1,54 @@ - - - - {{avatarText}} - - {{appointment.customerName}} - {{appointment.customerPhone}} + + 数据加载失败 + {{errorMessage}} + + + + + + + + {{avatarText}} + + {{appointment.customerName}} + {{appointment.customerPhone}} + + + + {{appointment.statusText}} + - - {{appointment.statusText}} - + + + 项目 + {{appointment.productTitle}} + + + 美甲师 + {{appointment.artistName}} + + + 时间 + {{timeText}} + + + 时长 + {{appointment.durationMinutes}}分钟 + - - - 项目 - {{appointment.productTitle}} - - - 美甲师 - {{appointment.artistName}} - - - 时间 - {{timeText}} - - - 时长 - {{appointment.durationMinutes}}分钟 - + + + 备注 + {{appointment.remark || '暂无备注'}} - - - 备注 - {{appointment.remark || '暂无备注'}} - - - - - - - + + + + + + diff --git a/FingertipManager-Program/pages/appointment-form/index.js b/FingertipManager-Program/pages/appointment-form/index.js index 2ceee872..0b28cf52 100644 --- a/FingertipManager-Program/pages/appointment-form/index.js +++ b/FingertipManager-Program/pages/appointment-form/index.js @@ -1,8 +1,15 @@ const planningApi = require('../../api/planning') const productsApi = require('../../api/products') +const config = require('../../utils/config') const mock = require('../../utils/mock') const dateUtil = require('../../utils/date') +const toDurationMinutes = value => { + if (typeof value === 'number') return value + const parsed = parseInt(String(value || ''), 10) + return Number.isFinite(parsed) && parsed > 0 ? parsed : 60 +} + Page({ data: { form: { @@ -16,15 +23,16 @@ Page({ remark: '' }, products: [], - artists: mock.artists, + artists: config.USE_DEV_MOCK_DATA ? mock.artists : [], selectedProduct: {}, selectedArtist: {}, conflictTip: '', conflictLevel: 'free', - loading: false + loading: false, + optionError: '' }, - onLoad(options) { + onLoad(options = {}) { this.setData({ 'form.appointmentDate': options.date || dateUtil.formatDate(new Date()), 'form.artistId': options.artistId || '' @@ -33,22 +41,38 @@ Page({ }, async loadOptions() { - const fallbackProducts = [ - { id: 1, title: '纯色美甲', approximateDuration: '90分钟' }, - { id: 2, title: '猫眼延长', approximateDuration: '120分钟' }, - { id: 3, title: '手部护理', approximateDuration: '60分钟' } - ] + let products = [] + let artists = [] + let optionError = '' try { const productsData = await productsApi.list({ page: 1, size: 100 }) - const products = productsData.list || productsData || fallbackProducts - this.setData({ products }) + products = productsData.list || productsData || [] } catch (error) { - this.setData({ products: fallbackProducts }) + optionError = error.message || '项目数据加载失败' + products = config.USE_DEV_MOCK_DATA + ? [ + { id: 1, title: '纯色美甲', approximateDuration: '90分钟' }, + { id: 2, title: '猫眼延长', approximateDuration: '120分钟' }, + { id: 3, title: '手部护理', approximateDuration: '60分钟' } + ] + : [] } - if (this.data.form.artistId) { - const selectedArtist = this.data.artists.find(item => String(item.id) === String(this.data.form.artistId)) || {} - this.setData({ selectedArtist }) + + try { + const calendar = await planningApi.calendar({ + startDate: this.data.form.appointmentDate, + endDate: this.data.form.appointmentDate + }) + artists = calendar.artists || [] + } catch (error) { + optionError = optionError || error.message || '美甲师数据加载失败' + artists = config.USE_DEV_MOCK_DATA ? mock.artists : [] } + + const selectedArtist = this.data.form.artistId + ? artists.find(item => String(item.id) === String(this.data.form.artistId)) || {} + : {} + this.setData({ products, artists, selectedArtist, optionError }) this.checkAvailability() }, @@ -60,7 +84,7 @@ Page({ onDateChange(event) { this.setData({ 'form.appointmentDate': event.detail.value }) - this.checkAvailability() + this.loadOptions() }, onTimeChange(event) { @@ -73,7 +97,7 @@ Page({ this.setData({ selectedProduct, 'form.productId': selectedProduct.id, - 'form.durationMinutes': String(parseInt(selectedProduct.approximateDuration, 10) || this.data.form.durationMinutes || 60) + 'form.durationMinutes': String(toDurationMinutes(selectedProduct.approximateDuration)) }) this.checkAvailability() }, @@ -101,40 +125,42 @@ Page({ this.setData({ conflictTip: tip, conflictLevel: 'danger' }) return { ok: false, tip } } + + let calendar try { - let calendar - try { - calendar = await planningApi.calendar({ - startDate: form.appointmentDate, - endDate: form.appointmentDate, - artistId: form.artistId - }) - } catch (error) { - calendar = mock.buildCalendar(form.appointmentDate) - } - const conflicts = (calendar.appointments || []).filter(item => { - if (String(item.artistId) !== String(form.artistId) || item.date !== form.appointmentDate) return false - if (item.status === 3 || item.statusText === '已取消') return false - const itemStart = Number(item.startMinute || dateUtil.minutesOfDay((item.startTime || '').slice(11, 16))) - const itemEnd = itemStart + Number(item.durationMinutes || 60) - return startMinute < itemEnd && endMinute > itemStart + calendar = await planningApi.calendar({ + startDate: form.appointmentDate, + endDate: form.appointmentDate, + artistId: form.artistId }) - if (conflicts.length > 0) { - const first = conflicts[0] - const itemStart = Number(first.startMinute || dateUtil.minutesOfDay((first.startTime || '').slice(11, 16))) - const itemEnd = itemStart + Number(first.durationMinutes || 60) - const tip = `${this.data.selectedArtist.name || '该美甲师'} ${dateUtil.timeFromMinutes(itemStart)}-${dateUtil.timeFromMinutes(itemEnd)} 已有预约` + } catch (error) { + if (config.USE_DEV_MOCK_DATA) { + calendar = mock.buildCalendar(form.appointmentDate) + } else { + const tip = error.message || '暂未获取到排班,无法确认该时段是否可预约' this.setData({ conflictTip: tip, conflictLevel: 'danger' }) return { ok: false, tip } } - const tip = `${this.data.selectedArtist.name || '该美甲师'} ${form.appointmentTime}-${dateUtil.timeFromMinutes(endMinute)} 可预约` - this.setData({ conflictTip: tip, conflictLevel: 'free' }) - return { ok: true, tip } - } catch (error) { - const tip = '暂未获取到排班,请保存时以系统校验为准' - this.setData({ conflictTip: tip, conflictLevel: 'warn' }) - return { ok: true, tip } } + + const conflicts = (calendar.appointments || []).filter(item => { + if (String(item.artistId) !== String(form.artistId) || item.date !== form.appointmentDate) return false + if (item.status === 3 || item.statusText === '已取消') return false + const itemStart = Number(item.startMinute || dateUtil.minutesOfDay((item.startTime || '').slice(11, 16))) + const itemEnd = itemStart + Number(item.durationMinutes || 60) + return startMinute < itemEnd && endMinute > itemStart + }) + if (conflicts.length > 0) { + const first = conflicts[0] + const itemStart = Number(first.startMinute || dateUtil.minutesOfDay((first.startTime || '').slice(11, 16))) + const itemEnd = itemStart + Number(first.durationMinutes || 60) + const tip = `${this.data.selectedArtist.name || '该美甲师'} ${dateUtil.timeFromMinutes(itemStart)}-${dateUtil.timeFromMinutes(itemEnd)} 已有预约` + this.setData({ conflictTip: tip, conflictLevel: 'danger' }) + return { ok: false, tip } + } + const tip = `${this.data.selectedArtist.name || '该美甲师'} ${form.appointmentTime}-${dateUtil.timeFromMinutes(endMinute)} 可预约` + this.setData({ conflictTip: tip, conflictLevel: 'free' }) + return { ok: true, tip } }, async submit() { @@ -145,7 +171,7 @@ Page({ } const availability = await this.checkAvailability() if (!availability.ok) { - wx.showToast({ title: availability.tip || '该时段已被预约', icon: 'none' }) + wx.showToast({ title: availability.tip || '该时段不可预约', icon: 'none' }) return } this.setData({ loading: true }) diff --git a/FingertipManager-Program/pages/appointment-form/index.wxml b/FingertipManager-Program/pages/appointment-form/index.wxml index c1029621..0b9d47ef 100644 --- a/FingertipManager-Program/pages/appointment-form/index.wxml +++ b/FingertipManager-Program/pages/appointment-form/index.wxml @@ -1,4 +1,10 @@ + + 选项加载不完整 + {{optionError}} + + + 客户姓名 diff --git a/FingertipManager-Program/pages/artist-transfer/index.js b/FingertipManager-Program/pages/artist-transfer/index.js index eab5face..39dbbe39 100644 --- a/FingertipManager-Program/pages/artist-transfer/index.js +++ b/FingertipManager-Program/pages/artist-transfer/index.js @@ -1,7 +1,18 @@ const planningApi = require('../../api/planning') +const config = require('../../utils/config') const mock = require('../../utils/mock') const dateUtil = require('../../utils/date') +const normalizeArtists = artists => (artists || []).map((item, index) => ({ + id: item.id || item.userId || item.artistId, + name: item.name || item.nickname || item.artistName || `美甲师${index + 1}`, + shortName: item.shortName || String(item.name || item.nickname || '师').slice(-1), + color: item.color || ['#7BA7C7', '#89A98B', '#A893BC', '#D49A89'][index % 4], + statusText: item.statusText || '可接单', + availableStatus: item.availableStatus || 'free', + availableText: item.availableText || '可接' +})) + Page({ data: { id: '', @@ -9,18 +20,35 @@ Page({ selectedArtistId: '', date: dateUtil.formatDate(new Date()), time: '13:00', - loading: false + loading: false, + loadError: false, + errorMessage: '' }, - onLoad(options) { - this.setData({ - id: options.id || '', - artists: mock.artists.map((item, index) => ({ - ...item, - availableStatus: index === 1 ? 'busy' : index === 2 ? 'full' : 'free', - availableText: index === 1 ? '有冲突' : index === 2 ? '已满' : '可接' - })) - }) + onLoad(options = {}) { + this.setData({ id: options.id || '' }) + this.loadArtists() + }, + + async loadArtists() { + this.setData({ loadError: false, errorMessage: '' }) + try { + const calendar = await planningApi.calendar({ + startDate: this.data.date, + endDate: this.data.date + }) + this.setData({ artists: normalizeArtists(calendar.artists || []) }) + } catch (error) { + if (config.USE_DEV_MOCK_DATA) { + this.setData({ artists: normalizeArtists(mock.artists) }) + } else { + this.setData({ + artists: [], + loadError: true, + errorMessage: error.message || '美甲师可接状态加载失败,请检查服务连接后重试' + }) + } + } }, selectArtist(event) { @@ -28,7 +56,8 @@ Page({ }, onDateChange(event) { - this.setData({ date: event.detail.value }) + this.setData({ date: event.detail.value, selectedArtistId: '' }) + this.loadArtists() }, onTimeChange(event) { @@ -36,6 +65,10 @@ Page({ }, async submit() { + if (this.data.loadError) { + wx.showToast({ title: '请先重新加载可接员工', icon: 'none' }) + return + } if (!this.data.selectedArtistId) { wx.showToast({ title: '请选择美甲师', icon: 'none' }) return diff --git a/FingertipManager-Program/pages/artist-transfer/index.wxml b/FingertipManager-Program/pages/artist-transfer/index.wxml index 52b46cd4..b68f9510 100644 --- a/FingertipManager-Program/pages/artist-transfer/index.wxml +++ b/FingertipManager-Program/pages/artist-transfer/index.wxml @@ -1,5 +1,13 @@ - + + 数据加载失败 + {{errorMessage}} + + + + 暂无可改派美甲师 + + diff --git a/FingertipManager-Program/pages/employee-detail/index.js b/FingertipManager-Program/pages/employee-detail/index.js index f00a3f7e..92f6a0e6 100644 --- a/FingertipManager-Program/pages/employee-detail/index.js +++ b/FingertipManager-Program/pages/employee-detail/index.js @@ -1,26 +1,62 @@ +const employeesApi = require('../../api/employees') +const config = require('../../utils/config') const mock = require('../../utils/mock') +const normalizeEmployee = (item = {}) => ({ + id: item.userId || item.id, + name: item.nickname || item.name || item.artistName || '美甲师', + shortName: (item.nickname || item.name || item.artistName || '师').slice(-1), + color: item.color || '#7BA7C7', + monthOrders: item.monthOrders || item.orderCount || 0, + monthAmount: item.monthAmount || item.turnover || 0, + avgAmount: item.avgAmount || item.averageAmount || 0 +}) + Page({ data: { id: '', - employee: {} + employee: {}, + loadError: false, + errorMessage: '' }, - onLoad(options) { - const id = options.id || mock.artists[0].id - const artist = mock.artists.find(item => String(item.id) === String(id)) || mock.artists[0] - this.setData({ - id, - employee: { - ...artist, - monthOrders: 32, - monthAmount: 5800, - avgAmount: 181 + onLoad(options = {}) { + const id = options.id || '' + this.setData({ id }) + this.loadEmployee() + }, + + async loadEmployee() { + this.setData({ loadError: false, errorMessage: '' }) + try { + const employee = await employeesApi.detail(this.data.id) + this.setData({ employee: normalizeEmployee(employee) }) + } catch (error) { + if (config.USE_DEV_MOCK_DATA) { + const artist = mock.artists.find(item => String(item.id) === String(this.data.id)) || mock.artists[0] + this.setData({ + employee: normalizeEmployee({ + ...artist, + monthOrders: 32, + monthAmount: 5800, + avgAmount: 181 + }) + }) + } else { + this.setData({ + employee: {}, + loadError: true, + errorMessage: error.message || '员工详情加载失败,请检查服务连接后重试' + }) } - }) + } }, go(event) { + if (this.data.loadError) { + wx.showToast({ title: '请先重新加载员工详情', icon: 'none' }) + return + } wx.navigateTo({ url: `${event.currentTarget.dataset.url}?id=${this.data.id}` }) }, diff --git a/FingertipManager-Program/pages/employee-detail/index.wxml b/FingertipManager-Program/pages/employee-detail/index.wxml index ec050539..5b60cfbb 100644 --- a/FingertipManager-Program/pages/employee-detail/index.wxml +++ b/FingertipManager-Program/pages/employee-detail/index.wxml @@ -1,33 +1,41 @@ - - {{employee.shortName}} - - {{employee.name}} - 员工色 - + + 数据加载失败 + {{errorMessage}} + - - - {{employee.monthOrders}} - 本月订单 + + + {{employee.shortName}} + + {{employee.name}} + 员工色 + - - ¥{{employee.monthAmount}} - 本月营业额 - - - ¥{{employee.avgAmount}} - 平均客单价 - - - - - 排班设置 - 请假管理 - 颜色设置 - 订单记录 + + + {{employee.monthOrders}} + 本月订单 + + + ¥{{employee.monthAmount}} + 本月营业额 + + + ¥{{employee.avgAmount}} + 平均客单价 + - + + + + 排班设置 + 请假管理 + 颜色设置 + 订单记录 + + + diff --git a/FingertipManager-Program/pages/employees/index.js b/FingertipManager-Program/pages/employees/index.js index 3e77cf8c..b2171e8b 100644 --- a/FingertipManager-Program/pages/employees/index.js +++ b/FingertipManager-Program/pages/employees/index.js @@ -1,9 +1,12 @@ const employeesApi = require('../../api/employees') -const mock = require('../../utils/mock') + +const EMPLOYEE_COLORS = ['#7BA7C7', '#89A98B', '#A893BC', '#D49A89', '#C9A66B', '#7E9A9A'] Page({ data: { - employees: [] + employees: [], + loadError: false, + errorMessage: '' }, onLoad() { @@ -11,11 +14,7 @@ Page({ }, async loadEmployees() { - const fallback = mock.artists.map((item, index) => ({ - ...item, - monthOrders: 32 - index * 5, - monthAmount: 5800 - index * 760 - })) + this.setData({ loadError: false, errorMessage: '' }) try { const data = await employeesApi.list({ page: 1, size: 50 }) const list = data.list || data || [] @@ -24,13 +23,17 @@ Page({ id: item.userId || item.id, name: item.nickname || item.name || item.artistName || `美甲师${index + 1}`, shortName: (item.nickname || item.name || '师').slice(-1), - color: mock.artists[index % mock.artists.length].color, + color: item.color || EMPLOYEE_COLORS[index % EMPLOYEE_COLORS.length], monthOrders: item.monthOrders || item.orderCount || 0, monthAmount: item.monthAmount || item.turnover || 0 })) }) } catch (error) { - this.setData({ employees: fallback }) + this.setData({ + employees: [], + loadError: true, + errorMessage: error.message || '员工数据加载失败,请检查服务连接后重试' + }) } }, diff --git a/FingertipManager-Program/pages/employees/index.wxml b/FingertipManager-Program/pages/employees/index.wxml index 35fa8129..b94a6024 100644 --- a/FingertipManager-Program/pages/employees/index.wxml +++ b/FingertipManager-Program/pages/employees/index.wxml @@ -4,7 +4,15 @@ - + + 数据加载失败 + {{errorMessage}} + + + + 暂无员工数据 + + {{item.shortName}} diff --git a/FingertipManager-Program/pages/planning/index.js b/FingertipManager-Program/pages/planning/index.js index 56fe3902..d5778438 100644 --- a/FingertipManager-Program/pages/planning/index.js +++ b/FingertipManager-Program/pages/planning/index.js @@ -1,5 +1,6 @@ const planningApi = require('../../api/planning') const dateUtil = require('../../utils/date') +const config = require('../../utils/config') const mock = require('../../utils/mock') Page({ @@ -40,7 +41,9 @@ Page({ dayTotal: 0, freeArtistCount: 0, pendingCount: 0, - loading: false + loading: false, + loadError: false, + errorMessage: '' }, onLoad() { @@ -130,9 +133,25 @@ Page({ endDate: range.end, artistId: this.data.selectedArtistId || undefined }) + this.setData({ loadError: false, errorMessage: '' }) this.applyCalendar(data) } catch (error) { - this.applyCalendar(mock.buildCalendar(this.data.currentDateText)) + if (config.USE_DEV_MOCK_DATA) { + this.setData({ loadError: false, errorMessage: '' }) + this.applyCalendar(mock.buildCalendar(this.data.currentDateText)) + } else { + this.setData({ + loadError: true, + errorMessage: error.message || '规划数据加载失败,请检查服务连接后重试' + }) + this.applyCalendar({ + businessStartTime: this.data.businessStartTime, + businessEndTime: this.data.businessEndTime, + artists: this.data.artists, + appointments: [], + daySummaries: [] + }) + } } finally { this.setData({ loading: false }) } diff --git a/FingertipManager-Program/pages/planning/index.wxml b/FingertipManager-Program/pages/planning/index.wxml index ca1a11da..d6652454 100644 --- a/FingertipManager-Program/pages/planning/index.wxml +++ b/FingertipManager-Program/pages/planning/index.wxml @@ -26,6 +26,12 @@ + + 数据加载失败 + {{errorMessage}} + + + diff --git a/FingertipManager-Program/utils/config.js b/FingertipManager-Program/utils/config.js index c40e8b05..4bd4a3a2 100644 --- a/FingertipManager-Program/utils/config.js +++ b/FingertipManager-Program/utils/config.js @@ -3,5 +3,6 @@ const DEFAULT_DOMAIN = 'http://127.0.0.1:63341' module.exports = { API_DOMAIN: DEFAULT_DOMAIN, ADMIN_API_BASE_URL: `${DEFAULT_DOMAIN}/admin`, - REQUEST_TIMEOUT: 10000 + REQUEST_TIMEOUT: 10000, + USE_DEV_MOCK_DATA: false } diff --git a/WeChatProgram/api/payment.js b/WeChatProgram/api/payment.js index b551479f..89caf52d 100644 --- a/WeChatProgram/api/payment.js +++ b/WeChatProgram/api/payment.js @@ -7,13 +7,5 @@ module.exports = { method: 'POST', data: {} }) - }, - - mockOrderPaymentSuccess(orderId) { - return request({ - url: `/payment/order/${orderId}/mock-success`, - method: 'POST', - data: {} - }) } } diff --git a/WeChatProgram/api/vnext.test.js b/WeChatProgram/api/vnext.test.js index 95d3a12a..154b78bc 100644 --- a/WeChatProgram/api/vnext.test.js +++ b/WeChatProgram/api/vnext.test.js @@ -19,7 +19,6 @@ const afterSaleApi = require('./after-sale') const growthApi = require('./growth') paymentApi.prepareOrderPayment(12) -paymentApi.mockOrderPaymentSuccess(12) afterSaleApi.applyAfterSale({ orderId: 12, reason: 'need refund' }) afterSaleApi.getMyAfterSales({ page: 2, size: 5 }) growthApi.getGrowthSummary() @@ -32,19 +31,14 @@ assert.deepStrictEqual(calls[0], { data: {} }) assert.deepStrictEqual(calls[1], { - url: '/payment/order/12/mock-success', - method: 'POST', - data: {} -}) -assert.deepStrictEqual(calls[2], { url: '/after-sale/apply', method: 'POST', data: { orderId: 12, reason: 'need refund' } }) -assert.deepStrictEqual(calls[3], { +assert.deepStrictEqual(calls[2], { url: '/after-sale/my', params: { page: 2, size: 5 } }) -assert.deepStrictEqual(calls[4], { +assert.deepStrictEqual(calls[3], { url: '/growth/summary' }) diff --git a/WeChatProgram/pages/orders/index.js b/WeChatProgram/pages/orders/index.js index f2a444cd..1329c732 100644 --- a/WeChatProgram/pages/orders/index.js +++ b/WeChatProgram/pages/orders/index.js @@ -864,9 +864,9 @@ Page({ }) const confirmed = await new Promise(resolve => { wx.showModal({ - title: '模拟支付', - content: `本次需支付 ${order.paymentInfo.amountText},确认模拟支付成功吗?`, - confirmText: '确认支付', + title: '准备支付', + content: `本次需支付 ${order.paymentInfo.amountText},支付单准备后请等待正式支付接入。`, + confirmText: '知道了', success: res => resolve(Boolean(res.confirm)), fail: () => resolve(false) }) @@ -874,11 +874,8 @@ Page({ if (!confirmed) { return } - await runWithLoading(() => paymentApi.mockOrderPaymentSuccess(orderId), { - title: '确认支付' - }) wx.showToast({ - title: '支付已确认', + title: '支付单已准备', icon: 'none' }) await this.loadOrders() diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/JwtProperties.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/JwtProperties.java index 2ec3281d..e3a6e408 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/JwtProperties.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/JwtProperties.java @@ -4,36 +4,38 @@ import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; -/** - * JWT 配置。 - */ +import java.nio.charset.StandardCharsets; + @Data @Configuration @ConfigurationProperties(prefix = "yuminail.security.jwt") public class JwtProperties { - /** - * HS512 密钥,生产环境请通过 Nacos 覆盖。 - */ - private String secret = "yuminail-secret-key-for-jwt-token-generation-2026-must-be-at-least-512-bits-long-for-hs512-algorithm-security-requirements"; + public static final String DEVELOPMENT_PLACEHOLDER_SECRET = "__CONFIGURE_YUMINAIL_JWT_SECRET_OUTSIDE_REPOSITORY__"; + private static final int HS512_MIN_SECRET_BYTES = 64; /** - * Token 发行者。 + * HS512 signing key. Production and shared environments must provide it through Nacos or environment variables. */ + private String secret = DEVELOPMENT_PLACEHOLDER_SECRET; + private String issuer = "yuminail"; - /** - * AccessToken 有效期,单位秒。 - */ private long accessTokenExpirationSeconds = 2 * 60 * 60; - /** - * RefreshToken 有效期,单位秒。 - */ private long refreshTokenExpirationSeconds = 7 * 24 * 60 * 60; - /** - * 时钟偏移容忍,单位秒。 - */ private long clockSkewSeconds = 30; + + public void requireValidSecret() { + if (secret == null || secret.isBlank()) { + throw new IllegalStateException("JWT 密钥不能为空,请通过外部配置提供 yuminail.security.jwt.secret"); + } + if (DEVELOPMENT_PLACEHOLDER_SECRET.equals(secret)) { + throw new IllegalStateException("JWT 密钥仍为仓库占位值,请通过外部配置覆盖后再启动服务"); + } + if (secret.getBytes(StandardCharsets.UTF_8).length < HS512_MIN_SECRET_BYTES) { + throw new IllegalStateException("JWT 密钥长度不足,HS512 至少需要 64 字节"); + } + } } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/artist/mapper/ArtistScheduleMapper.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/artist/mapper/ArtistScheduleMapper.java index 5f472cbc..293eea1a 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/artist/mapper/ArtistScheduleMapper.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/artist/mapper/ArtistScheduleMapper.java @@ -11,12 +11,22 @@ import java.time.LocalTime; @Mapper public interface ArtistScheduleMapper extends BaseMapper { + @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") + "AND is_delete = 0 ORDER BY CASE WHEN status = 1 THEN 0 ELSE 1 END, start_time ASC LIMIT 1") 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 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 selectCoveringScheduleForUpdate(@Param("shopId") Long shopId, + @Param("artistId") Long artistId, + @Param("workDate") LocalDate workDate, + @Param("startTime") LocalTime startTime, + @Param("endTime") LocalTime endTime); } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/auth/controller/front/LoginIdentityController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/auth/controller/front/LoginIdentityController.java index 206304fe..845a7c0b 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/auth/controller/front/LoginIdentityController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/auth/controller/front/LoginIdentityController.java @@ -1,12 +1,17 @@ package com.xiaowang.yuminailcore.modules.auth.controller.front; +import com.xiaowang.yuminailcore.annotation.RequirePermission; import com.xiaowang.yuminailcore.common.Result; import com.xiaowang.yuminailcore.modules.auth.dto.LoginIdentityDTO; import com.xiaowang.yuminailcore.modules.auth.vo.LoginIdentityVO; import com.xiaowang.yuminailcore.modules.auth.service.LoginIdentityService; +import com.xiaowang.yuminailcore.modules.security.support.AdminScopeHelper; +import com.xiaowang.yuminailcore.modules.shop.support.UserShopBindingSupport; +import com.xiaowang.yuminailcore.modules.user.entity.UserDO; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.*; +import javax.servlet.http.HttpServletRequest; import java.util.List; /** @@ -24,6 +29,8 @@ public class LoginIdentityController { * Variable `loginIdentityService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ private final LoginIdentityService loginIdentityService; + private final AdminScopeHelper adminScopeHelper; + private final UserShopBindingSupport userShopBindingSupport; /** * 创建登录标识 @@ -32,7 +39,10 @@ public class LoginIdentityController { * @return 登录标识ID */ @PostMapping("/create") - public Result createLoginIdentity(@RequestBody LoginIdentityDTO loginIdentityDTO) { + @RequirePermission("user:create") + public Result createLoginIdentity(HttpServletRequest request, @RequestBody LoginIdentityDTO loginIdentityDTO) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + ensureTargetUserAccessible(currentUser, loginIdentityDTO.getUserId(), "无权为其他店铺用户创建登录标识"); Long id = loginIdentityService.createLoginIdentity(loginIdentityDTO); return Result.success(id); } @@ -45,7 +55,14 @@ public class LoginIdentityController { * @return 是否更新成功 */ @PutMapping("/update/{id}") - public Result updateLoginIdentity(@PathVariable Long id, @RequestBody LoginIdentityDTO loginIdentityDTO) { + @RequirePermission("user:edit") + public Result updateLoginIdentity(HttpServletRequest request, @PathVariable Long id, @RequestBody LoginIdentityDTO loginIdentityDTO) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + LoginIdentityVO existing = loginIdentityService.getLoginIdentityById(id); + if (existing != null) { + ensureTargetUserAccessible(currentUser, existing.getUserId(), "无权编辑其他店铺用户登录标识"); + } + ensureTargetUserAccessible(currentUser, loginIdentityDTO.getUserId(), "无权将登录标识改到其他店铺用户"); boolean success = loginIdentityService.updateLoginIdentity(id, loginIdentityDTO); return Result.success(success); } @@ -57,7 +74,13 @@ public class LoginIdentityController { * @return 是否删除成功 */ @DeleteMapping("/delete/{id}") - public Result deleteLoginIdentity(@PathVariable Long id) { + @RequirePermission("user:delete") + public Result deleteLoginIdentity(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + LoginIdentityVO existing = loginIdentityService.getLoginIdentityById(id); + if (existing != null) { + ensureTargetUserAccessible(currentUser, existing.getUserId(), "无权删除其他店铺用户登录标识"); + } boolean success = loginIdentityService.deleteLoginIdentity(id); return Result.success(success); } @@ -69,8 +92,13 @@ public class LoginIdentityController { * @return 登录标识VO */ @GetMapping("/get/{id}") - public Result getLoginIdentityById(@PathVariable Long id) { + @RequirePermission("user:view") + public Result getLoginIdentityById(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); LoginIdentityVO loginIdentityVO = loginIdentityService.getLoginIdentityById(id); + if (loginIdentityVO != null) { + ensureTargetUserAccessible(currentUser, loginIdentityVO.getUserId(), "无权查看其他店铺用户登录标识"); + } return Result.success(loginIdentityVO); } @@ -80,8 +108,12 @@ public class LoginIdentityController { * @return 登录标识VO列表 */ @GetMapping("/list/all") - public Result> listAllLoginIdentities() { - List loginIdentityVOs = loginIdentityService.listAllLoginIdentities(); + @RequirePermission("user:view") + public Result> listAllLoginIdentities(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + List loginIdentityVOs = adminScopeHelper.isPlatformAdmin(currentUser) + ? loginIdentityService.listAllLoginIdentities() + : loginIdentityService.listLoginIdentitiesByUserIds(scopedUserIds(currentUser)); return Result.success(loginIdentityVOs); } @@ -92,7 +124,10 @@ public class LoginIdentityController { * @return 登录标识VO列表 */ @GetMapping("/list/user/{userId}") - public Result> listLoginIdentitiesByUserId(@PathVariable Long userId) { + @RequirePermission("user:view") + public Result> listLoginIdentitiesByUserId(HttpServletRequest request, @PathVariable Long userId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + ensureTargetUserAccessible(currentUser, userId, "无权查看其他店铺用户登录标识"); List loginIdentityVOs = loginIdentityService.listLoginIdentitiesByUserId(userId); return Result.success(loginIdentityVOs); } @@ -104,8 +139,21 @@ public class LoginIdentityController { * @return 登录标识VO列表 */ @GetMapping("/list/loginMethod/{loginMethod}") - public Result> listLoginIdentitiesByLoginMethod(@PathVariable String loginMethod) { - List loginIdentityVOs = loginIdentityService.listLoginIdentitiesByLoginMethod(loginMethod); + @RequirePermission("user:view") + public Result> listLoginIdentitiesByLoginMethod(HttpServletRequest request, @PathVariable String loginMethod) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + List loginIdentityVOs = adminScopeHelper.isPlatformAdmin(currentUser) + ? loginIdentityService.listLoginIdentitiesByLoginMethod(loginMethod) + : loginIdentityService.listLoginIdentitiesByLoginMethodAndUserIds(loginMethod, scopedUserIds(currentUser)); return Result.success(loginIdentityVOs); } + + private List scopedUserIds(UserDO currentUser) { + Long managedShopId = adminScopeHelper.getManagedShopId(currentUser); + return userShopBindingSupport.listUserIdsByShopId(managedShopId, true); + } + + private void ensureTargetUserAccessible(UserDO currentUser, Long targetUserId, String message) { + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, targetUserId, message); + } } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/auth/service/LoginIdentityService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/auth/service/LoginIdentityService.java index e8e0e78c..79849265 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/auth/service/LoginIdentityService.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/auth/service/LoginIdentityService.java @@ -5,6 +5,7 @@ import com.xiaowang.yuminailcore.modules.auth.entity.LoginIdentityDO; import com.xiaowang.yuminailcore.modules.auth.dto.LoginIdentityDTO; import com.xiaowang.yuminailcore.modules.auth.vo.LoginIdentityVO; +import java.util.Collection; import java.util.List; /** @@ -56,6 +57,8 @@ public interface LoginIdentityService extends IService { */ List listAllLoginIdentities(); + List listLoginIdentitiesByUserIds(Collection userIds); + /** * 根据用户ID查询登录标识 * @@ -71,4 +74,6 @@ public interface LoginIdentityService extends IService { * @return 登录标识VO列表 */ List listLoginIdentitiesByLoginMethod(String loginMethod); + + List listLoginIdentitiesByLoginMethodAndUserIds(String loginMethod, Collection userIds); } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/auth/service/impl/LoginIdentityServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/auth/service/impl/LoginIdentityServiceImpl.java index ab35c4b0..3d709e66 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/auth/service/impl/LoginIdentityServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/auth/service/impl/LoginIdentityServiceImpl.java @@ -10,6 +10,7 @@ import com.xiaowang.yuminailcore.modules.auth.vo.LoginIdentityVO; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; +import java.util.Collection; import java.util.List; import java.util.stream.Collectors; @@ -113,6 +114,21 @@ public class LoginIdentityServiceImpl extends ServiceImpl listLoginIdentitiesByUserIds(Collection userIds) { + List scopedUserIds = normalizeUserIds(userIds); + if (scopedUserIds.isEmpty()) { + return List.of(); + } + List loginIdentityDOs = loginIdentityMapper.selectList( + Wrappers.lambdaQuery(LoginIdentityDO.class) + .in(LoginIdentityDO::getUserId, scopedUserIds) + ); + return loginIdentityDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + @Override /** * List records for the current query or current user scope. @@ -147,6 +163,32 @@ public class LoginIdentityServiceImpl extends ServiceImpl listLoginIdentitiesByLoginMethodAndUserIds(String loginMethod, Collection userIds) { + List scopedUserIds = normalizeUserIds(userIds); + if (scopedUserIds.isEmpty()) { + return List.of(); + } + List loginIdentityDOs = loginIdentityMapper.selectList( + Wrappers.lambdaQuery(LoginIdentityDO.class) + .eq(LoginIdentityDO::getLoginMethod, loginMethod) + .in(LoginIdentityDO::getUserId, scopedUserIds) + ); + return loginIdentityDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + private List normalizeUserIds(Collection userIds) { + if (userIds == null || userIds.isEmpty()) { + return List.of(); + } + return userIds.stream() + .filter(id -> id != null && id > 0) + .distinct() + .collect(Collectors.toList()); + } + /** * 将 DO 转换为 VO * diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/marketing/controller/front/VipBenefitController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/marketing/controller/front/VipBenefitController.java index f869155a..599a9066 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/marketing/controller/front/VipBenefitController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/marketing/controller/front/VipBenefitController.java @@ -1,12 +1,15 @@ package com.xiaowang.yuminailcore.modules.marketing.controller.front; +import com.xiaowang.yuminailcore.annotation.RequirePermission; import com.xiaowang.yuminailcore.common.Result; import com.xiaowang.yuminailcore.modules.marketing.dto.VipBenefitDTO; import com.xiaowang.yuminailcore.modules.marketing.vo.VipBenefitVO; import com.xiaowang.yuminailcore.modules.marketing.service.VipBenefitService; +import com.xiaowang.yuminailcore.modules.security.support.AdminScopeHelper; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.*; +import javax.servlet.http.HttpServletRequest; import java.util.List; /** @@ -24,6 +27,7 @@ public class VipBenefitController { * Variable `vipBenefitService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ private final VipBenefitService vipBenefitService; + private final AdminScopeHelper adminScopeHelper; /** * 创建VIP权益 @@ -32,7 +36,9 @@ public class VipBenefitController { * @return VIP权益ID */ @PostMapping("/create") - public Result createVipBenefit(@RequestBody VipBenefitDTO vipBenefitDTO) { + @RequirePermission("user:vip:manage") + public Result createVipBenefit(HttpServletRequest request, @RequestBody VipBenefitDTO vipBenefitDTO) { + requirePlatformAdmin(request); Long id = vipBenefitService.createVipBenefit(vipBenefitDTO); return Result.success(id); } @@ -45,7 +51,9 @@ public class VipBenefitController { * @return 是否更新成功 */ @PutMapping("/update/{id}") - public Result updateVipBenefit(@PathVariable Long id, @RequestBody VipBenefitDTO vipBenefitDTO) { + @RequirePermission("user:vip:manage") + public Result updateVipBenefit(HttpServletRequest request, @PathVariable Long id, @RequestBody VipBenefitDTO vipBenefitDTO) { + requirePlatformAdmin(request); boolean success = vipBenefitService.updateVipBenefit(id, vipBenefitDTO); return Result.success(success); } @@ -57,7 +65,9 @@ public class VipBenefitController { * @return 是否删除成功 */ @DeleteMapping("/delete/{id}") - public Result deleteVipBenefit(@PathVariable Long id) { + @RequirePermission("user:vip:manage") + public Result deleteVipBenefit(HttpServletRequest request, @PathVariable Long id) { + requirePlatformAdmin(request); boolean success = vipBenefitService.deleteVipBenefit(id); return Result.success(success); } @@ -69,7 +79,9 @@ public class VipBenefitController { * @return VIP权益VO */ @GetMapping("/get/{id}") - public Result getVipBenefitById(@PathVariable Long id) { + @RequirePermission("user:vip:manage") + public Result getVipBenefitById(HttpServletRequest request, @PathVariable Long id) { + requirePlatformAdmin(request); VipBenefitVO vipBenefitVO = vipBenefitService.getVipBenefitById(id); return Result.success(vipBenefitVO); } @@ -80,7 +92,9 @@ public class VipBenefitController { * @return VIP权益VO列表 */ @GetMapping("/list/all") - public Result> listAllVipBenefits() { + @RequirePermission("user:vip:manage") + public Result> listAllVipBenefits(HttpServletRequest request) { + requirePlatformAdmin(request); List vipBenefitVOs = vipBenefitService.listAllVipBenefits(); return Result.success(vipBenefitVOs); } @@ -92,8 +106,17 @@ public class VipBenefitController { * @return VIP权益VO列表 */ @GetMapping("/list/requiredVipLevel/{requiredVipLevel}") - public Result> listVipBenefitsByRequiredVipLevel(@PathVariable String requiredVipLevel) { + @RequirePermission("user:vip:manage") + public Result> listVipBenefitsByRequiredVipLevel(HttpServletRequest request, @PathVariable String requiredVipLevel) { + requirePlatformAdmin(request); List vipBenefitVOs = vipBenefitService.listVipBenefitsByRequiredVipLevel(requiredVipLevel); return Result.success(vipBenefitVOs); } + + private void requirePlatformAdmin(HttpServletRequest request) { + adminScopeHelper.requirePlatformAdmin( + adminScopeHelper.getCurrentUser(request), + "只有平台管理员可以维护全局VIP权益配置" + ); + } } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/marketing/controller/front/VipInfoController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/marketing/controller/front/VipInfoController.java index 95fd64d4..cabfd56c 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/marketing/controller/front/VipInfoController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/marketing/controller/front/VipInfoController.java @@ -1,12 +1,17 @@ package com.xiaowang.yuminailcore.modules.marketing.controller.front; +import com.xiaowang.yuminailcore.annotation.RequirePermission; import com.xiaowang.yuminailcore.common.Result; import com.xiaowang.yuminailcore.modules.marketing.dto.VipInfoDTO; import com.xiaowang.yuminailcore.modules.marketing.vo.VipInfoVO; import com.xiaowang.yuminailcore.modules.marketing.service.VipInfoService; +import com.xiaowang.yuminailcore.modules.security.support.AdminScopeHelper; +import com.xiaowang.yuminailcore.modules.shop.support.UserShopBindingSupport; +import com.xiaowang.yuminailcore.modules.user.entity.UserDO; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.*; +import javax.servlet.http.HttpServletRequest; import java.util.List; /** @@ -24,6 +29,8 @@ public class VipInfoController { * Variable `vipInfoService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ private final VipInfoService vipInfoService; + private final AdminScopeHelper adminScopeHelper; + private final UserShopBindingSupport userShopBindingSupport; /** * 创建VIP信息 @@ -32,7 +39,10 @@ public class VipInfoController { * @return VIP信息ID */ @PostMapping("/create") - public Result createVipInfo(@RequestBody VipInfoDTO vipInfoDTO) { + @RequirePermission("user:vip:manage") + public Result createVipInfo(HttpServletRequest request, @RequestBody VipInfoDTO vipInfoDTO) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + ensureTargetUserAccessible(currentUser, vipInfoDTO.getUserId(), "无权为其他店铺用户创建VIP信息"); Long id = vipInfoService.createVipInfo(vipInfoDTO); return Result.success(id); } @@ -45,7 +55,14 @@ public class VipInfoController { * @return 是否更新成功 */ @PutMapping("/update/{id}") - public Result updateVipInfo(@PathVariable Long id, @RequestBody VipInfoDTO vipInfoDTO) { + @RequirePermission("user:vip:manage") + public Result updateVipInfo(HttpServletRequest request, @PathVariable Long id, @RequestBody VipInfoDTO vipInfoDTO) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + VipInfoVO existing = vipInfoService.getVipInfoById(id); + if (existing != null) { + ensureTargetUserAccessible(currentUser, existing.getUserId(), "无权编辑其他店铺用户VIP信息"); + } + ensureTargetUserAccessible(currentUser, vipInfoDTO.getUserId(), "无权将VIP信息改到其他店铺用户"); boolean success = vipInfoService.updateVipInfo(id, vipInfoDTO); return Result.success(success); } @@ -57,7 +74,13 @@ public class VipInfoController { * @return 是否删除成功 */ @DeleteMapping("/delete/{id}") - public Result deleteVipInfo(@PathVariable Long id) { + @RequirePermission("user:vip:manage") + public Result deleteVipInfo(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + VipInfoVO existing = vipInfoService.getVipInfoById(id); + if (existing != null) { + ensureTargetUserAccessible(currentUser, existing.getUserId(), "无权删除其他店铺用户VIP信息"); + } boolean success = vipInfoService.deleteVipInfo(id); return Result.success(success); } @@ -69,8 +92,13 @@ public class VipInfoController { * @return VIP信息VO */ @GetMapping("/get/{id}") - public Result getVipInfoById(@PathVariable Long id) { + @RequirePermission("user:vip:manage") + public Result getVipInfoById(HttpServletRequest request, @PathVariable Long id) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); VipInfoVO vipInfoVO = vipInfoService.getVipInfoById(id); + if (vipInfoVO != null) { + ensureTargetUserAccessible(currentUser, vipInfoVO.getUserId(), "无权查看其他店铺用户VIP信息"); + } return Result.success(vipInfoVO); } @@ -80,8 +108,12 @@ public class VipInfoController { * @return VIP信息VO列表 */ @GetMapping("/list/all") - public Result> listAllVipInfos() { - List vipInfoVOs = vipInfoService.listAllVipInfos(); + @RequirePermission("user:vip:manage") + public Result> listAllVipInfos(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + List vipInfoVOs = adminScopeHelper.isPlatformAdmin(currentUser) + ? vipInfoService.listAllVipInfos() + : vipInfoService.listVipInfosByUserIds(scopedUserIds(currentUser)); return Result.success(vipInfoVOs); } @@ -92,8 +124,21 @@ public class VipInfoController { * @return VIP信息VO列表 */ @GetMapping("/list/vipLevel/{vipLevel}") - public Result> listVipInfosByVipLevel(@PathVariable String vipLevel) { - List vipInfoVOs = vipInfoService.listVipInfosByVipLevel(vipLevel); + @RequirePermission("user:vip:manage") + public Result> listVipInfosByVipLevel(HttpServletRequest request, @PathVariable String vipLevel) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + List vipInfoVOs = adminScopeHelper.isPlatformAdmin(currentUser) + ? vipInfoService.listVipInfosByVipLevel(vipLevel) + : vipInfoService.listVipInfosByVipLevelAndUserIds(vipLevel, scopedUserIds(currentUser)); return Result.success(vipInfoVOs); } + + private List scopedUserIds(UserDO currentUser) { + Long managedShopId = adminScopeHelper.getManagedShopId(currentUser); + return userShopBindingSupport.listUserIdsByShopId(managedShopId, true); + } + + private void ensureTargetUserAccessible(UserDO currentUser, Long targetUserId, String message) { + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, targetUserId, message); + } } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/marketing/service/VipInfoService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/marketing/service/VipInfoService.java index 2bdf2a8f..1ece35fe 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/marketing/service/VipInfoService.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/marketing/service/VipInfoService.java @@ -5,6 +5,7 @@ import com.xiaowang.yuminailcore.modules.marketing.entity.VipInfoDO; import com.xiaowang.yuminailcore.modules.marketing.dto.VipInfoDTO; import com.xiaowang.yuminailcore.modules.marketing.vo.VipInfoVO; +import java.util.Collection; import java.util.List; /** @@ -56,6 +57,8 @@ public interface VipInfoService extends IService { */ List listAllVipInfos(); + List listVipInfosByUserIds(Collection userIds); + /** * 根据VIP等级查询VIP信息 * @@ -63,4 +66,6 @@ public interface VipInfoService extends IService { * @return VIP信息VO列表 */ List listVipInfosByVipLevel(String vipLevel); + + List listVipInfosByVipLevelAndUserIds(String vipLevel, Collection userIds); } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/marketing/service/impl/VipInfoServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/marketing/service/impl/VipInfoServiceImpl.java index bb54d345..718115c5 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/marketing/service/impl/VipInfoServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/marketing/service/impl/VipInfoServiceImpl.java @@ -10,6 +10,7 @@ import com.xiaowang.yuminailcore.modules.marketing.vo.VipInfoVO; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; +import java.util.Collection; import java.util.List; import java.util.stream.Collectors; @@ -117,6 +118,21 @@ public class VipInfoServiceImpl extends ServiceImpl im .collect(Collectors.toList()); } + @Override + public List listVipInfosByUserIds(Collection userIds) { + List scopedUserIds = normalizeUserIds(userIds); + if (scopedUserIds.isEmpty()) { + return List.of(); + } + List vipInfoDOs = vipInfoMapper.selectList( + Wrappers.lambdaQuery(VipInfoDO.class) + .in(VipInfoDO::getUserId, scopedUserIds) + ); + return vipInfoDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + @Override /** * List records for the current query or current user scope. @@ -134,6 +150,32 @@ public class VipInfoServiceImpl extends ServiceImpl im .collect(Collectors.toList()); } + @Override + public List listVipInfosByVipLevelAndUserIds(String vipLevel, Collection userIds) { + List scopedUserIds = normalizeUserIds(userIds); + if (scopedUserIds.isEmpty()) { + return List.of(); + } + List vipInfoDOs = vipInfoMapper.selectList( + Wrappers.lambdaQuery(VipInfoDO.class) + .eq(VipInfoDO::getVipLevel, vipLevel) + .in(VipInfoDO::getUserId, scopedUserIds) + ); + return vipInfoDOs.stream() + .map(this::convertToVO) + .collect(Collectors.toList()); + } + + private List normalizeUserIds(Collection userIds) { + if (userIds == null || userIds.isEmpty()) { + return List.of(); + } + return userIds.stream() + .filter(id -> id != null && id > 0) + .distinct() + .collect(Collectors.toList()); + } + /** * 将 DO 转换为 VO * diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/payment/controller/front/PaymentController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/payment/controller/front/PaymentController.java index 21697775..1ce64a7b 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/payment/controller/front/PaymentController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/payment/controller/front/PaymentController.java @@ -24,9 +24,4 @@ public class PaymentController { return Result.success(paymentService.prepareOrderPayment(userId, orderId)); } - @PostMapping("/order/{orderId}/mock-success") - public Result mockSuccess(HttpServletRequest request, @PathVariable Long orderId) { - Long userId = (Long) request.getAttribute("userId"); - return Result.success(paymentService.manualConfirmOrderPaid(userId, orderId, "mock-success")); - } } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/payment/service/impl/PaymentServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/payment/service/impl/PaymentServiceImpl.java index 90613564..1dcd9fa4 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/payment/service/impl/PaymentServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/payment/service/impl/PaymentServiceImpl.java @@ -1,9 +1,9 @@ package com.xiaowang.yuminailcore.modules.payment.service.impl; import com.xiaowang.yuminailcore.modules.order.entity.OrderDO; +import com.xiaowang.yuminailcore.modules.order.mapper.OrderMapper; import com.xiaowang.yuminailcore.modules.payment.entity.PaymentOrderDO; import com.xiaowang.yuminailcore.modules.payment.entity.RefundOrderDO; -import com.xiaowang.yuminailcore.modules.order.mapper.OrderMapper; import com.xiaowang.yuminailcore.modules.payment.mapper.PaymentOrderMapper; import com.xiaowang.yuminailcore.modules.payment.mapper.RefundOrderMapper; import com.xiaowang.yuminailcore.modules.payment.service.PaymentService; @@ -93,14 +93,14 @@ public class PaymentServiceImpl implements PaymentService { public RefundOrderVO manualRefundOrder(Long operatorId, Long orderId, Long afterSaleId, String remark) { OrderDO order = orderMapper.selectById(orderId); if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) { - throw new RuntimeException("璁㈠崟涓嶅瓨鍦?"); + throw new RuntimeException("订单不存在"); } if (!STATUS_PAID.equals(order.getPaymentStatus())) { - throw new RuntimeException("鏈敮浠樿鍗曚笉鍏佽閫€娆?"); + throw new RuntimeException("未支付订单不允许退款"); } PaymentOrderDO payment = paymentOrderMapper.selectLatestByOrderId(orderId); if (payment == null || !STATUS_PAID.equals(payment.getStatus())) { - throw new RuntimeException("鏈壘鍒板凡鏀粯鏀粯鍗?"); + throw new RuntimeException("未找到已支付的支付单"); } RefundOrderDO refund = new RefundOrderDO(); refund.setRefundNo("RF" + System.currentTimeMillis() + orderId); @@ -132,7 +132,7 @@ public class PaymentServiceImpl implements PaymentService { throw new RuntimeException("无权支付该订单"); } if (Integer.valueOf(0).equals(order.getStatus())) { - throw new RuntimeException("询价预约确认价格前暂不能支付"); + throw new RuntimeException("请先确认预约报价后再支付"); } if (STATUS_PAID.equals(order.getPaymentStatus())) { throw new RuntimeException("订单已支付"); diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/planning/mapper/AppointmentReservationMapper.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/planning/mapper/AppointmentReservationMapper.java index 9d77006c..286168b4 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/planning/mapper/AppointmentReservationMapper.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/planning/mapper/AppointmentReservationMapper.java @@ -11,20 +11,6 @@ import java.time.LocalDateTime; @Mapper public interface AppointmentReservationMapper extends BaseMapper { - @Select("SELECT COUNT(*) FROM t_appointment_reservation WHERE artist_id = #{artistId} " + - "AND status IN ('LOCKED','CONFIRMED') AND is_delete = 0 " + - "AND appointment_start_time < #{endTime} AND appointment_end_time > #{startTime} FOR UPDATE") - int countOverlappingActiveForUpdate(@Param("artistId") Long artistId, - @Param("startTime") LocalDateTime startTime, - @Param("endTime") LocalDateTime endTime); - - @Select("SELECT COUNT(*) FROM t_appointment_reservation WHERE artist_id = #{artistId} " + - "AND order_item_id <> #{orderItemId} AND status IN ('LOCKED','CONFIRMED') AND is_delete = 0 " + - "AND appointment_start_time < #{endTime} AND appointment_end_time > #{startTime} FOR UPDATE") - int countOverlappingActiveForUpdateExcludingOrderItem(@Param("artistId") Long artistId, - @Param("orderItemId") Long orderItemId, - @Param("startTime") LocalDateTime startTime, - @Param("endTime") LocalDateTime endTime); @Select("SELECT COUNT(*) FROM t_appointment_reservation WHERE artist_id = #{artistId} " + "AND status IN ('LOCKED','CONFIRMED') AND is_delete = 0 " + @@ -33,6 +19,14 @@ public interface AppointmentReservationMapper extends BaseMapper #{orderItemId} AND status IN ('LOCKED','CONFIRMED') AND is_delete = 0 " + + "AND appointment_start_time < #{endTime} AND appointment_end_time > #{startTime}") + int countOverlappingActiveExcludingOrderItem(@Param("artistId") Long artistId, + @Param("orderItemId") Long orderItemId, + @Param("startTime") LocalDateTime startTime, + @Param("endTime") LocalDateTime endTime); + @Update("UPDATE t_appointment_reservation SET status = #{status}, is_delete = 1, update_time = NOW() " + "WHERE order_id = #{orderId} AND is_delete = 0") int releaseByOrderId(@Param("orderId") Long orderId, @Param("status") String status); diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/planning/service/impl/AppointmentCapacityServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/planning/service/impl/AppointmentCapacityServiceImpl.java index 9a6620c4..5b32868c 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/planning/service/impl/AppointmentCapacityServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/planning/service/impl/AppointmentCapacityServiceImpl.java @@ -1,9 +1,9 @@ package com.xiaowang.yuminailcore.modules.planning.service.impl; -import com.xiaowang.yuminailcore.modules.planning.entity.AppointmentReservationDO; import com.xiaowang.yuminailcore.modules.artist.entity.ArtistScheduleDO; -import com.xiaowang.yuminailcore.modules.planning.mapper.AppointmentReservationMapper; import com.xiaowang.yuminailcore.modules.artist.mapper.ArtistScheduleMapper; +import com.xiaowang.yuminailcore.modules.planning.entity.AppointmentReservationDO; +import com.xiaowang.yuminailcore.modules.planning.mapper.AppointmentReservationMapper; import com.xiaowang.yuminailcore.modules.planning.service.AppointmentCapacityService; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; @@ -18,8 +18,8 @@ public class AppointmentCapacityServiceImpl implements AppointmentCapacityServic private static final int MIN_CAPACITY = 1; private static final String STATUS_CONFIRMED = "CONFIRMED"; private static final String STATUS_RELEASED = "RELEASED"; - private static final String UNAVAILABLE_MESSAGE = "涓嶅彲棰勭害"; - private static final String FULL_MESSAGE = "褰撳墠缇庣敳甯堣鏃堕棿娈靛凡绾︽弧锛岃閲嶆柊閫夋嫨棰勭害鏃堕棿"; + private static final String UNAVAILABLE_MESSAGE = "当前美甲师该时间段不可预约"; + private static final String FULL_MESSAGE = "当前美甲师该时间段已约满,请重新选择预约时间"; private final AppointmentReservationMapper reservationMapper; private final ArtistScheduleMapper scheduleMapper; @@ -79,17 +79,17 @@ public class AppointmentCapacityServiceImpl implements AppointmentCapacityServic private void assertCapacityAvailable(Long shopId, Long artistId, Long excludedOrderItemId, LocalDateTime startTime, LocalDateTime endTime) { - int capacity = resolveCapacity(shopId, artistId, startTime, endTime); + int capacity = resolveCapacityWithScheduleLock(shopId, artistId, startTime, endTime); int used = excludedOrderItemId == null - ? reservationMapper.countOverlappingActiveForUpdate(artistId, startTime, endTime) - : reservationMapper.countOverlappingActiveForUpdateExcludingOrderItem(artistId, excludedOrderItemId, startTime, endTime); + ? reservationMapper.countOverlappingActive(artistId, startTime, endTime) + : reservationMapper.countOverlappingActiveExcludingOrderItem(artistId, excludedOrderItemId, startTime, endTime); if (used >= capacity) { throw new RuntimeException(FULL_MESSAGE); } } - private int resolveCapacity(Long shopId, Long artistId, LocalDateTime startTime, LocalDateTime endTime) { - ArtistScheduleDO schedule = scheduleMapper.selectCoveringSchedule( + private int resolveCapacityWithScheduleLock(Long shopId, Long artistId, LocalDateTime startTime, LocalDateTime endTime) { + ArtistScheduleDO schedule = scheduleMapper.selectCoveringScheduleForUpdate( shopId, artistId, startTime.toLocalDate(), diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/utils/JwtUtil.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/utils/JwtUtil.java index c8b297d8..fd7cadd0 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/utils/JwtUtil.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/utils/JwtUtil.java @@ -8,6 +8,7 @@ import io.jsonwebtoken.security.Keys; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Component; +import javax.annotation.PostConstruct; import javax.crypto.SecretKey; import java.nio.charset.StandardCharsets; import java.util.Date; @@ -28,11 +29,17 @@ public class JwtUtil { */ private final JwtProperties jwtProperties; + @PostConstruct + void validateJwtSecret() { + jwtProperties.requireValidSecret(); + } + /** * Purpose: getKey supports JwtUtil.java by holding or executing the get key business role. * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. */ private SecretKey getKey() { + jwtProperties.requireValidSecret(); return Keys.hmacShaKeyFor(jwtProperties.getSecret().getBytes(StandardCharsets.UTF_8)); } diff --git a/YumiNail-Core/src/main/resources/bootstrap.yaml b/YumiNail-Core/src/main/resources/bootstrap.yaml index b188cb7c..af9e4e16 100644 --- a/YumiNail-Core/src/main/resources/bootstrap.yaml +++ b/YumiNail-Core/src/main/resources/bootstrap.yaml @@ -18,9 +18,9 @@ spring: # 是否启用服务注册 register-enabled: true # Nacos认证用户名 - username: xiaowang + username: ${NACOS_USERNAME:xiaowang} # Nacos认证密码 - password: 122503wcy.... + password: ${NACOS_PASSWORD:} config: # Nacos配置中心集群地址 server-addr: home-nacos01:8848,home-nacos02:8848,home-nacos03:8848 @@ -35,9 +35,9 @@ spring: # 是否启用配置中心 enabled: true # Nacos认证用户名 - username: xiaowang + username: ${NACOS_USERNAME:xiaowang} # Nacos认证密码 - password: 122503wcy.... + password: ${NACOS_PASSWORD:} # 共享配置文件列表 shared-configs: - data-id: rabbit-mq.yaml diff --git a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/config/JwtPropertiesTest.java b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/config/JwtPropertiesTest.java new file mode 100644 index 00000000..35bd2767 --- /dev/null +++ b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/config/JwtPropertiesTest.java @@ -0,0 +1,28 @@ +package com.xiaowang.yuminailcore.config; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +class JwtPropertiesTest { + + @Test + void rejectsMissingJwtSecretBeforeTokenOperations() { + JwtProperties properties = new JwtProperties(); + properties.setSecret(""); + + assertThatThrownBy(properties::requireValidSecret) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("JWT 密钥"); + } + + @Test + void rejectsCommittedDevelopmentJwtSecretBeforeTokenOperations() { + JwtProperties properties = new JwtProperties(); + properties.setSecret(JwtProperties.DEVELOPMENT_PLACEHOLDER_SECRET); + + assertThatThrownBy(properties::requireValidSecret) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("外部配置"); + } +} diff --git a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/payment/controller/front/PaymentControllerSecurityTest.java b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/payment/controller/front/PaymentControllerSecurityTest.java new file mode 100644 index 00000000..c6a5f2bb --- /dev/null +++ b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/payment/controller/front/PaymentControllerSecurityTest.java @@ -0,0 +1,21 @@ +package com.xiaowang.yuminailcore.modules.payment.controller.front; + +import org.junit.jupiter.api.Test; +import org.springframework.web.bind.annotation.PostMapping; + +import java.util.Arrays; + +import static org.assertj.core.api.Assertions.assertThat; + +class PaymentControllerSecurityTest { + + @Test + void frontPaymentControllerDoesNotExposeMockPaymentSuccessEndpoint() { + boolean hasMockSuccessRoute = Arrays.stream(PaymentController.class.getDeclaredMethods()) + .flatMap(method -> Arrays.stream(method.getAnnotationsByType(PostMapping.class))) + .flatMap(mapping -> Arrays.stream(mapping.value())) + .anyMatch(path -> path.contains("mock-success")); + + assertThat(hasMockSuccessRoute).isFalse(); + } +} diff --git a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/planning/service/impl/AppointmentCapacityServiceImplTest.java b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/planning/service/impl/AppointmentCapacityServiceImplTest.java index dc207e98..5b2e24d1 100644 --- a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/planning/service/impl/AppointmentCapacityServiceImplTest.java +++ b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/planning/service/impl/AppointmentCapacityServiceImplTest.java @@ -1,9 +1,9 @@ package com.xiaowang.yuminailcore.modules.planning.service.impl; -import com.xiaowang.yuminailcore.modules.planning.entity.AppointmentReservationDO; import com.xiaowang.yuminailcore.modules.artist.entity.ArtistScheduleDO; -import com.xiaowang.yuminailcore.modules.planning.mapper.AppointmentReservationMapper; import com.xiaowang.yuminailcore.modules.artist.mapper.ArtistScheduleMapper; +import com.xiaowang.yuminailcore.modules.planning.entity.AppointmentReservationDO; +import com.xiaowang.yuminailcore.modules.planning.mapper.AppointmentReservationMapper; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; @@ -16,8 +16,8 @@ import java.time.LocalTime; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.Mockito.verify; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; class AppointmentCapacityServiceImplTest { @@ -36,24 +36,28 @@ class AppointmentCapacityServiceImplTest { } @Test - void reserveRejectsWhenConfiguredCapacityIsFull() { + void reserveLocksCoveringScheduleRowAndRejectsWhenConfiguredCapacityIsFull() { LocalDateTime start = LocalDateTime.of(2026, 6, 1, 10, 0); LocalDateTime end = start.plusHours(1); - when(scheduleMapper.selectCoveringSchedule(9L, 30L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime())) + when(scheduleMapper.selectCoveringScheduleForUpdate(9L, 30L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime())) .thenReturn(schedule(2)); - when(reservationMapper.countOverlappingActiveForUpdate(30L, start, end)).thenReturn(2); + when(reservationMapper.countOverlappingActive(30L, start, end)).thenReturn(2); assertThatThrownBy(() -> service.reserveOrThrow(1L, 10L, 9L, 30L, "French", start, end)) - .isInstanceOf(RuntimeException.class); + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("已约满"); + + verify(scheduleMapper).selectCoveringScheduleForUpdate(9L, 30L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime()); + verify(reservationMapper, never()).insert(org.mockito.ArgumentMatchers.any(AppointmentReservationDO.class)); } @Test void reserveCreatesConfirmedReservationWhenCapacityRemains() { LocalDateTime start = LocalDateTime.of(2026, 6, 1, 10, 0); LocalDateTime end = start.plusHours(1); - when(scheduleMapper.selectCoveringSchedule(9L, 30L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime())) + when(scheduleMapper.selectCoveringScheduleForUpdate(9L, 30L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime())) .thenReturn(schedule(2)); - when(reservationMapper.countOverlappingActiveForUpdate(30L, start, end)).thenReturn(1); + when(reservationMapper.countOverlappingActive(30L, start, end)).thenReturn(1); service.reserveOrThrow(1L, 10L, 9L, 30L, "French", start, end); @@ -70,12 +74,12 @@ class AppointmentCapacityServiceImplTest { void reserveRejectsWhenNoCoveringScheduleExists() { LocalDateTime start = LocalDateTime.of(2026, 6, 2, 10, 0); LocalDateTime end = start.plusHours(1); - when(scheduleMapper.selectCoveringSchedule(9L, 30L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime())) + when(scheduleMapper.selectCoveringScheduleForUpdate(9L, 30L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime())) .thenReturn(null); assertThatThrownBy(() -> service.reserveOrThrow(1L, 10L, 9L, 30L, "French", start, end)) .isInstanceOf(RuntimeException.class) - .hasMessageContaining("涓嶅彲棰勭害"); + .hasMessageContaining("不可预约"); verify(reservationMapper, never()).insert(org.mockito.ArgumentMatchers.any(AppointmentReservationDO.class)); } @@ -86,12 +90,12 @@ class AppointmentCapacityServiceImplTest { LocalDateTime end = start.plusHours(1); ArtistScheduleDO disabled = schedule(1); disabled.setStatus(0); - when(scheduleMapper.selectCoveringSchedule(9L, 30L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime())) + when(scheduleMapper.selectCoveringScheduleForUpdate(9L, 30L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime())) .thenReturn(disabled); assertThatThrownBy(() -> service.reserveOrThrow(1L, 10L, 9L, 30L, "French", start, end)) .isInstanceOf(RuntimeException.class) - .hasMessageContaining("涓嶅彲棰勭害"); + .hasMessageContaining("不可预约"); verify(reservationMapper, never()).insert(org.mockito.ArgumentMatchers.any(AppointmentReservationDO.class)); } @@ -100,12 +104,12 @@ class AppointmentCapacityServiceImplTest { void reserveRejectsWhenCoveringScheduleHasZeroCapacity() { LocalDateTime start = LocalDateTime.of(2026, 6, 1, 10, 0); LocalDateTime end = start.plusHours(1); - when(scheduleMapper.selectCoveringSchedule(9L, 30L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime())) + when(scheduleMapper.selectCoveringScheduleForUpdate(9L, 30L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime())) .thenReturn(schedule(0)); assertThatThrownBy(() -> service.reserveOrThrow(1L, 10L, 9L, 30L, "French", start, end)) .isInstanceOf(RuntimeException.class) - .hasMessageContaining("涓嶅彲棰勭害"); + .hasMessageContaining("不可预约"); verify(reservationMapper, never()).insert(org.mockito.ArgumentMatchers.any(AppointmentReservationDO.class)); } @@ -114,9 +118,9 @@ class AppointmentCapacityServiceImplTest { void moveReservationRechecksNewArtistCapacityBeforeUpdatingArtist() { LocalDateTime start = LocalDateTime.of(2026, 6, 1, 10, 0); LocalDateTime end = start.plusHours(1); - when(scheduleMapper.selectCoveringSchedule(9L, 31L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime())) + when(scheduleMapper.selectCoveringScheduleForUpdate(9L, 31L, start.toLocalDate(), start.toLocalTime(), end.toLocalTime())) .thenReturn(schedule(1)); - when(reservationMapper.countOverlappingActiveForUpdateExcludingOrderItem(31L, 10L, start, end)).thenReturn(0); + when(reservationMapper.countOverlappingActiveExcludingOrderItem(31L, 10L, start, end)).thenReturn(0); when(reservationMapper.updateActiveReservationForOrderItem(10L, 1L, 9L, 31L, "French", start, end, "CONFIRMED")) .thenReturn(1); diff --git a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/security/SensitiveControllerPermissionTest.java b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/security/SensitiveControllerPermissionTest.java new file mode 100644 index 00000000..a0f781da --- /dev/null +++ b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/security/SensitiveControllerPermissionTest.java @@ -0,0 +1,135 @@ +package com.xiaowang.yuminailcore.modules.security; + +import com.xiaowang.yuminailcore.annotation.RequirePermission; +import com.xiaowang.yuminailcore.modules.auth.controller.front.LoginIdentityController; +import com.xiaowang.yuminailcore.modules.auth.service.LoginIdentityService; +import com.xiaowang.yuminailcore.modules.marketing.controller.front.VipBenefitController; +import com.xiaowang.yuminailcore.modules.marketing.controller.front.VipInfoController; +import com.xiaowang.yuminailcore.modules.marketing.service.VipBenefitService; +import com.xiaowang.yuminailcore.modules.marketing.service.VipInfoService; +import com.xiaowang.yuminailcore.modules.security.support.AdminScopeHelper; +import com.xiaowang.yuminailcore.modules.shop.support.UserShopBindingSupport; +import com.xiaowang.yuminailcore.modules.user.entity.UserDO; +import org.junit.jupiter.api.Test; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; + +import javax.servlet.http.HttpServletRequest; +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class SensitiveControllerPermissionTest { + + @Test + void sensitiveLoginIdentityEndpointsRequireUserManagementPermissions() { + assertPermission(LoginIdentityController.class, "createLoginIdentity", "user:create"); + assertPermission(LoginIdentityController.class, "updateLoginIdentity", "user:edit"); + assertPermission(LoginIdentityController.class, "deleteLoginIdentity", "user:delete"); + assertPermission(LoginIdentityController.class, "getLoginIdentityById", "user:view"); + assertPermission(LoginIdentityController.class, "listAllLoginIdentities", "user:view"); + assertPermission(LoginIdentityController.class, "listLoginIdentitiesByUserId", "user:view"); + assertPermission(LoginIdentityController.class, "listLoginIdentitiesByLoginMethod", "user:view"); + } + + @Test + void sensitiveVipEndpointsRequireVipManagementPermissions() { + for (Class controller : List.of(VipBenefitController.class, VipInfoController.class)) { + Arrays.stream(controller.getDeclaredMethods()) + .filter(SensitiveControllerPermissionTest::isRequestHandler) + .forEach(method -> assertThat(method.getAnnotation(RequirePermission.class)) + .as("%s#%s", controller.getSimpleName(), method.getName()) + .extracting(RequirePermission::value) + .isEqualTo("user:vip:manage")); + } + } + + @Test + void loginIdentityListScopesStoreUsersByCurrentShop() { + LoginIdentityService service = mock(LoginIdentityService.class); + AdminScopeHelper scopeHelper = mock(AdminScopeHelper.class); + UserShopBindingSupport bindingSupport = mock(UserShopBindingSupport.class); + LoginIdentityController controller = new LoginIdentityController(service, scopeHelper, bindingSupport); + HttpServletRequest request = mock(HttpServletRequest.class); + UserDO storeUser = currentStoreUser(); + + when(scopeHelper.getCurrentUser(request)).thenReturn(storeUser); + when(scopeHelper.isPlatformAdmin(storeUser)).thenReturn(false); + when(scopeHelper.getManagedShopId(storeUser)).thenReturn(7L); + when(bindingSupport.listUserIdsByShopId(7L, true)).thenReturn(List.of(11L, 12L)); + + controller.listAllLoginIdentities(request); + + verify(service).listLoginIdentitiesByUserIds(List.of(11L, 12L)); + verify(service, never()).listAllLoginIdentities(); + } + + @Test + void vipInfoListScopesStoreUsersByCurrentShop() { + VipInfoService service = mock(VipInfoService.class); + AdminScopeHelper scopeHelper = mock(AdminScopeHelper.class); + UserShopBindingSupport bindingSupport = mock(UserShopBindingSupport.class); + VipInfoController controller = new VipInfoController(service, scopeHelper, bindingSupport); + HttpServletRequest request = mock(HttpServletRequest.class); + UserDO storeUser = currentStoreUser(); + + when(scopeHelper.getCurrentUser(request)).thenReturn(storeUser); + when(scopeHelper.isPlatformAdmin(storeUser)).thenReturn(false); + when(scopeHelper.getManagedShopId(storeUser)).thenReturn(7L); + when(bindingSupport.listUserIdsByShopId(7L, true)).thenReturn(List.of(11L, 12L)); + + controller.listAllVipInfos(request); + + verify(service).listVipInfosByUserIds(List.of(11L, 12L)); + verify(service, never()).listAllVipInfos(); + } + + @Test + void vipBenefitRequiresPlatformAdminBecauseBenefitHasNoShopScope() { + VipBenefitService service = mock(VipBenefitService.class); + AdminScopeHelper scopeHelper = mock(AdminScopeHelper.class); + VipBenefitController controller = new VipBenefitController(service, scopeHelper); + HttpServletRequest request = mock(HttpServletRequest.class); + UserDO storeUser = currentStoreUser(); + + when(scopeHelper.getCurrentUser(request)).thenReturn(storeUser); + + controller.listAllVipBenefits(request); + + verify(scopeHelper).requirePlatformAdmin(storeUser, "只有平台管理员可以维护全局VIP权益配置"); + } + + private static void assertPermission(Class controller, String methodName, String permission) { + Method method = Arrays.stream(controller.getDeclaredMethods()) + .filter(candidate -> candidate.getName().equals(methodName)) + .findFirst() + .orElseThrow(); + assertThat(method.getAnnotation(RequirePermission.class)) + .as("%s#%s", controller.getSimpleName(), methodName) + .extracting(RequirePermission::value) + .isEqualTo(permission); + } + + private static boolean isRequestHandler(Method method) { + return method.isAnnotationPresent(PostMapping.class) + || method.isAnnotationPresent(PutMapping.class) + || method.isAnnotationPresent(DeleteMapping.class) + || method.isAnnotationPresent(GetMapping.class); + } + + private static UserDO currentStoreUser() { + UserDO user = new UserDO(); + user.setId(2L); + user.setType(2); + user.setShopId(7L); + return user; + } +} diff --git a/YumiNail-Frontend/src/api/order.ts b/YumiNail-Frontend/src/api/order.ts index eb656830..4bdef5cc 100644 --- a/YumiNail-Frontend/src/api/order.ts +++ b/YumiNail-Frontend/src/api/order.ts @@ -157,9 +157,6 @@ export interface GrowthSummaryVO { export const paymentApi = { prepareOrderPayment: async (orderId: IdType): Promise => { return await api.post(`/payment/order/${orderId}/prepare`) as unknown as PaymentOrderVO - }, - mockSuccess: async (orderId: IdType): Promise => { - return await api.post(`/payment/order/${orderId}/mock-success`) as unknown as PaymentOrderVO } } diff --git a/YumiNail-Frontend/src/views/OrderDetailView.vue b/YumiNail-Frontend/src/views/OrderDetailView.vue index 1367717a..5531b08e 100644 --- a/YumiNail-Frontend/src/views/OrderDetailView.vue +++ b/YumiNail-Frontend/src/views/OrderDetailView.vue @@ -37,7 +37,6 @@ const isQuoteConfirming = computed(() => isQuoteStatus(order.value?.status)) const statusClass = (status?: number) => isQuoteStatus(status) ? 'quote' : status === 2 ? 'done' : status === 3 ? 'cancelled' : 'pending' const isOrderPaid = (target: any) => String(target?.paymentStatus || '').toUpperCase() === 'PAID' const canPreparePayment = computed(() => !isQuoteConfirming.value && Number(order.value?.status) === 1 && !isOrderPaid(order.value)) -const canMockPay = computed(() => !isQuoteConfirming.value && Number(order.value?.status) === 1 && String(order.value?.paymentStatus || '').toUpperCase() === 'PAYING') const canApplyAfterSale = computed(() => !isQuoteConfirming.value && (Number(order.value?.status) === 2 || isOrderPaid(order.value))) const timeline = computed(() => { @@ -206,15 +205,6 @@ const preparePayment = async () => { message.success('支付单已准备') } -const mockPay = async () => { - if (!order.value?.id) return - await runWithGlobalLoading(async () => { - await paymentApi.mockSuccess(order.value.id) - await loadOrder() - }) - message.success('模拟支付成功') -} - const cancelOrder = () => { if (!order.value?.id) return Modal.confirm({ @@ -358,7 +348,6 @@ onMounted(loadOrder)
准备支付 - 模拟支付 申请售后 取消订单
diff --git a/YumiNail-Frontend/src/views/OrderView.vue b/YumiNail-Frontend/src/views/OrderView.vue index b765db9c..47730cdb 100644 --- a/YumiNail-Frontend/src/views/OrderView.vue +++ b/YumiNail-Frontend/src/views/OrderView.vue @@ -201,7 +201,6 @@
- @@ -470,8 +469,7 @@ const isQuoteConfirming = (order: any) => Number(order?.status) === 0 const orderPaymentStatus = (order: any) => String(order.paymentStatus || order.payStatus || '').toUpperCase() const isOrderPaid = (order: any) => orderPaymentStatus(order) === 'PAID' const orderNeedsPayment = (order: any) => Number(order.status) === 1 && !isOrderPaid(order) -const canPreparePayment = (order: any) => orderNeedsPayment(order) && orderPaymentStatus(order) !== 'PAYING' -const canMockPay = (order: any) => Number(order.status) === 1 && orderPaymentStatus(order) === 'PAYING' +const canPreparePayment = (order: any) => orderNeedsPayment(order) const canApplyAfterSale = (order: any) => !isQuoteConfirming(order) && (Number(order.status) === 2 || isOrderPaid(order)) /** @@ -779,18 +777,6 @@ const preparePayment = async (order: any) => { } } -const mockPay = async (order: any) => { - try { - await runWithGlobalLoading(async () => { - await paymentApi.mockSuccess(order.id) - await loadOrders() - }) - message.success('支付成功') - } catch (error: any) { - message.error(error?.message || '支付失败') - } -} - const submitQuoteReply = async (order: any) => { const key = quoteOrderKey(order) const remark = String(quoteReplyForms[key] || '').trim() diff --git a/YumiNail-Frontend/src/views/web-theme-governance.test.ts b/YumiNail-Frontend/src/views/web-theme-governance.test.ts index 3f5c6e1b..35d49969 100644 --- a/YumiNail-Frontend/src/views/web-theme-governance.test.ts +++ b/YumiNail-Frontend/src/views/web-theme-governance.test.ts @@ -68,7 +68,7 @@ describe('web theme governance', () => { it('keeps frontend and backend platform overview permission allowlists aligned', () => { const frontend = readSource('utils/platform-admin-permissions.ts') - const backend = readFileSync(join(coreRoot, 'com', 'xiaowang', 'yuminailcore', 'support', 'PermissionCatalog.java'), 'utf-8') + const backend = readFileSync(join(coreRoot, 'com', 'xiaowang', 'yuminailcore', 'modules', 'security', 'support', 'PermissionCatalog.java'), 'utf-8') expect(backend).toContain('"security:audit:view"') expect(frontend).toContain("'security:audit:view'") diff --git a/YumiNail-Frontend/tests/api/vnext-api-contracts.test.ts b/YumiNail-Frontend/tests/api/vnext-api-contracts.test.ts index b0793889..80dadaa6 100644 --- a/YumiNail-Frontend/tests/api/vnext-api-contracts.test.ts +++ b/YumiNail-Frontend/tests/api/vnext-api-contracts.test.ts @@ -109,14 +109,12 @@ describe('vNext API contracts', () => { api.defaults.adapter = captureAdapter(requests) await paymentApi.prepareOrderPayment(42) - await paymentApi.mockSuccess(42) await afterSaleApi.apply({ orderId: 42, type: 'REFUND', reason: 'schedule changed', refundAmount: 88 }) await afterSaleApi.listMy({ page: 1, size: 5 }) await growthApi.getSummary() expect(requests).toEqual([ { method: 'post', url: '/payment/order/42/prepare', params: undefined, data: undefined }, - { method: 'post', url: '/payment/order/42/mock-success', params: undefined, data: undefined }, { method: 'post', url: '/after-sale/apply', params: undefined, data: { orderId: 42, type: 'REFUND', reason: 'schedule changed', refundAmount: 88 } }, { method: 'get', url: '/after-sale/my', params: { page: 1, size: 5 }, data: undefined }, { method: 'get', url: '/growth/summary', params: undefined, data: undefined } diff --git a/YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/config/JwtProperties.java b/YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/config/JwtProperties.java index 90a20d49..86fada8b 100644 --- a/YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/config/JwtProperties.java +++ b/YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/config/JwtProperties.java @@ -4,17 +4,31 @@ import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; -/** - * Gateway JWT 校验配置。 - */ +import java.nio.charset.StandardCharsets; + @Data @Configuration @ConfigurationProperties(prefix = "yuminail.security.jwt") public class JwtProperties { - private String secret = "yuminail-secret-key-for-jwt-token-generation-2026-must-be-at-least-512-bits-long-for-hs512-algorithm-security-requirements"; + public static final String DEVELOPMENT_PLACEHOLDER_SECRET = "__CONFIGURE_YUMINAIL_JWT_SECRET_OUTSIDE_REPOSITORY__"; + private static final int HS512_MIN_SECRET_BYTES = 64; + + private String secret = DEVELOPMENT_PLACEHOLDER_SECRET; private String issuer = "yuminail"; private long clockSkewSeconds = 30; + + public void requireValidSecret() { + if (secret == null || secret.isBlank()) { + throw new IllegalStateException("JWT 密钥不能为空,请通过外部配置提供 yuminail.security.jwt.secret"); + } + if (DEVELOPMENT_PLACEHOLDER_SECRET.equals(secret)) { + throw new IllegalStateException("JWT 密钥仍为仓库占位值,请通过外部配置覆盖后再启动服务"); + } + if (secret.getBytes(StandardCharsets.UTF_8).length < HS512_MIN_SECRET_BYTES) { + throw new IllegalStateException("JWT 密钥长度不足,HS512 至少需要 64 字节"); + } + } } diff --git a/YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/filter/GatewayJwtValidator.java b/YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/filter/GatewayJwtValidator.java index 3f01d229..e82f0e40 100644 --- a/YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/filter/GatewayJwtValidator.java +++ b/YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/filter/GatewayJwtValidator.java @@ -7,6 +7,7 @@ import io.jsonwebtoken.security.Keys; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Component; +import javax.annotation.PostConstruct; import javax.crypto.SecretKey; import java.nio.charset.StandardCharsets; @@ -19,6 +20,11 @@ public class GatewayJwtValidator { private final JwtProperties jwtProperties; + @PostConstruct + void validateJwtSecret() { + jwtProperties.requireValidSecret(); + } + public boolean validateAccessToken(String token) { try { Claims claims = Jwts.parserBuilder() @@ -35,6 +41,7 @@ public class GatewayJwtValidator { } private SecretKey getKey() { + jwtProperties.requireValidSecret(); return Keys.hmacShaKeyFor(jwtProperties.getSecret().getBytes(StandardCharsets.UTF_8)); } } diff --git a/YumiNail-Gateway/src/main/resources/bootstrap.yaml b/YumiNail-Gateway/src/main/resources/bootstrap.yaml index 415d987a..cc6261ca 100644 --- a/YumiNail-Gateway/src/main/resources/bootstrap.yaml +++ b/YumiNail-Gateway/src/main/resources/bootstrap.yaml @@ -9,16 +9,16 @@ spring: namespace: YumiNail-Dev group: DEFAULT_GROUP service: ${spring.application.name} - username: xiaowang - password: 122503wcy.... + username: ${NACOS_USERNAME:xiaowang} + password: ${NACOS_PASSWORD:} config: server-addr: home-nacos01:8848,home-nacos02:8848,home-nacos03:8848 namespace: YumiNail-Dev group: DEFAULT_GROUP name: yuminail-gateway file-extension: yaml - username: xiaowang - password: 122503wcy.... + username: ${NACOS_USERNAME:xiaowang} + password: ${NACOS_PASSWORD:} shared-configs: - data-id: logging.yaml group: DEFAULT_GROUP