Author SHA1 Message Date
xiaowang 74f8fa5f4e 修复回归安全问题并补充验证 2026-06-05 16:10:58 +08:00
46 changed files with 917 additions and 311 deletions
+12 -1
View File
@@ -1,7 +1,7 @@
<!-- gitnexus:start --> <!-- gitnexus:start -->
# GitNexus — Code Intelligence # 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. > 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/processes` | All execution flows |
| `gitnexus://repo/xiaowang/process/{name}` | Step-by-step execution trace | | `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` |
<!-- gitnexus:end --> <!-- gitnexus:end -->
## Browser MCP Preference ## Browser MCP Preference
+12 -1
View File
@@ -1,7 +1,7 @@
<!-- gitnexus:start --> <!-- gitnexus:start -->
# GitNexus — Code Intelligence # 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. > 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/processes` | All execution flows |
| `gitnexus://repo/xiaowang/process/{name}` | Step-by-step execution trace | | `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` |
<!-- gitnexus:end --> <!-- gitnexus:end -->
+22
View File
@@ -255,3 +255,25 @@ button::after {
color: #a39b91; color: #a39b91;
text-align: center; 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;
}
@@ -1,4 +1,5 @@
const planningApi = require('../../api/planning') const planningApi = require('../../api/planning')
const config = require('../../utils/config')
const mock = require('../../utils/mock') const mock = require('../../utils/mock')
Page({ Page({
@@ -6,21 +7,34 @@ Page({
id: '', id: '',
appointment: {}, appointment: {},
avatarText: '', avatarText: '',
timeText: '' timeText: '',
loadError: false,
errorMessage: ''
}, },
onLoad(options) { onLoad(options = {}) {
this.setData({ id: options.id || '' }) this.setData({ id: options.id || '' })
this.loadDetail() this.loadDetail()
}, },
async loadDetail() { async loadDetail() {
this.setData({ loadError: false, errorMessage: '' })
try { try {
const appointment = await planningApi.appointment(this.data.id) const appointment = await planningApi.appointment(this.data.id)
this.applyAppointment(appointment) this.applyAppointment(appointment)
} catch (error) { } catch (error) {
const demo = mock.buildCalendar(new Date()).appointments[0] if (config.USE_DEV_MOCK_DATA) {
this.applyAppointment(demo) 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({ this.setData({
appointment, appointment,
avatarText: String(appointment.customerName || '客').slice(0, 1), 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) { async updateStatus(status) {
if (!this.data.appointment.orderId) {
wx.showToast({ title: '预约数据未加载', icon: 'none' })
return
}
try { try {
await planningApi.updateStatus(this.data.appointment.orderId, status) await planningApi.updateStatus(this.data.appointment.orderId, status)
wx.showToast({ title: '已更新' }) wx.showToast({ title: '已更新' })
@@ -1,46 +1,54 @@
<view class="page no-tab"> <view class="page no-tab">
<view class="card detail-card"> <view wx:if="{{loadError}}" class="card error-card">
<view class="detail-head"> <text class="error-title">数据加载失败</text>
<view class="detail-person"> <text class="error-desc">{{errorMessage}}</text>
<view class="avatar">{{avatarText}}</view> <button class="compact-btn" bindtap="loadDetail">重试</button>
<view> </view>
<text class="customer">{{appointment.customerName}}</text>
<text class="phone">{{appointment.customerPhone}}</text> <block wx:else>
<view class="card detail-card">
<view class="detail-head">
<view class="detail-person">
<view class="avatar">{{avatarText}}</view>
<view>
<text class="customer">{{appointment.customerName}}</text>
<text class="phone">{{appointment.customerPhone}}</text>
</view>
</view>
<view class="detail-actions">
<text class="tag">{{appointment.statusText}}</text>
<button class="small-action" bindtap="goTransfer">改派</button>
</view> </view>
</view> </view>
<view class="detail-actions"> <view class="detail-grid">
<text class="tag">{{appointment.statusText}}</text> <view>
<button class="small-action" bindtap="goTransfer">改派</button> <text class="label">项目</text>
<text class="value">{{appointment.productTitle}}</text>
</view>
<view>
<text class="label">美甲师</text>
<text class="value">{{appointment.artistName}}</text>
</view>
<view>
<text class="label">时间</text>
<text class="value">{{timeText}}</text>
</view>
<view>
<text class="label">时长</text>
<text class="value">{{appointment.durationMinutes}}分钟</text>
</view>
</view> </view>
</view> </view>
<view class="detail-grid">
<view> <view class="section">
<text class="label">项目</text> <view class="section-title">备注</view>
<text class="value">{{appointment.productTitle}}</text> <view class="card note-card">{{appointment.remark || '暂无备注'}}</view>
</view>
<view>
<text class="label">美甲师</text>
<text class="value">{{appointment.artistName}}</text>
</view>
<view>
<text class="label">时间</text>
<text class="value">{{timeText}}</text>
</view>
<view>
<text class="label">时长</text>
<text class="value">{{appointment.durationMinutes}}分钟</text>
</view>
</view> </view>
</view>
<view class="section"> <view class="fixed-bottom action-row">
<view class="section-title">备注</view> <button class="secondary-btn" bindtap="confirm">确认</button>
<view class="card note-card">{{appointment.remark || '暂无备注'}}</view> <button class="primary-btn" bindtap="complete">完成</button>
</view> <button class="danger-btn" bindtap="cancel">取消</button>
</view>
<view class="fixed-bottom action-row"> </block>
<button class="secondary-btn" bindtap="confirm">确认</button>
<button class="primary-btn" bindtap="complete">完成</button>
<button class="danger-btn" bindtap="cancel">取消</button>
</view>
</view> </view>
@@ -1,8 +1,15 @@
const planningApi = require('../../api/planning') const planningApi = require('../../api/planning')
const productsApi = require('../../api/products') const productsApi = require('../../api/products')
const config = require('../../utils/config')
const mock = require('../../utils/mock') const mock = require('../../utils/mock')
const dateUtil = require('../../utils/date') 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({ Page({
data: { data: {
form: { form: {
@@ -16,15 +23,16 @@ Page({
remark: '' remark: ''
}, },
products: [], products: [],
artists: mock.artists, artists: config.USE_DEV_MOCK_DATA ? mock.artists : [],
selectedProduct: {}, selectedProduct: {},
selectedArtist: {}, selectedArtist: {},
conflictTip: '', conflictTip: '',
conflictLevel: 'free', conflictLevel: 'free',
loading: false loading: false,
optionError: ''
}, },
onLoad(options) { onLoad(options = {}) {
this.setData({ this.setData({
'form.appointmentDate': options.date || dateUtil.formatDate(new Date()), 'form.appointmentDate': options.date || dateUtil.formatDate(new Date()),
'form.artistId': options.artistId || '' 'form.artistId': options.artistId || ''
@@ -33,22 +41,38 @@ Page({
}, },
async loadOptions() { async loadOptions() {
const fallbackProducts = [ let products = []
{ id: 1, title: '纯色美甲', approximateDuration: '90分钟' }, let artists = []
{ id: 2, title: '猫眼延长', approximateDuration: '120分钟' }, let optionError = ''
{ id: 3, title: '手部护理', approximateDuration: '60分钟' }
]
try { try {
const productsData = await productsApi.list({ page: 1, size: 100 }) const productsData = await productsApi.list({ page: 1, size: 100 })
const products = productsData.list || productsData || fallbackProducts products = productsData.list || productsData || []
this.setData({ products })
} catch (error) { } 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)) || {} try {
this.setData({ selectedArtist }) 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() this.checkAvailability()
}, },
@@ -60,7 +84,7 @@ Page({
onDateChange(event) { onDateChange(event) {
this.setData({ 'form.appointmentDate': event.detail.value }) this.setData({ 'form.appointmentDate': event.detail.value })
this.checkAvailability() this.loadOptions()
}, },
onTimeChange(event) { onTimeChange(event) {
@@ -73,7 +97,7 @@ Page({
this.setData({ this.setData({
selectedProduct, selectedProduct,
'form.productId': selectedProduct.id, 'form.productId': selectedProduct.id,
'form.durationMinutes': String(parseInt(selectedProduct.approximateDuration, 10) || this.data.form.durationMinutes || 60) 'form.durationMinutes': String(toDurationMinutes(selectedProduct.approximateDuration))
}) })
this.checkAvailability() this.checkAvailability()
}, },
@@ -101,40 +125,42 @@ Page({
this.setData({ conflictTip: tip, conflictLevel: 'danger' }) this.setData({ conflictTip: tip, conflictLevel: 'danger' })
return { ok: false, tip } return { ok: false, tip }
} }
let calendar
try { try {
let calendar calendar = await planningApi.calendar({
try { startDate: form.appointmentDate,
calendar = await planningApi.calendar({ endDate: form.appointmentDate,
startDate: form.appointmentDate, artistId: form.artistId
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
}) })
if (conflicts.length > 0) { } catch (error) {
const first = conflicts[0] if (config.USE_DEV_MOCK_DATA) {
const itemStart = Number(first.startMinute || dateUtil.minutesOfDay((first.startTime || '').slice(11, 16))) calendar = mock.buildCalendar(form.appointmentDate)
const itemEnd = itemStart + Number(first.durationMinutes || 60) } else {
const tip = `${this.data.selectedArtist.name || '该美甲师'} ${dateUtil.timeFromMinutes(itemStart)}-${dateUtil.timeFromMinutes(itemEnd)} 已有预约` const tip = error.message || '暂未获取到排班,无法确认该时段是否可预约'
this.setData({ conflictTip: tip, conflictLevel: 'danger' }) this.setData({ conflictTip: tip, conflictLevel: 'danger' })
return { ok: false, tip } 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() { async submit() {
@@ -145,7 +171,7 @@ Page({
} }
const availability = await this.checkAvailability() const availability = await this.checkAvailability()
if (!availability.ok) { if (!availability.ok) {
wx.showToast({ title: availability.tip || '该时段已被预约', icon: 'none' }) wx.showToast({ title: availability.tip || '该时段不可预约', icon: 'none' })
return return
} }
this.setData({ loading: true }) this.setData({ loading: true })
@@ -1,4 +1,10 @@
<view class="page no-tab"> <view class="page no-tab">
<view wx:if="{{optionError}}" class="card error-card">
<text class="error-title">选项加载不完整</text>
<text class="error-desc">{{optionError}}</text>
<button class="compact-btn" bindtap="loadOptions">重试</button>
</view>
<view class="card form-card"> <view class="card form-card">
<view class="field"> <view class="field">
<text class="field-label">客户姓名</text> <text class="field-label">客户姓名</text>
@@ -1,7 +1,18 @@
const planningApi = require('../../api/planning') const planningApi = require('../../api/planning')
const config = require('../../utils/config')
const mock = require('../../utils/mock') const mock = require('../../utils/mock')
const dateUtil = require('../../utils/date') 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({ Page({
data: { data: {
id: '', id: '',
@@ -9,18 +20,35 @@ Page({
selectedArtistId: '', selectedArtistId: '',
date: dateUtil.formatDate(new Date()), date: dateUtil.formatDate(new Date()),
time: '13:00', time: '13:00',
loading: false loading: false,
loadError: false,
errorMessage: ''
}, },
onLoad(options) { onLoad(options = {}) {
this.setData({ this.setData({ id: options.id || '' })
id: options.id || '', this.loadArtists()
artists: mock.artists.map((item, index) => ({ },
...item,
availableStatus: index === 1 ? 'busy' : index === 2 ? 'full' : 'free', async loadArtists() {
availableText: index === 1 ? '有冲突' : index === 2 ? '已满' : '可接' 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) { selectArtist(event) {
@@ -28,7 +56,8 @@ Page({
}, },
onDateChange(event) { onDateChange(event) {
this.setData({ date: event.detail.value }) this.setData({ date: event.detail.value, selectedArtistId: '' })
this.loadArtists()
}, },
onTimeChange(event) { onTimeChange(event) {
@@ -36,6 +65,10 @@ Page({
}, },
async submit() { async submit() {
if (this.data.loadError) {
wx.showToast({ title: '请先重新加载可接员工', icon: 'none' })
return
}
if (!this.data.selectedArtistId) { if (!this.data.selectedArtistId) {
wx.showToast({ title: '请选择美甲师', icon: 'none' }) wx.showToast({ title: '请选择美甲师', icon: 'none' })
return return
@@ -1,5 +1,13 @@
<view class="page no-tab"> <view class="page no-tab">
<view class="list"> <view wx:if="{{loadError}}" class="card error-card">
<text class="error-title">数据加载失败</text>
<text class="error-desc">{{errorMessage}}</text>
<button class="compact-btn" bindtap="loadArtists">重试</button>
</view>
<view wx:elif="{{!artists.length}}" class="empty">暂无可改派美甲师</view>
<view wx:else class="list">
<view wx:for="{{artists}}" wx:key="id" class="card transfer-card {{selectedArtistId == item.id ? 'active' : ''}}" data-id="{{item.id}}" bindtap="selectArtist"> <view wx:for="{{artists}}" wx:key="id" class="card transfer-card {{selectedArtistId == item.id ? 'active' : ''}}" data-id="{{item.id}}" bindtap="selectArtist">
<view class="row between"> <view class="row between">
<view class="row"> <view class="row">
@@ -1,26 +1,62 @@
const employeesApi = require('../../api/employees')
const config = require('../../utils/config')
const mock = require('../../utils/mock') 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({ Page({
data: { data: {
id: '', id: '',
employee: {} employee: {},
loadError: false,
errorMessage: ''
}, },
onLoad(options) { onLoad(options = {}) {
const id = options.id || mock.artists[0].id const id = options.id || ''
const artist = mock.artists.find(item => String(item.id) === String(id)) || mock.artists[0] this.setData({ id })
this.setData({ this.loadEmployee()
id, },
employee: {
...artist, async loadEmployee() {
monthOrders: 32, this.setData({ loadError: false, errorMessage: '' })
monthAmount: 5800, try {
avgAmount: 181 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) { go(event) {
if (this.data.loadError) {
wx.showToast({ title: '请先重新加载员工详情', icon: 'none' })
return
}
wx.navigateTo({ url: `${event.currentTarget.dataset.url}?id=${this.data.id}` }) wx.navigateTo({ url: `${event.currentTarget.dataset.url}?id=${this.data.id}` })
}, },
@@ -1,33 +1,41 @@
<view class="page no-tab"> <view class="page no-tab">
<view class="card employee-head"> <view wx:if="{{loadError}}" class="card error-card">
<view class="avatar" style="background: {{employee.color}};">{{employee.shortName}}</view> <text class="error-title">数据加载失败</text>
<view> <text class="error-desc">{{errorMessage}}</text>
<text class="employee-name">{{employee.name}}</text> <button class="compact-btn" bindtap="loadEmployee">重试</button>
<text class="tag" style="background: {{employee.color}}; color: #fff;">员工色</text>
</view>
</view> </view>
<view class="stats"> <block wx:else>
<view class="card stat"> <view class="card employee-head">
<text class="stat-value">{{employee.monthOrders}}</text> <view class="avatar" style="background: {{employee.color}};">{{employee.shortName}}</view>
<text class="stat-label">本月订单</text> <view>
<text class="employee-name">{{employee.name}}</text>
<text class="tag" style="background: {{employee.color}}; color: #fff;">员工色</text>
</view>
</view> </view>
<view class="card stat">
<text class="stat-value">¥{{employee.monthAmount}}</text>
<text class="stat-label">本月营业额</text>
</view>
<view class="card stat">
<text class="stat-value">¥{{employee.avgAmount}}</text>
<text class="stat-label">平均客单价</text>
</view>
</view>
<view class="section"> <view class="stats">
<view class="menu-grid"> <view class="card stat">
<view class="card menu-card" data-url="/pages/schedule-setting/index" bindtap="go">排班设置</view> <text class="stat-value">{{employee.monthOrders}}</text>
<view class="card menu-card" data-url="/pages/leave-management/index" bindtap="go">请假管理</view> <text class="stat-label">本月订单</text>
<view class="card menu-card" data-url="/pages/color-setting/index" bindtap="go">颜色设置</view> </view>
<view class="card menu-card" data-url="/pages/employee-orders/index" bindtap="go">订单记录</view> <view class="card stat">
<text class="stat-value">¥{{employee.monthAmount}}</text>
<text class="stat-label">本月营业额</text>
</view>
<view class="card stat">
<text class="stat-value">¥{{employee.avgAmount}}</text>
<text class="stat-label">平均客单价</text>
</view>
</view> </view>
</view>
<view class="section">
<view class="menu-grid">
<view class="card menu-card" data-url="/pages/schedule-setting/index" bindtap="go">排班设置</view>
<view class="card menu-card" data-url="/pages/leave-management/index" bindtap="go">请假管理</view>
<view class="card menu-card" data-url="/pages/color-setting/index" bindtap="go">颜色设置</view>
<view class="card menu-card" data-url="/pages/employee-orders/index" bindtap="go">订单记录</view>
</view>
</view>
</block>
</view> </view>
@@ -1,9 +1,12 @@
const employeesApi = require('../../api/employees') const employeesApi = require('../../api/employees')
const mock = require('../../utils/mock')
const EMPLOYEE_COLORS = ['#7BA7C7', '#89A98B', '#A893BC', '#D49A89', '#C9A66B', '#7E9A9A']
Page({ Page({
data: { data: {
employees: [] employees: [],
loadError: false,
errorMessage: ''
}, },
onLoad() { onLoad() {
@@ -11,11 +14,7 @@ Page({
}, },
async loadEmployees() { async loadEmployees() {
const fallback = mock.artists.map((item, index) => ({ this.setData({ loadError: false, errorMessage: '' })
...item,
monthOrders: 32 - index * 5,
monthAmount: 5800 - index * 760
}))
try { try {
const data = await employeesApi.list({ page: 1, size: 50 }) const data = await employeesApi.list({ page: 1, size: 50 })
const list = data.list || data || [] const list = data.list || data || []
@@ -24,13 +23,17 @@ Page({
id: item.userId || item.id, id: item.userId || item.id,
name: item.nickname || item.name || item.artistName || `美甲师${index + 1}`, name: item.nickname || item.name || item.artistName || `美甲师${index + 1}`,
shortName: (item.nickname || item.name || '师').slice(-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, monthOrders: item.monthOrders || item.orderCount || 0,
monthAmount: item.monthAmount || item.turnover || 0 monthAmount: item.monthAmount || item.turnover || 0
})) }))
}) })
} catch (error) { } catch (error) {
this.setData({ employees: fallback }) this.setData({
employees: [],
loadError: true,
errorMessage: error.message || '员工数据加载失败,请检查服务连接后重试'
})
} }
}, },
@@ -4,7 +4,15 @@
<button class="compact-btn" bindtap="addEmployee">新增</button> <button class="compact-btn" bindtap="addEmployee">新增</button>
</view> </view>
<view class="list"> <view wx:if="{{loadError}}" class="card error-card">
<text class="error-title">数据加载失败</text>
<text class="error-desc">{{errorMessage}}</text>
<button class="compact-btn" bindtap="loadEmployees">重试</button>
</view>
<view wx:elif="{{!employees.length}}" class="empty">暂无员工数据</view>
<view wx:else class="list">
<view wx:for="{{employees}}" wx:key="id" class="card employee-card" data-id="{{item.id}}" bindtap="openDetail"> <view wx:for="{{employees}}" wx:key="id" class="card employee-card" data-id="{{item.id}}" bindtap="openDetail">
<view class="employee-left"> <view class="employee-left">
<view class="avatar" style="background: {{item.color}};">{{item.shortName}}</view> <view class="avatar" style="background: {{item.color}};">{{item.shortName}}</view>
@@ -1,5 +1,6 @@
const planningApi = require('../../api/planning') const planningApi = require('../../api/planning')
const dateUtil = require('../../utils/date') const dateUtil = require('../../utils/date')
const config = require('../../utils/config')
const mock = require('../../utils/mock') const mock = require('../../utils/mock')
Page({ Page({
@@ -40,7 +41,9 @@ Page({
dayTotal: 0, dayTotal: 0,
freeArtistCount: 0, freeArtistCount: 0,
pendingCount: 0, pendingCount: 0,
loading: false loading: false,
loadError: false,
errorMessage: ''
}, },
onLoad() { onLoad() {
@@ -130,9 +133,25 @@ Page({
endDate: range.end, endDate: range.end,
artistId: this.data.selectedArtistId || undefined artistId: this.data.selectedArtistId || undefined
}) })
this.setData({ loadError: false, errorMessage: '' })
this.applyCalendar(data) this.applyCalendar(data)
} catch (error) { } 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 { } finally {
this.setData({ loading: false }) this.setData({ loading: false })
} }
@@ -26,6 +26,12 @@
</scroll-view> </scroll-view>
</view> </view>
<view wx:if="{{loadError}}" class="card error-card">
<text class="error-title">数据加载失败</text>
<text class="error-desc">{{errorMessage}}</text>
<button class="compact-btn" bindtap="loadCalendar">重试</button>
</view>
<view wx:if="{{viewMode === 'day'}}" class="section"> <view wx:if="{{viewMode === 'day'}}" class="section">
<view class="day-summary"> <view class="day-summary">
<view class="summary-item card"> <view class="summary-item card">
+2 -1
View File
@@ -3,5 +3,6 @@ const DEFAULT_DOMAIN = 'http://127.0.0.1:63341'
module.exports = { module.exports = {
API_DOMAIN: DEFAULT_DOMAIN, API_DOMAIN: DEFAULT_DOMAIN,
ADMIN_API_BASE_URL: `${DEFAULT_DOMAIN}/admin`, ADMIN_API_BASE_URL: `${DEFAULT_DOMAIN}/admin`,
REQUEST_TIMEOUT: 10000 REQUEST_TIMEOUT: 10000,
USE_DEV_MOCK_DATA: false
} }
-8
View File
@@ -7,13 +7,5 @@ module.exports = {
method: 'POST', method: 'POST',
data: {} data: {}
}) })
},
mockOrderPaymentSuccess(orderId) {
return request({
url: `/payment/order/${orderId}/mock-success`,
method: 'POST',
data: {}
})
} }
} }
+2 -8
View File
@@ -19,7 +19,6 @@ const afterSaleApi = require('./after-sale')
const growthApi = require('./growth') const growthApi = require('./growth')
paymentApi.prepareOrderPayment(12) paymentApi.prepareOrderPayment(12)
paymentApi.mockOrderPaymentSuccess(12)
afterSaleApi.applyAfterSale({ orderId: 12, reason: 'need refund' }) afterSaleApi.applyAfterSale({ orderId: 12, reason: 'need refund' })
afterSaleApi.getMyAfterSales({ page: 2, size: 5 }) afterSaleApi.getMyAfterSales({ page: 2, size: 5 })
growthApi.getGrowthSummary() growthApi.getGrowthSummary()
@@ -32,19 +31,14 @@ assert.deepStrictEqual(calls[0], {
data: {} data: {}
}) })
assert.deepStrictEqual(calls[1], { assert.deepStrictEqual(calls[1], {
url: '/payment/order/12/mock-success',
method: 'POST',
data: {}
})
assert.deepStrictEqual(calls[2], {
url: '/after-sale/apply', url: '/after-sale/apply',
method: 'POST', method: 'POST',
data: { orderId: 12, reason: 'need refund' } data: { orderId: 12, reason: 'need refund' }
}) })
assert.deepStrictEqual(calls[3], { assert.deepStrictEqual(calls[2], {
url: '/after-sale/my', url: '/after-sale/my',
params: { page: 2, size: 5 } params: { page: 2, size: 5 }
}) })
assert.deepStrictEqual(calls[4], { assert.deepStrictEqual(calls[3], {
url: '/growth/summary' url: '/growth/summary'
}) })
+4 -7
View File
@@ -864,9 +864,9 @@ Page({
}) })
const confirmed = await new Promise(resolve => { const confirmed = await new Promise(resolve => {
wx.showModal({ wx.showModal({
title: '模拟支付', title: '准备支付',
content: `本次需支付 ${order.paymentInfo.amountText},确认模拟支付成功吗?`, content: `本次需支付 ${order.paymentInfo.amountText},支付单准备后请等待正式支付接入。`,
confirmText: '确认支付', confirmText: '知道了',
success: res => resolve(Boolean(res.confirm)), success: res => resolve(Boolean(res.confirm)),
fail: () => resolve(false) fail: () => resolve(false)
}) })
@@ -874,11 +874,8 @@ Page({
if (!confirmed) { if (!confirmed) {
return return
} }
await runWithLoading(() => paymentApi.mockOrderPaymentSuccess(orderId), {
title: '确认支付'
})
wx.showToast({ wx.showToast({
title: '支付已确认', title: '支付单已准备',
icon: 'none' icon: 'none'
}) })
await this.loadOrders() await this.loadOrders()
@@ -4,36 +4,38 @@ import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
/** import java.nio.charset.StandardCharsets;
* JWT 配置。
*/
@Data @Data
@Configuration @Configuration
@ConfigurationProperties(prefix = "yuminail.security.jwt") @ConfigurationProperties(prefix = "yuminail.security.jwt")
public class JwtProperties { public class JwtProperties {
/** public static final String DEVELOPMENT_PLACEHOLDER_SECRET = "__CONFIGURE_YUMINAIL_JWT_SECRET_OUTSIDE_REPOSITORY__";
* HS512 密钥,生产环境请通过 Nacos 覆盖。 private static final int HS512_MIN_SECRET_BYTES = 64;
*/
private String secret = "yuminail-secret-key-for-jwt-token-generation-2026-must-be-at-least-512-bits-long-for-hs512-algorithm-security-requirements";
/** /**
* 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"; private String issuer = "yuminail";
/**
* AccessToken 有效期,单位秒。
*/
private long accessTokenExpirationSeconds = 2 * 60 * 60; private long accessTokenExpirationSeconds = 2 * 60 * 60;
/**
* RefreshToken 有效期,单位秒。
*/
private long refreshTokenExpirationSeconds = 7 * 24 * 60 * 60; private long refreshTokenExpirationSeconds = 7 * 24 * 60 * 60;
/**
* 时钟偏移容忍,单位秒。
*/
private long clockSkewSeconds = 30; 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 字节");
}
}
} }
@@ -11,12 +11,22 @@ import java.time.LocalTime;
@Mapper @Mapper
public interface ArtistScheduleMapper extends BaseMapper<ArtistScheduleDO> { public interface ArtistScheduleMapper extends BaseMapper<ArtistScheduleDO> {
@Select("SELECT * FROM t_artist_schedule WHERE shop_id = #{shopId} AND artist_id = #{artistId} " + @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 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, ArtistScheduleDO selectCoveringSchedule(@Param("shopId") Long shopId,
@Param("artistId") Long artistId, @Param("artistId") Long artistId,
@Param("workDate") LocalDate workDate, @Param("workDate") LocalDate workDate,
@Param("startTime") LocalTime startTime, @Param("startTime") LocalTime startTime,
@Param("endTime") LocalTime endTime); @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);
} }
@@ -1,12 +1,17 @@
package com.xiaowang.yuminailcore.modules.auth.controller.front; package com.xiaowang.yuminailcore.modules.auth.controller.front;
import com.xiaowang.yuminailcore.annotation.RequirePermission;
import com.xiaowang.yuminailcore.common.Result; import com.xiaowang.yuminailcore.common.Result;
import com.xiaowang.yuminailcore.modules.auth.dto.LoginIdentityDTO; import com.xiaowang.yuminailcore.modules.auth.dto.LoginIdentityDTO;
import com.xiaowang.yuminailcore.modules.auth.vo.LoginIdentityVO; import com.xiaowang.yuminailcore.modules.auth.vo.LoginIdentityVO;
import com.xiaowang.yuminailcore.modules.auth.service.LoginIdentityService; 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 lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.List; 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. * Variable `loginIdentityService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/ */
private final LoginIdentityService loginIdentityService; private final LoginIdentityService loginIdentityService;
private final AdminScopeHelper adminScopeHelper;
private final UserShopBindingSupport userShopBindingSupport;
/** /**
* 创建登录标识 * 创建登录标识
@@ -32,7 +39,10 @@ public class LoginIdentityController {
* @return 登录标识ID * @return 登录标识ID
*/ */
@PostMapping("/create") @PostMapping("/create")
public Result<Long> createLoginIdentity(@RequestBody LoginIdentityDTO loginIdentityDTO) { @RequirePermission("user:create")
public Result<Long> createLoginIdentity(HttpServletRequest request, @RequestBody LoginIdentityDTO loginIdentityDTO) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
ensureTargetUserAccessible(currentUser, loginIdentityDTO.getUserId(), "无权为其他店铺用户创建登录标识");
Long id = loginIdentityService.createLoginIdentity(loginIdentityDTO); Long id = loginIdentityService.createLoginIdentity(loginIdentityDTO);
return Result.success(id); return Result.success(id);
} }
@@ -45,7 +55,14 @@ public class LoginIdentityController {
* @return 是否更新成功 * @return 是否更新成功
*/ */
@PutMapping("/update/{id}") @PutMapping("/update/{id}")
public Result<Boolean> updateLoginIdentity(@PathVariable Long id, @RequestBody LoginIdentityDTO loginIdentityDTO) { @RequirePermission("user:edit")
public Result<Boolean> 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); boolean success = loginIdentityService.updateLoginIdentity(id, loginIdentityDTO);
return Result.success(success); return Result.success(success);
} }
@@ -57,7 +74,13 @@ public class LoginIdentityController {
* @return 是否删除成功 * @return 是否删除成功
*/ */
@DeleteMapping("/delete/{id}") @DeleteMapping("/delete/{id}")
public Result<Boolean> deleteLoginIdentity(@PathVariable Long id) { @RequirePermission("user:delete")
public Result<Boolean> 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); boolean success = loginIdentityService.deleteLoginIdentity(id);
return Result.success(success); return Result.success(success);
} }
@@ -69,8 +92,13 @@ public class LoginIdentityController {
* @return 登录标识VO * @return 登录标识VO
*/ */
@GetMapping("/get/{id}") @GetMapping("/get/{id}")
public Result<LoginIdentityVO> getLoginIdentityById(@PathVariable Long id) { @RequirePermission("user:view")
public Result<LoginIdentityVO> getLoginIdentityById(HttpServletRequest request, @PathVariable Long id) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
LoginIdentityVO loginIdentityVO = loginIdentityService.getLoginIdentityById(id); LoginIdentityVO loginIdentityVO = loginIdentityService.getLoginIdentityById(id);
if (loginIdentityVO != null) {
ensureTargetUserAccessible(currentUser, loginIdentityVO.getUserId(), "无权查看其他店铺用户登录标识");
}
return Result.success(loginIdentityVO); return Result.success(loginIdentityVO);
} }
@@ -80,8 +108,12 @@ public class LoginIdentityController {
* @return 登录标识VO列表 * @return 登录标识VO列表
*/ */
@GetMapping("/list/all") @GetMapping("/list/all")
public Result<List<LoginIdentityVO>> listAllLoginIdentities() { @RequirePermission("user:view")
List<LoginIdentityVO> loginIdentityVOs = loginIdentityService.listAllLoginIdentities(); public Result<List<LoginIdentityVO>> listAllLoginIdentities(HttpServletRequest request) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
List<LoginIdentityVO> loginIdentityVOs = adminScopeHelper.isPlatformAdmin(currentUser)
? loginIdentityService.listAllLoginIdentities()
: loginIdentityService.listLoginIdentitiesByUserIds(scopedUserIds(currentUser));
return Result.success(loginIdentityVOs); return Result.success(loginIdentityVOs);
} }
@@ -92,7 +124,10 @@ public class LoginIdentityController {
* @return 登录标识VO列表 * @return 登录标识VO列表
*/ */
@GetMapping("/list/user/{userId}") @GetMapping("/list/user/{userId}")
public Result<List<LoginIdentityVO>> listLoginIdentitiesByUserId(@PathVariable Long userId) { @RequirePermission("user:view")
public Result<List<LoginIdentityVO>> listLoginIdentitiesByUserId(HttpServletRequest request, @PathVariable Long userId) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
ensureTargetUserAccessible(currentUser, userId, "无权查看其他店铺用户登录标识");
List<LoginIdentityVO> loginIdentityVOs = loginIdentityService.listLoginIdentitiesByUserId(userId); List<LoginIdentityVO> loginIdentityVOs = loginIdentityService.listLoginIdentitiesByUserId(userId);
return Result.success(loginIdentityVOs); return Result.success(loginIdentityVOs);
} }
@@ -104,8 +139,21 @@ public class LoginIdentityController {
* @return 登录标识VO列表 * @return 登录标识VO列表
*/ */
@GetMapping("/list/loginMethod/{loginMethod}") @GetMapping("/list/loginMethod/{loginMethod}")
public Result<List<LoginIdentityVO>> listLoginIdentitiesByLoginMethod(@PathVariable String loginMethod) { @RequirePermission("user:view")
List<LoginIdentityVO> loginIdentityVOs = loginIdentityService.listLoginIdentitiesByLoginMethod(loginMethod); public Result<List<LoginIdentityVO>> listLoginIdentitiesByLoginMethod(HttpServletRequest request, @PathVariable String loginMethod) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
List<LoginIdentityVO> loginIdentityVOs = adminScopeHelper.isPlatformAdmin(currentUser)
? loginIdentityService.listLoginIdentitiesByLoginMethod(loginMethod)
: loginIdentityService.listLoginIdentitiesByLoginMethodAndUserIds(loginMethod, scopedUserIds(currentUser));
return Result.success(loginIdentityVOs); return Result.success(loginIdentityVOs);
} }
private List<Long> 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);
}
} }
@@ -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.dto.LoginIdentityDTO;
import com.xiaowang.yuminailcore.modules.auth.vo.LoginIdentityVO; import com.xiaowang.yuminailcore.modules.auth.vo.LoginIdentityVO;
import java.util.Collection;
import java.util.List; import java.util.List;
/** /**
@@ -56,6 +57,8 @@ public interface LoginIdentityService extends IService<LoginIdentityDO> {
*/ */
List<LoginIdentityVO> listAllLoginIdentities(); List<LoginIdentityVO> listAllLoginIdentities();
List<LoginIdentityVO> listLoginIdentitiesByUserIds(Collection<Long> userIds);
/** /**
* 根据用户ID查询登录标识 * 根据用户ID查询登录标识
* *
@@ -71,4 +74,6 @@ public interface LoginIdentityService extends IService<LoginIdentityDO> {
* @return 登录标识VO列表 * @return 登录标识VO列表
*/ */
List<LoginIdentityVO> listLoginIdentitiesByLoginMethod(String loginMethod); List<LoginIdentityVO> listLoginIdentitiesByLoginMethod(String loginMethod);
List<LoginIdentityVO> listLoginIdentitiesByLoginMethodAndUserIds(String loginMethod, Collection<Long> userIds);
} }
@@ -10,6 +10,7 @@ import com.xiaowang.yuminailcore.modules.auth.vo.LoginIdentityVO;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@@ -113,6 +114,21 @@ public class LoginIdentityServiceImpl extends ServiceImpl<LoginIdentityMapper, L
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
@Override
public List<LoginIdentityVO> listLoginIdentitiesByUserIds(Collection<Long> userIds) {
List<Long> scopedUserIds = normalizeUserIds(userIds);
if (scopedUserIds.isEmpty()) {
return List.of();
}
List<LoginIdentityDO> loginIdentityDOs = loginIdentityMapper.selectList(
Wrappers.lambdaQuery(LoginIdentityDO.class)
.in(LoginIdentityDO::getUserId, scopedUserIds)
);
return loginIdentityDOs.stream()
.map(this::convertToVO)
.collect(Collectors.toList());
}
@Override @Override
/** /**
* List records for the current query or current user scope. * List records for the current query or current user scope.
@@ -147,6 +163,32 @@ public class LoginIdentityServiceImpl extends ServiceImpl<LoginIdentityMapper, L
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
@Override
public List<LoginIdentityVO> listLoginIdentitiesByLoginMethodAndUserIds(String loginMethod, Collection<Long> userIds) {
List<Long> scopedUserIds = normalizeUserIds(userIds);
if (scopedUserIds.isEmpty()) {
return List.of();
}
List<LoginIdentityDO> 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<Long> normalizeUserIds(Collection<Long> userIds) {
if (userIds == null || userIds.isEmpty()) {
return List.of();
}
return userIds.stream()
.filter(id -> id != null && id > 0)
.distinct()
.collect(Collectors.toList());
}
/** /**
* 将 DO 转换为 VO * 将 DO 转换为 VO
* *
@@ -1,12 +1,15 @@
package com.xiaowang.yuminailcore.modules.marketing.controller.front; package com.xiaowang.yuminailcore.modules.marketing.controller.front;
import com.xiaowang.yuminailcore.annotation.RequirePermission;
import com.xiaowang.yuminailcore.common.Result; import com.xiaowang.yuminailcore.common.Result;
import com.xiaowang.yuminailcore.modules.marketing.dto.VipBenefitDTO; import com.xiaowang.yuminailcore.modules.marketing.dto.VipBenefitDTO;
import com.xiaowang.yuminailcore.modules.marketing.vo.VipBenefitVO; import com.xiaowang.yuminailcore.modules.marketing.vo.VipBenefitVO;
import com.xiaowang.yuminailcore.modules.marketing.service.VipBenefitService; import com.xiaowang.yuminailcore.modules.marketing.service.VipBenefitService;
import com.xiaowang.yuminailcore.modules.security.support.AdminScopeHelper;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.List; 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. * Variable `vipBenefitService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/ */
private final VipBenefitService vipBenefitService; private final VipBenefitService vipBenefitService;
private final AdminScopeHelper adminScopeHelper;
/** /**
* 创建VIP权益 * 创建VIP权益
@@ -32,7 +36,9 @@ public class VipBenefitController {
* @return VIP权益ID * @return VIP权益ID
*/ */
@PostMapping("/create") @PostMapping("/create")
public Result<Long> createVipBenefit(@RequestBody VipBenefitDTO vipBenefitDTO) { @RequirePermission("user:vip:manage")
public Result<Long> createVipBenefit(HttpServletRequest request, @RequestBody VipBenefitDTO vipBenefitDTO) {
requirePlatformAdmin(request);
Long id = vipBenefitService.createVipBenefit(vipBenefitDTO); Long id = vipBenefitService.createVipBenefit(vipBenefitDTO);
return Result.success(id); return Result.success(id);
} }
@@ -45,7 +51,9 @@ public class VipBenefitController {
* @return 是否更新成功 * @return 是否更新成功
*/ */
@PutMapping("/update/{id}") @PutMapping("/update/{id}")
public Result<Boolean> updateVipBenefit(@PathVariable Long id, @RequestBody VipBenefitDTO vipBenefitDTO) { @RequirePermission("user:vip:manage")
public Result<Boolean> updateVipBenefit(HttpServletRequest request, @PathVariable Long id, @RequestBody VipBenefitDTO vipBenefitDTO) {
requirePlatformAdmin(request);
boolean success = vipBenefitService.updateVipBenefit(id, vipBenefitDTO); boolean success = vipBenefitService.updateVipBenefit(id, vipBenefitDTO);
return Result.success(success); return Result.success(success);
} }
@@ -57,7 +65,9 @@ public class VipBenefitController {
* @return 是否删除成功 * @return 是否删除成功
*/ */
@DeleteMapping("/delete/{id}") @DeleteMapping("/delete/{id}")
public Result<Boolean> deleteVipBenefit(@PathVariable Long id) { @RequirePermission("user:vip:manage")
public Result<Boolean> deleteVipBenefit(HttpServletRequest request, @PathVariable Long id) {
requirePlatformAdmin(request);
boolean success = vipBenefitService.deleteVipBenefit(id); boolean success = vipBenefitService.deleteVipBenefit(id);
return Result.success(success); return Result.success(success);
} }
@@ -69,7 +79,9 @@ public class VipBenefitController {
* @return VIP权益VO * @return VIP权益VO
*/ */
@GetMapping("/get/{id}") @GetMapping("/get/{id}")
public Result<VipBenefitVO> getVipBenefitById(@PathVariable Long id) { @RequirePermission("user:vip:manage")
public Result<VipBenefitVO> getVipBenefitById(HttpServletRequest request, @PathVariable Long id) {
requirePlatformAdmin(request);
VipBenefitVO vipBenefitVO = vipBenefitService.getVipBenefitById(id); VipBenefitVO vipBenefitVO = vipBenefitService.getVipBenefitById(id);
return Result.success(vipBenefitVO); return Result.success(vipBenefitVO);
} }
@@ -80,7 +92,9 @@ public class VipBenefitController {
* @return VIP权益VO列表 * @return VIP权益VO列表
*/ */
@GetMapping("/list/all") @GetMapping("/list/all")
public Result<List<VipBenefitVO>> listAllVipBenefits() { @RequirePermission("user:vip:manage")
public Result<List<VipBenefitVO>> listAllVipBenefits(HttpServletRequest request) {
requirePlatformAdmin(request);
List<VipBenefitVO> vipBenefitVOs = vipBenefitService.listAllVipBenefits(); List<VipBenefitVO> vipBenefitVOs = vipBenefitService.listAllVipBenefits();
return Result.success(vipBenefitVOs); return Result.success(vipBenefitVOs);
} }
@@ -92,8 +106,17 @@ public class VipBenefitController {
* @return VIP权益VO列表 * @return VIP权益VO列表
*/ */
@GetMapping("/list/requiredVipLevel/{requiredVipLevel}") @GetMapping("/list/requiredVipLevel/{requiredVipLevel}")
public Result<List<VipBenefitVO>> listVipBenefitsByRequiredVipLevel(@PathVariable String requiredVipLevel) { @RequirePermission("user:vip:manage")
public Result<List<VipBenefitVO>> listVipBenefitsByRequiredVipLevel(HttpServletRequest request, @PathVariable String requiredVipLevel) {
requirePlatformAdmin(request);
List<VipBenefitVO> vipBenefitVOs = vipBenefitService.listVipBenefitsByRequiredVipLevel(requiredVipLevel); List<VipBenefitVO> vipBenefitVOs = vipBenefitService.listVipBenefitsByRequiredVipLevel(requiredVipLevel);
return Result.success(vipBenefitVOs); return Result.success(vipBenefitVOs);
} }
private void requirePlatformAdmin(HttpServletRequest request) {
adminScopeHelper.requirePlatformAdmin(
adminScopeHelper.getCurrentUser(request),
"只有平台管理员可以维护全局VIP权益配置"
);
}
} }
@@ -1,12 +1,17 @@
package com.xiaowang.yuminailcore.modules.marketing.controller.front; package com.xiaowang.yuminailcore.modules.marketing.controller.front;
import com.xiaowang.yuminailcore.annotation.RequirePermission;
import com.xiaowang.yuminailcore.common.Result; import com.xiaowang.yuminailcore.common.Result;
import com.xiaowang.yuminailcore.modules.marketing.dto.VipInfoDTO; import com.xiaowang.yuminailcore.modules.marketing.dto.VipInfoDTO;
import com.xiaowang.yuminailcore.modules.marketing.vo.VipInfoVO; import com.xiaowang.yuminailcore.modules.marketing.vo.VipInfoVO;
import com.xiaowang.yuminailcore.modules.marketing.service.VipInfoService; 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 lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.List; 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. * Variable `vipInfoService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/ */
private final VipInfoService vipInfoService; private final VipInfoService vipInfoService;
private final AdminScopeHelper adminScopeHelper;
private final UserShopBindingSupport userShopBindingSupport;
/** /**
* 创建VIP信息 * 创建VIP信息
@@ -32,7 +39,10 @@ public class VipInfoController {
* @return VIP信息ID * @return VIP信息ID
*/ */
@PostMapping("/create") @PostMapping("/create")
public Result<Long> createVipInfo(@RequestBody VipInfoDTO vipInfoDTO) { @RequirePermission("user:vip:manage")
public Result<Long> createVipInfo(HttpServletRequest request, @RequestBody VipInfoDTO vipInfoDTO) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
ensureTargetUserAccessible(currentUser, vipInfoDTO.getUserId(), "无权为其他店铺用户创建VIP信息");
Long id = vipInfoService.createVipInfo(vipInfoDTO); Long id = vipInfoService.createVipInfo(vipInfoDTO);
return Result.success(id); return Result.success(id);
} }
@@ -45,7 +55,14 @@ public class VipInfoController {
* @return 是否更新成功 * @return 是否更新成功
*/ */
@PutMapping("/update/{id}") @PutMapping("/update/{id}")
public Result<Boolean> updateVipInfo(@PathVariable Long id, @RequestBody VipInfoDTO vipInfoDTO) { @RequirePermission("user:vip:manage")
public Result<Boolean> 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); boolean success = vipInfoService.updateVipInfo(id, vipInfoDTO);
return Result.success(success); return Result.success(success);
} }
@@ -57,7 +74,13 @@ public class VipInfoController {
* @return 是否删除成功 * @return 是否删除成功
*/ */
@DeleteMapping("/delete/{id}") @DeleteMapping("/delete/{id}")
public Result<Boolean> deleteVipInfo(@PathVariable Long id) { @RequirePermission("user:vip:manage")
public Result<Boolean> 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); boolean success = vipInfoService.deleteVipInfo(id);
return Result.success(success); return Result.success(success);
} }
@@ -69,8 +92,13 @@ public class VipInfoController {
* @return VIP信息VO * @return VIP信息VO
*/ */
@GetMapping("/get/{id}") @GetMapping("/get/{id}")
public Result<VipInfoVO> getVipInfoById(@PathVariable Long id) { @RequirePermission("user:vip:manage")
public Result<VipInfoVO> getVipInfoById(HttpServletRequest request, @PathVariable Long id) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
VipInfoVO vipInfoVO = vipInfoService.getVipInfoById(id); VipInfoVO vipInfoVO = vipInfoService.getVipInfoById(id);
if (vipInfoVO != null) {
ensureTargetUserAccessible(currentUser, vipInfoVO.getUserId(), "无权查看其他店铺用户VIP信息");
}
return Result.success(vipInfoVO); return Result.success(vipInfoVO);
} }
@@ -80,8 +108,12 @@ public class VipInfoController {
* @return VIP信息VO列表 * @return VIP信息VO列表
*/ */
@GetMapping("/list/all") @GetMapping("/list/all")
public Result<List<VipInfoVO>> listAllVipInfos() { @RequirePermission("user:vip:manage")
List<VipInfoVO> vipInfoVOs = vipInfoService.listAllVipInfos(); public Result<List<VipInfoVO>> listAllVipInfos(HttpServletRequest request) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
List<VipInfoVO> vipInfoVOs = adminScopeHelper.isPlatformAdmin(currentUser)
? vipInfoService.listAllVipInfos()
: vipInfoService.listVipInfosByUserIds(scopedUserIds(currentUser));
return Result.success(vipInfoVOs); return Result.success(vipInfoVOs);
} }
@@ -92,8 +124,21 @@ public class VipInfoController {
* @return VIP信息VO列表 * @return VIP信息VO列表
*/ */
@GetMapping("/list/vipLevel/{vipLevel}") @GetMapping("/list/vipLevel/{vipLevel}")
public Result<List<VipInfoVO>> listVipInfosByVipLevel(@PathVariable String vipLevel) { @RequirePermission("user:vip:manage")
List<VipInfoVO> vipInfoVOs = vipInfoService.listVipInfosByVipLevel(vipLevel); public Result<List<VipInfoVO>> listVipInfosByVipLevel(HttpServletRequest request, @PathVariable String vipLevel) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
List<VipInfoVO> vipInfoVOs = adminScopeHelper.isPlatformAdmin(currentUser)
? vipInfoService.listVipInfosByVipLevel(vipLevel)
: vipInfoService.listVipInfosByVipLevelAndUserIds(vipLevel, scopedUserIds(currentUser));
return Result.success(vipInfoVOs); return Result.success(vipInfoVOs);
} }
private List<Long> 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);
}
} }
@@ -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.dto.VipInfoDTO;
import com.xiaowang.yuminailcore.modules.marketing.vo.VipInfoVO; import com.xiaowang.yuminailcore.modules.marketing.vo.VipInfoVO;
import java.util.Collection;
import java.util.List; import java.util.List;
/** /**
@@ -56,6 +57,8 @@ public interface VipInfoService extends IService<VipInfoDO> {
*/ */
List<VipInfoVO> listAllVipInfos(); List<VipInfoVO> listAllVipInfos();
List<VipInfoVO> listVipInfosByUserIds(Collection<Long> userIds);
/** /**
* 根据VIP等级查询VIP信息 * 根据VIP等级查询VIP信息
* *
@@ -63,4 +66,6 @@ public interface VipInfoService extends IService<VipInfoDO> {
* @return VIP信息VO列表 * @return VIP信息VO列表
*/ */
List<VipInfoVO> listVipInfosByVipLevel(String vipLevel); List<VipInfoVO> listVipInfosByVipLevel(String vipLevel);
List<VipInfoVO> listVipInfosByVipLevelAndUserIds(String vipLevel, Collection<Long> userIds);
} }
@@ -10,6 +10,7 @@ import com.xiaowang.yuminailcore.modules.marketing.vo.VipInfoVO;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@@ -117,6 +118,21 @@ public class VipInfoServiceImpl extends ServiceImpl<VipInfoMapper, VipInfoDO> im
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
@Override
public List<VipInfoVO> listVipInfosByUserIds(Collection<Long> userIds) {
List<Long> scopedUserIds = normalizeUserIds(userIds);
if (scopedUserIds.isEmpty()) {
return List.of();
}
List<VipInfoDO> vipInfoDOs = vipInfoMapper.selectList(
Wrappers.lambdaQuery(VipInfoDO.class)
.in(VipInfoDO::getUserId, scopedUserIds)
);
return vipInfoDOs.stream()
.map(this::convertToVO)
.collect(Collectors.toList());
}
@Override @Override
/** /**
* List records for the current query or current user scope. * List records for the current query or current user scope.
@@ -134,6 +150,32 @@ public class VipInfoServiceImpl extends ServiceImpl<VipInfoMapper, VipInfoDO> im
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
@Override
public List<VipInfoVO> listVipInfosByVipLevelAndUserIds(String vipLevel, Collection<Long> userIds) {
List<Long> scopedUserIds = normalizeUserIds(userIds);
if (scopedUserIds.isEmpty()) {
return List.of();
}
List<VipInfoDO> 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<Long> normalizeUserIds(Collection<Long> userIds) {
if (userIds == null || userIds.isEmpty()) {
return List.of();
}
return userIds.stream()
.filter(id -> id != null && id > 0)
.distinct()
.collect(Collectors.toList());
}
/** /**
* 将 DO 转换为 VO * 将 DO 转换为 VO
* *
@@ -24,9 +24,4 @@ public class PaymentController {
return Result.success(paymentService.prepareOrderPayment(userId, orderId)); return Result.success(paymentService.prepareOrderPayment(userId, orderId));
} }
@PostMapping("/order/{orderId}/mock-success")
public Result<PaymentOrderVO> mockSuccess(HttpServletRequest request, @PathVariable Long orderId) {
Long userId = (Long) request.getAttribute("userId");
return Result.success(paymentService.manualConfirmOrderPaid(userId, orderId, "mock-success"));
}
} }
@@ -1,9 +1,9 @@
package com.xiaowang.yuminailcore.modules.payment.service.impl; package com.xiaowang.yuminailcore.modules.payment.service.impl;
import com.xiaowang.yuminailcore.modules.order.entity.OrderDO; 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.PaymentOrderDO;
import com.xiaowang.yuminailcore.modules.payment.entity.RefundOrderDO; 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.PaymentOrderMapper;
import com.xiaowang.yuminailcore.modules.payment.mapper.RefundOrderMapper; import com.xiaowang.yuminailcore.modules.payment.mapper.RefundOrderMapper;
import com.xiaowang.yuminailcore.modules.payment.service.PaymentService; 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) { public RefundOrderVO manualRefundOrder(Long operatorId, Long orderId, Long afterSaleId, String remark) {
OrderDO order = orderMapper.selectById(orderId); OrderDO order = orderMapper.selectById(orderId);
if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) { if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) {
throw new RuntimeException("璁㈠崟涓嶅瓨鍦?"); throw new RuntimeException("订单不存在");
} }
if (!STATUS_PAID.equals(order.getPaymentStatus())) { if (!STATUS_PAID.equals(order.getPaymentStatus())) {
throw new RuntimeException("鏈敮浠樿鍗曚笉鍏佽閫€娆?"); throw new RuntimeException("未支付订单不允许退款");
} }
PaymentOrderDO payment = paymentOrderMapper.selectLatestByOrderId(orderId); PaymentOrderDO payment = paymentOrderMapper.selectLatestByOrderId(orderId);
if (payment == null || !STATUS_PAID.equals(payment.getStatus())) { if (payment == null || !STATUS_PAID.equals(payment.getStatus())) {
throw new RuntimeException("鏈壘鍒板凡鏀粯鏀粯鍗?"); throw new RuntimeException("未找到已支付的支付单");
} }
RefundOrderDO refund = new RefundOrderDO(); RefundOrderDO refund = new RefundOrderDO();
refund.setRefundNo("RF" + System.currentTimeMillis() + orderId); refund.setRefundNo("RF" + System.currentTimeMillis() + orderId);
@@ -132,7 +132,7 @@ public class PaymentServiceImpl implements PaymentService {
throw new RuntimeException("无权支付该订单"); throw new RuntimeException("无权支付该订单");
} }
if (Integer.valueOf(0).equals(order.getStatus())) { if (Integer.valueOf(0).equals(order.getStatus())) {
throw new RuntimeException("询价预约确认价格前暂不能支付"); throw new RuntimeException("请先确认预约报价后再支付");
} }
if (STATUS_PAID.equals(order.getPaymentStatus())) { if (STATUS_PAID.equals(order.getPaymentStatus())) {
throw new RuntimeException("订单已支付"); throw new RuntimeException("订单已支付");
@@ -11,20 +11,6 @@ import java.time.LocalDateTime;
@Mapper @Mapper
public interface AppointmentReservationMapper extends BaseMapper<AppointmentReservationDO> { public interface AppointmentReservationMapper extends BaseMapper<AppointmentReservationDO> {
@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} " + @Select("SELECT COUNT(*) FROM t_appointment_reservation WHERE artist_id = #{artistId} " +
"AND status IN ('LOCKED','CONFIRMED') AND is_delete = 0 " + "AND status IN ('LOCKED','CONFIRMED') AND is_delete = 0 " +
@@ -33,6 +19,14 @@ public interface AppointmentReservationMapper extends BaseMapper<AppointmentRese
@Param("startTime") LocalDateTime startTime, @Param("startTime") LocalDateTime startTime,
@Param("endTime") LocalDateTime endTime); @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}")
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() " + @Update("UPDATE t_appointment_reservation SET status = #{status}, is_delete = 1, update_time = NOW() " +
"WHERE order_id = #{orderId} AND is_delete = 0") "WHERE order_id = #{orderId} AND is_delete = 0")
int releaseByOrderId(@Param("orderId") Long orderId, @Param("status") String status); int releaseByOrderId(@Param("orderId") Long orderId, @Param("status") String status);
@@ -1,9 +1,9 @@
package com.xiaowang.yuminailcore.modules.planning.service.impl; 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.artist.entity.ArtistScheduleDO;
import com.xiaowang.yuminailcore.modules.planning.mapper.AppointmentReservationMapper;
import com.xiaowang.yuminailcore.modules.artist.mapper.ArtistScheduleMapper; 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 com.xiaowang.yuminailcore.modules.planning.service.AppointmentCapacityService;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -18,8 +18,8 @@ public class AppointmentCapacityServiceImpl implements AppointmentCapacityServic
private static final int MIN_CAPACITY = 1; private static final int MIN_CAPACITY = 1;
private static final String STATUS_CONFIRMED = "CONFIRMED"; private static final String STATUS_CONFIRMED = "CONFIRMED";
private static final String STATUS_RELEASED = "RELEASED"; private static final String STATUS_RELEASED = "RELEASED";
private static final String UNAVAILABLE_MESSAGE = "涓嶅彲棰勭害"; private static final String UNAVAILABLE_MESSAGE = "当前美甲师该时间段不可预约";
private static final String FULL_MESSAGE = "褰撳墠缇庣敳甯堣鏃堕棿娈靛凡绾︽弧锛岃閲嶆柊閫夋嫨棰勭害鏃堕棿"; private static final String FULL_MESSAGE = "当前美甲师该时间段已约满,请重新选择预约时间";
private final AppointmentReservationMapper reservationMapper; private final AppointmentReservationMapper reservationMapper;
private final ArtistScheduleMapper scheduleMapper; private final ArtistScheduleMapper scheduleMapper;
@@ -79,17 +79,17 @@ public class AppointmentCapacityServiceImpl implements AppointmentCapacityServic
private void assertCapacityAvailable(Long shopId, Long artistId, Long excludedOrderItemId, private void assertCapacityAvailable(Long shopId, Long artistId, Long excludedOrderItemId,
LocalDateTime startTime, LocalDateTime endTime) { LocalDateTime startTime, LocalDateTime endTime) {
int capacity = resolveCapacity(shopId, artistId, startTime, endTime); int capacity = resolveCapacityWithScheduleLock(shopId, artistId, startTime, endTime);
int used = excludedOrderItemId == null int used = excludedOrderItemId == null
? reservationMapper.countOverlappingActiveForUpdate(artistId, startTime, endTime) ? reservationMapper.countOverlappingActive(artistId, startTime, endTime)
: reservationMapper.countOverlappingActiveForUpdateExcludingOrderItem(artistId, excludedOrderItemId, startTime, endTime); : reservationMapper.countOverlappingActiveExcludingOrderItem(artistId, excludedOrderItemId, startTime, endTime);
if (used >= capacity) { if (used >= capacity) {
throw new RuntimeException(FULL_MESSAGE); throw new RuntimeException(FULL_MESSAGE);
} }
} }
private int resolveCapacity(Long shopId, Long artistId, LocalDateTime startTime, LocalDateTime endTime) { private int resolveCapacityWithScheduleLock(Long shopId, Long artistId, LocalDateTime startTime, LocalDateTime endTime) {
ArtistScheduleDO schedule = scheduleMapper.selectCoveringSchedule( ArtistScheduleDO schedule = scheduleMapper.selectCoveringScheduleForUpdate(
shopId, shopId,
artistId, artistId,
startTime.toLocalDate(), startTime.toLocalDate(),
@@ -8,6 +8,7 @@ import io.jsonwebtoken.security.Keys;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.crypto.SecretKey; import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.Date; import java.util.Date;
@@ -28,11 +29,17 @@ public class JwtUtil {
*/ */
private final JwtProperties jwtProperties; private final JwtProperties jwtProperties;
@PostConstruct
void validateJwtSecret() {
jwtProperties.requireValidSecret();
}
/** /**
* Purpose: getKey supports JwtUtil.java by holding or executing the get key business role. * 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. * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/ */
private SecretKey getKey() { private SecretKey getKey() {
jwtProperties.requireValidSecret();
return Keys.hmacShaKeyFor(jwtProperties.getSecret().getBytes(StandardCharsets.UTF_8)); return Keys.hmacShaKeyFor(jwtProperties.getSecret().getBytes(StandardCharsets.UTF_8));
} }
@@ -18,9 +18,9 @@ spring:
# 是否启用服务注册 # 是否启用服务注册
register-enabled: true register-enabled: true
# Nacos认证用户名 # Nacos认证用户名
username: xiaowang username: ${NACOS_USERNAME:xiaowang}
# Nacos认证密码 # Nacos认证密码
password: 122503wcy.... password: ${NACOS_PASSWORD:}
config: config:
# Nacos配置中心集群地址 # Nacos配置中心集群地址
server-addr: home-nacos01:8848,home-nacos02:8848,home-nacos03:8848 server-addr: home-nacos01:8848,home-nacos02:8848,home-nacos03:8848
@@ -35,9 +35,9 @@ spring:
# 是否启用配置中心 # 是否启用配置中心
enabled: true enabled: true
# Nacos认证用户名 # Nacos认证用户名
username: xiaowang username: ${NACOS_USERNAME:xiaowang}
# Nacos认证密码 # Nacos认证密码
password: 122503wcy.... password: ${NACOS_PASSWORD:}
# 共享配置文件列表 # 共享配置文件列表
shared-configs: shared-configs:
- data-id: rabbit-mq.yaml - data-id: rabbit-mq.yaml
@@ -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("外部配置");
}
}
@@ -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();
}
}
@@ -1,9 +1,9 @@
package com.xiaowang.yuminailcore.modules.planning.service.impl; 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.artist.entity.ArtistScheduleDO;
import com.xiaowang.yuminailcore.modules.planning.mapper.AppointmentReservationMapper;
import com.xiaowang.yuminailcore.modules.artist.mapper.ArtistScheduleMapper; 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.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor; 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.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy; 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.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
class AppointmentCapacityServiceImplTest { class AppointmentCapacityServiceImplTest {
@@ -36,24 +36,28 @@ class AppointmentCapacityServiceImplTest {
} }
@Test @Test
void reserveRejectsWhenConfiguredCapacityIsFull() { void reserveLocksCoveringScheduleRowAndRejectsWhenConfiguredCapacityIsFull() {
LocalDateTime start = LocalDateTime.of(2026, 6, 1, 10, 0); LocalDateTime start = LocalDateTime.of(2026, 6, 1, 10, 0);
LocalDateTime end = start.plusHours(1); 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)); .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)) 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 @Test
void reserveCreatesConfirmedReservationWhenCapacityRemains() { void reserveCreatesConfirmedReservationWhenCapacityRemains() {
LocalDateTime start = LocalDateTime.of(2026, 6, 1, 10, 0); LocalDateTime start = LocalDateTime.of(2026, 6, 1, 10, 0);
LocalDateTime end = start.plusHours(1); 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)); .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); service.reserveOrThrow(1L, 10L, 9L, 30L, "French", start, end);
@@ -70,12 +74,12 @@ class AppointmentCapacityServiceImplTest {
void reserveRejectsWhenNoCoveringScheduleExists() { void reserveRejectsWhenNoCoveringScheduleExists() {
LocalDateTime start = LocalDateTime.of(2026, 6, 2, 10, 0); LocalDateTime start = LocalDateTime.of(2026, 6, 2, 10, 0);
LocalDateTime end = start.plusHours(1); 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); .thenReturn(null);
assertThatThrownBy(() -> service.reserveOrThrow(1L, 10L, 9L, 30L, "French", start, end)) assertThatThrownBy(() -> service.reserveOrThrow(1L, 10L, 9L, 30L, "French", start, end))
.isInstanceOf(RuntimeException.class) .isInstanceOf(RuntimeException.class)
.hasMessageContaining("涓嶅彲棰勭害"); .hasMessageContaining("不可预约");
verify(reservationMapper, never()).insert(org.mockito.ArgumentMatchers.any(AppointmentReservationDO.class)); verify(reservationMapper, never()).insert(org.mockito.ArgumentMatchers.any(AppointmentReservationDO.class));
} }
@@ -86,12 +90,12 @@ class AppointmentCapacityServiceImplTest {
LocalDateTime end = start.plusHours(1); LocalDateTime end = start.plusHours(1);
ArtistScheduleDO disabled = schedule(1); ArtistScheduleDO disabled = schedule(1);
disabled.setStatus(0); 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); .thenReturn(disabled);
assertThatThrownBy(() -> service.reserveOrThrow(1L, 10L, 9L, 30L, "French", start, end)) assertThatThrownBy(() -> service.reserveOrThrow(1L, 10L, 9L, 30L, "French", start, end))
.isInstanceOf(RuntimeException.class) .isInstanceOf(RuntimeException.class)
.hasMessageContaining("涓嶅彲棰勭害"); .hasMessageContaining("不可预约");
verify(reservationMapper, never()).insert(org.mockito.ArgumentMatchers.any(AppointmentReservationDO.class)); verify(reservationMapper, never()).insert(org.mockito.ArgumentMatchers.any(AppointmentReservationDO.class));
} }
@@ -100,12 +104,12 @@ class AppointmentCapacityServiceImplTest {
void reserveRejectsWhenCoveringScheduleHasZeroCapacity() { void reserveRejectsWhenCoveringScheduleHasZeroCapacity() {
LocalDateTime start = LocalDateTime.of(2026, 6, 1, 10, 0); LocalDateTime start = LocalDateTime.of(2026, 6, 1, 10, 0);
LocalDateTime end = start.plusHours(1); 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)); .thenReturn(schedule(0));
assertThatThrownBy(() -> service.reserveOrThrow(1L, 10L, 9L, 30L, "French", start, end)) assertThatThrownBy(() -> service.reserveOrThrow(1L, 10L, 9L, 30L, "French", start, end))
.isInstanceOf(RuntimeException.class) .isInstanceOf(RuntimeException.class)
.hasMessageContaining("涓嶅彲棰勭害"); .hasMessageContaining("不可预约");
verify(reservationMapper, never()).insert(org.mockito.ArgumentMatchers.any(AppointmentReservationDO.class)); verify(reservationMapper, never()).insert(org.mockito.ArgumentMatchers.any(AppointmentReservationDO.class));
} }
@@ -114,9 +118,9 @@ class AppointmentCapacityServiceImplTest {
void moveReservationRechecksNewArtistCapacityBeforeUpdatingArtist() { void moveReservationRechecksNewArtistCapacityBeforeUpdatingArtist() {
LocalDateTime start = LocalDateTime.of(2026, 6, 1, 10, 0); LocalDateTime start = LocalDateTime.of(2026, 6, 1, 10, 0);
LocalDateTime end = start.plusHours(1); 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)); .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")) when(reservationMapper.updateActiveReservationForOrderItem(10L, 1L, 9L, 31L, "French", start, end, "CONFIRMED"))
.thenReturn(1); .thenReturn(1);
@@ -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;
}
}
-3
View File
@@ -157,9 +157,6 @@ export interface GrowthSummaryVO {
export const paymentApi = { export const paymentApi = {
prepareOrderPayment: async (orderId: IdType): Promise<PaymentOrderVO> => { prepareOrderPayment: async (orderId: IdType): Promise<PaymentOrderVO> => {
return await api.post<PaymentOrderVO>(`/payment/order/${orderId}/prepare`) as unknown as PaymentOrderVO return await api.post<PaymentOrderVO>(`/payment/order/${orderId}/prepare`) as unknown as PaymentOrderVO
},
mockSuccess: async (orderId: IdType): Promise<PaymentOrderVO> => {
return await api.post<PaymentOrderVO>(`/payment/order/${orderId}/mock-success`) as unknown as PaymentOrderVO
} }
} }
@@ -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 statusClass = (status?: number) => isQuoteStatus(status) ? 'quote' : status === 2 ? 'done' : status === 3 ? 'cancelled' : 'pending'
const isOrderPaid = (target: any) => String(target?.paymentStatus || '').toUpperCase() === 'PAID' const isOrderPaid = (target: any) => String(target?.paymentStatus || '').toUpperCase() === 'PAID'
const canPreparePayment = computed(() => !isQuoteConfirming.value && Number(order.value?.status) === 1 && !isOrderPaid(order.value)) 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 canApplyAfterSale = computed(() => !isQuoteConfirming.value && (Number(order.value?.status) === 2 || isOrderPaid(order.value)))
const timeline = computed(() => { const timeline = computed(() => {
@@ -206,15 +205,6 @@ const preparePayment = async () => {
message.success('支付单已准备') 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 = () => { const cancelOrder = () => {
if (!order.value?.id) return if (!order.value?.id) return
Modal.confirm({ Modal.confirm({
@@ -358,7 +348,6 @@ onMounted(loadOrder)
<section class="action-bar"> <section class="action-bar">
<a-button v-if="canPreparePayment" @click="preparePayment">准备支付</a-button> <a-button v-if="canPreparePayment" @click="preparePayment">准备支付</a-button>
<a-button v-if="canMockPay" type="primary" @click="mockPay">模拟支付</a-button>
<a-button v-if="canApplyAfterSale" @click="router.push({ path: '/after-sale/apply', query: { orderId } })">申请售后</a-button> <a-button v-if="canApplyAfterSale" @click="router.push({ path: '/after-sale/apply', query: { orderId } })">申请售后</a-button>
<a-button v-if="order.status === 1" danger @click="cancelOrder">取消订单</a-button> <a-button v-if="order.status === 1" danger @click="cancelOrder">取消订单</a-button>
</section> </section>
+1 -15
View File
@@ -201,7 +201,6 @@
<div class="order-card__actions"> <div class="order-card__actions">
<button v-if="orderNeedsReview(order)" type="button" class="order-action order-action--primary" @click="openReviewModal(firstPendingReview(order))">去评价</button> <button v-if="orderNeedsReview(order)" type="button" class="order-action order-action--primary" @click="openReviewModal(firstPendingReview(order))">去评价</button>
<button v-if="canPreparePayment(order)" type="button" class="order-action order-action--primary" @click="preparePayment(order)">立即支付</button> <button v-if="canPreparePayment(order)" type="button" class="order-action order-action--primary" @click="preparePayment(order)">立即支付</button>
<button v-if="canMockPay(order)" type="button" class="order-action order-action--primary" @click="mockPay(order)">立即支付</button>
<button type="button" class="order-action" @click="router.push(`/orders/${order.id}`)">查看详情</button> <button type="button" class="order-action" @click="router.push(`/orders/${order.id}`)">查看详情</button>
<button v-if="canApplyAfterSale(order)" type="button" class="order-action" @click="openAfterSaleModal(order)">申请售后</button> <button v-if="canApplyAfterSale(order)" type="button" class="order-action" @click="openAfterSaleModal(order)">申请售后</button>
<button v-if="hasRebookableItems(order)" type="button" class="order-action order-action--primary" @click="rebookOrder(order)">复刻同款</button> <button v-if="hasRebookableItems(order)" type="button" class="order-action order-action--primary" @click="rebookOrder(order)">复刻同款</button>
@@ -470,8 +469,7 @@ const isQuoteConfirming = (order: any) => Number(order?.status) === 0
const orderPaymentStatus = (order: any) => String(order.paymentStatus || order.payStatus || '').toUpperCase() const orderPaymentStatus = (order: any) => String(order.paymentStatus || order.payStatus || '').toUpperCase()
const isOrderPaid = (order: any) => orderPaymentStatus(order) === 'PAID' const isOrderPaid = (order: any) => orderPaymentStatus(order) === 'PAID'
const orderNeedsPayment = (order: any) => Number(order.status) === 1 && !isOrderPaid(order) const orderNeedsPayment = (order: any) => Number(order.status) === 1 && !isOrderPaid(order)
const canPreparePayment = (order: any) => orderNeedsPayment(order) && orderPaymentStatus(order) !== 'PAYING' const canPreparePayment = (order: any) => orderNeedsPayment(order)
const canMockPay = (order: any) => Number(order.status) === 1 && orderPaymentStatus(order) === 'PAYING'
const canApplyAfterSale = (order: any) => !isQuoteConfirming(order) && (Number(order.status) === 2 || isOrderPaid(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 submitQuoteReply = async (order: any) => {
const key = quoteOrderKey(order) const key = quoteOrderKey(order)
const remark = String(quoteReplyForms[key] || '').trim() const remark = String(quoteReplyForms[key] || '').trim()
@@ -68,7 +68,7 @@ describe('web theme governance', () => {
it('keeps frontend and backend platform overview permission allowlists aligned', () => { it('keeps frontend and backend platform overview permission allowlists aligned', () => {
const frontend = readSource('utils/platform-admin-permissions.ts') 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(backend).toContain('"security:audit:view"')
expect(frontend).toContain("'security:audit:view'") expect(frontend).toContain("'security:audit:view'")
@@ -109,14 +109,12 @@ describe('vNext API contracts', () => {
api.defaults.adapter = captureAdapter(requests) api.defaults.adapter = captureAdapter(requests)
await paymentApi.prepareOrderPayment(42) await paymentApi.prepareOrderPayment(42)
await paymentApi.mockSuccess(42)
await afterSaleApi.apply({ orderId: 42, type: 'REFUND', reason: 'schedule changed', refundAmount: 88 }) await afterSaleApi.apply({ orderId: 42, type: 'REFUND', reason: 'schedule changed', refundAmount: 88 })
await afterSaleApi.listMy({ page: 1, size: 5 }) await afterSaleApi.listMy({ page: 1, size: 5 })
await growthApi.getSummary() await growthApi.getSummary()
expect(requests).toEqual([ expect(requests).toEqual([
{ method: 'post', url: '/payment/order/42/prepare', params: undefined, data: undefined }, { 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: '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: '/after-sale/my', params: { page: 1, size: 5 }, data: undefined },
{ method: 'get', url: '/growth/summary', params: undefined, data: undefined } { method: 'get', url: '/growth/summary', params: undefined, data: undefined }
@@ -4,17 +4,31 @@ import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
/** import java.nio.charset.StandardCharsets;
* Gateway JWT 校验配置。
*/
@Data @Data
@Configuration @Configuration
@ConfigurationProperties(prefix = "yuminail.security.jwt") @ConfigurationProperties(prefix = "yuminail.security.jwt")
public class JwtProperties { 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 String issuer = "yuminail";
private long clockSkewSeconds = 30; 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 字节");
}
}
} }
@@ -7,6 +7,7 @@ import io.jsonwebtoken.security.Keys;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.crypto.SecretKey; import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
@@ -19,6 +20,11 @@ public class GatewayJwtValidator {
private final JwtProperties jwtProperties; private final JwtProperties jwtProperties;
@PostConstruct
void validateJwtSecret() {
jwtProperties.requireValidSecret();
}
public boolean validateAccessToken(String token) { public boolean validateAccessToken(String token) {
try { try {
Claims claims = Jwts.parserBuilder() Claims claims = Jwts.parserBuilder()
@@ -35,6 +41,7 @@ public class GatewayJwtValidator {
} }
private SecretKey getKey() { private SecretKey getKey() {
jwtProperties.requireValidSecret();
return Keys.hmacShaKeyFor(jwtProperties.getSecret().getBytes(StandardCharsets.UTF_8)); return Keys.hmacShaKeyFor(jwtProperties.getSecret().getBytes(StandardCharsets.UTF_8));
} }
} }
@@ -9,16 +9,16 @@ spring:
namespace: YumiNail-Dev namespace: YumiNail-Dev
group: DEFAULT_GROUP group: DEFAULT_GROUP
service: ${spring.application.name} service: ${spring.application.name}
username: xiaowang username: ${NACOS_USERNAME:xiaowang}
password: 122503wcy.... password: ${NACOS_PASSWORD:}
config: config:
server-addr: home-nacos01:8848,home-nacos02:8848,home-nacos03:8848 server-addr: home-nacos01:8848,home-nacos02:8848,home-nacos03:8848
namespace: YumiNail-Dev namespace: YumiNail-Dev
group: DEFAULT_GROUP group: DEFAULT_GROUP
name: yuminail-gateway name: yuminail-gateway
file-extension: yaml file-extension: yaml
username: xiaowang username: ${NACOS_USERNAME:xiaowang}
password: 122503wcy.... password: ${NACOS_PASSWORD:}
shared-configs: shared-configs:
- data-id: logging.yaml - data-id: logging.yaml
group: DEFAULT_GROUP group: DEFAULT_GROUP