功能:完善订单流程和加固
This commit is contained in:
@@ -19,6 +19,65 @@ module.exports = {
|
|||||||
})
|
})
|
||||||
},
|
},
|
||||||
|
|
||||||
|
listMyPendingReviews() {
|
||||||
|
return request({
|
||||||
|
url: '/order/review/my-pending'
|
||||||
|
})
|
||||||
|
},
|
||||||
|
|
||||||
|
listOrderReviews(orderId) {
|
||||||
|
return request({
|
||||||
|
url: `/order/${orderId}/reviews`
|
||||||
|
})
|
||||||
|
},
|
||||||
|
|
||||||
|
submitArtistReview(reviewId, data) {
|
||||||
|
return request({
|
||||||
|
url: `/order/review/${reviewId}/submit`,
|
||||||
|
method: 'POST',
|
||||||
|
data
|
||||||
|
})
|
||||||
|
},
|
||||||
|
|
||||||
|
getArtistChangeOptions(orderId, orderItemId) {
|
||||||
|
return request({
|
||||||
|
url: `/order/${orderId}/artist-change/options`,
|
||||||
|
params: {
|
||||||
|
orderItemId
|
||||||
|
}
|
||||||
|
})
|
||||||
|
},
|
||||||
|
|
||||||
|
requestArtistChange(data) {
|
||||||
|
return request({
|
||||||
|
url: '/order/artist-change/request',
|
||||||
|
method: 'POST',
|
||||||
|
data
|
||||||
|
})
|
||||||
|
},
|
||||||
|
|
||||||
|
listMyPendingArtistChangeRequests() {
|
||||||
|
return request({
|
||||||
|
url: '/order/artist-change/my-pending'
|
||||||
|
})
|
||||||
|
},
|
||||||
|
|
||||||
|
approveArtistChange(requestId) {
|
||||||
|
return request({
|
||||||
|
url: `/order/artist-change/${requestId}/approve`,
|
||||||
|
method: 'PUT',
|
||||||
|
data: {}
|
||||||
|
})
|
||||||
|
},
|
||||||
|
|
||||||
|
rejectArtistChange(requestId, data) {
|
||||||
|
return request({
|
||||||
|
url: `/order/artist-change/${requestId}/reject`,
|
||||||
|
method: 'PUT',
|
||||||
|
data: data || {}
|
||||||
|
})
|
||||||
|
},
|
||||||
|
|
||||||
cancelOrder(orderId) {
|
cancelOrder(orderId) {
|
||||||
return request({
|
return request({
|
||||||
url: `/order/cancel/${orderId}`,
|
url: `/order/cancel/${orderId}`,
|
||||||
|
|||||||
@@ -54,6 +54,24 @@ Page({
|
|||||||
if (!item) {
|
if (!item) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if (item.actionPath) {
|
||||||
|
try {
|
||||||
|
if (item.readStatus !== 1) {
|
||||||
|
await userApi.markMessageRead(item.id)
|
||||||
|
}
|
||||||
|
const opened = await navigation.openActionPath(item.actionPath)
|
||||||
|
await this.loadMessages()
|
||||||
|
if (opened) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
wx.showToast({
|
||||||
|
title: error.message || '打开消息失败',
|
||||||
|
icon: 'none'
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
this.setData({
|
this.setData({
|
||||||
currentMessage: item,
|
currentMessage: item,
|
||||||
detailVisible: true
|
detailVisible: true
|
||||||
|
|||||||
@@ -7,21 +7,157 @@ const { resolveLegacyImage } = require('../../utils/file')
|
|||||||
const { formatDateTime, formatPrice, getOrderStatusClass, getOrderStatusText } = require('../../utils/format')
|
const { formatDateTime, formatPrice, getOrderStatusClass, getOrderStatusText } = require('../../utils/format')
|
||||||
const { runWithLoading } = require('../../utils/loading')
|
const { runWithLoading } = require('../../utils/loading')
|
||||||
|
|
||||||
/**
|
const REVIEW_SCORE_OPTIONS = [0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5]
|
||||||
* orders page logic.
|
|
||||||
* Call guide: page data drives the WXML template, and each method is called by user events or lifecycle callbacks.
|
function toId(value) {
|
||||||
*/
|
return value === undefined || value === null ? '' : String(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
function sameId(left, right) {
|
||||||
|
const leftId = toId(left)
|
||||||
|
const rightId = toId(right)
|
||||||
|
return leftId !== '' && leftId === rightId
|
||||||
|
}
|
||||||
|
|
||||||
|
function safeList(value) {
|
||||||
|
return Array.isArray(value) ? value : []
|
||||||
|
}
|
||||||
|
|
||||||
|
function trimText(value) {
|
||||||
|
return String(value || '').trim()
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatRating(value) {
|
||||||
|
const rating = Number(value)
|
||||||
|
if (!isFinite(rating) || rating <= 0) {
|
||||||
|
return ''
|
||||||
|
}
|
||||||
|
return rating % 1 === 0 ? String(rating) : rating.toFixed(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
function isSubmittedReview(review) {
|
||||||
|
if (!review) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if (Number(review.status) === 1) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return Boolean(review.rating)
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveRelatedRecord(source, orderItemId) {
|
||||||
|
if (Array.isArray(source)) {
|
||||||
|
return source.find(item => sameId(item && item.orderItemId, orderItemId)) || null
|
||||||
|
}
|
||||||
|
if (source && typeof source === 'object') {
|
||||||
|
if (!source.orderItemId || sameId(source.orderItemId, orderItemId)) {
|
||||||
|
return source
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildReviewSummary(review) {
|
||||||
|
if (!review || !isSubmittedReview(review)) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
const ratingText = formatRating(review.rating)
|
||||||
|
return {
|
||||||
|
...review,
|
||||||
|
ratingText,
|
||||||
|
contentText: trimText(review.content),
|
||||||
|
displayText: ratingText ? `已评价:${ratingText} 分` : (review.statusText || '已评价')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildPendingReview(review) {
|
||||||
|
if (!review || isSubmittedReview(review)) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
return review
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildArtistChangeSummary(request) {
|
||||||
|
if (!request) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
const originalName = request.originalArtistName || '原美甲师'
|
||||||
|
const requestedName = request.requestedArtistName || '新美甲师'
|
||||||
|
return {
|
||||||
|
...request,
|
||||||
|
displayText: `改派申请:${originalName} → ${requestedName}`,
|
||||||
|
reasonText: trimText(request.reason)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function indexByOrderItemId(list) {
|
||||||
|
return safeList(list).reduce((result, item) => {
|
||||||
|
if (item && item.orderItemId) {
|
||||||
|
result[toId(item.orderItemId)] = item
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}, {})
|
||||||
|
}
|
||||||
|
|
||||||
|
async function safeCall(factory, fallbackValue) {
|
||||||
|
try {
|
||||||
|
const result = await factory()
|
||||||
|
return result === undefined || result === null ? fallbackValue : result
|
||||||
|
} catch (error) {
|
||||||
|
return fallbackValue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadAssistData(orders) {
|
||||||
|
const pendingReviewsPromise = safeCall(() => orderApi.listMyPendingReviews(), [])
|
||||||
|
const pendingChangesPromise = safeCall(() => orderApi.listMyPendingArtistChangeRequests(), [])
|
||||||
|
const orderReviewListsPromise = Promise.all(orders.map(order => (
|
||||||
|
safeCall(() => orderApi.listOrderReviews(order.id), [])
|
||||||
|
)))
|
||||||
|
const [pendingReviews, pendingChanges, orderReviewLists] = await Promise.all([
|
||||||
|
pendingReviewsPromise,
|
||||||
|
pendingChangesPromise,
|
||||||
|
orderReviewListsPromise
|
||||||
|
])
|
||||||
|
|
||||||
|
const submittedReviews = []
|
||||||
|
safeList(orderReviewLists).forEach(list => {
|
||||||
|
safeList(list).forEach(review => {
|
||||||
|
if (isSubmittedReview(review)) {
|
||||||
|
submittedReviews.push(review)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
return {
|
||||||
|
pendingReviewByItemId: indexByOrderItemId(pendingReviews),
|
||||||
|
submittedReviewByItemId: indexByOrderItemId(submittedReviews),
|
||||||
|
pendingChangeByItemId: indexByOrderItemId(pendingChanges)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function findReviewDraft(orders, reviewId) {
|
||||||
|
const reviewIdText = toId(reviewId)
|
||||||
|
for (let i = 0; i < orders.length; i += 1) {
|
||||||
|
const items = safeList(orders[i].items)
|
||||||
|
for (let j = 0; j < items.length; j += 1) {
|
||||||
|
const pendingReview = items[j].pendingReview
|
||||||
|
if (pendingReview && toId(pendingReview.id) === reviewIdText) {
|
||||||
|
return items[j].reviewDraft || {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {}
|
||||||
|
}
|
||||||
|
|
||||||
Page({
|
Page({
|
||||||
data: Object.assign(theme.pageThemeData(getApp().globalData.shopTheme), {
|
data: Object.assign(theme.pageThemeData(getApp().globalData.shopTheme), {
|
||||||
loading: false,
|
loading: false,
|
||||||
isLoggedIn: false,
|
isLoggedIn: false,
|
||||||
orders: []
|
orders: [],
|
||||||
|
reviewScoreOptions: REVIEW_SCORE_OPTIONS
|
||||||
}),
|
}),
|
||||||
|
|
||||||
/**
|
|
||||||
* `onShow` page method. Use this from WXML event bindings or lifecycle hooks.
|
|
||||||
* Call guide: read or update page data with `this.setData(...)` inside the method when state changes.
|
|
||||||
*/
|
|
||||||
onShow() {
|
onShow() {
|
||||||
this.loadOrders()
|
this.loadOrders()
|
||||||
},
|
},
|
||||||
@@ -33,10 +169,6 @@ Page({
|
|||||||
loading: isLoggedIn
|
loading: isLoggedIn
|
||||||
})
|
})
|
||||||
|
|
||||||
/**
|
|
||||||
* `if` page method. Use this from WXML event bindings or lifecycle hooks.
|
|
||||||
* Call guide: read or update page data with `this.setData(...)` inside the method when state changes.
|
|
||||||
*/
|
|
||||||
if (!isLoggedIn) {
|
if (!isLoggedIn) {
|
||||||
this.setData({
|
this.setData({
|
||||||
orders: [],
|
orders: [],
|
||||||
@@ -47,19 +179,34 @@ Page({
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
const orders = await orderApi.getOrderList()
|
const orders = await orderApi.getOrderList()
|
||||||
const list = Array.isArray(orders) ? orders : []
|
const list = safeList(orders)
|
||||||
|
const assistData = await loadAssistData(list)
|
||||||
const formattedOrders = await Promise.all(list.map(async order => ({
|
const formattedOrders = await Promise.all(list.map(async order => ({
|
||||||
...order,
|
...order,
|
||||||
statusText: getOrderStatusText(order),
|
statusText: getOrderStatusText(order),
|
||||||
statusClass: getOrderStatusClass(order),
|
statusClass: getOrderStatusClass(order),
|
||||||
shopNameText: order.shopName ? `所属店铺:${order.shopName}` : '',
|
shopNameText: order.shopName ? `所属店铺:${order.shopName}` : '',
|
||||||
actualAmountText: `\u00a5${formatPrice(order.actualAmount)}`,
|
actualAmountText: `\u00a5${formatPrice(order.actualAmount)}`,
|
||||||
items: await Promise.all((order.items || []).map(async item => ({
|
items: await Promise.all(safeList(order.items).map(async item => {
|
||||||
...item,
|
const itemId = toId(item.id)
|
||||||
productImageUrl: await resolveLegacyImage(item.productImage),
|
const inlinePendingReview = resolveRelatedRecord(item.pendingReview || order.pendingReview, item.id)
|
||||||
priceText: `\u00a5${formatPrice(item.price)}`,
|
const inlineReviewSummary = resolveRelatedRecord(item.reviewSummary || order.reviewSummary, item.id)
|
||||||
appointmentText: formatDateTime(item.appointmentTime)
|
const inlinePendingChange = resolveRelatedRecord(item.pendingArtistChangeRequest || order.pendingArtistChangeRequest, item.id)
|
||||||
})))
|
const pendingReview = buildPendingReview(inlinePendingReview || assistData.pendingReviewByItemId[itemId])
|
||||||
|
const reviewSummary = buildReviewSummary(inlineReviewSummary || assistData.submittedReviewByItemId[itemId])
|
||||||
|
const pendingArtistChangeRequest = buildArtistChangeSummary(inlinePendingChange || assistData.pendingChangeByItemId[itemId])
|
||||||
|
|
||||||
|
return {
|
||||||
|
...item,
|
||||||
|
productImageUrl: await resolveLegacyImage(item.productImage),
|
||||||
|
priceText: `\u00a5${formatPrice(item.price)}`,
|
||||||
|
appointmentText: formatDateTime(item.appointmentTime),
|
||||||
|
pendingReview,
|
||||||
|
reviewSummary,
|
||||||
|
reviewDraft: pendingReview ? { rating: 0, content: '' } : null,
|
||||||
|
pendingArtistChangeRequest
|
||||||
|
}
|
||||||
|
}))
|
||||||
})))
|
})))
|
||||||
|
|
||||||
this.setData({
|
this.setData({
|
||||||
@@ -80,28 +227,177 @@ Page({
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
|
||||||
* `handleOpenAuth` page method. Use this from WXML event bindings or lifecycle hooks.
|
|
||||||
* Call guide: read or update page data with `this.setData(...)` inside the method when state changes.
|
|
||||||
*/
|
|
||||||
handleOpenAuth() {
|
handleOpenAuth() {
|
||||||
navigation.openAuth('/pages/orders/index')
|
navigation.openAuth('/pages/orders/index')
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
|
||||||
* `handleBack` page method. Use this from WXML event bindings or lifecycle hooks.
|
|
||||||
* Call guide: read or update page data with `this.setData(...)` inside the method when state changes.
|
|
||||||
*/
|
|
||||||
handleBack() {
|
handleBack() {
|
||||||
navigation.goBack('/pages/profile/index')
|
navigation.goBack('/pages/profile/index')
|
||||||
},
|
},
|
||||||
|
|
||||||
|
updateReviewDraft(reviewId, patch) {
|
||||||
|
const reviewIdText = toId(reviewId)
|
||||||
|
const orders = this.data.orders.map(order => ({
|
||||||
|
...order,
|
||||||
|
items: safeList(order.items).map(item => {
|
||||||
|
const pendingReview = item.pendingReview
|
||||||
|
if (!pendingReview || toId(pendingReview.id) !== reviewIdText) {
|
||||||
|
return item
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
...item,
|
||||||
|
reviewDraft: {
|
||||||
|
...(item.reviewDraft || {}),
|
||||||
|
...patch
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}))
|
||||||
|
this.setData({
|
||||||
|
orders
|
||||||
|
})
|
||||||
|
},
|
||||||
|
|
||||||
|
handleSelectReviewScore(event) {
|
||||||
|
const reviewId = event.currentTarget.dataset.reviewId
|
||||||
|
const score = Number(event.currentTarget.dataset.score)
|
||||||
|
this.updateReviewDraft(reviewId, {
|
||||||
|
rating: score
|
||||||
|
})
|
||||||
|
},
|
||||||
|
|
||||||
|
handleReviewContentInput(event) {
|
||||||
|
const reviewId = event.currentTarget.dataset.reviewId
|
||||||
|
this.updateReviewDraft(reviewId, {
|
||||||
|
content: event.detail.value
|
||||||
|
})
|
||||||
|
},
|
||||||
|
|
||||||
|
async handleSubmitReview(event) {
|
||||||
|
const reviewId = event.currentTarget.dataset.reviewId
|
||||||
|
if (!reviewId) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await actionGuard.run(this, `order:review:${reviewId}`, async () => {
|
||||||
|
const draft = findReviewDraft(this.data.orders, reviewId)
|
||||||
|
const rating = Number(draft.rating)
|
||||||
|
if (!isFinite(rating) || rating < 0.5 || rating > 5 || rating * 2 % 1 !== 0) {
|
||||||
|
wx.showToast({
|
||||||
|
title: '请选择 0.5-5 分评分',
|
||||||
|
icon: 'none'
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
await runWithLoading(() => orderApi.submitArtistReview(reviewId, {
|
||||||
|
rating,
|
||||||
|
content: trimText(draft.content),
|
||||||
|
imageFileIds: []
|
||||||
|
}))
|
||||||
|
wx.showToast({
|
||||||
|
title: '评价已提交',
|
||||||
|
icon: 'none'
|
||||||
|
})
|
||||||
|
await this.loadOrders()
|
||||||
|
}, {
|
||||||
|
message: '评价正在提交中,请勿重复点击'
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
if (actionGuard.isGuardError(error)) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
wx.showToast({
|
||||||
|
title: error.message || '评价提交失败',
|
||||||
|
icon: 'none'
|
||||||
|
})
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
async handleApproveArtistChange(event) {
|
||||||
|
const requestId = event.currentTarget.dataset.requestId
|
||||||
|
if (!requestId) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await actionGuard.run(this, `order:artist-change:approve:${requestId}`, async () => {
|
||||||
|
const confirmed = await new Promise(resolve => {
|
||||||
|
wx.showModal({
|
||||||
|
title: '同意改派',
|
||||||
|
content: '确认同意这次美甲师改派申请吗?',
|
||||||
|
success: modalRes => resolve(Boolean(modalRes.confirm))
|
||||||
|
})
|
||||||
|
})
|
||||||
|
if (!confirmed) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
await runWithLoading(() => orderApi.approveArtistChange(requestId))
|
||||||
|
wx.showToast({
|
||||||
|
title: '已同意改派',
|
||||||
|
icon: 'none'
|
||||||
|
})
|
||||||
|
await this.loadOrders()
|
||||||
|
}, {
|
||||||
|
message: '改派处理中,请勿重复点击'
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
if (actionGuard.isGuardError(error)) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
wx.showToast({
|
||||||
|
title: error.message || '同意改派失败',
|
||||||
|
icon: 'none'
|
||||||
|
})
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
async handleRejectArtistChange(event) {
|
||||||
|
const requestId = event.currentTarget.dataset.requestId
|
||||||
|
if (!requestId) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await actionGuard.run(this, `order:artist-change:reject:${requestId}`, async () => {
|
||||||
|
const confirmed = await new Promise(resolve => {
|
||||||
|
wx.showModal({
|
||||||
|
title: '拒绝改派',
|
||||||
|
content: '确认拒绝这次美甲师改派申请吗?',
|
||||||
|
confirmText: '拒绝',
|
||||||
|
success: modalRes => resolve(Boolean(modalRes.confirm))
|
||||||
|
})
|
||||||
|
})
|
||||||
|
if (!confirmed) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
await runWithLoading(() => orderApi.rejectArtistChange(requestId, {
|
||||||
|
rejectReason: ''
|
||||||
|
}))
|
||||||
|
wx.showToast({
|
||||||
|
title: '已拒绝改派',
|
||||||
|
icon: 'none'
|
||||||
|
})
|
||||||
|
await this.loadOrders()
|
||||||
|
}, {
|
||||||
|
message: '改派处理中,请勿重复点击'
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
if (actionGuard.isGuardError(error)) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
wx.showToast({
|
||||||
|
title: error.message || '拒绝改派失败',
|
||||||
|
icon: 'none'
|
||||||
|
})
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
async handleCancelOrder(event) {
|
async handleCancelOrder(event) {
|
||||||
const orderId = event.currentTarget.dataset.orderId
|
const orderId = event.currentTarget.dataset.orderId
|
||||||
/**
|
|
||||||
* `if` page method. Use this from WXML event bindings or lifecycle hooks.
|
|
||||||
* Call guide: read or update page data with `this.setData(...)` inside the method when state changes.
|
|
||||||
*/
|
|
||||||
if (!orderId) {
|
if (!orderId) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -116,10 +412,6 @@ Page({
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
/**
|
|
||||||
* `if` page method. Use this from WXML event bindings or lifecycle hooks.
|
|
||||||
* Call guide: read or update page data with `this.setData(...)` inside the method when state changes.
|
|
||||||
*/
|
|
||||||
if (!confirmed) {
|
if (!confirmed) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -35,6 +35,50 @@
|
|||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
|
|
||||||
|
<view wx:if="{{orderItem.reviewSummary}}" class="review-summary">
|
||||||
|
<text class="assist-label">评价状态</text>
|
||||||
|
<text class="assist-main">{{orderItem.reviewSummary.displayText}}</text>
|
||||||
|
<text wx:if="{{orderItem.reviewSummary.contentText}}" class="assist-desc">{{orderItem.reviewSummary.contentText}}</text>
|
||||||
|
</view>
|
||||||
|
|
||||||
|
<view wx:elif="{{orderItem.pendingReview}}" class="review-panel">
|
||||||
|
<view class="review-panel-head">
|
||||||
|
<text class="assist-label">评价美甲师</text>
|
||||||
|
<text class="assist-desc">评分必填,文字可选</text>
|
||||||
|
</view>
|
||||||
|
<view class="score-row">
|
||||||
|
<view
|
||||||
|
wx:for="{{reviewScoreOptions}}"
|
||||||
|
wx:key="*this"
|
||||||
|
wx:for-item="score"
|
||||||
|
class="score-chip {{orderItem.reviewDraft.rating == score ? 'active' : ''}}"
|
||||||
|
data-review-id="{{orderItem.pendingReview.id}}"
|
||||||
|
data-score="{{score}}"
|
||||||
|
bindtap="handleSelectReviewScore"
|
||||||
|
>{{score}}</view>
|
||||||
|
</view>
|
||||||
|
<textarea
|
||||||
|
class="review-textarea"
|
||||||
|
maxlength="200"
|
||||||
|
placeholder="写下这次服务体验,可不填"
|
||||||
|
placeholder-class="textarea-placeholder"
|
||||||
|
value="{{orderItem.reviewDraft.content}}"
|
||||||
|
data-review-id="{{orderItem.pendingReview.id}}"
|
||||||
|
bindinput="handleReviewContentInput"
|
||||||
|
></textarea>
|
||||||
|
<view class="review-submit-btn" data-review-id="{{orderItem.pendingReview.id}}" bindtap="handleSubmitReview">提交评价</view>
|
||||||
|
</view>
|
||||||
|
|
||||||
|
<view wx:if="{{orderItem.pendingArtistChangeRequest}}" class="change-panel">
|
||||||
|
<text class="assist-label">待确认改派</text>
|
||||||
|
<text class="assist-main">{{orderItem.pendingArtistChangeRequest.displayText}}</text>
|
||||||
|
<text wx:if="{{orderItem.pendingArtistChangeRequest.reasonText}}" class="assist-desc">原因:{{orderItem.pendingArtistChangeRequest.reasonText}}</text>
|
||||||
|
<view class="change-actions">
|
||||||
|
<view class="change-btn primary" data-request-id="{{orderItem.pendingArtistChangeRequest.id}}" bindtap="handleApproveArtistChange">同意改派</view>
|
||||||
|
<view class="change-btn" data-request-id="{{orderItem.pendingArtistChangeRequest.id}}" bindtap="handleRejectArtistChange">拒绝</view>
|
||||||
|
</view>
|
||||||
|
</view>
|
||||||
|
|
||||||
<view class="order-foot">
|
<view class="order-foot">
|
||||||
<text class="order-amount">总计:{{item.actualAmountText}}</text>
|
<text class="order-amount">总计:{{item.actualAmountText}}</text>
|
||||||
<view wx:if="{{item.status == 1}}" class="cancel-btn" data-order-id="{{item.id}}" bindtap="handleCancelOrder">取消订单</view>
|
<view wx:if="{{item.status == 1}}" class="cancel-btn" data-order-id="{{item.id}}" bindtap="handleCancelOrder">取消订单</view>
|
||||||
|
|||||||
@@ -131,3 +131,129 @@
|
|||||||
font-size: 24rpx;
|
font-size: 24rpx;
|
||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.review-summary,
|
||||||
|
.review-panel,
|
||||||
|
.change-panel {
|
||||||
|
margin-top: 18rpx;
|
||||||
|
padding: 20rpx;
|
||||||
|
border-radius: 18rpx;
|
||||||
|
background: rgba(255, 247, 249, 0.82);
|
||||||
|
border: 2rpx solid var(--theme-border);
|
||||||
|
}
|
||||||
|
|
||||||
|
.review-panel-head {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 16rpx;
|
||||||
|
}
|
||||||
|
|
||||||
|
.assist-label,
|
||||||
|
.assist-main,
|
||||||
|
.assist-desc {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.assist-label {
|
||||||
|
font-size: 22rpx;
|
||||||
|
color: #8d7a84;
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.assist-main {
|
||||||
|
margin-top: 8rpx;
|
||||||
|
font-size: 26rpx;
|
||||||
|
font-weight: 700;
|
||||||
|
color: #2d2430;
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.assist-desc {
|
||||||
|
margin-top: 8rpx;
|
||||||
|
font-size: 24rpx;
|
||||||
|
color: #8d7a84;
|
||||||
|
line-height: 1.6;
|
||||||
|
}
|
||||||
|
|
||||||
|
.score-row {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 12rpx;
|
||||||
|
margin-top: 16rpx;
|
||||||
|
}
|
||||||
|
|
||||||
|
.score-chip {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: 72rpx;
|
||||||
|
height: 52rpx;
|
||||||
|
border-radius: 999rpx;
|
||||||
|
background: #ffffff;
|
||||||
|
border: 2rpx solid var(--theme-border);
|
||||||
|
color: #5d4b55;
|
||||||
|
font-size: 24rpx;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
|
||||||
|
.score-chip.active {
|
||||||
|
background: var(--theme-primary);
|
||||||
|
border-color: var(--theme-primary);
|
||||||
|
color: #ffffff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.review-textarea {
|
||||||
|
width: 100%;
|
||||||
|
min-height: 136rpx;
|
||||||
|
box-sizing: border-box;
|
||||||
|
margin-top: 16rpx;
|
||||||
|
padding: 16rpx;
|
||||||
|
border-radius: 16rpx;
|
||||||
|
background: #ffffff;
|
||||||
|
border: 2rpx solid var(--theme-border);
|
||||||
|
color: #2d2430;
|
||||||
|
font-size: 24rpx;
|
||||||
|
line-height: 1.6;
|
||||||
|
}
|
||||||
|
|
||||||
|
.textarea-placeholder {
|
||||||
|
color: #b49da9;
|
||||||
|
}
|
||||||
|
|
||||||
|
.review-submit-btn,
|
||||||
|
.change-btn {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
height: 58rpx;
|
||||||
|
padding: 0 22rpx;
|
||||||
|
border-radius: 999rpx;
|
||||||
|
font-size: 24rpx;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
|
||||||
|
.review-submit-btn {
|
||||||
|
margin-top: 16rpx;
|
||||||
|
background: var(--theme-primary);
|
||||||
|
color: #ffffff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.change-actions {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 14rpx;
|
||||||
|
margin-top: 16rpx;
|
||||||
|
}
|
||||||
|
|
||||||
|
.change-btn {
|
||||||
|
background: #ffffff;
|
||||||
|
border: 2rpx solid var(--theme-border);
|
||||||
|
color: #5d4b55;
|
||||||
|
}
|
||||||
|
|
||||||
|
.change-btn.primary {
|
||||||
|
background: var(--theme-primary);
|
||||||
|
border-color: var(--theme-primary);
|
||||||
|
color: #ffffff;
|
||||||
|
}
|
||||||
|
|||||||
@@ -194,6 +194,10 @@ Page({
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
await userApi.markMessagePopupShown(item.id)
|
await userApi.markMessagePopupShown(item.id)
|
||||||
|
const opened = await navigation.openActionPath(item.actionPath)
|
||||||
|
if (opened) {
|
||||||
|
break
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('加载待弹窗消息失败', error)
|
console.error('加载待弹窗消息失败', error)
|
||||||
|
|||||||
@@ -47,6 +47,45 @@ function switchTab(path) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function normalizeActionPath(value) {
|
||||||
|
const rawPath = String(value || '').trim()
|
||||||
|
if (!rawPath || !rawPath.startsWith('/') || rawPath.startsWith('//')) {
|
||||||
|
return ''
|
||||||
|
}
|
||||||
|
|
||||||
|
if (rawPath.startsWith('/orders')) {
|
||||||
|
const queryIndex = rawPath.indexOf('?')
|
||||||
|
const query = queryIndex >= 0 ? rawPath.slice(queryIndex) : ''
|
||||||
|
return `/pages/orders/index${query}`
|
||||||
|
}
|
||||||
|
|
||||||
|
if (rawPath.startsWith('/pages/')) {
|
||||||
|
return rawPath
|
||||||
|
}
|
||||||
|
|
||||||
|
return ''
|
||||||
|
}
|
||||||
|
|
||||||
|
function openActionPath(value) {
|
||||||
|
const target = normalizeActionPath(value)
|
||||||
|
if (!target) {
|
||||||
|
return Promise.resolve(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
const purePath = target.split('?')[0]
|
||||||
|
const openPromise = isTabPage(purePath) ? switchTab(purePath) : navigate(target)
|
||||||
|
return openPromise
|
||||||
|
.then(() => true)
|
||||||
|
.catch(error => {
|
||||||
|
console.error('Open message action path failed', error)
|
||||||
|
wx.showToast({
|
||||||
|
title: '无法打开消息链接',
|
||||||
|
icon: 'none'
|
||||||
|
})
|
||||||
|
return false
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
function goBack(fallbackPath) {
|
function goBack(fallbackPath) {
|
||||||
const pages = getCurrentPages()
|
const pages = getCurrentPages()
|
||||||
if (pages.length > 1) {
|
if (pages.length > 1) {
|
||||||
@@ -186,6 +225,8 @@ module.exports = {
|
|||||||
isTabPage,
|
isTabPage,
|
||||||
navigate,
|
navigate,
|
||||||
switchTab,
|
switchTab,
|
||||||
|
normalizeActionPath,
|
||||||
|
openActionPath,
|
||||||
goBack,
|
goBack,
|
||||||
redirectAfterLogin,
|
redirectAfterLogin,
|
||||||
openAuth,
|
openAuth,
|
||||||
|
|||||||
@@ -8,6 +8,35 @@ module.exports = {
|
|||||||
})
|
})
|
||||||
},
|
},
|
||||||
|
|
||||||
|
listOrderReviews(orderId) {
|
||||||
|
return request({
|
||||||
|
url: `/order/${orderId}/reviews`
|
||||||
|
})
|
||||||
|
},
|
||||||
|
|
||||||
|
getArtistChangeOptions(orderId, orderItemId) {
|
||||||
|
return request({
|
||||||
|
url: `/order/${orderId}/artist-change/options`,
|
||||||
|
params: {
|
||||||
|
orderItemId
|
||||||
|
}
|
||||||
|
})
|
||||||
|
},
|
||||||
|
|
||||||
|
requestArtistChange(data) {
|
||||||
|
return request({
|
||||||
|
url: '/order/artist-change/request',
|
||||||
|
method: 'POST',
|
||||||
|
data
|
||||||
|
})
|
||||||
|
},
|
||||||
|
|
||||||
|
listMyPendingArtistChangeRequests() {
|
||||||
|
return request({
|
||||||
|
url: '/order/artist-change/my-pending'
|
||||||
|
})
|
||||||
|
},
|
||||||
|
|
||||||
updateOrderStatus(id, status) {
|
updateOrderStatus(id, status) {
|
||||||
return request({
|
return request({
|
||||||
url: `/order/update-status/${id}`,
|
url: `/order/update-status/${id}`,
|
||||||
|
|||||||
@@ -12,6 +12,212 @@ const STATUS_OPTIONS = [
|
|||||||
{ label: '已取消', value: 0 }
|
{ label: '已取消', value: 0 }
|
||||||
]
|
]
|
||||||
|
|
||||||
|
function toId(value) {
|
||||||
|
return value === undefined || value === null ? '' : String(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
function sameId(left, right) {
|
||||||
|
const leftId = toId(left)
|
||||||
|
const rightId = toId(right)
|
||||||
|
return leftId !== '' && leftId === rightId
|
||||||
|
}
|
||||||
|
|
||||||
|
function safeList(value) {
|
||||||
|
return Array.isArray(value) ? value : []
|
||||||
|
}
|
||||||
|
|
||||||
|
function trimText(value) {
|
||||||
|
return String(value || '').trim()
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatRating(value) {
|
||||||
|
const rating = Number(value)
|
||||||
|
if (!isFinite(rating) || rating <= 0) {
|
||||||
|
return ''
|
||||||
|
}
|
||||||
|
return rating % 1 === 0 ? String(rating) : rating.toFixed(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
function isSubmittedReview(review) {
|
||||||
|
if (!review) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if (Number(review.status) === 1) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return Boolean(review.rating)
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveRelatedRecord(source, orderItemId) {
|
||||||
|
if (Array.isArray(source)) {
|
||||||
|
return source.find(item => sameId(item && item.orderItemId, orderItemId)) || null
|
||||||
|
}
|
||||||
|
if (source && typeof source === 'object') {
|
||||||
|
if (!source.orderItemId || sameId(source.orderItemId, orderItemId)) {
|
||||||
|
return source
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildReviewSummary(review) {
|
||||||
|
if (!review || !isSubmittedReview(review)) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
const ratingText = formatRating(review.rating)
|
||||||
|
return {
|
||||||
|
...review,
|
||||||
|
ratingText,
|
||||||
|
contentText: trimText(review.content),
|
||||||
|
displayText: ratingText ? `已评价:${ratingText} 分` : (review.statusText || '已评价')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildArtistChangeSummary(request) {
|
||||||
|
if (!request) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
const originalName = request.originalArtistName || '原美甲师'
|
||||||
|
const requestedName = request.requestedArtistName || '新美甲师'
|
||||||
|
return {
|
||||||
|
...request,
|
||||||
|
displayText: `${originalName} → ${requestedName}`,
|
||||||
|
reasonText: trimText(request.reason)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function indexByOrderItemId(list) {
|
||||||
|
return safeList(list).reduce((result, item) => {
|
||||||
|
if (item && item.orderItemId) {
|
||||||
|
result[toId(item.orderItemId)] = item
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}, {})
|
||||||
|
}
|
||||||
|
|
||||||
|
async function safeCall(factory, fallbackValue) {
|
||||||
|
try {
|
||||||
|
const result = await factory()
|
||||||
|
return result === undefined || result === null ? fallbackValue : result
|
||||||
|
} catch (error) {
|
||||||
|
return fallbackValue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadAssistData(orders) {
|
||||||
|
const pendingChangesPromise = safeCall(() => orderApi.listMyPendingArtistChangeRequests(), [])
|
||||||
|
const orderReviewListsPromise = Promise.all(orders.map(order => (
|
||||||
|
safeCall(() => orderApi.listOrderReviews(order.id), [])
|
||||||
|
)))
|
||||||
|
const [pendingChanges, orderReviewLists] = await Promise.all([
|
||||||
|
pendingChangesPromise,
|
||||||
|
orderReviewListsPromise
|
||||||
|
])
|
||||||
|
|
||||||
|
const submittedReviews = []
|
||||||
|
safeList(orderReviewLists).forEach(list => {
|
||||||
|
safeList(list).forEach(review => {
|
||||||
|
if (isSubmittedReview(review)) {
|
||||||
|
submittedReviews.push(review)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
return {
|
||||||
|
pendingChangeByItemId: indexByOrderItemId(pendingChanges),
|
||||||
|
submittedReviewByItemId: indexByOrderItemId(submittedReviews)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasProductionFlag(userInfo) {
|
||||||
|
const sources = [
|
||||||
|
userInfo && userInfo.participateProduction,
|
||||||
|
userInfo && userInfo.participateProductionFlag,
|
||||||
|
userInfo && userInfo.artistParticipateProduction,
|
||||||
|
userInfo && userInfo.nailArtistInfo && userInfo.nailArtistInfo.participateProduction,
|
||||||
|
userInfo && userInfo.artistInfo && userInfo.artistInfo.participateProduction
|
||||||
|
]
|
||||||
|
return sources.some(value => value === true || Number(value) === 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
function canRequestArtistChangeForItem(userInfo, order, item, pendingChange) {
|
||||||
|
if (!userInfo || !order || !item || pendingChange || Number(order.status) !== 1) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
if (permission.isNailArtist(userInfo)) {
|
||||||
|
return !item.artistId || sameId(item.artistId, userInfo.id)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sameId(item.artistId, userInfo.id)) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
return permission.isShopManager(userInfo) && hasProductionFlag(userInfo)
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatOrderItem(order, item, userInfo, assistData) {
|
||||||
|
const itemId = toId(item.id)
|
||||||
|
const inlineReviewSummary = resolveRelatedRecord(item.reviewSummary || order.reviewSummary, item.id)
|
||||||
|
const inlinePendingChange = resolveRelatedRecord(item.pendingArtistChangeRequest || order.pendingArtistChangeRequest, item.id)
|
||||||
|
const reviewSummary = buildReviewSummary(inlineReviewSummary || assistData.submittedReviewByItemId[itemId])
|
||||||
|
const pendingArtistChangeRequest = buildArtistChangeSummary(inlinePendingChange || assistData.pendingChangeByItemId[itemId])
|
||||||
|
|
||||||
|
return {
|
||||||
|
...item,
|
||||||
|
displayPrice: format.formatPrice(item.price),
|
||||||
|
displayAppointmentTime: format.formatDateTime(item.appointmentTime),
|
||||||
|
reviewSummary,
|
||||||
|
reviewStatusText: reviewSummary ? reviewSummary.displayText : '待评价',
|
||||||
|
pendingArtistChangeRequest,
|
||||||
|
canRequestArtistChange: canRequestArtistChangeForItem(userInfo, order, item, pendingArtistChangeRequest)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatOrder(order, userInfo, assistData) {
|
||||||
|
const items = safeList(order.items).map(item => formatOrderItem(order, item, userInfo, assistData))
|
||||||
|
const orderReviewSummary = buildReviewSummary(order.reviewSummary)
|
||||||
|
return {
|
||||||
|
...order,
|
||||||
|
displayStatusText: format.getOrderStatusText(order),
|
||||||
|
displayCreateTime: format.formatDateTime(order.createTime),
|
||||||
|
displayPayAmount: format.formatPrice(order.payAmount || order.actualAmount),
|
||||||
|
items,
|
||||||
|
reviewSummary: orderReviewSummary,
|
||||||
|
reviewStatusText: orderReviewSummary ? orderReviewSummary.displayText : ''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function selectArtist(artists) {
|
||||||
|
return new Promise(resolve => {
|
||||||
|
wx.showActionSheet({
|
||||||
|
itemList: artists.map(item => item.artistName || `美甲师 ${item.artistId}`),
|
||||||
|
success: result => resolve(artists[result.tapIndex] || null),
|
||||||
|
fail: () => resolve(null)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function promptChangeReason() {
|
||||||
|
return new Promise(resolve => {
|
||||||
|
wx.showModal({
|
||||||
|
title: '改派原因',
|
||||||
|
content: '可填写改派原因,留空也可以提交。',
|
||||||
|
editable: true,
|
||||||
|
placeholderText: '例如档期冲突、客户沟通调整',
|
||||||
|
confirmText: '提交',
|
||||||
|
success: result => {
|
||||||
|
if (!result.confirm) {
|
||||||
|
resolve(null)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
resolve(trimText(result.content))
|
||||||
|
},
|
||||||
|
fail: () => resolve(null)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
Page({
|
Page({
|
||||||
data: {
|
data: {
|
||||||
keyword: '',
|
keyword: '',
|
||||||
@@ -29,8 +235,9 @@ Page({
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const userInfo = getApp().globalData.userInfo
|
||||||
this.setData({
|
this.setData({
|
||||||
userInfo: getApp().globalData.userInfo
|
userInfo
|
||||||
})
|
})
|
||||||
|
|
||||||
if (!this.data.initialized || consumeDirty('admin-orders')) {
|
if (!this.data.initialized || consumeDirty('admin-orders')) {
|
||||||
@@ -73,16 +280,15 @@ Page({
|
|||||||
status: this.data.status === '' ? undefined : this.data.status
|
status: this.data.status === '' ? undefined : this.data.status
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const rawList = safeList(result && result.list)
|
||||||
|
const assistData = await loadAssistData(rawList)
|
||||||
|
|
||||||
if (requestId !== this._loadRequestId) {
|
if (requestId !== this._loadRequestId) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
this.setData({
|
this.setData({
|
||||||
list: (Array.isArray(result && result.list) ? result.list : []).map(item => ({
|
list: rawList.map(item => formatOrder(item, this.data.userInfo, assistData)),
|
||||||
...item,
|
|
||||||
displayStatusText: format.getOrderStatusText(item),
|
|
||||||
displayCreateTime: format.formatDateTime(item.createTime)
|
|
||||||
})),
|
|
||||||
total: Number(result && result.total) || 0,
|
total: Number(result && result.total) || 0,
|
||||||
initialized: true
|
initialized: true
|
||||||
})
|
})
|
||||||
@@ -119,6 +325,54 @@ Page({
|
|||||||
}).catch(() => undefined)
|
}).catch(() => undefined)
|
||||||
},
|
},
|
||||||
|
|
||||||
|
async handleRequestArtistChange(event) {
|
||||||
|
const orderId = event.currentTarget.dataset.orderId
|
||||||
|
const orderItemId = event.currentTarget.dataset.orderItemId
|
||||||
|
if (!orderId || !orderItemId) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const options = await orderApi.getArtistChangeOptions(orderId, orderItemId)
|
||||||
|
const artists = safeList(options && options.artists)
|
||||||
|
if (!artists.length) {
|
||||||
|
wx.showToast({
|
||||||
|
title: '暂无可改派美甲师',
|
||||||
|
icon: 'none'
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const targetArtist = await selectArtist(artists)
|
||||||
|
if (!targetArtist) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const reason = await promptChangeReason()
|
||||||
|
if (reason === null) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
await orderApi.requestArtistChange({
|
||||||
|
orderId,
|
||||||
|
orderItemId,
|
||||||
|
requestedArtistId: targetArtist.artistId,
|
||||||
|
reason
|
||||||
|
})
|
||||||
|
markDirty('admin-workbench')
|
||||||
|
wx.showToast({
|
||||||
|
title: '改派申请已提交',
|
||||||
|
icon: 'none'
|
||||||
|
})
|
||||||
|
this.loadOrders()
|
||||||
|
} catch (error) {
|
||||||
|
wx.showToast({
|
||||||
|
title: error.message || '改派申请失败',
|
||||||
|
icon: 'none'
|
||||||
|
})
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
async handleProcessOrder(event) {
|
async handleProcessOrder(event) {
|
||||||
const order = event.currentTarget.dataset.order
|
const order = event.currentTarget.dataset.order
|
||||||
if (!order) {
|
if (!order) {
|
||||||
|
|||||||
@@ -33,7 +33,7 @@
|
|||||||
<view class="meta-grid">
|
<view class="meta-grid">
|
||||||
<view class="meta-item">
|
<view class="meta-item">
|
||||||
<text class="meta-label">订单金额</text>
|
<text class="meta-label">订单金额</text>
|
||||||
<text class="meta-value">¥{{item.payAmount}}</text>
|
<text class="meta-value">¥{{item.displayPayAmount}}</text>
|
||||||
</view>
|
</view>
|
||||||
<view class="meta-item">
|
<view class="meta-item">
|
||||||
<text class="meta-label">所属门店</text>
|
<text class="meta-label">所属门店</text>
|
||||||
@@ -48,6 +48,27 @@
|
|||||||
<text class="meta-value">{{item.displayCreateTime}}</text>
|
<text class="meta-value">{{item.displayCreateTime}}</text>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
|
|
||||||
|
<view wx:if="{{item.items.length}}" class="order-items">
|
||||||
|
<view wx:for="{{item.items}}" wx:key="id" wx:for-item="orderItem" class="order-item-row">
|
||||||
|
<view class="order-item-main">
|
||||||
|
<text class="order-item-title">{{orderItem.productTitle || '订单项目'}}</text>
|
||||||
|
<text class="order-item-line">美甲师:{{orderItem.artistName || '--'}}</text>
|
||||||
|
<text wx:if="{{orderItem.displayAppointmentTime}}" class="order-item-line">预约时间:{{orderItem.displayAppointmentTime}}</text>
|
||||||
|
<text class="order-item-review">{{orderItem.reviewStatusText}}</text>
|
||||||
|
<text wx:if="{{orderItem.reviewSummary && orderItem.reviewSummary.contentText}}" class="order-item-line">评价内容:{{orderItem.reviewSummary.contentText}}</text>
|
||||||
|
<view wx:if="{{orderItem.pendingArtistChangeRequest}}" class="change-note">
|
||||||
|
<text class="change-note-title">改派申请待处理</text>
|
||||||
|
<text class="change-note-desc">{{orderItem.pendingArtistChangeRequest.displayText}}</text>
|
||||||
|
<text wx:if="{{orderItem.pendingArtistChangeRequest.reasonText}}" class="change-note-desc">原因:{{orderItem.pendingArtistChangeRequest.reasonText}}</text>
|
||||||
|
</view>
|
||||||
|
</view>
|
||||||
|
<view wx:if="{{orderItem.canRequestArtistChange}}" class="mini-btn soft" data-order-id="{{item.id}}" data-order-item-id="{{orderItem.id}}" bindtap="handleRequestArtistChange">申请改派</view>
|
||||||
|
</view>
|
||||||
|
</view>
|
||||||
|
|
||||||
|
<view wx:elif="{{item.reviewStatusText}}" class="order-review-line">{{item.reviewStatusText}}</view>
|
||||||
|
|
||||||
<view class="list-actions">
|
<view class="list-actions">
|
||||||
<view class="mini-btn" data-order="{{item}}" bindtap="handleOpenOrder">查看详情</view>
|
<view class="mini-btn" data-order="{{item}}" bindtap="handleOpenOrder">查看详情</view>
|
||||||
<view wx:if="{{item.status !== 2}}" class="mini-btn primary" data-order="{{item}}" bindtap="handleProcessOrder">处理订单</view>
|
<view wx:if="{{item.status !== 2}}" class="mini-btn primary" data-order="{{item}}" bindtap="handleProcessOrder">处理订单</view>
|
||||||
|
|||||||
@@ -1,3 +1,82 @@
|
|||||||
.page-shell {
|
.page-shell {
|
||||||
background: transparent;
|
background: transparent;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.order-items {
|
||||||
|
margin-top: 22rpx;
|
||||||
|
border-top: 1rpx solid rgba(246, 239, 231, 0.12);
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-item-row {
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 18rpx;
|
||||||
|
padding: 18rpx 0;
|
||||||
|
border-bottom: 1rpx solid rgba(246, 239, 231, 0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-item-row:last-child {
|
||||||
|
border-bottom: 0;
|
||||||
|
padding-bottom: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-item-main {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-item-title,
|
||||||
|
.order-item-line,
|
||||||
|
.order-item-review,
|
||||||
|
.order-review-line,
|
||||||
|
.change-note-title,
|
||||||
|
.change-note-desc {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-item-title {
|
||||||
|
color: #f6efe7;
|
||||||
|
font-size: 26rpx;
|
||||||
|
font-weight: 700;
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-item-line,
|
||||||
|
.order-review-line,
|
||||||
|
.change-note-desc {
|
||||||
|
margin-top: 8rpx;
|
||||||
|
color: rgba(246, 239, 231, 0.68);
|
||||||
|
font-size: 23rpx;
|
||||||
|
line-height: 1.55;
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-item-review {
|
||||||
|
margin-top: 10rpx;
|
||||||
|
color: #f0c987;
|
||||||
|
font-size: 23rpx;
|
||||||
|
font-weight: 700;
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.change-note {
|
||||||
|
margin-top: 14rpx;
|
||||||
|
padding: 16rpx;
|
||||||
|
border-radius: 14rpx;
|
||||||
|
background: rgba(240, 201, 135, 0.1);
|
||||||
|
border: 1rpx solid rgba(240, 201, 135, 0.3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.change-note-title {
|
||||||
|
color: #f0c987;
|
||||||
|
font-size: 23rpx;
|
||||||
|
font-weight: 700;
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mini-btn.soft {
|
||||||
|
color: #081518;
|
||||||
|
background: #f0c987;
|
||||||
|
border-color: #f0c987;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|||||||
@@ -111,31 +111,5 @@ Page({
|
|||||||
icon: 'none'
|
icon: 'none'
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
},
|
|
||||||
|
|
||||||
handleDelete(event) {
|
|
||||||
const shop = event.currentTarget.dataset.shop
|
|
||||||
wx.showModal({
|
|
||||||
title: '删除店铺',
|
|
||||||
content: `确认删除店铺“${shop.shopName}”吗?该操作会联动清理店铺下资源。`,
|
|
||||||
success: async result => {
|
|
||||||
if (!result.confirm) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
await shopApi.deleteShop(shop.id)
|
|
||||||
wx.showToast({
|
|
||||||
title: '店铺已删除',
|
|
||||||
icon: 'none'
|
|
||||||
})
|
|
||||||
this.loadShops()
|
|
||||||
} catch (error) {
|
|
||||||
wx.showToast({
|
|
||||||
title: error.message || '店铺删除失败',
|
|
||||||
icon: 'none'
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -32,7 +32,6 @@
|
|||||||
<view class="list-actions">
|
<view class="list-actions">
|
||||||
<view class="mini-btn primary" data-shop="{{item}}" bindtap="handleEdit">编辑</view>
|
<view class="mini-btn primary" data-shop="{{item}}" bindtap="handleEdit">编辑</view>
|
||||||
<view class="mini-btn" data-shop="{{item}}" bindtap="handleStatus">{{item.status === 0 ? '启用' : '停用'}}</view>
|
<view class="mini-btn" data-shop="{{item}}" bindtap="handleStatus">{{item.status === 0 ? '启用' : '停用'}}</view>
|
||||||
<view class="mini-btn danger" data-shop="{{item}}" bindtap="handleDelete">删除</view>
|
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
</block>
|
</block>
|
||||||
|
|||||||
@@ -3,8 +3,10 @@ package com.xiaowang.yuminailcore;
|
|||||||
import org.springframework.boot.SpringApplication;
|
import org.springframework.boot.SpringApplication;
|
||||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
|
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
|
||||||
|
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||||
|
|
||||||
@EnableDiscoveryClient
|
@EnableDiscoveryClient
|
||||||
|
@EnableScheduling
|
||||||
@SpringBootApplication
|
@SpringBootApplication
|
||||||
public class YumiNailCoreApplication {
|
public class YumiNailCoreApplication {
|
||||||
|
|
||||||
|
|||||||
+35
-8
@@ -9,6 +9,8 @@ import com.xiaowang.yuminailcore.entity.UserDO;
|
|||||||
import com.xiaowang.yuminailcore.service.PermissionService;
|
import com.xiaowang.yuminailcore.service.PermissionService;
|
||||||
import com.xiaowang.yuminailcore.service.UserService;
|
import com.xiaowang.yuminailcore.service.UserService;
|
||||||
import com.xiaowang.yuminailcore.support.AdminScopeHelper;
|
import com.xiaowang.yuminailcore.support.AdminScopeHelper;
|
||||||
|
import com.xiaowang.yuminailcore.support.SecurityAuditActions;
|
||||||
|
import com.xiaowang.yuminailcore.support.SecurityAuditSupport;
|
||||||
import com.xiaowang.yuminailcore.vo.PermissionVO;
|
import com.xiaowang.yuminailcore.vo.PermissionVO;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
@@ -36,6 +38,7 @@ public class AdminPermissionController {
|
|||||||
* Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
* Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||||
*/
|
*/
|
||||||
private final AdminScopeHelper adminScopeHelper;
|
private final AdminScopeHelper adminScopeHelper;
|
||||||
|
private final SecurityAuditSupport securityAuditSupport;
|
||||||
|
|
||||||
@PostMapping("/create")
|
@PostMapping("/create")
|
||||||
@RequirePermission("permission:create")
|
@RequirePermission("permission:create")
|
||||||
@@ -50,8 +53,14 @@ public class AdminPermissionController {
|
|||||||
public Result<Long> createPermission(HttpServletRequest request, @RequestBody PermissionDTO permissionDTO) {
|
public Result<Long> createPermission(HttpServletRequest request, @RequestBody PermissionDTO permissionDTO) {
|
||||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||||
adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以维护权限定义");
|
adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以维护权限定义");
|
||||||
Long id = permissionService.createPermission(permissionDTO);
|
try {
|
||||||
return Result.success(id);
|
Long id = permissionService.createPermission(permissionDTO);
|
||||||
|
securityAuditSupport.success(request, SecurityAuditActions.PERMISSION_CREATE, "permissionId=" + id);
|
||||||
|
return Result.success(id);
|
||||||
|
} catch (RuntimeException exception) {
|
||||||
|
securityAuditSupport.fail(request, SecurityAuditActions.PERMISSION_CREATE, "reason=" + exception.getMessage());
|
||||||
|
throw exception;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@PutMapping("/update/{id}")
|
@PutMapping("/update/{id}")
|
||||||
@@ -68,8 +77,14 @@ public class AdminPermissionController {
|
|||||||
public Result<Boolean> updatePermission(HttpServletRequest request, @PathVariable Long id, @RequestBody PermissionDTO permissionDTO) {
|
public Result<Boolean> updatePermission(HttpServletRequest request, @PathVariable Long id, @RequestBody PermissionDTO permissionDTO) {
|
||||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||||
adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以维护权限定义");
|
adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以维护权限定义");
|
||||||
boolean success = permissionService.updatePermission(id, permissionDTO);
|
try {
|
||||||
return Result.success(success);
|
boolean success = permissionService.updatePermission(id, permissionDTO);
|
||||||
|
securityAuditSupport.success(request, SecurityAuditActions.PERMISSION_UPDATE, "permissionId=" + id + ",result=" + success);
|
||||||
|
return Result.success(success);
|
||||||
|
} catch (RuntimeException exception) {
|
||||||
|
securityAuditSupport.fail(request, SecurityAuditActions.PERMISSION_UPDATE, "permissionId=" + id + ",reason=" + exception.getMessage());
|
||||||
|
throw exception;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@DeleteMapping("/delete/{id}")
|
@DeleteMapping("/delete/{id}")
|
||||||
@@ -85,8 +100,14 @@ public class AdminPermissionController {
|
|||||||
public Result<Boolean> deletePermission(HttpServletRequest request, @PathVariable Long id) {
|
public Result<Boolean> deletePermission(HttpServletRequest request, @PathVariable Long id) {
|
||||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||||
adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以维护权限定义");
|
adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以维护权限定义");
|
||||||
boolean success = permissionService.deletePermission(id);
|
try {
|
||||||
return Result.success(success);
|
boolean success = permissionService.deletePermission(id);
|
||||||
|
securityAuditSupport.success(request, SecurityAuditActions.PERMISSION_DELETE, "permissionId=" + id + ",result=" + success);
|
||||||
|
return Result.success(success);
|
||||||
|
} catch (RuntimeException exception) {
|
||||||
|
securityAuditSupport.fail(request, SecurityAuditActions.PERMISSION_DELETE, "permissionId=" + id + ",reason=" + exception.getMessage());
|
||||||
|
throw exception;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/get/{id}")
|
@GetMapping("/get/{id}")
|
||||||
@@ -199,7 +220,13 @@ public class AdminPermissionController {
|
|||||||
}
|
}
|
||||||
Long currentUserId = (Long) request.getAttribute("userId");
|
Long currentUserId = (Long) request.getAttribute("userId");
|
||||||
userPermissionDTO.setUserId(userId);
|
userPermissionDTO.setUserId(userId);
|
||||||
boolean success = permissionService.assignPermissions(userPermissionDTO, currentUserId);
|
try {
|
||||||
return Result.success(success);
|
boolean success = permissionService.assignPermissions(userPermissionDTO, currentUserId);
|
||||||
|
securityAuditSupport.success(request, SecurityAuditActions.PERMISSION_ASSIGN, "targetUserId=" + userId + ",result=" + success);
|
||||||
|
return Result.success(success);
|
||||||
|
} catch (RuntimeException exception) {
|
||||||
|
securityAuditSupport.fail(request, SecurityAuditActions.PERMISSION_ASSIGN, "targetUserId=" + userId + ",reason=" + exception.getMessage());
|
||||||
|
throw exception;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+59
@@ -0,0 +1,59 @@
|
|||||||
|
package com.xiaowang.yuminailcore.controller;
|
||||||
|
|
||||||
|
import com.xiaowang.yuminailcore.annotation.RequirePermission;
|
||||||
|
import com.xiaowang.yuminailcore.common.Result;
|
||||||
|
import com.xiaowang.yuminailcore.service.SecurityAuditLogService;
|
||||||
|
import com.xiaowang.yuminailcore.vo.PageResultVO;
|
||||||
|
import com.xiaowang.yuminailcore.vo.SecurityAuditLogVO;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestParam;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
import java.time.format.DateTimeParseException;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/admin/security-audit")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class AdminSecurityAuditController {
|
||||||
|
|
||||||
|
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
||||||
|
|
||||||
|
private final SecurityAuditLogService securityAuditLogService;
|
||||||
|
|
||||||
|
@GetMapping("/logs")
|
||||||
|
@RequirePermission("security:audit:view")
|
||||||
|
public Result<PageResultVO<SecurityAuditLogVO>> listLogs(
|
||||||
|
@RequestParam(required = false) String account,
|
||||||
|
@RequestParam(required = false) String action,
|
||||||
|
@RequestParam(required = false) String result,
|
||||||
|
@RequestParam(required = false) String startTime,
|
||||||
|
@RequestParam(required = false) String endTime,
|
||||||
|
@RequestParam(defaultValue = "1") Integer page,
|
||||||
|
@RequestParam(defaultValue = "20") Integer size) {
|
||||||
|
return Result.success(securityAuditLogService.pageLogs(
|
||||||
|
account,
|
||||||
|
action,
|
||||||
|
result,
|
||||||
|
parseDateTime(startTime),
|
||||||
|
parseDateTime(endTime),
|
||||||
|
page,
|
||||||
|
size
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
private LocalDateTime parseDateTime(String value) {
|
||||||
|
if (!StringUtils.hasText(value)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return LocalDateTime.parse(value.trim(), DATE_TIME_FORMATTER);
|
||||||
|
} catch (DateTimeParseException exception) {
|
||||||
|
return LocalDateTime.parse(value.trim());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+19
-4
@@ -7,6 +7,8 @@ import com.xiaowang.yuminailcore.dto.ShopDTO;
|
|||||||
import com.xiaowang.yuminailcore.entity.UserDO;
|
import com.xiaowang.yuminailcore.entity.UserDO;
|
||||||
import com.xiaowang.yuminailcore.service.ShopService;
|
import com.xiaowang.yuminailcore.service.ShopService;
|
||||||
import com.xiaowang.yuminailcore.support.AdminScopeHelper;
|
import com.xiaowang.yuminailcore.support.AdminScopeHelper;
|
||||||
|
import com.xiaowang.yuminailcore.support.SecurityAuditActions;
|
||||||
|
import com.xiaowang.yuminailcore.support.SecurityAuditSupport;
|
||||||
import com.xiaowang.yuminailcore.vo.PageResultVO;
|
import com.xiaowang.yuminailcore.vo.PageResultVO;
|
||||||
import com.xiaowang.yuminailcore.vo.ShopVO;
|
import com.xiaowang.yuminailcore.vo.ShopVO;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
@@ -32,6 +34,7 @@ public class AdminShopController {
|
|||||||
* Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
* Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||||
*/
|
*/
|
||||||
private final AdminScopeHelper adminScopeHelper;
|
private final AdminScopeHelper adminScopeHelper;
|
||||||
|
private final SecurityAuditSupport securityAuditSupport;
|
||||||
|
|
||||||
@GetMapping("/list")
|
@GetMapping("/list")
|
||||||
@RequirePermission("shop:view")
|
@RequirePermission("shop:view")
|
||||||
@@ -103,8 +106,14 @@ public class AdminShopController {
|
|||||||
public Result<Boolean> deleteShop(HttpServletRequest request, @PathVariable Long id) {
|
public Result<Boolean> deleteShop(HttpServletRequest request, @PathVariable Long id) {
|
||||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||||
adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以删除店铺");
|
adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以删除店铺");
|
||||||
boolean success = shopService.deleteShop(id);
|
try {
|
||||||
return Result.success(success);
|
boolean success = shopService.deleteShop(id);
|
||||||
|
securityAuditSupport.success(request, SecurityAuditActions.SHOP_DELETE_BLOCKED, "shopId=" + id + ",result=" + success);
|
||||||
|
return Result.success(success);
|
||||||
|
} catch (RuntimeException exception) {
|
||||||
|
securityAuditSupport.fail(request, SecurityAuditActions.SHOP_DELETE_BLOCKED, "shopId=" + id + ",reason=" + exception.getMessage());
|
||||||
|
throw exception;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@PutMapping("/status/{id}")
|
@PutMapping("/status/{id}")
|
||||||
@@ -121,8 +130,14 @@ public class AdminShopController {
|
|||||||
public Result<Boolean> updateShopStatus(HttpServletRequest request, @PathVariable Long id, @RequestBody StatusRequest statusRequest) {
|
public Result<Boolean> updateShopStatus(HttpServletRequest request, @PathVariable Long id, @RequestBody StatusRequest statusRequest) {
|
||||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||||
adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以启停店铺");
|
adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以启停店铺");
|
||||||
boolean success = shopService.updateShopStatus(id, statusRequest.getStatus());
|
try {
|
||||||
return Result.success(success);
|
boolean success = shopService.updateShopStatus(id, statusRequest.getStatus());
|
||||||
|
securityAuditSupport.success(request, SecurityAuditActions.SHOP_STATUS_UPDATE, "shopId=" + id + ",status=" + statusRequest.getStatus());
|
||||||
|
return Result.success(success);
|
||||||
|
} catch (RuntimeException exception) {
|
||||||
|
securityAuditSupport.fail(request, SecurityAuditActions.SHOP_STATUS_UPDATE, "shopId=" + id + ",status=" + statusRequest.getStatus() + ",reason=" + exception.getMessage());
|
||||||
|
throw exception;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/list/all")
|
@GetMapping("/list/all")
|
||||||
|
|||||||
+59
-14
@@ -13,6 +13,8 @@ import com.xiaowang.yuminailcore.service.UserService;
|
|||||||
import com.xiaowang.yuminailcore.service.ShopRoleService;
|
import com.xiaowang.yuminailcore.service.ShopRoleService;
|
||||||
import com.xiaowang.yuminailcore.support.AdminScopeHelper;
|
import com.xiaowang.yuminailcore.support.AdminScopeHelper;
|
||||||
import com.xiaowang.yuminailcore.support.BookableArtistSupport;
|
import com.xiaowang.yuminailcore.support.BookableArtistSupport;
|
||||||
|
import com.xiaowang.yuminailcore.support.SecurityAuditActions;
|
||||||
|
import com.xiaowang.yuminailcore.support.SecurityAuditSupport;
|
||||||
import com.xiaowang.yuminailcore.vo.BalanceChangeDetailVO;
|
import com.xiaowang.yuminailcore.vo.BalanceChangeDetailVO;
|
||||||
import com.xiaowang.yuminailcore.vo.PageResultVO;
|
import com.xiaowang.yuminailcore.vo.PageResultVO;
|
||||||
import com.xiaowang.yuminailcore.vo.UserStatisticsVO;
|
import com.xiaowang.yuminailcore.vo.UserStatisticsVO;
|
||||||
@@ -56,6 +58,7 @@ public class AdminUserController {
|
|||||||
* Variable `bookableArtistSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
* Variable `bookableArtistSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||||
*/
|
*/
|
||||||
private final BookableArtistSupport bookableArtistSupport;
|
private final BookableArtistSupport bookableArtistSupport;
|
||||||
|
private final SecurityAuditSupport securityAuditSupport;
|
||||||
|
|
||||||
@GetMapping("/list")
|
@GetMapping("/list")
|
||||||
@RequirePermission("user:view")
|
@RequirePermission("user:view")
|
||||||
@@ -214,8 +217,14 @@ public class AdminUserController {
|
|||||||
*/
|
*/
|
||||||
throw new RuntimeException("管理员账号不允许停用");
|
throw new RuntimeException("管理员账号不允许停用");
|
||||||
}
|
}
|
||||||
boolean success = userService.updateUserStatus(id, request.getStatus());
|
try {
|
||||||
return Result.success(success);
|
boolean success = userService.updateUserStatus(id, request.getStatus());
|
||||||
|
securityAuditSupport.success(httpRequest, SecurityAuditActions.USER_STATUS_UPDATE, "targetUserId=" + id + ",status=" + request.getStatus());
|
||||||
|
return Result.success(success);
|
||||||
|
} catch (RuntimeException exception) {
|
||||||
|
securityAuditSupport.fail(httpRequest, SecurityAuditActions.USER_STATUS_UPDATE, "targetUserId=" + id + ",reason=" + exception.getMessage());
|
||||||
|
throw exception;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/reset-password/{userId}")
|
@PostMapping("/reset-password/{userId}")
|
||||||
@@ -236,8 +245,14 @@ public class AdminUserController {
|
|||||||
}
|
}
|
||||||
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权重置其他店铺用户密码");
|
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权重置其他店铺用户密码");
|
||||||
Long currentUserId = (Long) request.getAttribute("userId");
|
Long currentUserId = (Long) request.getAttribute("userId");
|
||||||
boolean success = userService.resetPassword(userId, currentUserId);
|
try {
|
||||||
return Result.success(success);
|
boolean success = userService.resetPassword(userId, currentUserId);
|
||||||
|
securityAuditSupport.success(request, SecurityAuditActions.USER_RESET_PASSWORD, "targetUserId=" + userId + ",result=" + success);
|
||||||
|
return Result.success(success);
|
||||||
|
} catch (RuntimeException exception) {
|
||||||
|
securityAuditSupport.fail(request, SecurityAuditActions.USER_RESET_PASSWORD, "targetUserId=" + userId + ",reason=" + exception.getMessage());
|
||||||
|
throw exception;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@DeleteMapping("/delete/{id}")
|
@DeleteMapping("/delete/{id}")
|
||||||
@@ -265,8 +280,14 @@ public class AdminUserController {
|
|||||||
*/
|
*/
|
||||||
throw new RuntimeException("管理员账号不允许删除");
|
throw new RuntimeException("管理员账号不允许删除");
|
||||||
}
|
}
|
||||||
boolean success = userService.deleteUser(id);
|
try {
|
||||||
return Result.success(success);
|
boolean success = userService.deleteUser(id);
|
||||||
|
securityAuditSupport.success(request, SecurityAuditActions.USER_DELETE, "targetUserId=" + id + ",result=" + success);
|
||||||
|
return Result.success(success);
|
||||||
|
} catch (RuntimeException exception) {
|
||||||
|
securityAuditSupport.fail(request, SecurityAuditActions.USER_DELETE, "targetUserId=" + id + ",reason=" + exception.getMessage());
|
||||||
|
throw exception;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@PutMapping("/unbind/{id}")
|
@PutMapping("/unbind/{id}")
|
||||||
@@ -295,8 +316,14 @@ public class AdminUserController {
|
|||||||
*/
|
*/
|
||||||
throw new RuntimeException("管理员账号不允许解绑");
|
throw new RuntimeException("管理员账号不允许解绑");
|
||||||
}
|
}
|
||||||
boolean success = userService.unbindUserInShopWithOperator(id, currentUser.getShopId(), currentUser.getType());
|
try {
|
||||||
return Result.success(success);
|
boolean success = userService.unbindUserInShopWithOperator(id, currentUser.getShopId(), currentUser.getType());
|
||||||
|
securityAuditSupport.success(request, SecurityAuditActions.USER_UNBIND, "targetUserId=" + id + ",result=" + success);
|
||||||
|
return Result.success(success);
|
||||||
|
} catch (RuntimeException exception) {
|
||||||
|
securityAuditSupport.fail(request, SecurityAuditActions.USER_UNBIND, "targetUserId=" + id + ",reason=" + exception.getMessage());
|
||||||
|
throw exception;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/{id}/asset")
|
@GetMapping("/{id}/asset")
|
||||||
@@ -341,8 +368,14 @@ public class AdminUserController {
|
|||||||
) {
|
) {
|
||||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||||
UserVO targetUser = requireAccessibleUser(currentUser, id, "无权调整其他店铺用户余额");
|
UserVO targetUser = requireAccessibleUser(currentUser, id, "无权调整其他店铺用户余额");
|
||||||
UserAssetVO assetVO = userAssetService.changeBalance(currentUser.getId(), targetUser.getId(), balanceChangeDTO);
|
try {
|
||||||
return Result.success(assetVO);
|
UserAssetVO assetVO = userAssetService.changeBalance(currentUser.getId(), targetUser.getId(), balanceChangeDTO);
|
||||||
|
securityAuditSupport.success(request, SecurityAuditActions.USER_BALANCE_CHANGE, "targetUserId=" + id);
|
||||||
|
return Result.success(assetVO);
|
||||||
|
} catch (RuntimeException exception) {
|
||||||
|
securityAuditSupport.fail(request, SecurityAuditActions.USER_BALANCE_CHANGE, "targetUserId=" + id + ",reason=" + exception.getMessage());
|
||||||
|
throw exception;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/{id}/vip/override")
|
@PostMapping("/{id}/vip/override")
|
||||||
@@ -355,8 +388,14 @@ public class AdminUserController {
|
|||||||
) {
|
) {
|
||||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||||
UserVO targetUser = requireAccessibleUser(currentUser, id, "无权调整其他店铺用户 VIP");
|
UserVO targetUser = requireAccessibleUser(currentUser, id, "无权调整其他店铺用户 VIP");
|
||||||
UserAssetVO assetVO = userAssetService.overrideVip(currentUser.getId(), targetUser.getId(), vipOverrideDTO);
|
try {
|
||||||
return Result.success(assetVO);
|
UserAssetVO assetVO = userAssetService.overrideVip(currentUser.getId(), targetUser.getId(), vipOverrideDTO);
|
||||||
|
securityAuditSupport.success(request, SecurityAuditActions.USER_VIP_OVERRIDE, "targetUserId=" + id);
|
||||||
|
return Result.success(assetVO);
|
||||||
|
} catch (RuntimeException exception) {
|
||||||
|
securityAuditSupport.fail(request, SecurityAuditActions.USER_VIP_OVERRIDE, "targetUserId=" + id + ",reason=" + exception.getMessage());
|
||||||
|
throw exception;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/{id}/vip/recalculate")
|
@PostMapping("/{id}/vip/recalculate")
|
||||||
@@ -372,8 +411,14 @@ public class AdminUserController {
|
|||||||
public Result<UserAssetVO> recalculateUserVip(HttpServletRequest request, @PathVariable Long id) {
|
public Result<UserAssetVO> recalculateUserVip(HttpServletRequest request, @PathVariable Long id) {
|
||||||
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
|
||||||
UserVO targetUser = requireAccessibleUser(currentUser, id, "无权重算其他店铺用户 VIP");
|
UserVO targetUser = requireAccessibleUser(currentUser, id, "无权重算其他店铺用户 VIP");
|
||||||
UserAssetVO assetVO = userAssetService.recalculateVip(currentUser.getId(), targetUser.getId());
|
try {
|
||||||
return Result.success(assetVO);
|
UserAssetVO assetVO = userAssetService.recalculateVip(currentUser.getId(), targetUser.getId());
|
||||||
|
securityAuditSupport.success(request, SecurityAuditActions.USER_VIP_RECALCULATE, "targetUserId=" + id);
|
||||||
|
return Result.success(assetVO);
|
||||||
|
} catch (RuntimeException exception) {
|
||||||
|
securityAuditSupport.fail(request, SecurityAuditActions.USER_VIP_RECALCULATE, "targetUserId=" + id + ",reason=" + exception.getMessage());
|
||||||
|
throw exception;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/info")
|
@GetMapping("/info")
|
||||||
|
|||||||
+22
@@ -1,6 +1,9 @@
|
|||||||
package com.xiaowang.yuminailcore.controller;
|
package com.xiaowang.yuminailcore.controller;
|
||||||
|
|
||||||
import com.xiaowang.yuminailcore.common.Result;
|
import com.xiaowang.yuminailcore.common.Result;
|
||||||
|
import com.xiaowang.yuminailcore.mapper.EffectDiagramMapper;
|
||||||
|
import com.xiaowang.yuminailcore.mapper.ProductMapper;
|
||||||
|
import com.xiaowang.yuminailcore.mapper.ShopMapper;
|
||||||
import com.xiaowang.yuminailcore.service.MinioService;
|
import com.xiaowang.yuminailcore.service.MinioService;
|
||||||
import com.xiaowang.yuminailcore.service.ObjectStorageFileService;
|
import com.xiaowang.yuminailcore.service.ObjectStorageFileService;
|
||||||
import com.xiaowang.yuminailcore.support.ObjectStorageUrlSupport;
|
import com.xiaowang.yuminailcore.support.ObjectStorageUrlSupport;
|
||||||
@@ -31,6 +34,9 @@ public class FrontendFileController {
|
|||||||
* Variable `objectStorageUrlSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
* Variable `objectStorageUrlSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||||
*/
|
*/
|
||||||
private final ObjectStorageUrlSupport objectStorageUrlSupport;
|
private final ObjectStorageUrlSupport objectStorageUrlSupport;
|
||||||
|
private final ProductMapper productMapper;
|
||||||
|
private final ShopMapper shopMapper;
|
||||||
|
private final EffectDiagramMapper effectDiagramMapper;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取带签名的图片链接。
|
* 获取带签名的图片链接。
|
||||||
@@ -47,6 +53,9 @@ public class FrontendFileController {
|
|||||||
if (fileVO == null) {
|
if (fileVO == null) {
|
||||||
return Result.error("文件不存在");
|
return Result.error("文件不存在");
|
||||||
}
|
}
|
||||||
|
if (!Integer.valueOf(1).equals(fileVO.getStatus()) || !isPublicFileReference(fileId)) {
|
||||||
|
return Result.error("文件不可公开访问");
|
||||||
|
}
|
||||||
|
|
||||||
String objectName = objectStorageUrlSupport.extractObjectName(fileVO.getFileUrl());
|
String objectName = objectStorageUrlSupport.extractObjectName(fileVO.getFileUrl());
|
||||||
if (objectName == null || objectName.isEmpty()) {
|
if (objectName == null || objectName.isEmpty()) {
|
||||||
@@ -60,4 +69,17 @@ public class FrontendFileController {
|
|||||||
return Result.error("获取签名链接失败: " + e.getMessage());
|
return Result.error("获取签名链接失败: " + e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private boolean isPublicFileReference(Long fileId) {
|
||||||
|
if (fileId == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return positive(productMapper.countPublicImageReference(fileId))
|
||||||
|
|| positive(shopMapper.countPublicImageReference(fileId))
|
||||||
|
|| positive(effectDiagramMapper.countPublicImageReference(fileId));
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean positive(Long count) {
|
||||||
|
return count != null && count > 0;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+116
-6
@@ -4,8 +4,16 @@ import com.xiaowang.yuminailcore.annotation.OperationGuard;
|
|||||||
import com.xiaowang.yuminailcore.annotation.RequirePermission;
|
import com.xiaowang.yuminailcore.annotation.RequirePermission;
|
||||||
import com.xiaowang.yuminailcore.common.Result;
|
import com.xiaowang.yuminailcore.common.Result;
|
||||||
import com.xiaowang.yuminailcore.dto.OrderDTO;
|
import com.xiaowang.yuminailcore.dto.OrderDTO;
|
||||||
|
import com.xiaowang.yuminailcore.dto.OrderArtistChangeRejectDTO;
|
||||||
|
import com.xiaowang.yuminailcore.dto.OrderArtistChangeRequestDTO;
|
||||||
|
import com.xiaowang.yuminailcore.dto.OrderArtistReviewSubmitDTO;
|
||||||
import com.xiaowang.yuminailcore.service.OrderService;
|
import com.xiaowang.yuminailcore.service.OrderService;
|
||||||
import com.xiaowang.yuminailcore.service.UserService;
|
import com.xiaowang.yuminailcore.service.UserService;
|
||||||
|
import com.xiaowang.yuminailcore.support.SecurityAuditActions;
|
||||||
|
import com.xiaowang.yuminailcore.support.SecurityAuditSupport;
|
||||||
|
import com.xiaowang.yuminailcore.vo.OrderArtistChangeOptionsVO;
|
||||||
|
import com.xiaowang.yuminailcore.vo.OrderArtistChangeRequestVO;
|
||||||
|
import com.xiaowang.yuminailcore.vo.OrderArtistReviewVO;
|
||||||
import com.xiaowang.yuminailcore.vo.OrderVO;
|
import com.xiaowang.yuminailcore.vo.OrderVO;
|
||||||
import com.xiaowang.yuminailcore.vo.UserVO;
|
import com.xiaowang.yuminailcore.vo.UserVO;
|
||||||
import org.springframework.format.annotation.DateTimeFormat;
|
import org.springframework.format.annotation.DateTimeFormat;
|
||||||
@@ -30,6 +38,9 @@ public class OrderController {
|
|||||||
@Resource
|
@Resource
|
||||||
private UserService userService;
|
private UserService userService;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private SecurityAuditSupport securityAuditSupport;
|
||||||
|
|
||||||
@PostMapping("/create")
|
@PostMapping("/create")
|
||||||
@OperationGuard(action = "order-create", ttlSeconds = 15, message = "订单正在提交中,请勿重复点击")
|
@OperationGuard(action = "order-create", ttlSeconds = 15, message = "订单正在提交中,请勿重复点击")
|
||||||
/**
|
/**
|
||||||
@@ -145,8 +156,14 @@ public class OrderController {
|
|||||||
*/
|
*/
|
||||||
throw new RuntimeException("美甲师只能完成属于自己的订单");
|
throw new RuntimeException("美甲师只能完成属于自己的订单");
|
||||||
}
|
}
|
||||||
orderService.completeArtistOrder(orderId, userId);
|
try {
|
||||||
return Result.success();
|
orderService.completeArtistOrder(orderId, userId);
|
||||||
|
securityAuditSupport.success(request, SecurityAuditActions.ORDER_PROCESS, "orderId=" + orderId + ",status=" + status + ",artistId=" + userId);
|
||||||
|
return Result.success();
|
||||||
|
} catch (RuntimeException exception) {
|
||||||
|
securityAuditSupport.fail(request, SecurityAuditActions.ORDER_PROCESS, "orderId=" + orderId + ",status=" + status + ",artistId=" + userId + ",reason=" + exception.getMessage());
|
||||||
|
throw exception;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (!Integer.valueOf(4).equals(userType)) {
|
if (!Integer.valueOf(4).equals(userType)) {
|
||||||
UserVO currentUser = userService.getUserById(userId);
|
UserVO currentUser = userService.getUserById(userId);
|
||||||
@@ -171,8 +188,14 @@ public class OrderController {
|
|||||||
throw new RuntimeException("无权处理其他店铺订单");
|
throw new RuntimeException("无权处理其他店铺订单");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
orderService.processOrder(orderId, status);
|
try {
|
||||||
return Result.success();
|
orderService.processOrder(orderId, status);
|
||||||
|
securityAuditSupport.success(request, SecurityAuditActions.ORDER_PROCESS, "orderId=" + orderId + ",status=" + status);
|
||||||
|
return Result.success();
|
||||||
|
} catch (RuntimeException exception) {
|
||||||
|
securityAuditSupport.fail(request, SecurityAuditActions.ORDER_PROCESS, "orderId=" + orderId + ",status=" + status + ",reason=" + exception.getMessage());
|
||||||
|
throw exception;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 美甲师查看自己的订单
|
// 美甲师查看自己的订单
|
||||||
@@ -244,7 +267,94 @@ public class OrderController {
|
|||||||
*/
|
*/
|
||||||
throw new RuntimeException("仅美甲师可完成自己的订单");
|
throw new RuntimeException("仅美甲师可完成自己的订单");
|
||||||
}
|
}
|
||||||
orderService.completeArtistOrder(orderId, userId);
|
try {
|
||||||
return Result.success();
|
orderService.completeArtistOrder(orderId, userId);
|
||||||
|
securityAuditSupport.success(request, SecurityAuditActions.ORDER_PROCESS, "orderId=" + orderId + ",status=2,artistId=" + userId);
|
||||||
|
return Result.success();
|
||||||
|
} catch (RuntimeException exception) {
|
||||||
|
securityAuditSupport.fail(request, SecurityAuditActions.ORDER_PROCESS, "orderId=" + orderId + ",status=2,artistId=" + userId + ",reason=" + exception.getMessage());
|
||||||
|
throw exception;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/review/my-pending")
|
||||||
|
public Result<List<OrderArtistReviewVO>> listMyPendingReviews(HttpServletRequest request) {
|
||||||
|
Long userId = (Long) request.getAttribute("userId");
|
||||||
|
return Result.success(orderService.listMyPendingReviews(userId));
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/{orderId}/reviews")
|
||||||
|
public Result<List<OrderArtistReviewVO>> listOrderReviews(@PathVariable Long orderId, HttpServletRequest request) {
|
||||||
|
Long userId = (Long) request.getAttribute("userId");
|
||||||
|
Integer userType = (Integer) request.getAttribute("userType");
|
||||||
|
return Result.success(orderService.listOrderReviews(orderId, userId, userType));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/review/{reviewId}/submit")
|
||||||
|
@OperationGuard(action = "order-artist-review-submit", ttlSeconds = 15, message = "评价正在提交中,请勿重复操作")
|
||||||
|
public Result<OrderArtistReviewVO> submitArtistReview(@PathVariable Long reviewId,
|
||||||
|
@RequestBody OrderArtistReviewSubmitDTO dto,
|
||||||
|
HttpServletRequest request) {
|
||||||
|
Long userId = (Long) request.getAttribute("userId");
|
||||||
|
return Result.success(orderService.submitArtistReview(reviewId, userId, dto));
|
||||||
|
}
|
||||||
|
|
||||||
|
@RequirePermission("order:artist-change")
|
||||||
|
@GetMapping("/{orderId}/artist-change/options")
|
||||||
|
public Result<OrderArtistChangeOptionsVO> getArtistChangeOptions(@PathVariable Long orderId,
|
||||||
|
@RequestParam Long orderItemId,
|
||||||
|
HttpServletRequest request) {
|
||||||
|
Long userId = (Long) request.getAttribute("userId");
|
||||||
|
Integer userType = (Integer) request.getAttribute("userType");
|
||||||
|
return Result.success(orderService.getArtistChangeOptions(orderId, orderItemId, userId, userType));
|
||||||
|
}
|
||||||
|
|
||||||
|
@RequirePermission("order:artist-change")
|
||||||
|
@PostMapping("/artist-change/request")
|
||||||
|
@OperationGuard(action = "order-artist-change-request", ttlSeconds = 15, message = "改派申请正在提交中,请勿重复操作")
|
||||||
|
public Result<OrderArtistChangeRequestVO> requestArtistChange(@RequestBody OrderArtistChangeRequestDTO dto,
|
||||||
|
HttpServletRequest request) {
|
||||||
|
Long userId = (Long) request.getAttribute("userId");
|
||||||
|
return Result.success(orderService.requestArtistChange(userId, dto));
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/artist-change/my-pending")
|
||||||
|
public Result<List<OrderArtistChangeRequestVO>> listMyPendingArtistChangeRequests(HttpServletRequest request) {
|
||||||
|
Long userId = (Long) request.getAttribute("userId");
|
||||||
|
Integer userType = (Integer) request.getAttribute("userType");
|
||||||
|
return Result.success(orderService.listMyPendingArtistChangeRequests(userId, userType));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PutMapping("/artist-change/{requestId}/approve")
|
||||||
|
@OperationGuard(action = "order-artist-change-approve", ttlSeconds = 15, message = "改派申请正在处理中,请勿重复操作")
|
||||||
|
public Result<OrderArtistChangeRequestVO> approveArtistChange(@PathVariable Long requestId,
|
||||||
|
HttpServletRequest request) {
|
||||||
|
Long userId = (Long) request.getAttribute("userId");
|
||||||
|
Integer userType = (Integer) request.getAttribute("userType");
|
||||||
|
try {
|
||||||
|
OrderArtistChangeRequestVO result = orderService.approveArtistChange(requestId, userId, userType);
|
||||||
|
securityAuditSupport.success(request, SecurityAuditActions.ARTIST_CHANGE_APPROVE, "requestId=" + requestId);
|
||||||
|
return Result.success(result);
|
||||||
|
} catch (RuntimeException exception) {
|
||||||
|
securityAuditSupport.fail(request, SecurityAuditActions.ARTIST_CHANGE_APPROVE, "requestId=" + requestId + ",reason=" + exception.getMessage());
|
||||||
|
throw exception;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@PutMapping("/artist-change/{requestId}/reject")
|
||||||
|
@OperationGuard(action = "order-artist-change-reject", ttlSeconds = 15, message = "改派申请正在处理中,请勿重复操作")
|
||||||
|
public Result<OrderArtistChangeRequestVO> rejectArtistChange(@PathVariable Long requestId,
|
||||||
|
@RequestBody(required = false) OrderArtistChangeRejectDTO dto,
|
||||||
|
HttpServletRequest request) {
|
||||||
|
Long userId = (Long) request.getAttribute("userId");
|
||||||
|
Integer userType = (Integer) request.getAttribute("userType");
|
||||||
|
try {
|
||||||
|
OrderArtistChangeRequestVO result = orderService.rejectArtistChange(requestId, userId, userType, dto);
|
||||||
|
securityAuditSupport.success(request, SecurityAuditActions.ARTIST_CHANGE_REJECT, "requestId=" + requestId);
|
||||||
|
return Result.success(result);
|
||||||
|
} catch (RuntimeException exception) {
|
||||||
|
securityAuditSupport.fail(request, SecurityAuditActions.ARTIST_CHANGE_REJECT, "requestId=" + requestId + ",reason=" + exception.getMessage());
|
||||||
|
throw exception;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+8
@@ -0,0 +1,8 @@
|
|||||||
|
package com.xiaowang.yuminailcore.dto;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public class OrderArtistChangeRejectDTO {
|
||||||
|
private String rejectReason;
|
||||||
|
}
|
||||||
+11
@@ -0,0 +1,11 @@
|
|||||||
|
package com.xiaowang.yuminailcore.dto;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public class OrderArtistChangeRequestDTO {
|
||||||
|
private Long orderId;
|
||||||
|
private Long orderItemId;
|
||||||
|
private Long requestedArtistId;
|
||||||
|
private String reason;
|
||||||
|
}
|
||||||
+13
@@ -0,0 +1,13 @@
|
|||||||
|
package com.xiaowang.yuminailcore.dto;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public class OrderArtistReviewSubmitDTO {
|
||||||
|
private BigDecimal rating;
|
||||||
|
private String content;
|
||||||
|
private List<Long> imageFileIds;
|
||||||
|
}
|
||||||
@@ -48,4 +48,10 @@ public class SystemMessageCreateDTO {
|
|||||||
* Field `popupEnabled` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
* Field `popupEnabled` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||||
*/
|
*/
|
||||||
private Integer popupEnabled = 1;
|
private Integer popupEnabled = 1;
|
||||||
|
|
||||||
|
private String businessType;
|
||||||
|
|
||||||
|
private Long businessId;
|
||||||
|
|
||||||
|
private String actionPath;
|
||||||
}
|
}
|
||||||
|
|||||||
+50
@@ -0,0 +1,50 @@
|
|||||||
|
package com.xiaowang.yuminailcore.entity;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableField;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableName;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.EqualsAndHashCode;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@EqualsAndHashCode(callSuper = true)
|
||||||
|
@TableName("t_business_event_outbox")
|
||||||
|
public class BusinessEventOutboxDO extends BaseEntity {
|
||||||
|
|
||||||
|
@TableField("event_key")
|
||||||
|
private String eventKey;
|
||||||
|
|
||||||
|
@TableField("event_type")
|
||||||
|
private String eventType;
|
||||||
|
|
||||||
|
@TableField("business_type")
|
||||||
|
private String businessType;
|
||||||
|
|
||||||
|
@TableField("business_id")
|
||||||
|
private Long businessId;
|
||||||
|
|
||||||
|
@TableField("payload_json")
|
||||||
|
private String payloadJson;
|
||||||
|
|
||||||
|
@TableField("status")
|
||||||
|
private String status;
|
||||||
|
|
||||||
|
@TableField("retry_count")
|
||||||
|
private Integer retryCount;
|
||||||
|
|
||||||
|
@TableField("next_retry_time")
|
||||||
|
private LocalDateTime nextRetryTime;
|
||||||
|
|
||||||
|
@TableField("last_error")
|
||||||
|
private String lastError;
|
||||||
|
|
||||||
|
@TableField("claimed_at")
|
||||||
|
private LocalDateTime claimedAt;
|
||||||
|
|
||||||
|
@TableField("processed_at")
|
||||||
|
private LocalDateTime processedAt;
|
||||||
|
|
||||||
|
@TableField("is_delete")
|
||||||
|
private Integer isDelete;
|
||||||
|
}
|
||||||
+65
@@ -0,0 +1,65 @@
|
|||||||
|
package com.xiaowang.yuminailcore.entity;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableField;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableName;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.EqualsAndHashCode;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@EqualsAndHashCode(callSuper = true)
|
||||||
|
@TableName("t_order_artist_change_request")
|
||||||
|
public class OrderArtistChangeRequestDO extends BaseEntity {
|
||||||
|
|
||||||
|
@TableField("order_id")
|
||||||
|
private Long orderId;
|
||||||
|
|
||||||
|
@TableField("order_item_id")
|
||||||
|
private Long orderItemId;
|
||||||
|
|
||||||
|
@TableField("product_id")
|
||||||
|
private Long productId;
|
||||||
|
|
||||||
|
@TableField("shop_id")
|
||||||
|
private Long shopId;
|
||||||
|
|
||||||
|
@TableField("customer_id")
|
||||||
|
private Long customerId;
|
||||||
|
|
||||||
|
@TableField("from_artist_id")
|
||||||
|
private Long fromArtistId;
|
||||||
|
|
||||||
|
@TableField("to_artist_id")
|
||||||
|
private Long toArtistId;
|
||||||
|
|
||||||
|
@TableField("requester_id")
|
||||||
|
private Long requesterId;
|
||||||
|
|
||||||
|
@TableField("status")
|
||||||
|
private String status;
|
||||||
|
|
||||||
|
@TableField("reason")
|
||||||
|
private String reason;
|
||||||
|
|
||||||
|
@TableField("reject_reason")
|
||||||
|
private String rejectReason;
|
||||||
|
|
||||||
|
@TableField("message_id")
|
||||||
|
private Long messageId;
|
||||||
|
|
||||||
|
@TableField("pending_key")
|
||||||
|
private String pendingKey;
|
||||||
|
|
||||||
|
@TableField("approved_time")
|
||||||
|
private LocalDateTime approvedTime;
|
||||||
|
|
||||||
|
@TableField("rejected_time")
|
||||||
|
private LocalDateTime rejectedTime;
|
||||||
|
|
||||||
|
@TableField("expire_time")
|
||||||
|
private LocalDateTime expireTime;
|
||||||
|
|
||||||
|
@TableField("is_delete")
|
||||||
|
private Integer isDelete;
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
package com.xiaowang.yuminailcore.entity;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableField;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableName;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.EqualsAndHashCode;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@EqualsAndHashCode(callSuper = true)
|
||||||
|
@TableName("t_order_artist_review")
|
||||||
|
public class OrderArtistReviewDO extends BaseEntity {
|
||||||
|
|
||||||
|
@TableField("order_id")
|
||||||
|
private Long orderId;
|
||||||
|
|
||||||
|
@TableField("order_item_id")
|
||||||
|
private Long orderItemId;
|
||||||
|
|
||||||
|
@TableField("product_id")
|
||||||
|
private Long productId;
|
||||||
|
|
||||||
|
@TableField("artist_id")
|
||||||
|
private Long artistId;
|
||||||
|
|
||||||
|
@TableField("shop_id")
|
||||||
|
private Long shopId;
|
||||||
|
|
||||||
|
@TableField("customer_id")
|
||||||
|
private Long customerId;
|
||||||
|
|
||||||
|
@TableField("status")
|
||||||
|
private Integer status;
|
||||||
|
|
||||||
|
@TableField("rating_score")
|
||||||
|
private BigDecimal ratingScore;
|
||||||
|
|
||||||
|
@TableField("content")
|
||||||
|
private String content;
|
||||||
|
|
||||||
|
@TableField("image_file_ids")
|
||||||
|
private String imageFileIds;
|
||||||
|
|
||||||
|
@TableField("reminder_message_id")
|
||||||
|
private Long reminderMessageId;
|
||||||
|
|
||||||
|
@TableField("submitted_at")
|
||||||
|
private LocalDateTime submittedAt;
|
||||||
|
|
||||||
|
@TableField("is_delete")
|
||||||
|
private Integer isDelete;
|
||||||
|
}
|
||||||
@@ -65,6 +65,18 @@ public class SystemMessageDO extends BaseEntity {
|
|||||||
*/
|
*/
|
||||||
private String targetIds;
|
private String targetIds;
|
||||||
|
|
||||||
|
@TableField("business_type")
|
||||||
|
private String businessType;
|
||||||
|
|
||||||
|
@TableField("business_id")
|
||||||
|
private Long businessId;
|
||||||
|
|
||||||
|
@TableField("action_path")
|
||||||
|
private String actionPath;
|
||||||
|
|
||||||
|
@TableField("idempotency_key")
|
||||||
|
private String idempotencyKey;
|
||||||
|
|
||||||
@TableField("popup_enabled")
|
@TableField("popup_enabled")
|
||||||
/**
|
/**
|
||||||
* Field `popupEnabled` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
* Field `popupEnabled` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||||
|
|||||||
+27
@@ -0,0 +1,27 @@
|
|||||||
|
package com.xiaowang.yuminailcore.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import com.xiaowang.yuminailcore.entity.BusinessEventOutboxDO;
|
||||||
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
|
import org.apache.ibatis.annotations.Param;
|
||||||
|
import org.apache.ibatis.annotations.Select;
|
||||||
|
import org.apache.ibatis.annotations.Update;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Mapper
|
||||||
|
public interface BusinessEventOutboxMapper extends BaseMapper<BusinessEventOutboxDO> {
|
||||||
|
|
||||||
|
@Select("SELECT * FROM t_business_event_outbox WHERE status IN ('PENDING', 'FAILED') AND is_delete = 0 AND (next_retry_time IS NULL OR next_retry_time <= #{now}) ORDER BY create_time ASC, id ASC LIMIT #{limit}")
|
||||||
|
List<BusinessEventOutboxDO> selectDueEvents(@Param("now") LocalDateTime now, @Param("limit") int limit);
|
||||||
|
|
||||||
|
@Update("UPDATE t_business_event_outbox SET status = 'PROCESSING', claimed_at = #{now} WHERE id = #{id} AND status IN ('PENDING', 'FAILED') AND is_delete = 0")
|
||||||
|
int claimDueEvent(@Param("id") Long id, @Param("now") LocalDateTime now);
|
||||||
|
|
||||||
|
@Update("UPDATE t_business_event_outbox SET status = 'SUCCEEDED', processed_at = #{now}, last_error = NULL WHERE id = #{id} AND status = 'PROCESSING' AND is_delete = 0")
|
||||||
|
int markSucceeded(@Param("id") Long id, @Param("now") LocalDateTime now);
|
||||||
|
|
||||||
|
@Update("UPDATE t_business_event_outbox SET status = 'FAILED', retry_count = COALESCE(retry_count, 0) + 1, next_retry_time = #{nextRetryTime}, last_error = #{lastError} WHERE id = #{id} AND status = 'PROCESSING' AND is_delete = 0")
|
||||||
|
int markFailed(@Param("id") Long id, @Param("nextRetryTime") LocalDateTime nextRetryTime, @Param("lastError") String lastError);
|
||||||
|
}
|
||||||
@@ -2,6 +2,8 @@ package com.xiaowang.yuminailcore.mapper;
|
|||||||
|
|
||||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
import com.xiaowang.yuminailcore.entity.EffectDiagramDO;
|
import com.xiaowang.yuminailcore.entity.EffectDiagramDO;
|
||||||
|
import org.apache.ibatis.annotations.Param;
|
||||||
|
import org.apache.ibatis.annotations.Select;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 商品效果图信息表 Mapper
|
* 商品效果图信息表 Mapper
|
||||||
@@ -11,4 +13,7 @@ import com.xiaowang.yuminailcore.entity.EffectDiagramDO;
|
|||||||
* @date 2026-02-13
|
* @date 2026-02-13
|
||||||
*/
|
*/
|
||||||
public interface EffectDiagramMapper extends BaseMapper<EffectDiagramDO> {
|
public interface EffectDiagramMapper extends BaseMapper<EffectDiagramDO> {
|
||||||
|
|
||||||
|
@Select("SELECT COUNT(1) FROM t_effect_diagram e INNER JOIN t_product p ON p.id = e.product_id AND p.is_delete = 0 INNER JOIN t_shop s ON s.id = p.shop_id AND s.is_delete = 0 AND s.status = 1 WHERE e.is_delete = 0 AND FIND_IN_SET(#{fileId}, REPLACE(e.image_file_ids, ' ', '')) > 0")
|
||||||
|
Long countPublicImageReference(@Param("fileId") Long fileId);
|
||||||
}
|
}
|
||||||
|
|||||||
+40
@@ -0,0 +1,40 @@
|
|||||||
|
package com.xiaowang.yuminailcore.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import com.xiaowang.yuminailcore.entity.OrderArtistChangeRequestDO;
|
||||||
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
|
import org.apache.ibatis.annotations.Param;
|
||||||
|
import org.apache.ibatis.annotations.Select;
|
||||||
|
import org.apache.ibatis.annotations.Update;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Mapper
|
||||||
|
public interface OrderArtistChangeRequestMapper extends BaseMapper<OrderArtistChangeRequestDO> {
|
||||||
|
|
||||||
|
@Select("SELECT * FROM t_order_artist_change_request WHERE order_item_id = #{orderItemId} AND status = 'PENDING' AND is_delete = 0 AND (expire_time IS NULL OR expire_time > NOW()) LIMIT 1")
|
||||||
|
OrderArtistChangeRequestDO selectPendingByOrderItemId(@Param("orderItemId") Long orderItemId);
|
||||||
|
|
||||||
|
@Select("SELECT * FROM t_order_artist_change_request WHERE customer_id = #{userId} AND status = 'PENDING' AND is_delete = 0 AND (expire_time IS NULL OR expire_time > NOW()) ORDER BY create_time DESC, id DESC")
|
||||||
|
List<OrderArtistChangeRequestDO> selectPendingByUserId(@Param("userId") Long userId);
|
||||||
|
|
||||||
|
@Select("SELECT * FROM t_order_artist_change_request WHERE (from_artist_id = #{artistId} OR to_artist_id = #{artistId} OR requester_id = #{artistId}) AND status = 'PENDING' AND is_delete = 0 AND (expire_time IS NULL OR expire_time > NOW()) ORDER BY create_time DESC, id DESC")
|
||||||
|
List<OrderArtistChangeRequestDO> selectPendingByArtistId(@Param("artistId") Long artistId);
|
||||||
|
|
||||||
|
@Select("SELECT * FROM t_order_artist_change_request WHERE shop_id = #{shopId} AND status = 'PENDING' AND is_delete = 0 AND (expire_time IS NULL OR expire_time > NOW()) ORDER BY create_time DESC, id DESC")
|
||||||
|
List<OrderArtistChangeRequestDO> selectPendingByShopId(@Param("shopId") Long shopId);
|
||||||
|
|
||||||
|
@Update("UPDATE t_order_artist_change_request SET status = 'APPROVED', approved_time = #{approvedTime}, pending_key = NULL WHERE id = #{id} AND status = 'PENDING' AND is_delete = 0 AND (expire_time IS NULL OR expire_time > #{approvedTime})")
|
||||||
|
int approvePending(@Param("id") Long id, @Param("approvedTime") LocalDateTime approvedTime);
|
||||||
|
|
||||||
|
@Update("UPDATE t_order_artist_change_request SET status = 'REJECTED', reject_reason = #{rejectReason}, rejected_time = #{rejectedTime}, pending_key = NULL WHERE id = #{id} AND status = 'PENDING' AND is_delete = 0 AND (expire_time IS NULL OR expire_time > #{rejectedTime})")
|
||||||
|
int rejectPending(@Param("id") Long id, @Param("rejectReason") String rejectReason, @Param("rejectedTime") LocalDateTime rejectedTime);
|
||||||
|
|
||||||
|
@Update("UPDATE t_order_artist_change_request SET status = 'EXPIRED', pending_key = NULL WHERE id = #{id} AND status = 'PENDING' AND is_delete = 0 AND expire_time IS NOT NULL AND expire_time <= #{now}")
|
||||||
|
int expirePendingById(@Param("id") Long id, @Param("now") LocalDateTime now);
|
||||||
|
|
||||||
|
@Update("UPDATE t_order_artist_change_request SET status = 'EXPIRED', pending_key = NULL WHERE status = 'PENDING' AND is_delete = 0 AND expire_time IS NOT NULL AND expire_time <= #{now}")
|
||||||
|
int expirePendingBefore(@Param("now") LocalDateTime now);
|
||||||
|
}
|
||||||
+26
@@ -0,0 +1,26 @@
|
|||||||
|
package com.xiaowang.yuminailcore.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import com.xiaowang.yuminailcore.entity.OrderArtistReviewDO;
|
||||||
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
|
import org.apache.ibatis.annotations.Param;
|
||||||
|
import org.apache.ibatis.annotations.Select;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Mapper
|
||||||
|
public interface OrderArtistReviewMapper extends BaseMapper<OrderArtistReviewDO> {
|
||||||
|
|
||||||
|
@Select("SELECT * FROM t_order_artist_review WHERE customer_id = #{userId} AND status = 0 AND is_delete = 0 ORDER BY create_time DESC, id DESC")
|
||||||
|
List<OrderArtistReviewDO> selectPendingByUserId(@Param("userId") Long userId);
|
||||||
|
|
||||||
|
@Select("SELECT * FROM t_order_artist_review WHERE order_id = #{orderId} AND is_delete = 0 ORDER BY create_time ASC, id ASC")
|
||||||
|
List<OrderArtistReviewDO> selectByOrderId(@Param("orderId") Long orderId);
|
||||||
|
|
||||||
|
@Select("SELECT * FROM t_order_artist_review WHERE order_item_id = #{orderItemId} AND is_delete = 0 LIMIT 1")
|
||||||
|
OrderArtistReviewDO selectByOrderItemId(@Param("orderItemId") Long orderItemId);
|
||||||
|
|
||||||
|
@Select("SELECT AVG(rating_score) FROM t_order_artist_review WHERE artist_id = #{artistId} AND status = 1 AND is_delete = 0")
|
||||||
|
BigDecimal selectAverageSubmittedRatingByArtistId(@Param("artistId") Long artistId);
|
||||||
|
}
|
||||||
@@ -18,6 +18,9 @@ public interface OrderItemMapper extends BaseMapper<OrderItemDO> {
|
|||||||
@Select("SELECT * FROM t_order_item WHERE order_id = #{orderId}")
|
@Select("SELECT * FROM t_order_item WHERE order_id = #{orderId}")
|
||||||
List<OrderItemDO> selectByOrderId(@Param("orderId") Long orderId);
|
List<OrderItemDO> selectByOrderId(@Param("orderId") Long orderId);
|
||||||
|
|
||||||
|
@Select("SELECT * FROM t_order_item WHERE id = #{id} FOR UPDATE")
|
||||||
|
OrderItemDO selectByIdForUpdate(@Param("id") Long id);
|
||||||
|
|
||||||
@Select("SELECT oi.* FROM t_order_item oi " +
|
@Select("SELECT oi.* FROM t_order_item oi " +
|
||||||
"INNER JOIN t_order o ON o.id = oi.order_id " +
|
"INNER JOIN t_order o ON o.id = oi.order_id " +
|
||||||
"WHERE oi.artist_id = #{artistId} " +
|
"WHERE oi.artist_id = #{artistId} " +
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import com.xiaowang.yuminailcore.entity.OrderDO;
|
|||||||
import org.apache.ibatis.annotations.Mapper;
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
import org.apache.ibatis.annotations.Param;
|
import org.apache.ibatis.annotations.Param;
|
||||||
import org.apache.ibatis.annotations.Select;
|
import org.apache.ibatis.annotations.Select;
|
||||||
|
import org.apache.ibatis.annotations.Update;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
@@ -25,4 +26,9 @@ public interface OrderMapper extends BaseMapper<OrderDO> {
|
|||||||
"WHERE oi.artist_id = #{artistId} AND o.is_delete = 0 " +
|
"WHERE oi.artist_id = #{artistId} AND o.is_delete = 0 " +
|
||||||
"ORDER BY o.create_time DESC")
|
"ORDER BY o.create_time DESC")
|
||||||
List<OrderDO> selectByArtistId(@Param("artistId") Long artistId);
|
List<OrderDO> selectByArtistId(@Param("artistId") Long artistId);
|
||||||
}
|
|
||||||
|
@Update("UPDATE t_order SET status = #{toStatus} WHERE id = #{orderId} AND status = #{fromStatus} AND is_delete = 0")
|
||||||
|
int updateStatusIfCurrent(@Param("orderId") Long orderId,
|
||||||
|
@Param("fromStatus") Integer fromStatus,
|
||||||
|
@Param("toStatus") Integer toStatus);
|
||||||
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package com.xiaowang.yuminailcore.mapper;
|
|||||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
import com.xiaowang.yuminailcore.entity.ProductDO;
|
import com.xiaowang.yuminailcore.entity.ProductDO;
|
||||||
import org.apache.ibatis.annotations.Param;
|
import org.apache.ibatis.annotations.Param;
|
||||||
|
import org.apache.ibatis.annotations.Select;
|
||||||
import org.apache.ibatis.annotations.Update;
|
import org.apache.ibatis.annotations.Update;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -49,4 +50,7 @@ public interface ProductMapper extends BaseMapper<ProductDO> {
|
|||||||
*/
|
*/
|
||||||
@Update("UPDATE t_product SET like_count = CASE WHEN like_count > 0 THEN like_count - 1 ELSE 0 END WHERE id = #{productId}")
|
@Update("UPDATE t_product SET like_count = CASE WHEN like_count > 0 THEN like_count - 1 ELSE 0 END WHERE id = #{productId}")
|
||||||
int decrementLikeCount(@Param("productId") Long productId);
|
int decrementLikeCount(@Param("productId") Long productId);
|
||||||
|
|
||||||
|
@Select("SELECT COUNT(1) FROM t_product p INNER JOIN t_shop s ON s.id = p.shop_id AND s.is_delete = 0 AND s.status = 1 WHERE p.is_delete = 0 AND FIND_IN_SET(#{fileId}, REPLACE(p.image_file_ids, ' ', '')) > 0")
|
||||||
|
Long countPublicImageReference(@Param("fileId") Long fileId);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ package com.xiaowang.yuminailcore.mapper;
|
|||||||
|
|
||||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
import com.xiaowang.yuminailcore.entity.ShopDO;
|
import com.xiaowang.yuminailcore.entity.ShopDO;
|
||||||
|
import org.apache.ibatis.annotations.Param;
|
||||||
|
import org.apache.ibatis.annotations.Select;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 店铺信息表 Mapper
|
* 店铺信息表 Mapper
|
||||||
@@ -11,4 +13,7 @@ import com.xiaowang.yuminailcore.entity.ShopDO;
|
|||||||
* @date 2026-02-13
|
* @date 2026-02-13
|
||||||
*/
|
*/
|
||||||
public interface ShopMapper extends BaseMapper<ShopDO> {
|
public interface ShopMapper extends BaseMapper<ShopDO> {
|
||||||
|
|
||||||
|
@Select("SELECT COUNT(1) FROM t_shop WHERE is_delete = 0 AND status = 1 AND (FIND_IN_SET(#{fileId}, REPLACE(COALESCE(cover_image_file_id, ''), ' ', '')) > 0 OR FIND_IN_SET(#{fileId}, REPLACE(COALESCE(image_file_ids, ''), ' ', '')) > 0 OR FIND_IN_SET(#{fileId}, REPLACE(COALESCE(theme_background_image_file_id, ''), ' ', '')) > 0)")
|
||||||
|
Long countPublicImageReference(@Param("fileId") Long fileId);
|
||||||
}
|
}
|
||||||
|
|||||||
+8
@@ -0,0 +1,8 @@
|
|||||||
|
package com.xiaowang.yuminailcore.service;
|
||||||
|
|
||||||
|
public interface BusinessEventOutboxService {
|
||||||
|
|
||||||
|
void enqueueOrderCompleted(Long orderId);
|
||||||
|
|
||||||
|
void processDueEvents();
|
||||||
|
}
|
||||||
@@ -1,7 +1,13 @@
|
|||||||
package com.xiaowang.yuminailcore.service;
|
package com.xiaowang.yuminailcore.service;
|
||||||
|
|
||||||
import com.xiaowang.yuminailcore.dto.OrderDTO;
|
import com.xiaowang.yuminailcore.dto.OrderDTO;
|
||||||
|
import com.xiaowang.yuminailcore.dto.OrderArtistChangeRejectDTO;
|
||||||
|
import com.xiaowang.yuminailcore.dto.OrderArtistChangeRequestDTO;
|
||||||
|
import com.xiaowang.yuminailcore.dto.OrderArtistReviewSubmitDTO;
|
||||||
import com.xiaowang.yuminailcore.vo.ArtistCalendarAppointmentVO;
|
import com.xiaowang.yuminailcore.vo.ArtistCalendarAppointmentVO;
|
||||||
|
import com.xiaowang.yuminailcore.vo.OrderArtistChangeOptionsVO;
|
||||||
|
import com.xiaowang.yuminailcore.vo.OrderArtistChangeRequestVO;
|
||||||
|
import com.xiaowang.yuminailcore.vo.OrderArtistReviewVO;
|
||||||
import com.xiaowang.yuminailcore.vo.OrderVO;
|
import com.xiaowang.yuminailcore.vo.OrderVO;
|
||||||
|
|
||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
@@ -93,4 +99,20 @@ public interface OrderService {
|
|||||||
* @return List<ArtistCalendarAppointmentVO> result consumed by the caller or returned to the frontend
|
* @return List<ArtistCalendarAppointmentVO> result consumed by the caller or returned to the frontend
|
||||||
*/
|
*/
|
||||||
List<ArtistCalendarAppointmentVO> getArtistCalendarDay(Long userId, Integer userType, LocalDate date);
|
List<ArtistCalendarAppointmentVO> getArtistCalendarDay(Long userId, Integer userType, LocalDate date);
|
||||||
|
|
||||||
|
List<OrderArtistReviewVO> listMyPendingReviews(Long userId);
|
||||||
|
|
||||||
|
List<OrderArtistReviewVO> listOrderReviews(Long orderId, Long userId, Integer userType);
|
||||||
|
|
||||||
|
OrderArtistReviewVO submitArtistReview(Long reviewId, Long userId, OrderArtistReviewSubmitDTO dto);
|
||||||
|
|
||||||
|
OrderArtistChangeOptionsVO getArtistChangeOptions(Long orderId, Long orderItemId, Long userId, Integer userType);
|
||||||
|
|
||||||
|
OrderArtistChangeRequestVO requestArtistChange(Long userId, OrderArtistChangeRequestDTO dto);
|
||||||
|
|
||||||
|
List<OrderArtistChangeRequestVO> listMyPendingArtistChangeRequests(Long userId, Integer userType);
|
||||||
|
|
||||||
|
OrderArtistChangeRequestVO approveArtistChange(Long requestId, Long userId, Integer userType);
|
||||||
|
|
||||||
|
OrderArtistChangeRequestVO rejectArtistChange(Long requestId, Long userId, Integer userType, OrderArtistChangeRejectDTO dto);
|
||||||
}
|
}
|
||||||
|
|||||||
+12
@@ -1,8 +1,20 @@
|
|||||||
package com.xiaowang.yuminailcore.service;
|
package com.xiaowang.yuminailcore.service;
|
||||||
|
|
||||||
import javax.servlet.http.HttpServletRequest;
|
import javax.servlet.http.HttpServletRequest;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
import com.xiaowang.yuminailcore.vo.PageResultVO;
|
||||||
|
import com.xiaowang.yuminailcore.vo.SecurityAuditLogVO;
|
||||||
|
|
||||||
public interface SecurityAuditLogService {
|
public interface SecurityAuditLogService {
|
||||||
|
|
||||||
void record(Long userId, String account, String action, String result, String reason, HttpServletRequest request);
|
void record(Long userId, String account, String action, String result, String reason, HttpServletRequest request);
|
||||||
|
|
||||||
|
PageResultVO<SecurityAuditLogVO> pageLogs(String account,
|
||||||
|
String action,
|
||||||
|
String result,
|
||||||
|
LocalDateTime startTime,
|
||||||
|
LocalDateTime endTime,
|
||||||
|
Integer page,
|
||||||
|
Integer size);
|
||||||
}
|
}
|
||||||
|
|||||||
+58
@@ -0,0 +1,58 @@
|
|||||||
|
package com.xiaowang.yuminailcore.service.impl;
|
||||||
|
|
||||||
|
import com.xiaowang.yuminailcore.entity.BusinessEventOutboxDO;
|
||||||
|
import com.xiaowang.yuminailcore.entity.OrderDO;
|
||||||
|
import com.xiaowang.yuminailcore.mapper.BusinessEventOutboxMapper;
|
||||||
|
import com.xiaowang.yuminailcore.mapper.OrderMapper;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.scheduling.annotation.Scheduled;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class BusinessEventOutboxProcessor {
|
||||||
|
|
||||||
|
private static final String EVENT_ORDER_COMPLETED = "ORDER_COMPLETED";
|
||||||
|
private static final int PROCESS_BATCH_SIZE = 20;
|
||||||
|
|
||||||
|
private final BusinessEventOutboxMapper outboxMapper;
|
||||||
|
private final OrderMapper orderMapper;
|
||||||
|
private final OrderServiceImpl orderService;
|
||||||
|
|
||||||
|
@Scheduled(fixedDelay = 10000L)
|
||||||
|
@Transactional
|
||||||
|
public void processDueEvents() {
|
||||||
|
LocalDateTime now = LocalDateTime.now();
|
||||||
|
List<BusinessEventOutboxDO> events = outboxMapper.selectDueEvents(now, PROCESS_BATCH_SIZE);
|
||||||
|
for (BusinessEventOutboxDO event : events) {
|
||||||
|
processOne(event);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public void processOne(BusinessEventOutboxDO event) {
|
||||||
|
if (event == null || event.getId() == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
LocalDateTime now = LocalDateTime.now();
|
||||||
|
if (outboxMapper.claimDueEvent(event.getId(), now) == 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
if (EVENT_ORDER_COMPLETED.equals(event.getEventType())) {
|
||||||
|
OrderDO order = orderMapper.selectById(event.getBusinessId());
|
||||||
|
orderService.createPendingArtistReviewTasksAndNotifyFromOutbox(order);
|
||||||
|
}
|
||||||
|
outboxMapper.markSucceeded(event.getId(), LocalDateTime.now());
|
||||||
|
} catch (Exception exception) {
|
||||||
|
int retryCount = event.getRetryCount() == null ? 0 : event.getRetryCount();
|
||||||
|
LocalDateTime nextRetryTime = LocalDateTime.now().plusSeconds(Math.min(300L, (long) Math.pow(2, retryCount) * 10L));
|
||||||
|
outboxMapper.markFailed(event.getId(), nextRetryTime,
|
||||||
|
BusinessEventOutboxServiceImpl.limit(exception.getMessage(), 500));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+57
@@ -0,0 +1,57 @@
|
|||||||
|
package com.xiaowang.yuminailcore.service.impl;
|
||||||
|
|
||||||
|
import com.xiaowang.yuminailcore.entity.BusinessEventOutboxDO;
|
||||||
|
import com.xiaowang.yuminailcore.mapper.BusinessEventOutboxMapper;
|
||||||
|
import com.xiaowang.yuminailcore.service.BusinessEventOutboxService;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.dao.DuplicateKeyException;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class BusinessEventOutboxServiceImpl implements BusinessEventOutboxService {
|
||||||
|
|
||||||
|
private static final String EVENT_ORDER_COMPLETED = "ORDER_COMPLETED";
|
||||||
|
private static final String BUSINESS_ORDER = "ORDER";
|
||||||
|
private static final String STATUS_PENDING = "PENDING";
|
||||||
|
|
||||||
|
private final BusinessEventOutboxMapper outboxMapper;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void enqueueOrderCompleted(Long orderId) {
|
||||||
|
if (orderId == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
BusinessEventOutboxDO event = new BusinessEventOutboxDO();
|
||||||
|
event.setEventKey("ORDER:" + orderId + ":COMPLETED");
|
||||||
|
event.setEventType(EVENT_ORDER_COMPLETED);
|
||||||
|
event.setBusinessType(BUSINESS_ORDER);
|
||||||
|
event.setBusinessId(orderId);
|
||||||
|
event.setPayloadJson("{\"orderId\":" + orderId + "}");
|
||||||
|
event.setStatus(STATUS_PENDING);
|
||||||
|
event.setRetryCount(0);
|
||||||
|
event.setNextRetryTime(LocalDateTime.now());
|
||||||
|
event.setIsDelete(0);
|
||||||
|
try {
|
||||||
|
outboxMapper.insert(event);
|
||||||
|
} catch (DuplicateKeyException ignored) {
|
||||||
|
// The order-completed event is idempotent by event_key.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void processDueEvents() {
|
||||||
|
// Processing is owned by BusinessEventOutboxProcessor. This method remains on
|
||||||
|
// the public service contract for callers that only need enqueue capability.
|
||||||
|
}
|
||||||
|
|
||||||
|
static String limit(String value, int max) {
|
||||||
|
if (!StringUtils.hasText(value) || value.length() <= max) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
return value.substring(0, max);
|
||||||
|
}
|
||||||
|
}
|
||||||
+775
-4
@@ -3,39 +3,55 @@ package com.xiaowang.yuminailcore.service.impl;
|
|||||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
import com.xiaowang.yuminailcore.dto.OrderDTO;
|
import com.xiaowang.yuminailcore.dto.OrderDTO;
|
||||||
|
import com.xiaowang.yuminailcore.dto.OrderArtistChangeRejectDTO;
|
||||||
|
import com.xiaowang.yuminailcore.dto.OrderArtistChangeRequestDTO;
|
||||||
|
import com.xiaowang.yuminailcore.dto.OrderArtistReviewSubmitDTO;
|
||||||
import com.xiaowang.yuminailcore.dto.OrderItemDTO;
|
import com.xiaowang.yuminailcore.dto.OrderItemDTO;
|
||||||
import com.xiaowang.yuminailcore.entity.CartDO;
|
import com.xiaowang.yuminailcore.entity.CartDO;
|
||||||
import com.xiaowang.yuminailcore.entity.CouponDO;
|
import com.xiaowang.yuminailcore.entity.CouponDO;
|
||||||
import com.xiaowang.yuminailcore.entity.NailArtistInfoDO;
|
import com.xiaowang.yuminailcore.entity.NailArtistInfoDO;
|
||||||
|
import com.xiaowang.yuminailcore.entity.OrderArtistChangeRequestDO;
|
||||||
|
import com.xiaowang.yuminailcore.entity.OrderArtistReviewDO;
|
||||||
import com.xiaowang.yuminailcore.entity.OrderDO;
|
import com.xiaowang.yuminailcore.entity.OrderDO;
|
||||||
import com.xiaowang.yuminailcore.entity.OrderItemDO;
|
import com.xiaowang.yuminailcore.entity.OrderItemDO;
|
||||||
import com.xiaowang.yuminailcore.entity.ProductDO;
|
import com.xiaowang.yuminailcore.entity.ProductDO;
|
||||||
import com.xiaowang.yuminailcore.entity.ShopDO;
|
import com.xiaowang.yuminailcore.entity.ShopDO;
|
||||||
|
import com.xiaowang.yuminailcore.entity.SystemMessageDO;
|
||||||
import com.xiaowang.yuminailcore.entity.UserCouponDO;
|
import com.xiaowang.yuminailcore.entity.UserCouponDO;
|
||||||
import com.xiaowang.yuminailcore.entity.UserDO;
|
import com.xiaowang.yuminailcore.entity.UserDO;
|
||||||
import com.xiaowang.yuminailcore.mapper.CartMapper;
|
import com.xiaowang.yuminailcore.mapper.CartMapper;
|
||||||
import com.xiaowang.yuminailcore.mapper.CouponMapper;
|
import com.xiaowang.yuminailcore.mapper.CouponMapper;
|
||||||
import com.xiaowang.yuminailcore.mapper.NailArtistInfoMapper;
|
import com.xiaowang.yuminailcore.mapper.NailArtistInfoMapper;
|
||||||
|
import com.xiaowang.yuminailcore.mapper.OrderArtistChangeRequestMapper;
|
||||||
|
import com.xiaowang.yuminailcore.mapper.OrderArtistReviewMapper;
|
||||||
import com.xiaowang.yuminailcore.mapper.OrderItemMapper;
|
import com.xiaowang.yuminailcore.mapper.OrderItemMapper;
|
||||||
import com.xiaowang.yuminailcore.mapper.OrderMapper;
|
import com.xiaowang.yuminailcore.mapper.OrderMapper;
|
||||||
import com.xiaowang.yuminailcore.mapper.ProductMapper;
|
import com.xiaowang.yuminailcore.mapper.ProductMapper;
|
||||||
import com.xiaowang.yuminailcore.mapper.ShopMapper;
|
import com.xiaowang.yuminailcore.mapper.ShopMapper;
|
||||||
|
import com.xiaowang.yuminailcore.mapper.SystemMessageMapper;
|
||||||
import com.xiaowang.yuminailcore.mapper.UserCouponMapper;
|
import com.xiaowang.yuminailcore.mapper.UserCouponMapper;
|
||||||
import com.xiaowang.yuminailcore.mapper.UserMapper;
|
import com.xiaowang.yuminailcore.mapper.UserMapper;
|
||||||
|
import com.xiaowang.yuminailcore.service.BusinessEventOutboxService;
|
||||||
import com.xiaowang.yuminailcore.service.CouponService;
|
import com.xiaowang.yuminailcore.service.CouponService;
|
||||||
import com.xiaowang.yuminailcore.service.OrderService;
|
import com.xiaowang.yuminailcore.service.OrderService;
|
||||||
import com.xiaowang.yuminailcore.service.TagService;
|
import com.xiaowang.yuminailcore.service.TagService;
|
||||||
import com.xiaowang.yuminailcore.support.BookableArtistSupport;
|
import com.xiaowang.yuminailcore.support.BookableArtistSupport;
|
||||||
import com.xiaowang.yuminailcore.support.ObjectStorageUrlSupport;
|
import com.xiaowang.yuminailcore.support.ObjectStorageUrlSupport;
|
||||||
|
import com.xiaowang.yuminailcore.support.OrderStateMachine;
|
||||||
|
import com.xiaowang.yuminailcore.support.OrderStatus;
|
||||||
import com.xiaowang.yuminailcore.support.id.TimeOrderedSnowflakeIdGenerator;
|
import com.xiaowang.yuminailcore.support.id.TimeOrderedSnowflakeIdGenerator;
|
||||||
import com.xiaowang.yuminailcore.support.UserShopBindingSupport;
|
import com.xiaowang.yuminailcore.support.UserShopBindingSupport;
|
||||||
import com.xiaowang.yuminailcore.vo.ArtistCalendarAppointmentVO;
|
import com.xiaowang.yuminailcore.vo.ArtistCalendarAppointmentVO;
|
||||||
|
import com.xiaowang.yuminailcore.vo.OrderArtistChangeOptionsVO;
|
||||||
|
import com.xiaowang.yuminailcore.vo.OrderArtistChangeRequestVO;
|
||||||
|
import com.xiaowang.yuminailcore.vo.OrderArtistReviewVO;
|
||||||
import com.xiaowang.yuminailcore.vo.OrderItemVO;
|
import com.xiaowang.yuminailcore.vo.OrderItemVO;
|
||||||
import com.xiaowang.yuminailcore.vo.OrderVO;
|
import com.xiaowang.yuminailcore.vo.OrderVO;
|
||||||
import com.xiaowang.yuminailcore.vo.TagVO;
|
import com.xiaowang.yuminailcore.vo.TagVO;
|
||||||
import com.xiaowang.yuminailcore.vo.UserCouponVO;
|
import com.xiaowang.yuminailcore.vo.UserCouponVO;
|
||||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||||
import org.springframework.data.redis.core.script.DefaultRedisScript;
|
import org.springframework.data.redis.core.script.DefaultRedisScript;
|
||||||
|
import org.springframework.dao.DuplicateKeyException;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
import org.springframework.transaction.support.TransactionTemplate;
|
import org.springframework.transaction.support.TransactionTemplate;
|
||||||
@@ -44,6 +60,7 @@ import org.springframework.util.StringUtils;
|
|||||||
import javax.annotation.Resource;
|
import javax.annotation.Resource;
|
||||||
import javax.annotation.PreDestroy;
|
import javax.annotation.PreDestroy;
|
||||||
import java.math.BigDecimal;
|
import java.math.BigDecimal;
|
||||||
|
import java.math.RoundingMode;
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
@@ -59,6 +76,7 @@ import java.util.LinkedHashMap;
|
|||||||
import java.util.LinkedHashSet;
|
import java.util.LinkedHashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
import java.util.regex.Matcher;
|
import java.util.regex.Matcher;
|
||||||
@@ -68,6 +86,7 @@ import java.util.concurrent.ScheduledExecutorService;
|
|||||||
import java.util.concurrent.ScheduledFuture;
|
import java.util.concurrent.ScheduledFuture;
|
||||||
import java.util.concurrent.ThreadFactory;
|
import java.util.concurrent.ThreadFactory;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
/**
|
/**
|
||||||
@@ -81,6 +100,16 @@ public class OrderServiceImpl implements OrderService {
|
|||||||
private static final String COUPON_SOURCE_NONE = "NONE";
|
private static final String COUPON_SOURCE_NONE = "NONE";
|
||||||
private static final String COUPON_SOURCE_USER = "USER_COUPON";
|
private static final String COUPON_SOURCE_USER = "USER_COUPON";
|
||||||
private static final String COUPON_SOURCE_SYSTEM_VIP = "SYSTEM_VIP";
|
private static final String COUPON_SOURCE_SYSTEM_VIP = "SYSTEM_VIP";
|
||||||
|
private static final int REVIEW_STATUS_PENDING = 0;
|
||||||
|
private static final int REVIEW_STATUS_SUBMITTED = 1;
|
||||||
|
private static final String CHANGE_STATUS_PENDING = "PENDING";
|
||||||
|
private static final String CHANGE_STATUS_APPROVED = "APPROVED";
|
||||||
|
private static final String CHANGE_STATUS_REJECTED = "REJECTED";
|
||||||
|
private static final String CHANGE_STATUS_EXPIRED = "EXPIRED";
|
||||||
|
private static final String ARTIST_CHANGE_PENDING_KEY_PREFIX = "ORDER_ITEM:";
|
||||||
|
private static final String MESSAGE_TARGET_SELECTED_USERS = "SELECTED_USERS";
|
||||||
|
private static final String REVIEW_BUSINESS_TYPE = "ORDER_ARTIST_REVIEW";
|
||||||
|
private static final String CHANGE_BUSINESS_TYPE = "ORDER_ARTIST_CHANGE";
|
||||||
private static final String ORDER_CREATE_USER_LOCK_PREFIX = "order:create:user:";
|
private static final String ORDER_CREATE_USER_LOCK_PREFIX = "order:create:user:";
|
||||||
private static final String ORDER_CREATE_ARTIST_LOCK_PREFIX = "order:create:artist:";
|
private static final String ORDER_CREATE_ARTIST_LOCK_PREFIX = "order:create:artist:";
|
||||||
private static final Duration ORDER_CREATE_LOCK_TTL = Duration.ofSeconds(15);
|
private static final Duration ORDER_CREATE_LOCK_TTL = Duration.ofSeconds(15);
|
||||||
@@ -123,6 +152,12 @@ public class OrderServiceImpl implements OrderService {
|
|||||||
@Resource
|
@Resource
|
||||||
private OrderItemMapper orderItemMapper;
|
private OrderItemMapper orderItemMapper;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private OrderArtistReviewMapper orderArtistReviewMapper;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private OrderArtistChangeRequestMapper orderArtistChangeRequestMapper;
|
||||||
|
|
||||||
@Resource
|
@Resource
|
||||||
private CartMapper cartMapper;
|
private CartMapper cartMapper;
|
||||||
|
|
||||||
@@ -144,6 +179,9 @@ public class OrderServiceImpl implements OrderService {
|
|||||||
@Resource
|
@Resource
|
||||||
private ShopMapper shopMapper;
|
private ShopMapper shopMapper;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private SystemMessageMapper systemMessageMapper;
|
||||||
|
|
||||||
@Resource
|
@Resource
|
||||||
private CouponService couponService;
|
private CouponService couponService;
|
||||||
|
|
||||||
@@ -156,6 +194,9 @@ public class OrderServiceImpl implements OrderService {
|
|||||||
@Resource
|
@Resource
|
||||||
private BookableArtistSupport bookableArtistSupport;
|
private BookableArtistSupport bookableArtistSupport;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private BusinessEventOutboxService businessEventOutboxService;
|
||||||
|
|
||||||
@Resource
|
@Resource
|
||||||
private TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
|
private TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
|
||||||
|
|
||||||
@@ -629,6 +670,7 @@ public class OrderServiceImpl implements OrderService {
|
|||||||
*/
|
*/
|
||||||
throw new RuntimeException("无效的订单状态");
|
throw new RuntimeException("无效的订单状态");
|
||||||
}
|
}
|
||||||
|
OrderStatus targetStatus = OrderStatus.requireKnown(status);
|
||||||
if (order.getStatus() != 1) {
|
if (order.getStatus() != 1) {
|
||||||
/**
|
/**
|
||||||
* Run business method `RuntimeException`.
|
* Run business method `RuntimeException`.
|
||||||
@@ -638,9 +680,15 @@ public class OrderServiceImpl implements OrderService {
|
|||||||
throw new RuntimeException("订单状态不允许处理");
|
throw new RuntimeException("订单状态不允许处理");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
OrderStateMachine.requireAllowedTransition(order.getStatus(), status);
|
||||||
|
if (orderMapper.updateStatusIfCurrent(order.getId(), order.getStatus(), status) == 0) {
|
||||||
|
throw new RuntimeException("订单状态已变化,请刷新后重试");
|
||||||
|
}
|
||||||
order.setStatus(status);
|
order.setStatus(status);
|
||||||
orderMapper.updateById(order);
|
if (targetStatus == OrderStatus.COMPLETED) {
|
||||||
if (status == 3) {
|
businessEventOutboxService.enqueueOrderCompleted(order.getId());
|
||||||
|
}
|
||||||
|
if (targetStatus == OrderStatus.CANCELLED) {
|
||||||
restoreUserCoupon(order, order.getUserId());
|
restoreUserCoupon(order, order.getUserId());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -694,8 +742,12 @@ public class OrderServiceImpl implements OrderService {
|
|||||||
throw new RuntimeException("只能完成全部由自己承接的订单");
|
throw new RuntimeException("只能完成全部由自己承接的订单");
|
||||||
}
|
}
|
||||||
|
|
||||||
order.setStatus(2);
|
OrderStateMachine.requireAllowedTransition(order.getStatus(), OrderStatus.COMPLETED.getCode());
|
||||||
orderMapper.updateById(order);
|
if (orderMapper.updateStatusIfCurrent(order.getId(), order.getStatus(), OrderStatus.COMPLETED.getCode()) == 0) {
|
||||||
|
throw new RuntimeException("订单状态已变化,请刷新后重试");
|
||||||
|
}
|
||||||
|
order.setStatus(OrderStatus.COMPLETED.getCode());
|
||||||
|
businessEventOutboxService.enqueueOrderCompleted(order.getId());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -818,6 +870,710 @@ public class OrderServiceImpl implements OrderService {
|
|||||||
return listArtistCalendarAppointments(userId, targetDate.atStartOfDay(), targetDate.plusDays(1).atStartOfDay());
|
return listArtistCalendarAppointments(userId, targetDate.atStartOfDay(), targetDate.plusDays(1).atStartOfDay());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<OrderArtistReviewVO> listMyPendingReviews(Long userId) {
|
||||||
|
return orderArtistReviewMapper.selectPendingByUserId(userId).stream()
|
||||||
|
.map(this::buildArtistReviewVO)
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<OrderArtistReviewVO> listOrderReviews(Long orderId, Long userId, Integer userType) {
|
||||||
|
OrderDO order = requireActiveOrder(orderId);
|
||||||
|
if (!canAccessOrder(order, userId, userType)) {
|
||||||
|
throw new RuntimeException("无权查看该订单评价");
|
||||||
|
}
|
||||||
|
return orderArtistReviewMapper.selectByOrderId(orderId).stream()
|
||||||
|
.map(this::buildArtistReviewVO)
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional
|
||||||
|
public OrderArtistReviewVO submitArtistReview(Long reviewId, Long userId, OrderArtistReviewSubmitDTO dto) {
|
||||||
|
OrderArtistReviewDO review = orderArtistReviewMapper.selectById(reviewId);
|
||||||
|
if (review == null || Integer.valueOf(1).equals(review.getIsDelete())) {
|
||||||
|
throw new RuntimeException("评价任务不存在");
|
||||||
|
}
|
||||||
|
if (!Objects.equals(userId, review.getCustomerId())) {
|
||||||
|
throw new RuntimeException("只能提交自己的评价");
|
||||||
|
}
|
||||||
|
if (!Integer.valueOf(REVIEW_STATUS_PENDING).equals(review.getStatus())) {
|
||||||
|
throw new RuntimeException("评价已提交,不能重复提交");
|
||||||
|
}
|
||||||
|
|
||||||
|
BigDecimal rating = normalizeReviewRating(dto == null ? null : dto.getRating());
|
||||||
|
review.setRatingScore(rating);
|
||||||
|
review.setContent(trimToNull(dto == null ? null : dto.getContent()));
|
||||||
|
review.setImageFileIds(joinLongIds(dto == null ? null : dto.getImageFileIds()));
|
||||||
|
review.setStatus(REVIEW_STATUS_SUBMITTED);
|
||||||
|
review.setSubmittedAt(LocalDateTime.now());
|
||||||
|
orderArtistReviewMapper.updateById(review);
|
||||||
|
refreshArtistRating(review.getArtistId());
|
||||||
|
return buildArtistReviewVO(review);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public OrderArtistChangeOptionsVO getArtistChangeOptions(Long orderId, Long orderItemId, Long userId, Integer userType) {
|
||||||
|
OrderDO order = requireActiveOrder(orderId);
|
||||||
|
if (!canAccessOrder(order, userId, userType)) {
|
||||||
|
throw new RuntimeException("无权查看该订单改派选项");
|
||||||
|
}
|
||||||
|
OrderItemDO item = requireOrderItem(orderItemId, orderId);
|
||||||
|
ProductDO product = requireActiveProduct(item.getProductId());
|
||||||
|
|
||||||
|
OrderArtistChangeOptionsVO vo = new OrderArtistChangeOptionsVO();
|
||||||
|
vo.setOrderId(orderId);
|
||||||
|
vo.setOrderItemId(orderItemId);
|
||||||
|
vo.setCurrentArtistId(item.getArtistId());
|
||||||
|
UserDO currentArtist = item.getArtistId() == null ? null : userMapper.selectById(item.getArtistId());
|
||||||
|
vo.setCurrentArtistName(currentArtist == null ? null : currentArtist.getNickname());
|
||||||
|
vo.setArtists(parseIdSet(product.getBookableArtists()).stream()
|
||||||
|
.filter(artistId -> !Objects.equals(artistId, item.getArtistId()))
|
||||||
|
.filter(artistId -> isArtistAvailableForItem(order.getShopId(), artistId, item, product))
|
||||||
|
.map(this::buildArtistOptionVO)
|
||||||
|
.filter(Objects::nonNull)
|
||||||
|
.toList());
|
||||||
|
return vo;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional
|
||||||
|
public OrderArtistChangeRequestVO requestArtistChange(Long userId, OrderArtistChangeRequestDTO dto) {
|
||||||
|
if (dto == null || dto.getOrderId() == null || dto.getOrderItemId() == null || dto.getRequestedArtistId() == null) {
|
||||||
|
throw new RuntimeException("改派申请信息不完整");
|
||||||
|
}
|
||||||
|
ensureArtistChangeRequester(userId);
|
||||||
|
OrderDO order = requireActiveOrder(dto.getOrderId());
|
||||||
|
if (!canAccessOrder(order, userId, null)) {
|
||||||
|
throw new RuntimeException("只能为自己的订单申请改派");
|
||||||
|
}
|
||||||
|
if (!Integer.valueOf(1).equals(order.getStatus())) {
|
||||||
|
throw new RuntimeException("仅待服务订单允许申请改派");
|
||||||
|
}
|
||||||
|
OrderItemDO item = requireOrderItemForUpdate(dto.getOrderItemId(), order.getId());
|
||||||
|
if (!canRequestArtistChangeForItem(order, item, userId)) {
|
||||||
|
throw new RuntimeException("只能为自己承接的待服务订单项申请改派");
|
||||||
|
}
|
||||||
|
if (item.getArtistId() == null) {
|
||||||
|
throw new RuntimeException("订单项未分配美甲师");
|
||||||
|
}
|
||||||
|
if (Objects.equals(item.getArtistId(), dto.getRequestedArtistId())) {
|
||||||
|
throw new RuntimeException("新美甲师不能与原美甲师相同");
|
||||||
|
}
|
||||||
|
if (orderArtistChangeRequestMapper.selectPendingByOrderItemId(item.getId()) != null) {
|
||||||
|
throw new RuntimeException("该订单项已有待处理改派申请");
|
||||||
|
}
|
||||||
|
ProductDO product = requireActiveProduct(item.getProductId());
|
||||||
|
validateRequestedArtistForItem(order.getShopId(), dto.getRequestedArtistId(), item, product);
|
||||||
|
|
||||||
|
OrderArtistChangeRequestDO request = new OrderArtistChangeRequestDO();
|
||||||
|
request.setOrderId(order.getId());
|
||||||
|
request.setOrderItemId(item.getId());
|
||||||
|
request.setProductId(item.getProductId());
|
||||||
|
request.setShopId(order.getShopId());
|
||||||
|
request.setCustomerId(order.getUserId());
|
||||||
|
request.setFromArtistId(item.getArtistId());
|
||||||
|
request.setToArtistId(dto.getRequestedArtistId());
|
||||||
|
request.setRequesterId(userId);
|
||||||
|
request.setStatus(CHANGE_STATUS_PENDING);
|
||||||
|
request.setReason(trimToNull(dto.getReason()));
|
||||||
|
request.setPendingKey(buildArtistChangePendingKey(item.getId()));
|
||||||
|
request.setExpireTime(LocalDateTime.now().plusDays(2));
|
||||||
|
request.setIsDelete(0);
|
||||||
|
try {
|
||||||
|
orderArtistChangeRequestMapper.insert(request);
|
||||||
|
} catch (DuplicateKeyException exception) {
|
||||||
|
throw new RuntimeException("该订单项已有待处理改派申请");
|
||||||
|
}
|
||||||
|
createArtistChangeMessage(order, request);
|
||||||
|
return buildArtistChangeRequestVO(request);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<OrderArtistChangeRequestVO> listMyPendingArtistChangeRequests(Long userId, Integer userType) {
|
||||||
|
expireDueArtistChangeRequests();
|
||||||
|
List<OrderArtistChangeRequestDO> requests;
|
||||||
|
if (Integer.valueOf(2).equals(userType)) {
|
||||||
|
UserDO user = userMapper.selectById(userId);
|
||||||
|
requests = user != null && user.getShopId() != null
|
||||||
|
? orderArtistChangeRequestMapper.selectPendingByShopId(user.getShopId())
|
||||||
|
: orderArtistChangeRequestMapper.selectPendingByArtistId(userId);
|
||||||
|
} else if (Integer.valueOf(3).equals(userType)) {
|
||||||
|
requests = orderArtistChangeRequestMapper.selectPendingByArtistId(userId);
|
||||||
|
} else {
|
||||||
|
requests = orderArtistChangeRequestMapper.selectPendingByUserId(userId);
|
||||||
|
}
|
||||||
|
return requests.stream()
|
||||||
|
.map(this::buildArtistChangeRequestVO)
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional
|
||||||
|
public OrderArtistChangeRequestVO approveArtistChange(Long requestId, Long userId, Integer userType) {
|
||||||
|
OrderArtistChangeRequestDO request = requirePendingArtistChangeRequest(requestId);
|
||||||
|
assertCanProcessArtistChange(request, userId, userType);
|
||||||
|
|
||||||
|
OrderDO order = requireActiveOrder(request.getOrderId());
|
||||||
|
if (!Integer.valueOf(1).equals(order.getStatus())) {
|
||||||
|
throw new RuntimeException("仅待服务订单允许改派");
|
||||||
|
}
|
||||||
|
if (!Objects.equals(order.getUserId(), request.getCustomerId())) {
|
||||||
|
throw new RuntimeException("改派申请客户与订单不匹配");
|
||||||
|
}
|
||||||
|
|
||||||
|
OrderItemDO item = orderItemMapper.selectByIdForUpdate(request.getOrderItemId());
|
||||||
|
if (item == null || Integer.valueOf(1).equals(item.getIsDelete()) || !Objects.equals(item.getOrderId(), order.getId())) {
|
||||||
|
throw new RuntimeException("订单项不存在");
|
||||||
|
}
|
||||||
|
if (!Objects.equals(item.getArtistId(), request.getFromArtistId())) {
|
||||||
|
throw new RuntimeException("原美甲师已变更,无法继续改派");
|
||||||
|
}
|
||||||
|
|
||||||
|
ProductDO product = requireActiveProduct(item.getProductId());
|
||||||
|
validateRequestedArtistForItem(order.getShopId(), request.getToArtistId(), item, product);
|
||||||
|
|
||||||
|
LocalDateTime approvedTime = LocalDateTime.now();
|
||||||
|
if (orderArtistChangeRequestMapper.approvePending(request.getId(), approvedTime) == 0) {
|
||||||
|
throw new RuntimeException("改派申请已处理");
|
||||||
|
}
|
||||||
|
item.setArtistId(request.getToArtistId());
|
||||||
|
orderItemMapper.updateById(item);
|
||||||
|
request.setStatus(CHANGE_STATUS_APPROVED);
|
||||||
|
request.setApprovedTime(approvedTime);
|
||||||
|
request.setPendingKey(null);
|
||||||
|
return buildArtistChangeRequestVO(request);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional
|
||||||
|
public OrderArtistChangeRequestVO rejectArtistChange(Long requestId, Long userId, Integer userType, OrderArtistChangeRejectDTO dto) {
|
||||||
|
OrderArtistChangeRequestDO request = requirePendingArtistChangeRequest(requestId);
|
||||||
|
assertCanProcessArtistChange(request, userId, userType);
|
||||||
|
LocalDateTime rejectedTime = LocalDateTime.now();
|
||||||
|
String rejectReason = trimToNull(dto == null ? null : dto.getRejectReason());
|
||||||
|
if (orderArtistChangeRequestMapper.rejectPending(request.getId(), rejectReason, rejectedTime) == 0) {
|
||||||
|
throw new RuntimeException("改派申请已处理");
|
||||||
|
}
|
||||||
|
request.setStatus(CHANGE_STATUS_REJECTED);
|
||||||
|
request.setRejectReason(rejectReason);
|
||||||
|
request.setRejectedTime(rejectedTime);
|
||||||
|
request.setPendingKey(null);
|
||||||
|
return buildArtistChangeRequestVO(request);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void createPendingArtistReviewTasksAndNotifyFromOutbox(OrderDO order) {
|
||||||
|
createPendingArtistReviewTasksAndNotify(order);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void createPendingArtistReviewTasksAndNotify(OrderDO order) {
|
||||||
|
if (order == null || order.getId() == null || !Integer.valueOf(2).equals(order.getStatus())) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
List<OrderItemDO> items = orderItemMapper.selectByOrderId(order.getId());
|
||||||
|
if (items == null || items.isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (OrderItemDO item : items) {
|
||||||
|
if (item == null
|
||||||
|
|| item.getId() == null
|
||||||
|
|| Integer.valueOf(1).equals(item.getIsDelete())
|
||||||
|
|| item.getArtistId() == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (orderArtistReviewMapper.selectByOrderItemId(item.getId()) != null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
ProductDO product = getProductFromCache(item.getProductId(), new HashMap<>());
|
||||||
|
OrderArtistReviewDO review = new OrderArtistReviewDO();
|
||||||
|
review.setOrderId(order.getId());
|
||||||
|
review.setOrderItemId(item.getId());
|
||||||
|
review.setProductId(item.getProductId());
|
||||||
|
review.setShopId(order.getShopId());
|
||||||
|
review.setArtistId(item.getArtistId());
|
||||||
|
review.setCustomerId(order.getUserId());
|
||||||
|
review.setStatus(REVIEW_STATUS_PENDING);
|
||||||
|
review.setIsDelete(0);
|
||||||
|
review = insertPendingArtistReview(review);
|
||||||
|
if (review == null || review.getId() == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Long messageId = createReviewReminderMessage(order, item, product, review);
|
||||||
|
if (messageId != null) {
|
||||||
|
review.setReminderMessageId(messageId);
|
||||||
|
orderArtistReviewMapper.updateById(review);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private OrderArtistReviewDO insertPendingArtistReview(OrderArtistReviewDO review) {
|
||||||
|
try {
|
||||||
|
orderArtistReviewMapper.insert(review);
|
||||||
|
return review;
|
||||||
|
} catch (DuplicateKeyException exception) {
|
||||||
|
OrderArtistReviewDO existingReview = review == null || review.getOrderItemId() == null
|
||||||
|
? null
|
||||||
|
: orderArtistReviewMapper.selectByOrderItemId(review.getOrderItemId());
|
||||||
|
if (existingReview != null) {
|
||||||
|
return existingReview;
|
||||||
|
}
|
||||||
|
throw exception;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Long createReviewReminderMessage(OrderDO order, OrderItemDO item, ProductDO product, OrderArtistReviewDO review) {
|
||||||
|
String productTitle = product == null ? "订单项目" : product.getTitle();
|
||||||
|
UserDO artist = item == null || item.getArtistId() == null ? null : userMapper.selectById(item.getArtistId());
|
||||||
|
String artistName = artist == null || !StringUtils.hasText(artist.getNickname()) ? "美甲师" : artist.getNickname();
|
||||||
|
return createSystemBusinessMessage(
|
||||||
|
order == null ? null : order.getUserId(),
|
||||||
|
"订单已完成,记得评价美甲师",
|
||||||
|
"您预约的「" + productTitle + "」已完成,请为" + artistName + "提交本次服务评价。",
|
||||||
|
REVIEW_BUSINESS_TYPE,
|
||||||
|
review == null ? null : review.getId(),
|
||||||
|
order == null ? null : "/orders?orderId=" + order.getId(),
|
||||||
|
0L,
|
||||||
|
"系统通知",
|
||||||
|
4
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private OrderArtistReviewVO buildArtistReviewVO(OrderArtistReviewDO review) {
|
||||||
|
if (review == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
OrderArtistReviewVO vo = new OrderArtistReviewVO();
|
||||||
|
vo.setId(review.getId());
|
||||||
|
vo.setOrderId(review.getOrderId());
|
||||||
|
vo.setOrderItemId(review.getOrderItemId());
|
||||||
|
vo.setProductId(review.getProductId());
|
||||||
|
ProductDO product = getProductFromCache(review.getProductId(), new HashMap<>());
|
||||||
|
vo.setProductTitle(product == null ? null : product.getTitle());
|
||||||
|
vo.setArtistId(review.getArtistId());
|
||||||
|
UserDO artist = review.getArtistId() == null ? null : userMapper.selectById(review.getArtistId());
|
||||||
|
vo.setArtistName(artist == null ? null : artist.getNickname());
|
||||||
|
vo.setArtistAvatar(artist == null ? null : objectStorageUrlSupport.toAccessibleUrl(artist.getAvatar()));
|
||||||
|
vo.setUserId(review.getCustomerId());
|
||||||
|
vo.setCustomerId(review.getCustomerId());
|
||||||
|
vo.setRating(review.getRatingScore());
|
||||||
|
vo.setRatingScore(review.getRatingScore());
|
||||||
|
vo.setContent(review.getContent());
|
||||||
|
vo.setImageFileIds(new ArrayList<>(parseIdSet(review.getImageFileIds())));
|
||||||
|
vo.setStatus(review.getStatus());
|
||||||
|
vo.setStatusText(Integer.valueOf(REVIEW_STATUS_SUBMITTED).equals(review.getStatus()) ? "已评价" : "待评价");
|
||||||
|
vo.setReminderMessageId(review.getReminderMessageId());
|
||||||
|
vo.setSubmitTime(review.getSubmittedAt());
|
||||||
|
vo.setSubmittedAt(review.getSubmittedAt());
|
||||||
|
vo.setCreateTime(review.getCreateTime());
|
||||||
|
return vo;
|
||||||
|
}
|
||||||
|
|
||||||
|
private OrderDO requireActiveOrder(Long orderId) {
|
||||||
|
if (orderId == null) {
|
||||||
|
throw new RuntimeException("订单信息不完整");
|
||||||
|
}
|
||||||
|
OrderDO order = orderMapper.selectById(orderId);
|
||||||
|
if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) {
|
||||||
|
throw new RuntimeException("订单不存在");
|
||||||
|
}
|
||||||
|
return order;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean canAccessOrder(OrderDO order, Long userId, Integer userType) {
|
||||||
|
if (order == null || userId == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (Objects.equals(order.getUserId(), userId)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
UserDO user = userMapper.selectById(userId);
|
||||||
|
Integer effectiveType = userType == null && user != null ? user.getType() : userType;
|
||||||
|
if (Integer.valueOf(4).equals(effectiveType)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (order.getShopId() != null && userShopBindingSupport.isUserAccessibleInShop(userId, order.getShopId())) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
List<OrderItemDO> items = orderItemMapper.selectByOrderId(order.getId());
|
||||||
|
return items != null && items.stream()
|
||||||
|
.filter(item -> item != null && !Integer.valueOf(1).equals(item.getIsDelete()))
|
||||||
|
.anyMatch(item -> Objects.equals(item.getArtistId(), userId));
|
||||||
|
}
|
||||||
|
|
||||||
|
private BigDecimal normalizeReviewRating(BigDecimal rating) {
|
||||||
|
if (rating == null) {
|
||||||
|
throw new RuntimeException("评分不能为空");
|
||||||
|
}
|
||||||
|
BigDecimal normalized;
|
||||||
|
try {
|
||||||
|
normalized = rating.setScale(1, RoundingMode.UNNECESSARY);
|
||||||
|
} catch (ArithmeticException exception) {
|
||||||
|
throw new RuntimeException("评分必须按0.5分递增");
|
||||||
|
}
|
||||||
|
if (normalized.compareTo(new BigDecimal("0.5")) < 0 || normalized.compareTo(new BigDecimal("5.0")) > 0) {
|
||||||
|
throw new RuntimeException("评分必须在0.5到5分之间");
|
||||||
|
}
|
||||||
|
BigDecimal doubled = normalized.multiply(new BigDecimal("2"));
|
||||||
|
if (doubled.stripTrailingZeros().scale() > 0) {
|
||||||
|
throw new RuntimeException("评分必须按0.5分递增");
|
||||||
|
}
|
||||||
|
return normalized;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String trimToNull(String value) {
|
||||||
|
if (!StringUtils.hasText(value)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return value.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
private String joinLongIds(List<Long> ids) {
|
||||||
|
if (ids == null || ids.isEmpty()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String joined = ids.stream()
|
||||||
|
.filter(Objects::nonNull)
|
||||||
|
.distinct()
|
||||||
|
.map(String::valueOf)
|
||||||
|
.collect(Collectors.joining(","));
|
||||||
|
return joined.isBlank() ? null : joined;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Set<Long> parseIdSet(String rawIds) {
|
||||||
|
if (!StringUtils.hasText(rawIds)) {
|
||||||
|
return Collections.emptySet();
|
||||||
|
}
|
||||||
|
LinkedHashSet<Long> result = new LinkedHashSet<>();
|
||||||
|
for (String part : rawIds.split("[,;]")) {
|
||||||
|
if (!StringUtils.hasText(part)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
result.add(Long.parseLong(part.trim()));
|
||||||
|
} catch (NumberFormatException ignored) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void refreshArtistRating(Long artistId) {
|
||||||
|
if (artistId == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
BigDecimal average = orderArtistReviewMapper.selectAverageSubmittedRatingByArtistId(artistId);
|
||||||
|
if (average == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
NailArtistInfoDO artistInfo = getArtistInfoByUserId(artistId);
|
||||||
|
if (artistInfo == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
artistInfo.setRating(average.setScale(1, RoundingMode.HALF_UP));
|
||||||
|
nailArtistInfoMapper.updateById(artistInfo);
|
||||||
|
}
|
||||||
|
|
||||||
|
private OrderItemDO requireOrderItem(Long orderItemId, Long orderId) {
|
||||||
|
return requireOrderItem(orderItemId, orderId, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private OrderItemDO requireOrderItemForUpdate(Long orderItemId, Long orderId) {
|
||||||
|
return requireOrderItem(orderItemId, orderId, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String buildArtistChangePendingKey(Long orderItemId) {
|
||||||
|
return orderItemId == null ? null : ARTIST_CHANGE_PENDING_KEY_PREFIX + orderItemId;
|
||||||
|
}
|
||||||
|
|
||||||
|
private OrderItemDO requireOrderItem(Long orderItemId, Long orderId, boolean forUpdate) {
|
||||||
|
if (orderItemId == null) {
|
||||||
|
throw new RuntimeException("订单项信息不完整");
|
||||||
|
}
|
||||||
|
OrderItemDO item = forUpdate
|
||||||
|
? orderItemMapper.selectByIdForUpdate(orderItemId)
|
||||||
|
: orderItemMapper.selectById(orderItemId);
|
||||||
|
if (item == null || Integer.valueOf(1).equals(item.getIsDelete()) || !Objects.equals(item.getOrderId(), orderId)) {
|
||||||
|
throw new RuntimeException("订单项不存在");
|
||||||
|
}
|
||||||
|
return item;
|
||||||
|
}
|
||||||
|
|
||||||
|
private ProductDO requireActiveProduct(Long productId) {
|
||||||
|
ProductDO product = getProductFromCache(productId, new HashMap<>());
|
||||||
|
if (product == null) {
|
||||||
|
throw new RuntimeException("商品不存在或已删除");
|
||||||
|
}
|
||||||
|
return product;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isArtistAvailableForItem(Long shopId, Long artistId, OrderItemDO item, ProductDO product) {
|
||||||
|
try {
|
||||||
|
validateRequestedArtistForItem(shopId, artistId, item, product);
|
||||||
|
return true;
|
||||||
|
} catch (RuntimeException exception) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private OrderArtistChangeOptionsVO.ArtistOptionVO buildArtistOptionVO(Long artistId) {
|
||||||
|
UserDO artist = userMapper.selectById(artistId);
|
||||||
|
if (artist == null || Integer.valueOf(1).equals(artist.getIsDelete()) || !bookableArtistSupport.isBookableServiceUser(artist)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
NailArtistInfoDO info = getArtistInfoByUserId(artistId);
|
||||||
|
OrderArtistChangeOptionsVO.ArtistOptionVO vo = new OrderArtistChangeOptionsVO.ArtistOptionVO();
|
||||||
|
vo.setArtistId(artist.getId());
|
||||||
|
vo.setArtistName(artist.getNickname());
|
||||||
|
vo.setArtistAvatar(objectStorageUrlSupport.toAccessibleUrl(artist.getAvatar()));
|
||||||
|
vo.setUserType(artist.getType());
|
||||||
|
vo.setParticipateProduction(info != null && Integer.valueOf(1).equals(info.getParticipateProduction()));
|
||||||
|
return vo;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void validateRequestedArtistForItem(Long shopId, Long artistId, OrderItemDO item, ProductDO product) {
|
||||||
|
validateArtistForProduct(product, artistId);
|
||||||
|
if (!bookableArtistSupport.isValidBookableArtist(shopId, artistId)) {
|
||||||
|
throw new RuntimeException("新美甲师不可预约或不属于当前店铺");
|
||||||
|
}
|
||||||
|
if (item == null || item.getAppointmentTime() == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
int quantity = Math.max(1, item.getQuantity() == null ? 1 : item.getQuantity());
|
||||||
|
long durationMinutes = resolveServiceDurationMinutes(product) * quantity;
|
||||||
|
LocalDateTime startTime = item.getAppointmentTime();
|
||||||
|
LocalDateTime endTime = startTime.plusMinutes(durationMinutes);
|
||||||
|
validateBusinessHours(getShopFromCache(shopId == null ? product.getShopId() : shopId, new HashMap<>()), startTime, endTime, product.getTitle());
|
||||||
|
validateArtistScheduleConflicts(artistId, Collections.singletonList(new AppointmentSlot(product.getTitle(), startTime, endTime)), new HashMap<>());
|
||||||
|
}
|
||||||
|
|
||||||
|
private Long createArtistChangeMessage(OrderDO order, OrderArtistChangeRequestDO request) {
|
||||||
|
ProductDO product = getProductFromCache(request.getProductId(), new HashMap<>());
|
||||||
|
UserDO fromArtist = request.getFromArtistId() == null ? null : userMapper.selectById(request.getFromArtistId());
|
||||||
|
UserDO toArtist = request.getToArtistId() == null ? null : userMapper.selectById(request.getToArtistId());
|
||||||
|
String fromName = fromArtist == null || !StringUtils.hasText(fromArtist.getNickname()) ? "原美甲师" : fromArtist.getNickname();
|
||||||
|
String toName = toArtist == null || !StringUtils.hasText(toArtist.getNickname()) ? "新美甲师" : toArtist.getNickname();
|
||||||
|
Long messageId = createSystemBusinessMessage(
|
||||||
|
request.getCustomerId(),
|
||||||
|
"美甲师改派申请待确认",
|
||||||
|
"您的订单项目「" + (product == null ? "订单项目" : product.getTitle()) + "」申请由" + fromName + "改派给" + toName + ",请在订单页确认。",
|
||||||
|
CHANGE_BUSINESS_TYPE,
|
||||||
|
request.getId(),
|
||||||
|
order == null ? null : "/orders?orderId=" + order.getId(),
|
||||||
|
request.getRequesterId(),
|
||||||
|
fromName,
|
||||||
|
3
|
||||||
|
);
|
||||||
|
if (messageId != null) {
|
||||||
|
request.setMessageId(messageId);
|
||||||
|
orderArtistChangeRequestMapper.updateById(request);
|
||||||
|
}
|
||||||
|
return messageId;
|
||||||
|
}
|
||||||
|
|
||||||
|
private OrderArtistChangeRequestVO buildArtistChangeRequestVO(OrderArtistChangeRequestDO request) {
|
||||||
|
if (request == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
OrderArtistChangeRequestVO vo = new OrderArtistChangeRequestVO();
|
||||||
|
vo.setId(request.getId());
|
||||||
|
vo.setOrderId(request.getOrderId());
|
||||||
|
vo.setOrderItemId(request.getOrderItemId());
|
||||||
|
vo.setProductId(request.getProductId());
|
||||||
|
ProductDO product = getProductFromCache(request.getProductId(), new HashMap<>());
|
||||||
|
vo.setProductTitle(product == null ? null : product.getTitle());
|
||||||
|
vo.setShopId(request.getShopId());
|
||||||
|
vo.setUserId(request.getCustomerId());
|
||||||
|
vo.setCustomerId(request.getCustomerId());
|
||||||
|
vo.setOriginalArtistId(request.getFromArtistId());
|
||||||
|
vo.setFromArtistId(request.getFromArtistId());
|
||||||
|
UserDO fromArtist = request.getFromArtistId() == null ? null : userMapper.selectById(request.getFromArtistId());
|
||||||
|
vo.setOriginalArtistName(fromArtist == null ? null : fromArtist.getNickname());
|
||||||
|
vo.setFromArtistName(fromArtist == null ? null : fromArtist.getNickname());
|
||||||
|
vo.setRequestedArtistId(request.getToArtistId());
|
||||||
|
vo.setToArtistId(request.getToArtistId());
|
||||||
|
UserDO toArtist = request.getToArtistId() == null ? null : userMapper.selectById(request.getToArtistId());
|
||||||
|
vo.setRequestedArtistName(toArtist == null ? null : toArtist.getNickname());
|
||||||
|
vo.setToArtistName(toArtist == null ? null : toArtist.getNickname());
|
||||||
|
vo.setRequesterId(request.getRequesterId());
|
||||||
|
UserDO requester = request.getRequesterId() == null ? null : userMapper.selectById(request.getRequesterId());
|
||||||
|
vo.setRequesterName(requester == null ? null : requester.getNickname());
|
||||||
|
vo.setStatus(request.getStatus());
|
||||||
|
vo.setStatusText(resolveArtistChangeStatusText(request.getStatus()));
|
||||||
|
vo.setReason(request.getReason());
|
||||||
|
vo.setRejectReason(request.getRejectReason());
|
||||||
|
vo.setReviewerId(request.getCustomerId());
|
||||||
|
vo.setMessageId(request.getMessageId());
|
||||||
|
vo.setReviewTime(request.getApprovedTime() != null ? request.getApprovedTime() : request.getRejectedTime());
|
||||||
|
vo.setApprovedTime(request.getApprovedTime());
|
||||||
|
vo.setRejectedTime(request.getRejectedTime());
|
||||||
|
vo.setExpireTime(request.getExpireTime());
|
||||||
|
vo.setCreateTime(request.getCreateTime());
|
||||||
|
return vo;
|
||||||
|
}
|
||||||
|
|
||||||
|
private OrderArtistChangeRequestDO requirePendingArtistChangeRequest(Long requestId) {
|
||||||
|
if (requestId == null) {
|
||||||
|
throw new RuntimeException("改派申请信息不完整");
|
||||||
|
}
|
||||||
|
OrderArtistChangeRequestDO request = orderArtistChangeRequestMapper.selectById(requestId);
|
||||||
|
if (request == null || Integer.valueOf(1).equals(request.getIsDelete())) {
|
||||||
|
throw new RuntimeException("改派申请不存在");
|
||||||
|
}
|
||||||
|
if (!CHANGE_STATUS_PENDING.equals(request.getStatus())) {
|
||||||
|
throw new RuntimeException("改派申请已处理");
|
||||||
|
}
|
||||||
|
LocalDateTime now = LocalDateTime.now();
|
||||||
|
if (request.getExpireTime() != null && !request.getExpireTime().isAfter(now)) {
|
||||||
|
orderArtistChangeRequestMapper.expirePendingById(request.getId(), now);
|
||||||
|
request.setStatus(CHANGE_STATUS_EXPIRED);
|
||||||
|
request.setPendingKey(null);
|
||||||
|
throw new RuntimeException("改派申请已过期");
|
||||||
|
}
|
||||||
|
return request;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void assertCanProcessArtistChange(OrderArtistChangeRequestDO request, Long userId, Integer userType) {
|
||||||
|
if (request == null || userId == null || !Objects.equals(request.getCustomerId(), userId)) {
|
||||||
|
throw new RuntimeException("仅订单客户可以处理改派申请");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@org.springframework.scheduling.annotation.Scheduled(fixedDelay = 300000L)
|
||||||
|
public void expireDueArtistChangeRequests() {
|
||||||
|
orderArtistChangeRequestMapper.expirePendingBefore(LocalDateTime.now());
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean canRequestArtistChangeForItem(OrderDO order, OrderItemDO item, Long userId) {
|
||||||
|
if (order == null || item == null || userId == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (Objects.equals(item.getArtistId(), userId)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
UserDO user = userMapper.selectById(userId);
|
||||||
|
if (user == null || !Integer.valueOf(2).equals(user.getType())) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
NailArtistInfoDO info = getArtistInfoByUserId(userId);
|
||||||
|
return info != null
|
||||||
|
&& Integer.valueOf(1).equals(info.getParticipateProduction())
|
||||||
|
&& order.getShopId() != null
|
||||||
|
&& userShopBindingSupport.isUserAccessibleInShop(userId, order.getShopId());
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ensureArtistChangeRequester(Long userId) {
|
||||||
|
UserDO user = userMapper.selectById(userId);
|
||||||
|
if (user == null || Integer.valueOf(1).equals(user.getIsDelete()) || !Integer.valueOf(1).equals(user.getStatus())) {
|
||||||
|
throw new RuntimeException("请先登录有效账号");
|
||||||
|
}
|
||||||
|
if (Integer.valueOf(3).equals(user.getType())) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (Integer.valueOf(2).equals(user.getType())) {
|
||||||
|
NailArtistInfoDO info = getArtistInfoByUserId(userId);
|
||||||
|
if (info != null && Integer.valueOf(1).equals(info.getParticipateProduction())) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new RuntimeException("仅美甲师或参与制作的店长可以申请改派");
|
||||||
|
}
|
||||||
|
|
||||||
|
private NailArtistInfoDO getArtistInfoByUserId(Long userId) {
|
||||||
|
if (userId == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return nailArtistInfoMapper.selectOne(new LambdaQueryWrapper<NailArtistInfoDO>()
|
||||||
|
.eq(NailArtistInfoDO::getUserId, userId)
|
||||||
|
.eq(NailArtistInfoDO::getIsDelete, 0)
|
||||||
|
.last("LIMIT 1"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private String resolveArtistChangeStatusText(String status) {
|
||||||
|
if (CHANGE_STATUS_APPROVED.equals(status)) {
|
||||||
|
return "已同意";
|
||||||
|
}
|
||||||
|
if (CHANGE_STATUS_REJECTED.equals(status)) {
|
||||||
|
return "已拒绝";
|
||||||
|
}
|
||||||
|
return "待确认";
|
||||||
|
}
|
||||||
|
|
||||||
|
private Long createSystemBusinessMessage(Long targetUserId,
|
||||||
|
String title,
|
||||||
|
String content,
|
||||||
|
String businessType,
|
||||||
|
Long businessId,
|
||||||
|
String actionPath,
|
||||||
|
Long publisherId,
|
||||||
|
String publisherName,
|
||||||
|
Integer publisherType) {
|
||||||
|
if (targetUserId == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String targetIds = String.valueOf(targetUserId);
|
||||||
|
String idempotencyKey = buildSystemMessageIdempotencyKey(businessType, businessId, targetUserId);
|
||||||
|
if (StringUtils.hasText(idempotencyKey)) {
|
||||||
|
Long existingMessageId = findSystemBusinessMessageId(businessType, businessId, targetIds, idempotencyKey);
|
||||||
|
if (existingMessageId != null) {
|
||||||
|
return existingMessageId;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
SystemMessageDO message = new SystemMessageDO();
|
||||||
|
message.setTitle(title);
|
||||||
|
message.setContent(content);
|
||||||
|
message.setPublisherId(publisherId == null ? 0L : publisherId);
|
||||||
|
message.setPublisherName(StringUtils.hasText(publisherName) ? publisherName : "系统通知");
|
||||||
|
message.setPublisherType(publisherType == null ? 4 : publisherType);
|
||||||
|
message.setTargetType(MESSAGE_TARGET_SELECTED_USERS);
|
||||||
|
message.setTargetIds(targetIds);
|
||||||
|
message.setBusinessType(businessType);
|
||||||
|
message.setBusinessId(businessId);
|
||||||
|
message.setActionPath(actionPath);
|
||||||
|
message.setIdempotencyKey(idempotencyKey);
|
||||||
|
message.setPopupEnabled(1);
|
||||||
|
message.setStatus(1);
|
||||||
|
message.setPublishTime(LocalDateTime.now());
|
||||||
|
message.setIsDelete(0);
|
||||||
|
try {
|
||||||
|
systemMessageMapper.insert(message);
|
||||||
|
} catch (DuplicateKeyException exception) {
|
||||||
|
Long existingMessageId = findSystemBusinessMessageId(businessType, businessId, targetIds, idempotencyKey);
|
||||||
|
if (existingMessageId != null) {
|
||||||
|
return existingMessageId;
|
||||||
|
}
|
||||||
|
throw exception;
|
||||||
|
}
|
||||||
|
return message.getId();
|
||||||
|
}
|
||||||
|
|
||||||
|
private String buildSystemMessageIdempotencyKey(String businessType, Long businessId, Long targetUserId) {
|
||||||
|
if (!StringUtils.hasText(businessType) || businessId == null || targetUserId == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return businessType + ":" + businessId + ":" + targetUserId;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Long findSystemBusinessMessageId(String businessType,
|
||||||
|
Long businessId,
|
||||||
|
String targetIds,
|
||||||
|
String idempotencyKey) {
|
||||||
|
if (!StringUtils.hasText(idempotencyKey)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
SystemMessageDO existingMessage = systemMessageMapper.selectOne(new LambdaQueryWrapper<SystemMessageDO>()
|
||||||
|
.eq(SystemMessageDO::getBusinessType, businessType)
|
||||||
|
.eq(SystemMessageDO::getBusinessId, businessId)
|
||||||
|
.eq(SystemMessageDO::getTargetType, MESSAGE_TARGET_SELECTED_USERS)
|
||||||
|
.eq(SystemMessageDO::getTargetIds, targetIds)
|
||||||
|
.eq(SystemMessageDO::getIsDelete, 0)
|
||||||
|
.and(wrapper -> wrapper
|
||||||
|
.eq(SystemMessageDO::getIdempotencyKey, idempotencyKey)
|
||||||
|
.or()
|
||||||
|
.isNull(SystemMessageDO::getIdempotencyKey))
|
||||||
|
.last("LIMIT 1"));
|
||||||
|
return existingMessage == null ? null : existingMessage.getId();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Run business method `buildOrderVO`.
|
* Run business method `buildOrderVO`.
|
||||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||||
@@ -1045,6 +1801,21 @@ public class OrderServiceImpl implements OrderService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
OrderArtistReviewDO review = orderArtistReviewMapper.selectByOrderItemId(item.getId());
|
||||||
|
if (review != null) {
|
||||||
|
OrderArtistReviewVO reviewVO = buildArtistReviewVO(review);
|
||||||
|
if (Integer.valueOf(REVIEW_STATUS_PENDING).equals(review.getStatus())) {
|
||||||
|
itemVO.setPendingReview(reviewVO);
|
||||||
|
} else if (Integer.valueOf(REVIEW_STATUS_SUBMITTED).equals(review.getStatus())) {
|
||||||
|
itemVO.setReviewSummary(reviewVO);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
OrderArtistChangeRequestDO pendingChangeRequest = orderArtistChangeRequestMapper.selectPendingByOrderItemId(item.getId());
|
||||||
|
if (pendingChangeRequest != null) {
|
||||||
|
itemVO.setPendingArtistChangeRequest(buildArtistChangeRequestVO(pendingChangeRequest));
|
||||||
|
}
|
||||||
|
|
||||||
orderItemVOs.add(itemVO);
|
orderItemVOs.add(itemVO);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+99
-52
@@ -193,6 +193,17 @@ public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permiss
|
|||||||
*/
|
*/
|
||||||
public List<PermissionVO> listUserPermissions(Long userId) {
|
public List<PermissionVO> listUserPermissions(Long userId) {
|
||||||
UserDO userDO = userMapper.selectById(userId);
|
UserDO userDO = userMapper.selectById(userId);
|
||||||
|
if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
|
||||||
|
List<UserShopRoleDO> activeShopRoles = listActiveShopRoles(userId);
|
||||||
|
if (usesShopRoleEffectivePermissions(userDO, activeShopRoles)) {
|
||||||
|
return listPermissionsByIds(listPermissionIdsByShopRoles(activeShopRoles)).stream()
|
||||||
|
.filter(permission -> isPermissionAllowedForUserType(userDO, permission.getPermissionCode()))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
List<UserPermissionDO> userPermissions = userPermissionMapper.selectList(
|
List<UserPermissionDO> userPermissions = userPermissionMapper.selectList(
|
||||||
Wrappers.lambdaQuery(UserPermissionDO.class)
|
Wrappers.lambdaQuery(UserPermissionDO.class)
|
||||||
.eq(UserPermissionDO::getUserId, userId)
|
.eq(UserPermissionDO::getUserId, userId)
|
||||||
@@ -224,7 +235,9 @@ public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permiss
|
|||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
return permissionVOs;
|
return permissionVOs.stream()
|
||||||
|
.filter(permission -> isPermissionAllowedForUserType(userDO, permission.getPermissionCode()))
|
||||||
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -440,6 +453,21 @@ public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permiss
|
|||||||
*/
|
*/
|
||||||
public boolean hasPermission(Long userId, String permissionCode) {
|
public boolean hasPermission(Long userId, String permissionCode) {
|
||||||
UserDO userDO = userMapper.selectById(userId);
|
UserDO userDO = userMapper.selectById(userId);
|
||||||
|
if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (isShopBootstrapAdmin(userDO)) {
|
||||||
|
return SHOP_BOOTSTRAP_PERMISSION_CODES.contains(permissionCode);
|
||||||
|
}
|
||||||
|
if (!isPermissionAllowedForUserType(userDO, permissionCode)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
List<UserShopRoleDO> activeShopRoles = listActiveShopRoles(userId);
|
||||||
|
if (usesShopRoleEffectivePermissions(userDO, activeShopRoles)) {
|
||||||
|
return hasShopRolePermission(activeShopRoles, permissionCode);
|
||||||
|
}
|
||||||
|
|
||||||
List<UserPermissionDO> userPermissions = userPermissionMapper.selectList(
|
List<UserPermissionDO> userPermissions = userPermissionMapper.selectList(
|
||||||
Wrappers.lambdaQuery(UserPermissionDO.class)
|
Wrappers.lambdaQuery(UserPermissionDO.class)
|
||||||
.eq(UserPermissionDO::getUserId, userId)
|
.eq(UserPermissionDO::getUserId, userId)
|
||||||
@@ -463,50 +491,14 @@ public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permiss
|
|||||||
.eq(PermissionDO::getIsDelete, 0)
|
.eq(PermissionDO::getIsDelete, 0)
|
||||||
);
|
);
|
||||||
if (permissionDO == null || !permissionIds.contains(permissionDO.getId())) {
|
if (permissionDO == null || !permissionIds.contains(permissionDO.getId())) {
|
||||||
/**
|
return false;
|
||||||
* Run business method `hasShopRolePermission`.
|
|
||||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
|
||||||
* @param userId parameter `userId` supplied by the caller
|
|
||||||
* @param permissionCode parameter `permissionCode` supplied by the caller
|
|
||||||
* @return return result consumed by the caller or returned to the frontend
|
|
||||||
*/
|
|
||||||
return hasShopRolePermission(userId, permissionCode);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isShopBootstrapAdmin(userDO)) {
|
|
||||||
return SHOP_BOOTSTRAP_PERMISSION_CODES.contains(permissionCode);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
private boolean hasShopRolePermission(List<UserShopRoleDO> activeShopRoles, String permissionCode) {
|
||||||
* Run business method `hasShopRolePermission`.
|
List<Long> permissionIds = listPermissionIdsByShopRoles(activeShopRoles);
|
||||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
|
||||||
* @param userId parameter `userId` supplied by the caller
|
|
||||||
* @param permissionCode parameter `permissionCode` supplied by the caller
|
|
||||||
* @return private boolean result consumed by the caller or returned to the frontend
|
|
||||||
*/
|
|
||||||
private boolean hasShopRolePermission(Long userId, String permissionCode) {
|
|
||||||
List<UserShopRoleDO> roles = userShopRoleMapper.selectList(Wrappers.lambdaQuery(UserShopRoleDO.class)
|
|
||||||
.eq(UserShopRoleDO::getUserId, userId)
|
|
||||||
.eq(UserShopRoleDO::getIsDelete, 0)
|
|
||||||
.eq(UserShopRoleDO::getStatus, 1));
|
|
||||||
if (roles.isEmpty()) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
List<Long> roleIds = roles.stream().map(UserShopRoleDO::getRoleId).filter(Objects::nonNull).distinct().collect(Collectors.toList());
|
|
||||||
if (roleIds.isEmpty()) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
List<Long> permissionIds = shopRolePermissionMapper.selectList(Wrappers.lambdaQuery(ShopRolePermissionDO.class)
|
|
||||||
.in(ShopRolePermissionDO::getRoleId, roleIds)
|
|
||||||
.eq(ShopRolePermissionDO::getIsDelete, 0))
|
|
||||||
.stream()
|
|
||||||
.map(ShopRolePermissionDO::getPermissionId)
|
|
||||||
.filter(Objects::nonNull)
|
|
||||||
.distinct()
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
if (permissionIds.isEmpty()) {
|
if (permissionIds.isEmpty()) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -555,21 +547,58 @@ public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permiss
|
|||||||
* @return private Set<String> result consumed by the caller or returned to the frontend
|
* @return private Set<String> result consumed by the caller or returned to the frontend
|
||||||
*/
|
*/
|
||||||
private Set<String> listPermissionCodesByUserId(Long userId) {
|
private Set<String> listPermissionCodesByUserId(Long userId) {
|
||||||
List<UserPermissionDO> userPermissions = userPermissionMapper.selectList(
|
return listUserPermissions(userId).stream()
|
||||||
Wrappers.lambdaQuery(UserPermissionDO.class)
|
.map(PermissionVO::getPermissionCode)
|
||||||
.eq(UserPermissionDO::getUserId, userId)
|
.collect(Collectors.toSet());
|
||||||
);
|
}
|
||||||
if (userPermissions.isEmpty()) {
|
|
||||||
return Collections.emptySet();
|
private List<UserShopRoleDO> listActiveShopRoles(Long userId) {
|
||||||
|
if (userId == null) {
|
||||||
|
return List.of();
|
||||||
}
|
}
|
||||||
|
|
||||||
List<Long> permissionIds = userPermissions.stream()
|
Long currentShopId = RequestShopContext.getCurrentShopId();
|
||||||
.map(UserPermissionDO::getPermissionId)
|
List<UserShopRoleDO> activeShopRoles = userShopRoleMapper.selectList(Wrappers.lambdaQuery(UserShopRoleDO.class)
|
||||||
|
.eq(UserShopRoleDO::getUserId, userId)
|
||||||
|
.eq(currentShopId != null, UserShopRoleDO::getShopId, currentShopId)
|
||||||
|
.eq(UserShopRoleDO::getIsDelete, 0)
|
||||||
|
.eq(UserShopRoleDO::getStatus, 1));
|
||||||
|
if (currentShopId == null) {
|
||||||
|
return activeShopRoles;
|
||||||
|
}
|
||||||
|
return activeShopRoles.stream()
|
||||||
|
.filter(role -> Objects.equals(currentShopId, role.getShopId()))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<Long> listPermissionIdsByShopRoles(List<UserShopRoleDO> activeShopRoles) {
|
||||||
|
if (activeShopRoles == null || activeShopRoles.isEmpty()) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Long> roleIds = activeShopRoles.stream()
|
||||||
|
.map(UserShopRoleDO::getRoleId)
|
||||||
.filter(Objects::nonNull)
|
.filter(Objects::nonNull)
|
||||||
.distinct()
|
.distinct()
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
if (permissionIds.isEmpty()) {
|
if (roleIds.isEmpty()) {
|
||||||
return Collections.emptySet();
|
return List.of();
|
||||||
|
}
|
||||||
|
|
||||||
|
return shopRolePermissionMapper.selectList(Wrappers.lambdaQuery(ShopRolePermissionDO.class)
|
||||||
|
.in(ShopRolePermissionDO::getRoleId, roleIds)
|
||||||
|
.eq(ShopRolePermissionDO::getIsDelete, 0))
|
||||||
|
.stream()
|
||||||
|
.filter(permission -> roleIds.contains(permission.getRoleId()))
|
||||||
|
.map(ShopRolePermissionDO::getPermissionId)
|
||||||
|
.filter(Objects::nonNull)
|
||||||
|
.distinct()
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<PermissionVO> listPermissionsByIds(List<Long> permissionIds) {
|
||||||
|
if (permissionIds == null || permissionIds.isEmpty()) {
|
||||||
|
return List.of();
|
||||||
}
|
}
|
||||||
|
|
||||||
return permissionMapper.selectList(
|
return permissionMapper.selectList(
|
||||||
@@ -577,8 +606,26 @@ public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permiss
|
|||||||
.in(PermissionDO::getId, permissionIds)
|
.in(PermissionDO::getId, permissionIds)
|
||||||
.eq(PermissionDO::getIsDelete, 0)
|
.eq(PermissionDO::getIsDelete, 0)
|
||||||
).stream()
|
).stream()
|
||||||
.map(PermissionDO::getPermissionCode)
|
.map(this::convertToVO)
|
||||||
.collect(Collectors.toSet());
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean usesShopRoleEffectivePermissions(UserDO userDO, List<UserShopRoleDO> activeShopRoles) {
|
||||||
|
return !isPlatformAdmin(userDO) && activeShopRoles != null && !activeShopRoles.isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isPermissionAllowedForUserType(UserDO userDO, String permissionCode) {
|
||||||
|
if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (isPlatformAdmin(userDO)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return PermissionPolicy.getDefaultPermissionCodeSet(userDO.getType()).contains(permissionCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isPlatformAdmin(UserDO userDO) {
|
||||||
|
return userDO != null && Integer.valueOf(4).equals(userDO.getType());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
+55
@@ -1,9 +1,13 @@
|
|||||||
package com.xiaowang.yuminailcore.service.impl;
|
package com.xiaowang.yuminailcore.service.impl;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
|
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||||
import com.xiaowang.yuminailcore.entity.SecurityAuditLogDO;
|
import com.xiaowang.yuminailcore.entity.SecurityAuditLogDO;
|
||||||
import com.xiaowang.yuminailcore.mapper.SecurityAuditLogMapper;
|
import com.xiaowang.yuminailcore.mapper.SecurityAuditLogMapper;
|
||||||
import com.xiaowang.yuminailcore.service.SecurityAuditLogService;
|
import com.xiaowang.yuminailcore.service.SecurityAuditLogService;
|
||||||
import com.xiaowang.yuminailcore.support.security.RequestThrottleService;
|
import com.xiaowang.yuminailcore.support.security.RequestThrottleService;
|
||||||
|
import com.xiaowang.yuminailcore.vo.PageResultVO;
|
||||||
|
import com.xiaowang.yuminailcore.vo.SecurityAuditLogVO;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.util.StringUtils;
|
import org.springframework.util.StringUtils;
|
||||||
@@ -35,6 +39,57 @@ public class SecurityAuditLogServiceImpl implements SecurityAuditLogService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public PageResultVO<SecurityAuditLogVO> pageLogs(String account,
|
||||||
|
String action,
|
||||||
|
String result,
|
||||||
|
LocalDateTime startTime,
|
||||||
|
LocalDateTime endTime,
|
||||||
|
Integer page,
|
||||||
|
Integer size) {
|
||||||
|
int pageNo = page == null || page < 1 ? 1 : page;
|
||||||
|
int pageSize = size == null || size < 1 ? 20 : Math.min(size, 100);
|
||||||
|
LambdaQueryWrapper<SecurityAuditLogDO> wrapper = new LambdaQueryWrapper<>();
|
||||||
|
if (StringUtils.hasText(account)) {
|
||||||
|
wrapper.like(SecurityAuditLogDO::getAccount, account.trim());
|
||||||
|
}
|
||||||
|
if (StringUtils.hasText(action)) {
|
||||||
|
wrapper.eq(SecurityAuditLogDO::getAction, action.trim());
|
||||||
|
}
|
||||||
|
if (StringUtils.hasText(result)) {
|
||||||
|
wrapper.eq(SecurityAuditLogDO::getResult, result.trim());
|
||||||
|
}
|
||||||
|
if (startTime != null) {
|
||||||
|
wrapper.ge(SecurityAuditLogDO::getOperateTime, startTime);
|
||||||
|
}
|
||||||
|
if (endTime != null) {
|
||||||
|
wrapper.le(SecurityAuditLogDO::getOperateTime, endTime);
|
||||||
|
}
|
||||||
|
wrapper.orderByDesc(SecurityAuditLogDO::getOperateTime).orderByDesc(SecurityAuditLogDO::getId);
|
||||||
|
Page<SecurityAuditLogDO> logPage = auditLogMapper.selectPage(new Page<>(pageNo, pageSize), wrapper);
|
||||||
|
|
||||||
|
PageResultVO<SecurityAuditLogVO> resultVO = new PageResultVO<>();
|
||||||
|
resultVO.setList(logPage.getRecords().stream().map(this::toVO).toList());
|
||||||
|
resultVO.setTotal(logPage.getTotal());
|
||||||
|
resultVO.setPage(pageNo);
|
||||||
|
resultVO.setSize(pageSize);
|
||||||
|
return resultVO;
|
||||||
|
}
|
||||||
|
|
||||||
|
private SecurityAuditLogVO toVO(SecurityAuditLogDO log) {
|
||||||
|
SecurityAuditLogVO vo = new SecurityAuditLogVO();
|
||||||
|
vo.setId(log.getId());
|
||||||
|
vo.setUserId(log.getUserId());
|
||||||
|
vo.setAccount(log.getAccount());
|
||||||
|
vo.setAction(log.getAction());
|
||||||
|
vo.setResult(log.getResult());
|
||||||
|
vo.setReason(log.getReason());
|
||||||
|
vo.setIpAddress(log.getIpAddress());
|
||||||
|
vo.setDeviceId(log.getDeviceId());
|
||||||
|
vo.setOperateTime(log.getOperateTime());
|
||||||
|
return vo;
|
||||||
|
}
|
||||||
|
|
||||||
private String resolveClientIp(HttpServletRequest request) {
|
private String resolveClientIp(HttpServletRequest request) {
|
||||||
if (request == null) {
|
if (request == null) {
|
||||||
return null;
|
return null;
|
||||||
|
|||||||
+6
-47
@@ -50,6 +50,8 @@ import java.util.stream.Collectors;
|
|||||||
public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopDO> implements ShopService {
|
public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopDO> implements ShopService {
|
||||||
private static final String SHOP_DETAIL_CACHE_PREFIX = "cache:shop:detail:";
|
private static final String SHOP_DETAIL_CACHE_PREFIX = "cache:shop:detail:";
|
||||||
private static final String SHOP_LIST_CACHE_PREFIX = "cache:shop:list:";
|
private static final String SHOP_LIST_CACHE_PREFIX = "cache:shop:list:";
|
||||||
|
private static final String SHOP_DELETE_DISABLED_MESSAGE = "店铺删除已停用,请使用停用封存";
|
||||||
|
private static final String DISABLED_SHOP_ARCHIVED_MESSAGE = "停用店铺已封存,仅允许重新启用";
|
||||||
/**
|
/**
|
||||||
* Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
* Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||||
*/
|
*/
|
||||||
@@ -134,6 +136,9 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopDO> implements
|
|||||||
if (shopDO == null) {
|
if (shopDO == null) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
if (Integer.valueOf(0).equals(normalizeStatus(shopDO.getStatus()))) {
|
||||||
|
throw new RuntimeException(DISABLED_SHOP_ARCHIVED_MESSAGE);
|
||||||
|
}
|
||||||
shopDO.setShopName(shopDTO.getShopName());
|
shopDO.setShopName(shopDTO.getShopName());
|
||||||
shopDO.setDescription(shopDTO.getDescription());
|
shopDO.setDescription(shopDTO.getDescription());
|
||||||
shopDO.setAddress(shopDTO.getAddress());
|
shopDO.setAddress(shopDTO.getAddress());
|
||||||
@@ -170,53 +175,7 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopDO> implements
|
|||||||
* @return boolean result consumed by the caller or returned to the frontend
|
* @return boolean result consumed by the caller or returned to the frontend
|
||||||
*/
|
*/
|
||||||
public boolean deleteShop(Long id) {
|
public boolean deleteShop(Long id) {
|
||||||
ShopDO shopDO = shopMapper.selectById(id);
|
throw new RuntimeException(SHOP_DELETE_DISABLED_MESSAGE);
|
||||||
if (shopDO == null || Integer.valueOf(1).equals(shopDO.getIsDelete())) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
List<Long> couponIds = couponMapper.selectList(Wrappers.lambdaQuery(CouponDO.class)
|
|
||||||
.select(CouponDO::getId)
|
|
||||||
.eq(CouponDO::getShopId, id)
|
|
||||||
.eq(CouponDO::getIsDelete, 0))
|
|
||||||
.stream()
|
|
||||||
.map(CouponDO::getId)
|
|
||||||
.toList();
|
|
||||||
productMapper.update(null, Wrappers.lambdaUpdate(ProductDO.class)
|
|
||||||
.eq(ProductDO::getShopId, id)
|
|
||||||
.eq(ProductDO::getIsDelete, 0)
|
|
||||||
.set(ProductDO::getIsDelete, 1));
|
|
||||||
couponMapper.update(null, Wrappers.lambdaUpdate(CouponDO.class)
|
|
||||||
.eq(CouponDO::getShopId, id)
|
|
||||||
.eq(CouponDO::getIsDelete, 0)
|
|
||||||
.set(CouponDO::getIsDelete, 1));
|
|
||||||
tagMapper.update(null, Wrappers.lambdaUpdate(TagDO.class)
|
|
||||||
.eq(TagDO::getShopId, id)
|
|
||||||
.eq(TagDO::getIsDelete, 0)
|
|
||||||
.set(TagDO::getIsDelete, 1));
|
|
||||||
commentMapper.update(null, Wrappers.lambdaUpdate(CommentDO.class)
|
|
||||||
.eq(CommentDO::getShopId, id)
|
|
||||||
.eq(CommentDO::getIsDelete, 0)
|
|
||||||
.set(CommentDO::getIsDelete, 1));
|
|
||||||
if (!couponIds.isEmpty()) {
|
|
||||||
userCouponMapper.update(null, Wrappers.lambdaUpdate(UserCouponDO.class)
|
|
||||||
.in(UserCouponDO::getCouponId, couponIds)
|
|
||||||
.eq(UserCouponDO::getIsDelete, 0)
|
|
||||||
.set(UserCouponDO::getIsDelete, 1));
|
|
||||||
}
|
|
||||||
userShopBindingSupport.deleteBindingsByShopId(id);
|
|
||||||
shopDO.setStatus(0);
|
|
||||||
shopDO.setIsDelete(1);
|
|
||||||
boolean deleted = shopMapper.updateById(shopDO) > 0;
|
|
||||||
if (deleted) {
|
|
||||||
/**
|
|
||||||
* Run business method `evictShopCaches`.
|
|
||||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
|
||||||
* @param id parameter `id` supplied by the caller
|
|
||||||
* @return result consumed by the caller or returned to the frontend
|
|
||||||
*/
|
|
||||||
evictShopCaches(id);
|
|
||||||
}
|
|
||||||
return deleted;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
+13
@@ -134,6 +134,9 @@ public class SystemMessageServiceImpl extends ServiceImpl<SystemMessageMapper, S
|
|||||||
message.setPublisherType(currentUser.getType());
|
message.setPublisherType(currentUser.getType());
|
||||||
message.setTargetType(targetType);
|
message.setTargetType(targetType);
|
||||||
message.setTargetIds(joinIds(targetIds));
|
message.setTargetIds(joinIds(targetIds));
|
||||||
|
message.setBusinessType(trimToNull(dto.getBusinessType()));
|
||||||
|
message.setBusinessId(dto.getBusinessId());
|
||||||
|
message.setActionPath(trimToNull(dto.getActionPath()));
|
||||||
message.setPopupEnabled(Integer.valueOf(0).equals(dto.getPopupEnabled()) ? 0 : 1);
|
message.setPopupEnabled(Integer.valueOf(0).equals(dto.getPopupEnabled()) ? 0 : 1);
|
||||||
message.setStatus(1);
|
message.setStatus(1);
|
||||||
message.setPublishTime(LocalDateTime.now());
|
message.setPublishTime(LocalDateTime.now());
|
||||||
@@ -640,6 +643,9 @@ public class SystemMessageServiceImpl extends ServiceImpl<SystemMessageMapper, S
|
|||||||
vo.setTargetType(message.getTargetType());
|
vo.setTargetType(message.getTargetType());
|
||||||
vo.setTargetTypeName(targetTypeName(message.getTargetType()));
|
vo.setTargetTypeName(targetTypeName(message.getTargetType()));
|
||||||
vo.setTargetIds(new ArrayList<>(parseIds(message.getTargetIds())));
|
vo.setTargetIds(new ArrayList<>(parseIds(message.getTargetIds())));
|
||||||
|
vo.setBusinessType(message.getBusinessType());
|
||||||
|
vo.setBusinessId(message.getBusinessId());
|
||||||
|
vo.setActionPath(message.getActionPath());
|
||||||
vo.setPopupEnabled(message.getPopupEnabled());
|
vo.setPopupEnabled(message.getPopupEnabled());
|
||||||
vo.setStatus(message.getStatus());
|
vo.setStatus(message.getStatus());
|
||||||
vo.setPublishTime(message.getPublishTime());
|
vo.setPublishTime(message.getPublishTime());
|
||||||
@@ -775,6 +781,13 @@ public class SystemMessageServiceImpl extends ServiceImpl<SystemMessageMapper, S
|
|||||||
return targetType.trim().toUpperCase();
|
return targetType.trim().toUpperCase();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private String trimToNull(String value) {
|
||||||
|
if (!StringUtils.hasText(value)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return value.trim();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Run business method `normalizeIds`.
|
* Run business method `normalizeIds`.
|
||||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
package com.xiaowang.yuminailcore.support;
|
||||||
|
|
||||||
|
public final class OrderStateMachine {
|
||||||
|
|
||||||
|
private OrderStateMachine() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean isAllowedTransition(Integer fromStatus, Integer toStatus) {
|
||||||
|
OrderStatus from = OrderStatus.requireKnown(fromStatus);
|
||||||
|
OrderStatus to = OrderStatus.requireKnown(toStatus);
|
||||||
|
return from == OrderStatus.PENDING_SERVICE
|
||||||
|
&& (to == OrderStatus.COMPLETED || to == OrderStatus.CANCELLED);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void requireAllowedTransition(Integer fromStatus, Integer toStatus) {
|
||||||
|
if (!isAllowedTransition(fromStatus, toStatus)) {
|
||||||
|
throw new RuntimeException("订单状态不允许处理");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package com.xiaowang.yuminailcore.support;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
public enum OrderStatus {
|
||||||
|
PENDING_SERVICE(1),
|
||||||
|
COMPLETED(2),
|
||||||
|
CANCELLED(3);
|
||||||
|
|
||||||
|
private final int code;
|
||||||
|
|
||||||
|
OrderStatus(int code) {
|
||||||
|
this.code = code;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getCode() {
|
||||||
|
return code;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static OrderStatus requireKnown(Integer code) {
|
||||||
|
return Arrays.stream(values())
|
||||||
|
.filter(status -> Integer.valueOf(status.code).equals(code))
|
||||||
|
.findFirst()
|
||||||
|
.orElseThrow(() -> new RuntimeException("无效的订单状态"));
|
||||||
|
}
|
||||||
|
}
|
||||||
+10
-6
@@ -26,11 +26,12 @@ public final class PermissionCatalog {
|
|||||||
"tag:view", "tag:create", "tag:edit", "tag:delete", "tag:assign",
|
"tag:view", "tag:create", "tag:edit", "tag:delete", "tag:assign",
|
||||||
"coupon:view", "coupon:create", "coupon:edit", "coupon:delete", "coupon:assign",
|
"coupon:view", "coupon:create", "coupon:edit", "coupon:delete", "coupon:assign",
|
||||||
"comment:view", "comment:delete",
|
"comment:view", "comment:delete",
|
||||||
"order:view", "order:process", "order:edit", "order:delete",
|
"order:view", "order:process", "order:edit", "order:delete", "order:artist-change",
|
||||||
"nail_artist:view", "nail_artist:edit",
|
"nail_artist:view", "nail_artist:edit",
|
||||||
"message:view", "message:create", "message:delete",
|
"message:view", "message:create", "message:delete",
|
||||||
"announcement:view", "announcement:create", "announcement:delete",
|
"announcement:view", "announcement:create", "announcement:delete",
|
||||||
"messagehub:config:manage",
|
"messagehub:config:manage",
|
||||||
|
"security:audit:view",
|
||||||
"legal_agreement:manage"
|
"legal_agreement:manage"
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -46,7 +47,7 @@ public final class PermissionCatalog {
|
|||||||
"tag:view", "tag:create", "tag:edit", "tag:delete", "tag:assign",
|
"tag:view", "tag:create", "tag:edit", "tag:delete", "tag:assign",
|
||||||
"coupon:view", "coupon:create", "coupon:edit", "coupon:delete", "coupon:assign",
|
"coupon:view", "coupon:create", "coupon:edit", "coupon:delete", "coupon:assign",
|
||||||
"comment:view", "comment:delete",
|
"comment:view", "comment:delete",
|
||||||
"order:view", "order:process", "order:edit", "order:delete",
|
"order:view", "order:process", "order:edit", "order:delete", "order:artist-change",
|
||||||
"nail_artist:view", "nail_artist:edit",
|
"nail_artist:view", "nail_artist:edit",
|
||||||
"message:view", "message:create",
|
"message:view", "message:create",
|
||||||
"announcement:view", "announcement:create"
|
"announcement:view", "announcement:create"
|
||||||
@@ -54,14 +55,14 @@ public final class PermissionCatalog {
|
|||||||
|
|
||||||
private static final List<String> NAIL_ARTIST_DEFAULT_PERMISSION_CODES = List.of(
|
private static final List<String> NAIL_ARTIST_DEFAULT_PERMISSION_CODES = List.of(
|
||||||
"home:view",
|
"home:view",
|
||||||
"user:view", "user:create",
|
"user:view",
|
||||||
"user:balance:view",
|
"user:balance:view",
|
||||||
"product:view", "product:create",
|
"product:view",
|
||||||
"shop:view",
|
"shop:view",
|
||||||
"tag:view", "tag:create",
|
"tag:view",
|
||||||
"coupon:view",
|
"coupon:view",
|
||||||
"comment:view",
|
"comment:view",
|
||||||
"order:view", "order:process"
|
"order:view", "order:process", "order:artist-change"
|
||||||
);
|
);
|
||||||
|
|
||||||
private static final Set<String> PLATFORM_OVERVIEW_PREFIXES = Set.of(
|
private static final Set<String> PLATFORM_OVERVIEW_PREFIXES = Set.of(
|
||||||
@@ -74,6 +75,7 @@ public final class PermissionCatalog {
|
|||||||
|
|
||||||
private static final Set<String> PLATFORM_OVERVIEW_PERMISSIONS = Set.of(
|
private static final Set<String> PLATFORM_OVERVIEW_PERMISSIONS = Set.of(
|
||||||
"messagehub:config:manage",
|
"messagehub:config:manage",
|
||||||
|
"security:audit:view",
|
||||||
"legal_agreement:manage"
|
"legal_agreement:manage"
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -202,6 +204,7 @@ public final class PermissionCatalog {
|
|||||||
put(definitions, "order:process", "处理订单", "订单管理", "处理订单状态或由美甲师完结订单");
|
put(definitions, "order:process", "处理订单", "订单管理", "处理订单状态或由美甲师完结订单");
|
||||||
put(definitions, "order:edit", "编辑订单", "订单管理", "编辑订单信息的预留权限");
|
put(definitions, "order:edit", "编辑订单", "订单管理", "编辑订单信息的预留权限");
|
||||||
put(definitions, "order:delete", "删除订单", "订单管理", "删除订单的预留权限");
|
put(definitions, "order:delete", "删除订单", "订单管理", "删除订单的预留权限");
|
||||||
|
put(definitions, "order:artist-change", "处理改派申请", "订单管理", "处理订单美甲师改派申请");
|
||||||
put(definitions, "nail_artist:view", "查看美甲师", "美甲师管理", "查看美甲师信息与排班入口");
|
put(definitions, "nail_artist:view", "查看美甲师", "美甲师管理", "查看美甲师信息与排班入口");
|
||||||
put(definitions, "nail_artist:edit", "编辑美甲师", "美甲师管理", "编辑美甲师信息");
|
put(definitions, "nail_artist:edit", "编辑美甲师", "美甲师管理", "编辑美甲师信息");
|
||||||
put(definitions, "message:view", "查看消息", "消息管理", "查看站内消息发布与通知");
|
put(definitions, "message:view", "查看消息", "消息管理", "查看站内消息发布与通知");
|
||||||
@@ -211,6 +214,7 @@ public final class PermissionCatalog {
|
|||||||
put(definitions, "announcement:create", "发布公告", "公告管理", "发布公告");
|
put(definitions, "announcement:create", "发布公告", "公告管理", "发布公告");
|
||||||
put(definitions, "announcement:delete", "撤回公告", "公告管理", "撤回已发布公告");
|
put(definitions, "announcement:delete", "撤回公告", "公告管理", "撤回已发布公告");
|
||||||
put(definitions, "messagehub:config:manage", "管理消息参数", "参数管理", "管理地图 Key、短信 MessageHub 等平台参数");
|
put(definitions, "messagehub:config:manage", "管理消息参数", "参数管理", "管理地图 Key、短信 MessageHub 等平台参数");
|
||||||
|
put(definitions, "security:audit:view", "查看安全审计", "安全审计", "查看高危操作和登录安全审计日志");
|
||||||
put(definitions, "legal_agreement:manage", "管理协议", "协议管理", "管理用户协议和隐私政策版本");
|
put(definitions, "legal_agreement:manage", "管理协议", "协议管理", "管理用户协议和隐私政策版本");
|
||||||
return Map.copyOf(definitions);
|
return Map.copyOf(definitions);
|
||||||
}
|
}
|
||||||
|
|||||||
+27
@@ -0,0 +1,27 @@
|
|||||||
|
package com.xiaowang.yuminailcore.support;
|
||||||
|
|
||||||
|
public final class SecurityAuditActions {
|
||||||
|
|
||||||
|
public static final String SUCCESS = "SUCCESS";
|
||||||
|
public static final String FAIL = "FAIL";
|
||||||
|
|
||||||
|
public static final String ORDER_PROCESS = "ORDER_PROCESS";
|
||||||
|
public static final String ARTIST_CHANGE_APPROVE = "ARTIST_CHANGE_APPROVE";
|
||||||
|
public static final String ARTIST_CHANGE_REJECT = "ARTIST_CHANGE_REJECT";
|
||||||
|
public static final String SHOP_DELETE_BLOCKED = "SHOP_DELETE_BLOCKED";
|
||||||
|
public static final String SHOP_STATUS_UPDATE = "SHOP_STATUS_UPDATE";
|
||||||
|
public static final String PERMISSION_CREATE = "PERMISSION_CREATE";
|
||||||
|
public static final String PERMISSION_UPDATE = "PERMISSION_UPDATE";
|
||||||
|
public static final String PERMISSION_DELETE = "PERMISSION_DELETE";
|
||||||
|
public static final String PERMISSION_ASSIGN = "PERMISSION_ASSIGN";
|
||||||
|
public static final String USER_STATUS_UPDATE = "USER_STATUS_UPDATE";
|
||||||
|
public static final String USER_RESET_PASSWORD = "USER_RESET_PASSWORD";
|
||||||
|
public static final String USER_DELETE = "USER_DELETE";
|
||||||
|
public static final String USER_UNBIND = "USER_UNBIND";
|
||||||
|
public static final String USER_BALANCE_CHANGE = "USER_BALANCE_CHANGE";
|
||||||
|
public static final String USER_VIP_OVERRIDE = "USER_VIP_OVERRIDE";
|
||||||
|
public static final String USER_VIP_RECALCULATE = "USER_VIP_RECALCULATE";
|
||||||
|
|
||||||
|
private SecurityAuditActions() {
|
||||||
|
}
|
||||||
|
}
|
||||||
+46
@@ -0,0 +1,46 @@
|
|||||||
|
package com.xiaowang.yuminailcore.support;
|
||||||
|
|
||||||
|
import com.xiaowang.yuminailcore.service.SecurityAuditLogService;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import javax.servlet.http.HttpServletRequest;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class SecurityAuditSupport {
|
||||||
|
|
||||||
|
private final SecurityAuditLogService securityAuditLogService;
|
||||||
|
|
||||||
|
public void success(HttpServletRequest request, String action, String reason) {
|
||||||
|
record(request, action, SecurityAuditActions.SUCCESS, reason);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void fail(HttpServletRequest request, String action, String reason) {
|
||||||
|
record(request, action, SecurityAuditActions.FAIL, reason);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void record(HttpServletRequest request, String action, String result, String reason) {
|
||||||
|
try {
|
||||||
|
Long userId = request == null ? null : asLong(request.getAttribute("userId"));
|
||||||
|
String account = request == null ? null : asString(request.getAttribute("account"));
|
||||||
|
securityAuditLogService.record(userId, account, action, result, reason, request);
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
// Audit failure must never block the guarded business operation.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Long asLong(Object value) {
|
||||||
|
if (value instanceof Long) {
|
||||||
|
return (Long) value;
|
||||||
|
}
|
||||||
|
if (value instanceof Number) {
|
||||||
|
return ((Number) value).longValue();
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String asString(Object value) {
|
||||||
|
return value == null ? null : String.valueOf(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
+23
@@ -0,0 +1,23 @@
|
|||||||
|
package com.xiaowang.yuminailcore.vo;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public class OrderArtistChangeOptionsVO {
|
||||||
|
private Long orderId;
|
||||||
|
private Long orderItemId;
|
||||||
|
private Long currentArtistId;
|
||||||
|
private String currentArtistName;
|
||||||
|
private List<ArtistOptionVO> artists;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public static class ArtistOptionVO {
|
||||||
|
private Long artistId;
|
||||||
|
private String artistName;
|
||||||
|
private String artistAvatar;
|
||||||
|
private Integer userType;
|
||||||
|
private Boolean participateProduction;
|
||||||
|
}
|
||||||
|
}
|
||||||
+38
@@ -0,0 +1,38 @@
|
|||||||
|
package com.xiaowang.yuminailcore.vo;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public class OrderArtistChangeRequestVO {
|
||||||
|
private Long id;
|
||||||
|
private Long orderId;
|
||||||
|
private Long orderItemId;
|
||||||
|
private Long productId;
|
||||||
|
private String productTitle;
|
||||||
|
private Long shopId;
|
||||||
|
private Long userId;
|
||||||
|
private Long customerId;
|
||||||
|
private Long originalArtistId;
|
||||||
|
private String originalArtistName;
|
||||||
|
private Long requestedArtistId;
|
||||||
|
private String requestedArtistName;
|
||||||
|
private Long fromArtistId;
|
||||||
|
private String fromArtistName;
|
||||||
|
private Long toArtistId;
|
||||||
|
private String toArtistName;
|
||||||
|
private Long requesterId;
|
||||||
|
private String requesterName;
|
||||||
|
private String status;
|
||||||
|
private String statusText;
|
||||||
|
private String reason;
|
||||||
|
private String rejectReason;
|
||||||
|
private Long reviewerId;
|
||||||
|
private Long messageId;
|
||||||
|
private LocalDateTime reviewTime;
|
||||||
|
private LocalDateTime approvedTime;
|
||||||
|
private LocalDateTime rejectedTime;
|
||||||
|
private LocalDateTime expireTime;
|
||||||
|
private LocalDateTime createTime;
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package com.xiaowang.yuminailcore.vo;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public class OrderArtistReviewVO {
|
||||||
|
private Long id;
|
||||||
|
private Long orderId;
|
||||||
|
private Long orderItemId;
|
||||||
|
private Long productId;
|
||||||
|
private String productTitle;
|
||||||
|
private Long artistId;
|
||||||
|
private String artistName;
|
||||||
|
private String artistAvatar;
|
||||||
|
private Long userId;
|
||||||
|
private Long customerId;
|
||||||
|
private BigDecimal rating;
|
||||||
|
private BigDecimal ratingScore;
|
||||||
|
private String content;
|
||||||
|
private List<Long> imageFileIds;
|
||||||
|
private Integer status;
|
||||||
|
private String statusText;
|
||||||
|
private Long reminderMessageId;
|
||||||
|
private LocalDateTime submitTime;
|
||||||
|
private LocalDateTime submittedAt;
|
||||||
|
private LocalDateTime createTime;
|
||||||
|
}
|
||||||
@@ -54,4 +54,7 @@ public class OrderItemVO {
|
|||||||
* Field `appointmentTime` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
* Field `appointmentTime` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||||
*/
|
*/
|
||||||
private String appointmentTime;
|
private String appointmentTime;
|
||||||
|
private OrderArtistReviewVO pendingReview;
|
||||||
|
private OrderArtistReviewVO reviewSummary;
|
||||||
|
private OrderArtistChangeRequestVO pendingArtistChangeRequest;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package com.xiaowang.yuminailcore.vo;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public class SecurityAuditLogVO {
|
||||||
|
|
||||||
|
private Long id;
|
||||||
|
private Long userId;
|
||||||
|
private String account;
|
||||||
|
private String action;
|
||||||
|
private String result;
|
||||||
|
private String reason;
|
||||||
|
private String ipAddress;
|
||||||
|
private String deviceId;
|
||||||
|
private LocalDateTime operateTime;
|
||||||
|
}
|
||||||
@@ -55,6 +55,9 @@ public class SystemMessageVO {
|
|||||||
* Field `targetIds` (List<Long>): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
* Field `targetIds` (List<Long>): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||||
*/
|
*/
|
||||||
private List<Long> targetIds;
|
private List<Long> targetIds;
|
||||||
|
private String businessType;
|
||||||
|
private Long businessId;
|
||||||
|
private String actionPath;
|
||||||
/**
|
/**
|
||||||
* Field `popupEnabled` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
* Field `popupEnabled` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ create table t_balance
|
|||||||
last_recharge_time datetime null comment '最近一次充值时间',
|
last_recharge_time datetime null comment '最近一次充值时间',
|
||||||
create_time datetime default CURRENT_TIMESTAMP not null comment '余额账户创建时间',
|
create_time datetime default CURRENT_TIMESTAMP not null comment '余额账户创建时间',
|
||||||
last_update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '最近一次更新时间',
|
last_update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '最近一次更新时间',
|
||||||
|
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
|
||||||
constraint uk_user_id
|
constraint uk_user_id
|
||||||
unique (user_id) comment '用户余额唯一索引(一个用户对应一条余额记录)'
|
unique (user_id) comment '用户余额唯一索引(一个用户对应一条余额记录)'
|
||||||
)
|
)
|
||||||
@@ -336,6 +337,75 @@ create index idx_order_id
|
|||||||
on t_order_item (order_id)
|
on t_order_item (order_id)
|
||||||
comment '按订单查询商品的索引';
|
comment '按订单查询商品的索引';
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS t_order_artist_review
|
||||||
|
(
|
||||||
|
id bigint unsigned auto_increment comment '评价任务ID'
|
||||||
|
primary key,
|
||||||
|
order_id bigint unsigned not null comment '订单ID',
|
||||||
|
order_item_id bigint unsigned not null comment '订单项ID',
|
||||||
|
customer_id bigint unsigned not null comment '下单客户ID',
|
||||||
|
shop_id bigint unsigned null comment '店铺ID',
|
||||||
|
artist_id bigint unsigned not null comment '被评价美甲师ID',
|
||||||
|
product_id bigint unsigned null comment '商品ID',
|
||||||
|
rating_score decimal(2, 1) null comment '评分,提交后必填0.5-5',
|
||||||
|
content varchar(1000) null comment '评价文字',
|
||||||
|
image_file_ids text null comment '评价图片文件ID集合',
|
||||||
|
status tinyint unsigned default 0 not null comment '状态:0-待评价,1-已评价',
|
||||||
|
reminder_message_id bigint unsigned null comment '提醒消息ID',
|
||||||
|
submitted_at datetime null comment '提交时间',
|
||||||
|
create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间',
|
||||||
|
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
|
||||||
|
is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删'
|
||||||
|
)
|
||||||
|
comment '订单美甲师评价任务表';
|
||||||
|
|
||||||
|
create unique index uk_order_artist_review_item
|
||||||
|
on t_order_artist_review (order_item_id, is_delete);
|
||||||
|
|
||||||
|
create index idx_order_artist_review_customer
|
||||||
|
on t_order_artist_review (customer_id, status, create_time);
|
||||||
|
|
||||||
|
create index idx_order_artist_review_artist
|
||||||
|
on t_order_artist_review (artist_id, status);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS t_order_artist_change_request
|
||||||
|
(
|
||||||
|
id bigint unsigned auto_increment comment '改派申请ID'
|
||||||
|
primary key,
|
||||||
|
order_id bigint unsigned not null comment '订单ID',
|
||||||
|
order_item_id bigint unsigned not null comment '订单项ID',
|
||||||
|
customer_id bigint unsigned not null comment '下单客户ID',
|
||||||
|
shop_id bigint unsigned null comment '店铺ID',
|
||||||
|
product_id bigint unsigned null comment '商品ID',
|
||||||
|
from_artist_id bigint unsigned not null comment '原美甲师ID',
|
||||||
|
to_artist_id bigint unsigned not null comment '新美甲师ID',
|
||||||
|
requester_id bigint unsigned not null comment '申请人ID',
|
||||||
|
status varchar(20) default 'PENDING' not null comment '状态:PENDING/APPROVED/REJECTED',
|
||||||
|
reason varchar(500) null comment '申请原因',
|
||||||
|
reject_reason varchar(500) null comment '拒绝原因',
|
||||||
|
message_id bigint unsigned null comment '提醒消息ID',
|
||||||
|
pending_key varchar(80) null comment '待处理唯一键,PENDING时为订单项维度',
|
||||||
|
approved_time datetime null comment '同意时间',
|
||||||
|
rejected_time datetime null comment '拒绝时间',
|
||||||
|
expire_time datetime null comment '过期时间',
|
||||||
|
create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间',
|
||||||
|
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
|
||||||
|
is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删'
|
||||||
|
)
|
||||||
|
comment '订单美甲师改派申请表';
|
||||||
|
|
||||||
|
create index idx_order_artist_change_customer
|
||||||
|
on t_order_artist_change_request (customer_id, status, create_time);
|
||||||
|
|
||||||
|
create index idx_order_artist_change_artist
|
||||||
|
on t_order_artist_change_request (from_artist_id, to_artist_id, status);
|
||||||
|
|
||||||
|
create index idx_order_artist_change_shop
|
||||||
|
on t_order_artist_change_request (shop_id, status, create_time);
|
||||||
|
|
||||||
|
create unique index uk_order_artist_change_pending_key
|
||||||
|
on t_order_artist_change_request (pending_key);
|
||||||
|
|
||||||
-- auto-generated definition
|
-- auto-generated definition
|
||||||
create table t_permission
|
create table t_permission
|
||||||
(
|
(
|
||||||
@@ -572,6 +642,10 @@ create table if not exists t_system_message
|
|||||||
publisher_type tinyint not null comment '发布人类型:2-店长,4-管理员',
|
publisher_type tinyint not null comment '发布人类型:2-店长,4-管理员',
|
||||||
target_type varchar(30) not null comment '目标范围:PLATFORM_ALL/CURRENT_SHOP_ALL/SHOP_ALL/SELECTED_SHOPS/SELECTED_USERS',
|
target_type varchar(30) not null comment '目标范围:PLATFORM_ALL/CURRENT_SHOP_ALL/SHOP_ALL/SELECTED_SHOPS/SELECTED_USERS',
|
||||||
target_ids text null comment '目标ID集合,多个ID以逗号分隔',
|
target_ids text null comment '目标ID集合,多个ID以逗号分隔',
|
||||||
|
business_type varchar(64) null comment '业务类型',
|
||||||
|
business_id bigint unsigned null comment '业务ID',
|
||||||
|
action_path varchar(255) null comment '业务跳转路径',
|
||||||
|
idempotency_key varchar(160) null comment '业务消息幂等键',
|
||||||
popup_enabled tinyint unsigned default 1 not null comment '是否弹窗:1-弹窗,0-不弹窗',
|
popup_enabled tinyint unsigned default 1 not null comment '是否弹窗:1-弹窗,0-不弹窗',
|
||||||
status tinyint unsigned default 1 not null comment '状态:1-已发布,0-已撤回',
|
status tinyint unsigned default 1 not null comment '状态:1-已发布,0-已撤回',
|
||||||
publish_time datetime default CURRENT_TIMESTAMP not null comment '发布时间',
|
publish_time datetime default CURRENT_TIMESTAMP not null comment '发布时间',
|
||||||
@@ -587,6 +661,9 @@ create index idx_t_system_message_publish_time
|
|||||||
create index idx_t_system_message_target
|
create index idx_t_system_message_target
|
||||||
on t_system_message (target_type, status);
|
on t_system_message (target_type, status);
|
||||||
|
|
||||||
|
create unique index uk_t_system_message_idempotency
|
||||||
|
on t_system_message (idempotency_key);
|
||||||
|
|
||||||
create table if not exists t_system_message_user_state
|
create table if not exists t_system_message_user_state
|
||||||
(
|
(
|
||||||
id bigint unsigned auto_increment comment '用户消息状态主键'
|
id bigint unsigned auto_increment comment '用户消息状态主键'
|
||||||
@@ -804,6 +881,7 @@ DELIMITER ;
|
|||||||
|
|
||||||
CALL sp_add_column_if_not_exists('t_balance', 'total_recharge_amount', 'decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT ''累计充值金额''');
|
CALL sp_add_column_if_not_exists('t_balance', 'total_recharge_amount', 'decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT ''累计充值金额''');
|
||||||
CALL sp_add_column_if_not_exists('t_balance', 'last_recharge_time', 'datetime NULL COMMENT ''最近一次充值时间''');
|
CALL sp_add_column_if_not_exists('t_balance', 'last_recharge_time', 'datetime NULL COMMENT ''最近一次充值时间''');
|
||||||
|
CALL sp_add_column_if_not_exists('t_balance', 'update_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT ''更新时间''');
|
||||||
|
|
||||||
UPDATE t_balance
|
UPDATE t_balance
|
||||||
SET total_recharge_amount = COALESCE(total_recharge_amount, 0.00)
|
SET total_recharge_amount = COALESCE(total_recharge_amount, 0.00)
|
||||||
@@ -1195,6 +1273,99 @@ CALL sp_add_column_if_not_exists('t_nail_artist_info', 'work_end_time', 'time NU
|
|||||||
CALL sp_add_index_if_not_exists('t_nail_artist_info', 'idx_t_nail_artist_info_participate', '(`participate_production`, `status`)');
|
CALL sp_add_index_if_not_exists('t_nail_artist_info', 'idx_t_nail_artist_info_participate', '(`participate_production`, `status`)');
|
||||||
CALL sp_add_column_if_not_exists('t_system_message', 'image_file_id', 'bigint unsigned NULL COMMENT ''消息图片文件ID''');
|
CALL sp_add_column_if_not_exists('t_system_message', 'image_file_id', 'bigint unsigned NULL COMMENT ''消息图片文件ID''');
|
||||||
|
|
||||||
|
CALL sp_add_column_if_not_exists('t_system_message', 'business_type', 'varchar(64) NULL COMMENT ''业务类型''');
|
||||||
|
CALL sp_add_column_if_not_exists('t_system_message', 'business_id', 'bigint unsigned NULL COMMENT ''业务ID''');
|
||||||
|
CALL sp_add_column_if_not_exists('t_system_message', 'action_path', 'varchar(255) NULL COMMENT ''业务跳转路径''');
|
||||||
|
CALL sp_add_column_if_not_exists('t_system_message', 'idempotency_key', 'varchar(160) NULL COMMENT ''业务消息幂等键''');
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS t_order_artist_review
|
||||||
|
(
|
||||||
|
id bigint unsigned auto_increment comment '评价任务ID'
|
||||||
|
primary key,
|
||||||
|
order_id bigint unsigned not null comment '订单ID',
|
||||||
|
order_item_id bigint unsigned not null comment '订单项ID',
|
||||||
|
customer_id bigint unsigned not null comment '下单客户ID',
|
||||||
|
shop_id bigint unsigned null comment '店铺ID',
|
||||||
|
artist_id bigint unsigned not null comment '被评价美甲师ID',
|
||||||
|
product_id bigint unsigned null comment '商品ID',
|
||||||
|
rating_score decimal(2, 1) null comment '评分,提交后必填0.5-5',
|
||||||
|
content varchar(1000) null comment '评价文字',
|
||||||
|
image_file_ids text null comment '评价图片文件ID集合',
|
||||||
|
status tinyint unsigned default 0 not null comment '状态:0-待评价,1-已评价',
|
||||||
|
reminder_message_id bigint unsigned null comment '提醒消息ID',
|
||||||
|
submitted_at datetime null comment '提交时间',
|
||||||
|
create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间',
|
||||||
|
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
|
||||||
|
is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删'
|
||||||
|
)
|
||||||
|
comment '订单美甲师评价任务表';
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS t_order_artist_change_request
|
||||||
|
(
|
||||||
|
id bigint unsigned auto_increment comment '改派申请ID'
|
||||||
|
primary key,
|
||||||
|
order_id bigint unsigned not null comment '订单ID',
|
||||||
|
order_item_id bigint unsigned not null comment '订单项ID',
|
||||||
|
customer_id bigint unsigned not null comment '下单客户ID',
|
||||||
|
shop_id bigint unsigned null comment '店铺ID',
|
||||||
|
product_id bigint unsigned null comment '商品ID',
|
||||||
|
from_artist_id bigint unsigned not null comment '原美甲师ID',
|
||||||
|
to_artist_id bigint unsigned not null comment '新美甲师ID',
|
||||||
|
requester_id bigint unsigned not null comment '申请人ID',
|
||||||
|
status varchar(20) default 'PENDING' not null comment '状态:PENDING/APPROVED/REJECTED',
|
||||||
|
reason varchar(500) null comment '申请原因',
|
||||||
|
reject_reason varchar(500) null comment '拒绝原因',
|
||||||
|
message_id bigint unsigned null comment '提醒消息ID',
|
||||||
|
pending_key varchar(80) null comment '待处理唯一键,PENDING时为订单项维度',
|
||||||
|
approved_time datetime null comment '同意时间',
|
||||||
|
rejected_time datetime null comment '拒绝时间',
|
||||||
|
expire_time datetime null comment '过期时间',
|
||||||
|
create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间',
|
||||||
|
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
|
||||||
|
is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删'
|
||||||
|
)
|
||||||
|
comment '订单美甲师改派申请表';
|
||||||
|
|
||||||
|
CALL sp_add_unique_index_if_not_exists('t_order_artist_review', 'uk_order_artist_review_item', '(`order_item_id`, `is_delete`)');
|
||||||
|
CALL sp_add_index_if_not_exists('t_order_artist_review', 'idx_order_artist_review_customer', '(`customer_id`, `status`, `create_time`)');
|
||||||
|
CALL sp_add_index_if_not_exists('t_order_artist_review', 'idx_order_artist_review_artist', '(`artist_id`, `status`)');
|
||||||
|
CALL sp_add_index_if_not_exists('t_order_artist_review', 'idx_order_artist_review_order', '(`order_id`)');
|
||||||
|
CALL sp_add_unique_index_if_not_exists('t_system_message', 'uk_t_system_message_idempotency', '(`idempotency_key`)');
|
||||||
|
CALL sp_add_column_if_not_exists('t_order_artist_change_request', 'pending_key', 'varchar(80) NULL COMMENT ''待处理唯一键,PENDING时为订单项维度''');
|
||||||
|
CALL sp_add_unique_index_if_not_exists('t_order_artist_change_request', 'uk_order_artist_change_pending_key', '(`pending_key`)');
|
||||||
|
CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_item_status', '(`order_item_id`, `status`, `is_delete`)');
|
||||||
|
CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_customer', '(`customer_id`, `status`, `create_time`)');
|
||||||
|
CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_artist', '(`from_artist_id`, `to_artist_id`, `status`)');
|
||||||
|
CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_shop', '(`shop_id`, `status`, `create_time`)');
|
||||||
|
CALL sp_add_index_if_not_exists('t_order_artist_change_request', 'idx_order_artist_change_expire', '(`status`, `expire_time`, `is_delete`)');
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS t_business_event_outbox
|
||||||
|
(
|
||||||
|
id bigint unsigned auto_increment comment '事件ID'
|
||||||
|
primary key,
|
||||||
|
event_key varchar(160) not null comment '事件幂等键',
|
||||||
|
event_type varchar(64) not null comment '事件类型',
|
||||||
|
business_type varchar(64) not null comment '业务类型',
|
||||||
|
business_id bigint unsigned not null comment '业务ID',
|
||||||
|
payload_json text null comment '事件载荷',
|
||||||
|
status varchar(20) default 'PENDING' not null comment 'PENDING/PROCESSING/SUCCEEDED/FAILED',
|
||||||
|
retry_count int unsigned default 0 not null comment '重试次数',
|
||||||
|
next_retry_time datetime null comment '下次重试时间',
|
||||||
|
last_error varchar(500) null comment '最近错误',
|
||||||
|
claimed_at datetime null comment '认领时间',
|
||||||
|
processed_at datetime null comment '处理完成时间',
|
||||||
|
create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间',
|
||||||
|
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
|
||||||
|
is_delete tinyint unsigned default 0 null comment '逻辑删除'
|
||||||
|
)
|
||||||
|
comment '业务事件Outbox表';
|
||||||
|
|
||||||
|
CALL sp_add_unique_index_if_not_exists('t_business_event_outbox', 'uk_business_event_outbox_event_key', '(`event_key`)');
|
||||||
|
CALL sp_add_index_if_not_exists('t_business_event_outbox', 'idx_business_event_outbox_due', '(`status`, `next_retry_time`, `create_time`)');
|
||||||
|
|
||||||
|
-- Artist change requests can be expired asynchronously; expired rows release pending_key for a new request.
|
||||||
|
-- EXPIRED
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS `t_messagehub_push_config` (
|
CREATE TABLE IF NOT EXISTS `t_messagehub_push_config` (
|
||||||
`id` bigint unsigned NOT NULL COMMENT '主键ID',
|
`id` bigint unsigned NOT NULL COMMENT '主键ID',
|
||||||
`scene_code` varchar(80) NOT NULL COMMENT '业务场景编码',
|
`scene_code` varchar(80) NOT NULL COMMENT '业务场景编码',
|
||||||
@@ -1312,6 +1483,15 @@ ON DUPLICATE KEY UPDATE
|
|||||||
update_time = NOW(),
|
update_time = NOW(),
|
||||||
is_delete = 0;
|
is_delete = 0;
|
||||||
|
|
||||||
|
INSERT INTO t_permission (permission_code, permission_name, permission_group, description, create_time, update_time, is_delete)
|
||||||
|
VALUES ('order:artist-change', '处理改派申请', '订单管理', '处理订单美甲师改派申请', NOW(), NOW(), 0)
|
||||||
|
ON DUPLICATE KEY UPDATE
|
||||||
|
permission_name = VALUES(permission_name),
|
||||||
|
permission_group = VALUES(permission_group),
|
||||||
|
description = VALUES(description),
|
||||||
|
update_time = NOW(),
|
||||||
|
is_delete = 0;
|
||||||
|
|
||||||
INSERT INTO t_user (
|
INSERT INTO t_user (
|
||||||
shop_id,
|
shop_id,
|
||||||
nickname,
|
nickname,
|
||||||
@@ -1396,6 +1576,7 @@ INNER JOIN t_permission p
|
|||||||
'comment:delete',
|
'comment:delete',
|
||||||
'order:view',
|
'order:view',
|
||||||
'order:process',
|
'order:process',
|
||||||
|
'order:artist-change',
|
||||||
'order:edit',
|
'order:edit',
|
||||||
'order:delete',
|
'order:delete',
|
||||||
'nail_artist:view',
|
'nail_artist:view',
|
||||||
@@ -1456,6 +1637,7 @@ INNER JOIN t_permission p
|
|||||||
'comment:delete',
|
'comment:delete',
|
||||||
'order:view',
|
'order:view',
|
||||||
'order:process',
|
'order:process',
|
||||||
|
'order:artist-change',
|
||||||
'order:edit',
|
'order:edit',
|
||||||
'order:delete',
|
'order:delete',
|
||||||
'nail_artist:view',
|
'nail_artist:view',
|
||||||
@@ -1482,17 +1664,15 @@ INNER JOIN t_permission p
|
|||||||
AND p.permission_code IN (
|
AND p.permission_code IN (
|
||||||
'home:view',
|
'home:view',
|
||||||
'user:view',
|
'user:view',
|
||||||
'user:create',
|
|
||||||
'user:balance:view',
|
'user:balance:view',
|
||||||
'product:view',
|
'product:view',
|
||||||
'product:create',
|
|
||||||
'shop:view',
|
'shop:view',
|
||||||
'tag:view',
|
'tag:view',
|
||||||
'tag:create',
|
|
||||||
'coupon:view',
|
'coupon:view',
|
||||||
'comment:view',
|
'comment:view',
|
||||||
'order:view',
|
'order:view',
|
||||||
'order:process'
|
'order:process',
|
||||||
|
'order:artist-change'
|
||||||
)
|
)
|
||||||
WHERE u.is_delete = 0
|
WHERE u.is_delete = 0
|
||||||
AND u.type = 3
|
AND u.type = 3
|
||||||
@@ -1884,3 +2064,13 @@ ON DUPLICATE KEY UPDATE
|
|||||||
is_delete = 0,
|
is_delete = 0,
|
||||||
update_by = VALUES(update_by),
|
update_by = VALUES(update_by),
|
||||||
update_time = NOW();
|
update_time = NOW();
|
||||||
|
|
||||||
|
INSERT INTO t_permission (id, permission_code, permission_name, permission_group, description, create_time, update_time, is_delete)
|
||||||
|
VALUES
|
||||||
|
(313931273555136602, 'security:audit:view', '查看安全审计', '安全审计', '查看高危操作和登录安全审计日志', NOW(), NOW(), 0)
|
||||||
|
ON DUPLICATE KEY UPDATE
|
||||||
|
permission_name = VALUES(permission_name),
|
||||||
|
permission_group = VALUES(permission_group),
|
||||||
|
description = VALUES(description),
|
||||||
|
is_delete = 0,
|
||||||
|
update_time = NOW();
|
||||||
|
|||||||
+46
@@ -0,0 +1,46 @@
|
|||||||
|
package com.xiaowang.yuminailcore.controller;
|
||||||
|
|
||||||
|
import com.xiaowang.yuminailcore.common.Result;
|
||||||
|
import com.xiaowang.yuminailcore.service.SecurityAuditLogService;
|
||||||
|
import com.xiaowang.yuminailcore.vo.PageResultVO;
|
||||||
|
import com.xiaowang.yuminailcore.vo.SecurityAuditLogVO;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.MockitoAnnotations;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
class AdminSecurityAuditControllerTest {
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private SecurityAuditLogService securityAuditLogService;
|
||||||
|
|
||||||
|
private AdminSecurityAuditController controller;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
MockitoAnnotations.openMocks(this);
|
||||||
|
controller = new AdminSecurityAuditController(securityAuditLogService);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void listLogsDelegatesToServiceWithFilters() {
|
||||||
|
PageResultVO<SecurityAuditLogVO> page = new PageResultVO<>();
|
||||||
|
page.setTotal(0L);
|
||||||
|
when(securityAuditLogService.pageLogs(eq("admin"), eq("ORDER_PROCESS"), eq("SUCCESS"),
|
||||||
|
any(), any(), eq(1), eq(20))).thenReturn(page);
|
||||||
|
|
||||||
|
Result<PageResultVO<SecurityAuditLogVO>> result = controller.listLogs(
|
||||||
|
"admin", "ORDER_PROCESS", "SUCCESS",
|
||||||
|
"2026-05-01 00:00:00", "2026-05-23 23:59:59", 1, 20);
|
||||||
|
|
||||||
|
assertThat(result.getData()).isSameAs(page);
|
||||||
|
verify(securityAuditLogService).pageLogs(eq("admin"), eq("ORDER_PROCESS"), eq("SUCCESS"),
|
||||||
|
any(), any(), eq(1), eq(20));
|
||||||
|
}
|
||||||
|
}
|
||||||
+83
@@ -0,0 +1,83 @@
|
|||||||
|
package com.xiaowang.yuminailcore.controller;
|
||||||
|
|
||||||
|
import com.xiaowang.yuminailcore.common.Result;
|
||||||
|
import com.xiaowang.yuminailcore.mapper.EffectDiagramMapper;
|
||||||
|
import com.xiaowang.yuminailcore.mapper.ProductMapper;
|
||||||
|
import com.xiaowang.yuminailcore.mapper.ShopMapper;
|
||||||
|
import com.xiaowang.yuminailcore.service.MinioService;
|
||||||
|
import com.xiaowang.yuminailcore.service.ObjectStorageFileService;
|
||||||
|
import com.xiaowang.yuminailcore.support.ObjectStorageUrlSupport;
|
||||||
|
import com.xiaowang.yuminailcore.vo.ObjectStorageFileVO;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
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 FrontendFileControllerTest {
|
||||||
|
|
||||||
|
private ObjectStorageFileService objectStorageFileService;
|
||||||
|
private MinioService minioService;
|
||||||
|
private ProductMapper productMapper;
|
||||||
|
private ShopMapper shopMapper;
|
||||||
|
private EffectDiagramMapper effectDiagramMapper;
|
||||||
|
private FrontendFileController controller;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
objectStorageFileService = mock(ObjectStorageFileService.class);
|
||||||
|
minioService = mock(MinioService.class);
|
||||||
|
ObjectStorageUrlSupport objectStorageUrlSupport = mock(ObjectStorageUrlSupport.class);
|
||||||
|
productMapper = mock(ProductMapper.class);
|
||||||
|
shopMapper = mock(ShopMapper.class);
|
||||||
|
effectDiagramMapper = mock(EffectDiagramMapper.class);
|
||||||
|
controller = new FrontendFileController(
|
||||||
|
objectStorageFileService,
|
||||||
|
minioService,
|
||||||
|
objectStorageUrlSupport,
|
||||||
|
productMapper,
|
||||||
|
shopMapper,
|
||||||
|
effectDiagramMapper
|
||||||
|
);
|
||||||
|
when(objectStorageUrlSupport.extractObjectName("https://cdn.test/public/a.png")).thenReturn("public/a.png");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getSignedUrlRejectsAvailableFileWhenItIsNotPubliclyReferenced() throws Exception {
|
||||||
|
ObjectStorageFileVO file = file();
|
||||||
|
when(objectStorageFileService.getObjectStorageFileById(12L)).thenReturn(file);
|
||||||
|
when(productMapper.countPublicImageReference(12L)).thenReturn(0L);
|
||||||
|
when(shopMapper.countPublicImageReference(12L)).thenReturn(0L);
|
||||||
|
when(effectDiagramMapper.countPublicImageReference(12L)).thenReturn(0L);
|
||||||
|
|
||||||
|
Result<String> result = controller.getSignedUrl(12L, 60);
|
||||||
|
|
||||||
|
assertThat(result.getCode()).isNotEqualTo(200);
|
||||||
|
assertThat(result.getMessage()).contains("文件不可公开访问");
|
||||||
|
verify(minioService, never()).getPresignedUrl(org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyInt());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getSignedUrlAllowsPublicProductImageReference() throws Exception {
|
||||||
|
ObjectStorageFileVO file = file();
|
||||||
|
when(objectStorageFileService.getObjectStorageFileById(12L)).thenReturn(file);
|
||||||
|
when(productMapper.countPublicImageReference(12L)).thenReturn(1L);
|
||||||
|
when(minioService.getPresignedUrl("public/a.png", 30)).thenReturn("https://signed.test/public/a.png");
|
||||||
|
|
||||||
|
Result<String> result = controller.getSignedUrl(12L, 30);
|
||||||
|
|
||||||
|
assertThat(result.getCode()).isEqualTo(200);
|
||||||
|
assertThat(result.getData()).isEqualTo("https://signed.test/public/a.png");
|
||||||
|
}
|
||||||
|
|
||||||
|
private ObjectStorageFileVO file() {
|
||||||
|
ObjectStorageFileVO file = new ObjectStorageFileVO();
|
||||||
|
file.setId(12L);
|
||||||
|
file.setStatus(1);
|
||||||
|
file.setFileUrl("https://cdn.test/public/a.png");
|
||||||
|
return file;
|
||||||
|
}
|
||||||
|
}
|
||||||
+53
@@ -0,0 +1,53 @@
|
|||||||
|
package com.xiaowang.yuminailcore.service.impl;
|
||||||
|
|
||||||
|
import com.xiaowang.yuminailcore.entity.BusinessEventOutboxDO;
|
||||||
|
import com.xiaowang.yuminailcore.mapper.BusinessEventOutboxMapper;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.mockito.ArgumentCaptor;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.MockitoAnnotations;
|
||||||
|
import org.springframework.dao.DuplicateKeyException;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
class BusinessEventOutboxServiceTest {
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private BusinessEventOutboxMapper outboxMapper;
|
||||||
|
|
||||||
|
private BusinessEventOutboxServiceImpl service;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
MockitoAnnotations.openMocks(this);
|
||||||
|
service = new BusinessEventOutboxServiceImpl(outboxMapper);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void enqueueOrderCompletedCreatesIdempotentEvent() {
|
||||||
|
service.enqueueOrderCompleted(1L);
|
||||||
|
|
||||||
|
ArgumentCaptor<BusinessEventOutboxDO> captor = ArgumentCaptor.forClass(BusinessEventOutboxDO.class);
|
||||||
|
verify(outboxMapper).insert(captor.capture());
|
||||||
|
BusinessEventOutboxDO event = captor.getValue();
|
||||||
|
assertThat(event.getEventType()).isEqualTo("ORDER_COMPLETED");
|
||||||
|
assertThat(event.getBusinessType()).isEqualTo("ORDER");
|
||||||
|
assertThat(event.getBusinessId()).isEqualTo(1L);
|
||||||
|
assertThat(event.getEventKey()).isEqualTo("ORDER:1:COMPLETED");
|
||||||
|
assertThat(event.getStatus()).isEqualTo("PENDING");
|
||||||
|
assertThat(event.getPayloadJson()).contains("\"orderId\":1");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void duplicateOrderCompletedEventIsIgnored() {
|
||||||
|
when(outboxMapper.insert(any(BusinessEventOutboxDO.class))).thenThrow(new DuplicateKeyException("duplicate"));
|
||||||
|
|
||||||
|
service.enqueueOrderCompleted(1L);
|
||||||
|
|
||||||
|
verify(outboxMapper).insert(any(BusinessEventOutboxDO.class));
|
||||||
|
}
|
||||||
|
}
|
||||||
+513
@@ -0,0 +1,513 @@
|
|||||||
|
package com.xiaowang.yuminailcore.service.impl;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
|
import com.xiaowang.yuminailcore.dto.OrderArtistChangeRejectDTO;
|
||||||
|
import com.xiaowang.yuminailcore.dto.OrderArtistChangeRequestDTO;
|
||||||
|
import com.xiaowang.yuminailcore.dto.OrderArtistReviewSubmitDTO;
|
||||||
|
import com.xiaowang.yuminailcore.entity.NailArtistInfoDO;
|
||||||
|
import com.xiaowang.yuminailcore.entity.OrderArtistChangeRequestDO;
|
||||||
|
import com.xiaowang.yuminailcore.entity.OrderArtistReviewDO;
|
||||||
|
import com.xiaowang.yuminailcore.entity.OrderDO;
|
||||||
|
import com.xiaowang.yuminailcore.entity.OrderItemDO;
|
||||||
|
import com.xiaowang.yuminailcore.entity.ProductDO;
|
||||||
|
import com.xiaowang.yuminailcore.entity.SystemMessageDO;
|
||||||
|
import com.xiaowang.yuminailcore.entity.UserDO;
|
||||||
|
import com.xiaowang.yuminailcore.mapper.NailArtistInfoMapper;
|
||||||
|
import com.xiaowang.yuminailcore.mapper.OrderArtistChangeRequestMapper;
|
||||||
|
import com.xiaowang.yuminailcore.mapper.OrderArtistReviewMapper;
|
||||||
|
import com.xiaowang.yuminailcore.mapper.OrderItemMapper;
|
||||||
|
import com.xiaowang.yuminailcore.mapper.OrderMapper;
|
||||||
|
import com.xiaowang.yuminailcore.mapper.ProductMapper;
|
||||||
|
import com.xiaowang.yuminailcore.mapper.SystemMessageMapper;
|
||||||
|
import com.xiaowang.yuminailcore.mapper.UserMapper;
|
||||||
|
import com.xiaowang.yuminailcore.service.BusinessEventOutboxService;
|
||||||
|
import com.xiaowang.yuminailcore.support.BookableArtistSupport;
|
||||||
|
import com.xiaowang.yuminailcore.support.ObjectStorageUrlSupport;
|
||||||
|
import com.xiaowang.yuminailcore.support.UserShopBindingSupport;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.mockito.ArgumentCaptor;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.MockitoAnnotations;
|
||||||
|
import org.springframework.dao.DuplicateKeyException;
|
||||||
|
import org.springframework.test.util.ReflectionTestUtils;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
|
import static org.mockito.Mockito.inOrder;
|
||||||
|
import static org.mockito.Mockito.never;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
class OrderServiceImplReviewChangeTest {
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private OrderMapper orderMapper;
|
||||||
|
@Mock
|
||||||
|
private OrderItemMapper orderItemMapper;
|
||||||
|
@Mock
|
||||||
|
private OrderArtistReviewMapper orderArtistReviewMapper;
|
||||||
|
@Mock
|
||||||
|
private OrderArtistChangeRequestMapper orderArtistChangeRequestMapper;
|
||||||
|
@Mock
|
||||||
|
private ProductMapper productMapper;
|
||||||
|
@Mock
|
||||||
|
private UserMapper userMapper;
|
||||||
|
@Mock
|
||||||
|
private SystemMessageMapper systemMessageMapper;
|
||||||
|
@Mock
|
||||||
|
private NailArtistInfoMapper nailArtistInfoMapper;
|
||||||
|
@Mock
|
||||||
|
private ObjectStorageUrlSupport objectStorageUrlSupport;
|
||||||
|
@Mock
|
||||||
|
private UserShopBindingSupport userShopBindingSupport;
|
||||||
|
@Mock
|
||||||
|
private BookableArtistSupport bookableArtistSupport;
|
||||||
|
@Mock
|
||||||
|
private BusinessEventOutboxService businessEventOutboxService;
|
||||||
|
|
||||||
|
private OrderServiceImpl service;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
MockitoAnnotations.openMocks(this);
|
||||||
|
service = new OrderServiceImpl();
|
||||||
|
ReflectionTestUtils.setField(service, "orderMapper", orderMapper);
|
||||||
|
ReflectionTestUtils.setField(service, "orderItemMapper", orderItemMapper);
|
||||||
|
ReflectionTestUtils.setField(service, "orderArtistReviewMapper", orderArtistReviewMapper);
|
||||||
|
ReflectionTestUtils.setField(service, "orderArtistChangeRequestMapper", orderArtistChangeRequestMapper);
|
||||||
|
ReflectionTestUtils.setField(service, "productMapper", productMapper);
|
||||||
|
ReflectionTestUtils.setField(service, "userMapper", userMapper);
|
||||||
|
ReflectionTestUtils.setField(service, "systemMessageMapper", systemMessageMapper);
|
||||||
|
ReflectionTestUtils.setField(service, "nailArtistInfoMapper", nailArtistInfoMapper);
|
||||||
|
ReflectionTestUtils.setField(service, "objectStorageUrlSupport", objectStorageUrlSupport);
|
||||||
|
ReflectionTestUtils.setField(service, "userShopBindingSupport", userShopBindingSupport);
|
||||||
|
ReflectionTestUtils.setField(service, "bookableArtistSupport", bookableArtistSupport);
|
||||||
|
ReflectionTestUtils.setField(service, "businessEventOutboxService", businessEventOutboxService);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void processOrderCompletionUpdatesStatusAndEnqueuesOutboxEvent() {
|
||||||
|
OrderDO order = pendingOrder();
|
||||||
|
when(orderMapper.selectById(1L)).thenReturn(order);
|
||||||
|
when(orderMapper.updateStatusIfCurrent(1L, 1, 2)).thenReturn(1);
|
||||||
|
|
||||||
|
service.processOrder(1L, 2);
|
||||||
|
|
||||||
|
verify(orderMapper).updateStatusIfCurrent(1L, 1, 2);
|
||||||
|
verify(businessEventOutboxService).enqueueOrderCompleted(1L);
|
||||||
|
verify(orderArtistReviewMapper, never()).insert(any(OrderArtistReviewDO.class));
|
||||||
|
verify(systemMessageMapper, never()).insert(any(SystemMessageDO.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void processOrderCompletionRejectsConcurrentStatusChangeBeforeSideEffects() {
|
||||||
|
OrderDO order = pendingOrder();
|
||||||
|
when(orderMapper.selectById(1L)).thenReturn(order);
|
||||||
|
when(orderMapper.updateStatusIfCurrent(1L, 1, 2)).thenReturn(0);
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> service.processOrder(1L, 2))
|
||||||
|
.isInstanceOf(RuntimeException.class)
|
||||||
|
.hasMessageContaining("状态已变化");
|
||||||
|
|
||||||
|
verify(businessEventOutboxService, never()).enqueueOrderCompleted(any());
|
||||||
|
verify(orderArtistReviewMapper, never()).insert(any(OrderArtistReviewDO.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void outboxOrderCompletedCreatesPendingReviewTaskAndPopupMessageOnce() {
|
||||||
|
OrderDO order = completedOrder();
|
||||||
|
OrderItemDO item = orderItem();
|
||||||
|
ProductDO product = product();
|
||||||
|
UserDO artist = artist(30L);
|
||||||
|
|
||||||
|
when(orderItemMapper.selectByOrderId(1L)).thenReturn(List.of(item));
|
||||||
|
when(orderArtistReviewMapper.selectByOrderItemId(10L)).thenReturn(null);
|
||||||
|
when(productMapper.selectById(20L)).thenReturn(product);
|
||||||
|
when(userMapper.selectById(30L)).thenReturn(artist);
|
||||||
|
when(orderArtistReviewMapper.insert(any(OrderArtistReviewDO.class))).thenAnswer(invocation -> {
|
||||||
|
OrderArtistReviewDO review = invocation.getArgument(0);
|
||||||
|
review.setId(1000L);
|
||||||
|
return 1;
|
||||||
|
});
|
||||||
|
|
||||||
|
service.createPendingArtistReviewTasksAndNotifyFromOutbox(order);
|
||||||
|
|
||||||
|
ArgumentCaptor<OrderArtistReviewDO> reviewCaptor = ArgumentCaptor.forClass(OrderArtistReviewDO.class);
|
||||||
|
verify(orderArtistReviewMapper).insert(reviewCaptor.capture());
|
||||||
|
OrderArtistReviewDO review = reviewCaptor.getValue();
|
||||||
|
assertThat(review.getOrderItemId()).isEqualTo(10L);
|
||||||
|
assertThat(review.getCustomerId()).isEqualTo(2L);
|
||||||
|
assertThat(review.getArtistId()).isEqualTo(30L);
|
||||||
|
assertThat(review.getStatus()).isZero();
|
||||||
|
|
||||||
|
ArgumentCaptor<SystemMessageDO> messageCaptor = ArgumentCaptor.forClass(SystemMessageDO.class);
|
||||||
|
verify(systemMessageMapper).insert(messageCaptor.capture());
|
||||||
|
assertThat(messageCaptor.getValue().getBusinessType()).isEqualTo("ORDER_ARTIST_REVIEW");
|
||||||
|
assertThat(messageCaptor.getValue().getTargetIds()).isEqualTo("2");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void outboxOrderCompletedDoesNotCreateDuplicateReviewTask() {
|
||||||
|
OrderDO order = completedOrder();
|
||||||
|
OrderItemDO item = orderItem();
|
||||||
|
OrderArtistReviewDO existingReview = new OrderArtistReviewDO();
|
||||||
|
existingReview.setId(99L);
|
||||||
|
|
||||||
|
when(orderItemMapper.selectByOrderId(1L)).thenReturn(List.of(item));
|
||||||
|
when(orderArtistReviewMapper.selectByOrderItemId(10L)).thenReturn(existingReview);
|
||||||
|
|
||||||
|
service.createPendingArtistReviewTasksAndNotifyFromOutbox(order);
|
||||||
|
|
||||||
|
verify(orderArtistReviewMapper, never()).insert(any(OrderArtistReviewDO.class));
|
||||||
|
verify(systemMessageMapper, never()).insert(any(SystemMessageDO.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void outboxOrderCompletedRecoversWhenConcurrentReviewTaskInsertWins() {
|
||||||
|
OrderDO order = completedOrder();
|
||||||
|
OrderItemDO item = orderItem();
|
||||||
|
OrderArtistReviewDO existingReview = new OrderArtistReviewDO();
|
||||||
|
existingReview.setId(99L);
|
||||||
|
|
||||||
|
when(orderItemMapper.selectByOrderId(1L)).thenReturn(List.of(item));
|
||||||
|
when(orderArtistReviewMapper.selectByOrderItemId(10L)).thenReturn(null, existingReview);
|
||||||
|
when(orderArtistReviewMapper.insert(any(OrderArtistReviewDO.class))).thenThrow(new DuplicateKeyException("duplicate"));
|
||||||
|
|
||||||
|
service.createPendingArtistReviewTasksAndNotifyFromOutbox(order);
|
||||||
|
|
||||||
|
verify(orderArtistReviewMapper).insert(any(OrderArtistReviewDO.class));
|
||||||
|
verify(orderArtistReviewMapper, never()).updateById(existingReview);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void outboxOrderCompletedReusesExistingReviewReminderMessage() {
|
||||||
|
OrderDO order = completedOrder();
|
||||||
|
OrderItemDO item = orderItem();
|
||||||
|
ProductDO product = product();
|
||||||
|
SystemMessageDO existingMessage = new SystemMessageDO();
|
||||||
|
existingMessage.setId(300L);
|
||||||
|
|
||||||
|
when(orderItemMapper.selectByOrderId(1L)).thenReturn(List.of(item));
|
||||||
|
when(orderArtistReviewMapper.selectByOrderItemId(10L)).thenReturn(null);
|
||||||
|
when(productMapper.selectById(20L)).thenReturn(product);
|
||||||
|
when(userMapper.selectById(30L)).thenReturn(artist(30L));
|
||||||
|
when(orderArtistReviewMapper.insert(any(OrderArtistReviewDO.class))).thenAnswer(invocation -> {
|
||||||
|
OrderArtistReviewDO review = invocation.getArgument(0);
|
||||||
|
review.setId(1000L);
|
||||||
|
return 1;
|
||||||
|
});
|
||||||
|
when(systemMessageMapper.selectOne(any(LambdaQueryWrapper.class))).thenReturn(existingMessage);
|
||||||
|
|
||||||
|
service.createPendingArtistReviewTasksAndNotifyFromOutbox(order);
|
||||||
|
|
||||||
|
ArgumentCaptor<OrderArtistReviewDO> reviewCaptor = ArgumentCaptor.forClass(OrderArtistReviewDO.class);
|
||||||
|
verify(orderArtistReviewMapper).insert(reviewCaptor.capture());
|
||||||
|
verify(systemMessageMapper, never()).insert(any(SystemMessageDO.class));
|
||||||
|
verify(orderArtistReviewMapper).updateById(reviewCaptor.getValue());
|
||||||
|
assertThat(reviewCaptor.getValue().getReminderMessageId()).isEqualTo(300L);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void outboxOrderCompletedRecoversReviewReminderWhenConcurrentInsertWins() {
|
||||||
|
OrderDO order = completedOrder();
|
||||||
|
OrderItemDO item = orderItem();
|
||||||
|
ProductDO product = product();
|
||||||
|
SystemMessageDO existingMessage = new SystemMessageDO();
|
||||||
|
existingMessage.setId(301L);
|
||||||
|
|
||||||
|
when(orderItemMapper.selectByOrderId(1L)).thenReturn(List.of(item));
|
||||||
|
when(orderArtistReviewMapper.selectByOrderItemId(10L)).thenReturn(null);
|
||||||
|
when(productMapper.selectById(20L)).thenReturn(product);
|
||||||
|
when(userMapper.selectById(30L)).thenReturn(artist(30L));
|
||||||
|
when(orderArtistReviewMapper.insert(any(OrderArtistReviewDO.class))).thenAnswer(invocation -> {
|
||||||
|
OrderArtistReviewDO review = invocation.getArgument(0);
|
||||||
|
review.setId(1001L);
|
||||||
|
return 1;
|
||||||
|
});
|
||||||
|
when(systemMessageMapper.selectOne(any(LambdaQueryWrapper.class))).thenReturn(null, existingMessage);
|
||||||
|
when(systemMessageMapper.insert(any(SystemMessageDO.class))).thenThrow(new DuplicateKeyException("duplicate"));
|
||||||
|
|
||||||
|
service.createPendingArtistReviewTasksAndNotifyFromOutbox(order);
|
||||||
|
|
||||||
|
ArgumentCaptor<SystemMessageDO> messageCaptor = ArgumentCaptor.forClass(SystemMessageDO.class);
|
||||||
|
verify(systemMessageMapper).insert(messageCaptor.capture());
|
||||||
|
assertThat(messageCaptor.getValue().getIdempotencyKey()).isEqualTo("ORDER_ARTIST_REVIEW:1001:2");
|
||||||
|
ArgumentCaptor<OrderArtistReviewDO> reviewCaptor = ArgumentCaptor.forClass(OrderArtistReviewDO.class);
|
||||||
|
verify(orderArtistReviewMapper).updateById(reviewCaptor.capture());
|
||||||
|
assertThat(reviewCaptor.getValue().getReminderMessageId()).isEqualTo(301L);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void requestArtistChangeLocksOrderItemBeforeCheckingPendingRequest() {
|
||||||
|
OrderDO order = pendingOrder();
|
||||||
|
OrderItemDO item = orderItem();
|
||||||
|
ProductDO product = product();
|
||||||
|
UserDO requester = artist(30L);
|
||||||
|
UserDO requestedArtist = artist(31L);
|
||||||
|
product.setBookableArtists("30,31");
|
||||||
|
OrderArtistChangeRequestDTO dto = new OrderArtistChangeRequestDTO();
|
||||||
|
dto.setOrderId(1L);
|
||||||
|
dto.setOrderItemId(10L);
|
||||||
|
dto.setRequestedArtistId(31L);
|
||||||
|
dto.setReason("临时调整");
|
||||||
|
|
||||||
|
when(userMapper.selectById(30L)).thenReturn(requester);
|
||||||
|
when(userMapper.selectById(31L)).thenReturn(requestedArtist);
|
||||||
|
when(orderMapper.selectById(1L)).thenReturn(order);
|
||||||
|
when(orderItemMapper.selectByIdForUpdate(10L)).thenReturn(item);
|
||||||
|
when(productMapper.selectById(20L)).thenReturn(product);
|
||||||
|
when(userShopBindingSupport.isUserAccessibleInShop(30L, 3L)).thenReturn(true);
|
||||||
|
when(userShopBindingSupport.isUserAccessibleInShop(31L, 3L)).thenReturn(true);
|
||||||
|
when(bookableArtistSupport.isBookableServiceUser(requestedArtist)).thenReturn(true);
|
||||||
|
when(bookableArtistSupport.isValidBookableArtist(3L, 31L)).thenReturn(true);
|
||||||
|
|
||||||
|
service.requestArtistChange(30L, dto);
|
||||||
|
|
||||||
|
ArgumentCaptor<OrderArtistChangeRequestDO> requestCaptor = ArgumentCaptor.forClass(OrderArtistChangeRequestDO.class);
|
||||||
|
verify(orderArtistChangeRequestMapper).insert(requestCaptor.capture());
|
||||||
|
assertThat(requestCaptor.getValue().getPendingKey()).isEqualTo("ORDER_ITEM:10");
|
||||||
|
inOrder(orderItemMapper, orderArtistChangeRequestMapper).verify(orderItemMapper).selectByIdForUpdate(10L);
|
||||||
|
inOrder(orderItemMapper, orderArtistChangeRequestMapper).verify(orderArtistChangeRequestMapper).selectPendingByOrderItemId(10L);
|
||||||
|
verify(orderItemMapper, never()).selectById(10L);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void approveArtistChangeRejectsAlreadyProcessedRequest() {
|
||||||
|
OrderArtistChangeRequestDO request = pendingChangeRequest();
|
||||||
|
request.setStatus("APPROVED");
|
||||||
|
when(orderArtistChangeRequestMapper.selectById(500L)).thenReturn(request);
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> service.approveArtistChange(500L, 2L, 0))
|
||||||
|
.isInstanceOf(RuntimeException.class)
|
||||||
|
.hasMessage("改派申请已处理");
|
||||||
|
|
||||||
|
verify(orderItemMapper, never()).selectByIdForUpdate(any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void approveArtistChangeUsesPendingConditionalUpdateBeforeAssigningArtist() {
|
||||||
|
OrderArtistChangeRequestDO request = pendingChangeRequest();
|
||||||
|
OrderDO order = pendingOrder();
|
||||||
|
OrderItemDO item = orderItem();
|
||||||
|
ProductDO product = product();
|
||||||
|
UserDO newArtist = artist(31L);
|
||||||
|
product.setBookableArtists("30,31");
|
||||||
|
|
||||||
|
when(orderArtistChangeRequestMapper.selectById(500L)).thenReturn(request);
|
||||||
|
when(orderMapper.selectById(1L)).thenReturn(order);
|
||||||
|
when(orderItemMapper.selectByIdForUpdate(10L)).thenReturn(item);
|
||||||
|
when(productMapper.selectById(20L)).thenReturn(product);
|
||||||
|
when(userMapper.selectById(31L)).thenReturn(newArtist);
|
||||||
|
when(userShopBindingSupport.isUserAccessibleInShop(31L, 3L)).thenReturn(true);
|
||||||
|
when(bookableArtistSupport.isBookableServiceUser(newArtist)).thenReturn(true);
|
||||||
|
when(bookableArtistSupport.isValidBookableArtist(3L, 31L)).thenReturn(true);
|
||||||
|
when(orderArtistChangeRequestMapper.approvePending(eq(500L), any(LocalDateTime.class))).thenReturn(1);
|
||||||
|
|
||||||
|
service.approveArtistChange(500L, 2L, 0);
|
||||||
|
|
||||||
|
inOrder(orderArtistChangeRequestMapper, orderItemMapper)
|
||||||
|
.verify(orderArtistChangeRequestMapper).approvePending(eq(500L), any(LocalDateTime.class));
|
||||||
|
inOrder(orderArtistChangeRequestMapper, orderItemMapper).verify(orderItemMapper).updateById(item);
|
||||||
|
assertThat(item.getArtistId()).isEqualTo(31L);
|
||||||
|
verify(orderArtistChangeRequestMapper, never()).updateById(any(OrderArtistChangeRequestDO.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void approveArtistChangeRejectsConcurrentProcessedRequestBeforeAssigningArtist() {
|
||||||
|
OrderArtistChangeRequestDO request = pendingChangeRequest();
|
||||||
|
OrderDO order = pendingOrder();
|
||||||
|
OrderItemDO item = orderItem();
|
||||||
|
ProductDO product = product();
|
||||||
|
UserDO newArtist = artist(31L);
|
||||||
|
product.setBookableArtists("30,31");
|
||||||
|
|
||||||
|
when(orderArtistChangeRequestMapper.selectById(500L)).thenReturn(request);
|
||||||
|
when(orderMapper.selectById(1L)).thenReturn(order);
|
||||||
|
when(orderItemMapper.selectByIdForUpdate(10L)).thenReturn(item);
|
||||||
|
when(productMapper.selectById(20L)).thenReturn(product);
|
||||||
|
when(userMapper.selectById(31L)).thenReturn(newArtist);
|
||||||
|
when(userShopBindingSupport.isUserAccessibleInShop(31L, 3L)).thenReturn(true);
|
||||||
|
when(bookableArtistSupport.isBookableServiceUser(newArtist)).thenReturn(true);
|
||||||
|
when(bookableArtistSupport.isValidBookableArtist(3L, 31L)).thenReturn(true);
|
||||||
|
when(orderArtistChangeRequestMapper.approvePending(eq(500L), any(LocalDateTime.class))).thenReturn(0);
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> service.approveArtistChange(500L, 2L, 0))
|
||||||
|
.isInstanceOf(RuntimeException.class)
|
||||||
|
.hasMessage("改派申请已处理");
|
||||||
|
|
||||||
|
verify(orderItemMapper, never()).updateById(any(OrderItemDO.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void approveArtistChangeExpiresPendingRequestBeforeProcessing() {
|
||||||
|
OrderArtistChangeRequestDO request = pendingChangeRequest();
|
||||||
|
request.setExpireTime(LocalDateTime.now().minusMinutes(1));
|
||||||
|
when(orderArtistChangeRequestMapper.selectById(500L)).thenReturn(request);
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> service.approveArtistChange(500L, 2L, 0))
|
||||||
|
.isInstanceOf(RuntimeException.class)
|
||||||
|
.hasMessageContaining("过期");
|
||||||
|
|
||||||
|
verify(orderArtistChangeRequestMapper).expirePendingById(eq(500L), any(LocalDateTime.class));
|
||||||
|
verify(orderItemMapper, never()).selectByIdForUpdate(any());
|
||||||
|
verify(orderItemMapper, never()).updateById(any(OrderItemDO.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rejectArtistChangeUsesPendingConditionalUpdate() {
|
||||||
|
OrderArtistChangeRequestDO request = pendingChangeRequest();
|
||||||
|
when(orderArtistChangeRequestMapper.selectById(500L)).thenReturn(request);
|
||||||
|
when(orderArtistChangeRequestMapper.rejectPending(eq(500L), eq("客户不方便"), any(LocalDateTime.class))).thenReturn(1);
|
||||||
|
|
||||||
|
OrderArtistChangeRejectDTO dto = new OrderArtistChangeRejectDTO();
|
||||||
|
dto.setRejectReason("客户不方便");
|
||||||
|
|
||||||
|
service.rejectArtistChange(500L, 2L, 0, dto);
|
||||||
|
|
||||||
|
verify(orderArtistChangeRequestMapper).rejectPending(eq(500L), eq("客户不方便"), any(LocalDateTime.class));
|
||||||
|
verify(orderArtistChangeRequestMapper, never()).updateById(any(OrderArtistChangeRequestDO.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rejectArtistChangeRejectsConcurrentProcessedRequest() {
|
||||||
|
OrderArtistChangeRequestDO request = pendingChangeRequest();
|
||||||
|
when(orderArtistChangeRequestMapper.selectById(500L)).thenReturn(request);
|
||||||
|
when(orderArtistChangeRequestMapper.rejectPending(eq(500L), eq("客户不方便"), any(LocalDateTime.class))).thenReturn(0);
|
||||||
|
|
||||||
|
OrderArtistChangeRejectDTO dto = new OrderArtistChangeRejectDTO();
|
||||||
|
dto.setRejectReason("客户不方便");
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> service.rejectArtistChange(500L, 2L, 0, dto))
|
||||||
|
.isInstanceOf(RuntimeException.class)
|
||||||
|
.hasMessage("改派申请已处理");
|
||||||
|
|
||||||
|
verify(orderArtistChangeRequestMapper, never()).updateById(any(OrderArtistChangeRequestDO.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void listMyPendingArtistChangeRequestsExpiresDueRequestsFirst() {
|
||||||
|
when(orderArtistChangeRequestMapper.selectPendingByUserId(2L)).thenReturn(List.of());
|
||||||
|
|
||||||
|
assertThat(service.listMyPendingArtistChangeRequests(2L, 0)).isEmpty();
|
||||||
|
|
||||||
|
verify(orderArtistChangeRequestMapper).expirePendingBefore(any(LocalDateTime.class));
|
||||||
|
verify(orderArtistChangeRequestMapper).selectPendingByUserId(2L);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void submitArtistReviewRequiresHalfPointRating() {
|
||||||
|
OrderArtistReviewDO review = pendingReview();
|
||||||
|
when(orderArtistReviewMapper.selectById(100L)).thenReturn(review);
|
||||||
|
|
||||||
|
OrderArtistReviewSubmitDTO dto = new OrderArtistReviewSubmitDTO();
|
||||||
|
dto.setRating(new BigDecimal("4.25"));
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> service.submitArtistReview(100L, 2L, dto))
|
||||||
|
.isInstanceOf(RuntimeException.class)
|
||||||
|
.hasMessage("评分必须按0.5分递增");
|
||||||
|
|
||||||
|
verify(orderArtistReviewMapper, never()).updateById(any(OrderArtistReviewDO.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void submitArtistReviewAcceptsValidRatingAndRefreshesArtistRating() {
|
||||||
|
OrderArtistReviewDO review = pendingReview();
|
||||||
|
NailArtistInfoDO artistInfo = new NailArtistInfoDO();
|
||||||
|
artistInfo.setId(200L);
|
||||||
|
when(orderArtistReviewMapper.selectById(100L)).thenReturn(review);
|
||||||
|
when(orderArtistReviewMapper.selectAverageSubmittedRatingByArtistId(30L)).thenReturn(new BigDecimal("4.75"));
|
||||||
|
when(nailArtistInfoMapper.selectOne(any(LambdaQueryWrapper.class))).thenReturn(artistInfo);
|
||||||
|
|
||||||
|
OrderArtistReviewSubmitDTO dto = new OrderArtistReviewSubmitDTO();
|
||||||
|
dto.setRating(new BigDecimal("4.5"));
|
||||||
|
dto.setContent("服务很细致");
|
||||||
|
|
||||||
|
assertThat(service.submitArtistReview(100L, 2L, dto).getRatingScore()).isEqualByComparingTo("4.5");
|
||||||
|
|
||||||
|
verify(orderArtistReviewMapper).updateById(review);
|
||||||
|
verify(nailArtistInfoMapper).updateById(artistInfo);
|
||||||
|
assertThat(artistInfo.getRating()).isEqualByComparingTo("4.8");
|
||||||
|
}
|
||||||
|
|
||||||
|
private OrderDO pendingOrder() {
|
||||||
|
OrderDO order = new OrderDO();
|
||||||
|
order.setId(1L);
|
||||||
|
order.setUserId(2L);
|
||||||
|
order.setShopId(3L);
|
||||||
|
order.setStatus(1);
|
||||||
|
order.setIsDelete(0);
|
||||||
|
return order;
|
||||||
|
}
|
||||||
|
|
||||||
|
private OrderDO completedOrder() {
|
||||||
|
OrderDO order = pendingOrder();
|
||||||
|
order.setStatus(2);
|
||||||
|
return order;
|
||||||
|
}
|
||||||
|
|
||||||
|
private OrderItemDO orderItem() {
|
||||||
|
OrderItemDO item = new OrderItemDO();
|
||||||
|
item.setId(10L);
|
||||||
|
item.setOrderId(1L);
|
||||||
|
item.setProductId(20L);
|
||||||
|
item.setArtistId(30L);
|
||||||
|
item.setQuantity(1);
|
||||||
|
item.setIsDelete(0);
|
||||||
|
return item;
|
||||||
|
}
|
||||||
|
|
||||||
|
private ProductDO product() {
|
||||||
|
ProductDO product = new ProductDO();
|
||||||
|
product.setId(20L);
|
||||||
|
product.setTitle("凝胶美甲");
|
||||||
|
product.setIsDelete(0);
|
||||||
|
return product;
|
||||||
|
}
|
||||||
|
|
||||||
|
private UserDO artist(Long id) {
|
||||||
|
UserDO artist = new UserDO();
|
||||||
|
artist.setId(id);
|
||||||
|
artist.setType(3);
|
||||||
|
artist.setStatus(1);
|
||||||
|
artist.setIsDelete(0);
|
||||||
|
artist.setNickname("美甲师" + id);
|
||||||
|
return artist;
|
||||||
|
}
|
||||||
|
|
||||||
|
private OrderArtistReviewDO pendingReview() {
|
||||||
|
OrderArtistReviewDO review = new OrderArtistReviewDO();
|
||||||
|
review.setId(100L);
|
||||||
|
review.setOrderId(1L);
|
||||||
|
review.setOrderItemId(10L);
|
||||||
|
review.setProductId(20L);
|
||||||
|
review.setCustomerId(2L);
|
||||||
|
review.setArtistId(30L);
|
||||||
|
review.setStatus(0);
|
||||||
|
review.setIsDelete(0);
|
||||||
|
return review;
|
||||||
|
}
|
||||||
|
|
||||||
|
private OrderArtistChangeRequestDO pendingChangeRequest() {
|
||||||
|
OrderArtistChangeRequestDO request = new OrderArtistChangeRequestDO();
|
||||||
|
request.setId(500L);
|
||||||
|
request.setOrderId(1L);
|
||||||
|
request.setOrderItemId(10L);
|
||||||
|
request.setProductId(20L);
|
||||||
|
request.setShopId(3L);
|
||||||
|
request.setCustomerId(2L);
|
||||||
|
request.setFromArtistId(30L);
|
||||||
|
request.setToArtistId(31L);
|
||||||
|
request.setRequesterId(30L);
|
||||||
|
request.setStatus("PENDING");
|
||||||
|
request.setExpireTime(LocalDateTime.now().plusDays(1));
|
||||||
|
request.setIsDelete(0);
|
||||||
|
return request;
|
||||||
|
}
|
||||||
|
}
|
||||||
+235
@@ -0,0 +1,235 @@
|
|||||||
|
package com.xiaowang.yuminailcore.service.impl;
|
||||||
|
|
||||||
|
import com.xiaowang.yuminailcore.entity.PermissionDO;
|
||||||
|
import com.xiaowang.yuminailcore.entity.ShopRolePermissionDO;
|
||||||
|
import com.xiaowang.yuminailcore.entity.UserDO;
|
||||||
|
import com.xiaowang.yuminailcore.entity.UserPermissionDO;
|
||||||
|
import com.xiaowang.yuminailcore.entity.UserShopRoleDO;
|
||||||
|
import com.xiaowang.yuminailcore.mapper.PermissionMapper;
|
||||||
|
import com.xiaowang.yuminailcore.mapper.ShopRolePermissionMapper;
|
||||||
|
import com.xiaowang.yuminailcore.mapper.UserMapper;
|
||||||
|
import com.xiaowang.yuminailcore.mapper.UserPermissionMapper;
|
||||||
|
import com.xiaowang.yuminailcore.mapper.UserShopRoleMapper;
|
||||||
|
import com.xiaowang.yuminailcore.support.RequestShopContext;
|
||||||
|
import com.xiaowang.yuminailcore.support.UserShopBindingSupport;
|
||||||
|
import com.xiaowang.yuminailcore.vo.PermissionVO;
|
||||||
|
import org.junit.jupiter.api.AfterEach;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.MockitoAnnotations;
|
||||||
|
import org.springframework.mock.web.MockHttpServletRequest;
|
||||||
|
import org.springframework.web.context.request.RequestContextHolder;
|
||||||
|
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.Mockito.verifyNoInteractions;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
class PermissionServiceImplTest {
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private PermissionMapper permissionMapper;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private UserPermissionMapper userPermissionMapper;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private ShopRolePermissionMapper shopRolePermissionMapper;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private UserShopRoleMapper userShopRoleMapper;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private UserMapper userMapper;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private UserShopBindingSupport userShopBindingSupport;
|
||||||
|
|
||||||
|
private PermissionServiceImpl service;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
MockitoAnnotations.openMocks(this);
|
||||||
|
service = new PermissionServiceImpl(
|
||||||
|
permissionMapper,
|
||||||
|
userPermissionMapper,
|
||||||
|
shopRolePermissionMapper,
|
||||||
|
userShopRoleMapper,
|
||||||
|
userMapper,
|
||||||
|
userShopBindingSupport
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterEach
|
||||||
|
void tearDown() {
|
||||||
|
RequestContextHolder.resetRequestAttributes();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void activeShopRoleRestrictsWritePermissionFromDefaultUserPermissions() {
|
||||||
|
long userId = 10L;
|
||||||
|
long productCreateId = 101L;
|
||||||
|
long productViewId = 102L;
|
||||||
|
long roleId = 201L;
|
||||||
|
|
||||||
|
UserDO user = new UserDO();
|
||||||
|
user.setId(userId);
|
||||||
|
user.setType(2);
|
||||||
|
user.setIsDelete(0);
|
||||||
|
when(userMapper.selectById(userId)).thenReturn(user);
|
||||||
|
|
||||||
|
UserPermissionDO defaultProductCreate = new UserPermissionDO();
|
||||||
|
defaultProductCreate.setUserId(userId);
|
||||||
|
defaultProductCreate.setPermissionId(productCreateId);
|
||||||
|
when(userPermissionMapper.selectList(any())).thenReturn(List.of(defaultProductCreate));
|
||||||
|
|
||||||
|
PermissionDO productCreate = permission(productCreateId, "product:create");
|
||||||
|
PermissionDO productView = permission(productViewId, "product:view");
|
||||||
|
when(permissionMapper.selectOne(any()))
|
||||||
|
.thenReturn(productCreate)
|
||||||
|
.thenReturn(productView);
|
||||||
|
|
||||||
|
UserShopRoleDO roleBinding = new UserShopRoleDO();
|
||||||
|
roleBinding.setUserId(userId);
|
||||||
|
roleBinding.setRoleId(roleId);
|
||||||
|
roleBinding.setStatus(1);
|
||||||
|
roleBinding.setIsDelete(0);
|
||||||
|
when(userShopRoleMapper.selectList(any())).thenReturn(List.of(roleBinding));
|
||||||
|
|
||||||
|
ShopRolePermissionDO rolePermission = new ShopRolePermissionDO();
|
||||||
|
rolePermission.setRoleId(roleId);
|
||||||
|
rolePermission.setPermissionId(productViewId);
|
||||||
|
rolePermission.setIsDelete(0);
|
||||||
|
when(shopRolePermissionMapper.selectList(any())).thenReturn(List.of(rolePermission));
|
||||||
|
|
||||||
|
assertThat(service.hasPermission(userId, "product:create")).isFalse();
|
||||||
|
assertThat(service.hasPermission(userId, "product:view")).isTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void listUserPermissionsUsesActiveShopRoleAsVisiblePermissions() {
|
||||||
|
long userId = 10L;
|
||||||
|
long productCreateId = 101L;
|
||||||
|
long productViewId = 102L;
|
||||||
|
long roleId = 201L;
|
||||||
|
|
||||||
|
UserDO user = new UserDO();
|
||||||
|
user.setId(userId);
|
||||||
|
user.setType(2);
|
||||||
|
user.setIsDelete(0);
|
||||||
|
when(userMapper.selectById(userId)).thenReturn(user);
|
||||||
|
|
||||||
|
UserPermissionDO defaultProductCreate = new UserPermissionDO();
|
||||||
|
defaultProductCreate.setUserId(userId);
|
||||||
|
defaultProductCreate.setPermissionId(productCreateId);
|
||||||
|
when(userPermissionMapper.selectList(any())).thenReturn(List.of(defaultProductCreate));
|
||||||
|
|
||||||
|
UserShopRoleDO roleBinding = new UserShopRoleDO();
|
||||||
|
roleBinding.setUserId(userId);
|
||||||
|
roleBinding.setRoleId(roleId);
|
||||||
|
roleBinding.setStatus(1);
|
||||||
|
roleBinding.setIsDelete(0);
|
||||||
|
when(userShopRoleMapper.selectList(any())).thenReturn(List.of(roleBinding));
|
||||||
|
|
||||||
|
ShopRolePermissionDO rolePermission = new ShopRolePermissionDO();
|
||||||
|
rolePermission.setRoleId(roleId);
|
||||||
|
rolePermission.setPermissionId(productViewId);
|
||||||
|
rolePermission.setIsDelete(0);
|
||||||
|
when(shopRolePermissionMapper.selectList(any())).thenReturn(List.of(rolePermission));
|
||||||
|
|
||||||
|
when(permissionMapper.selectList(any())).thenReturn(List.of(permission(productViewId, "product:view")));
|
||||||
|
|
||||||
|
List<PermissionVO> permissions = service.listUserPermissions(userId);
|
||||||
|
|
||||||
|
assertThat(permissions)
|
||||||
|
.extracting(PermissionVO::getPermissionCode)
|
||||||
|
.containsExactly("product:view");
|
||||||
|
verify(shopRolePermissionMapper).selectList(any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void staleDirectPermissionsCannotExceedUserTypeDefaultPermissions() {
|
||||||
|
long userId = 30L;
|
||||||
|
|
||||||
|
UserDO user = new UserDO();
|
||||||
|
user.setId(userId);
|
||||||
|
user.setType(3);
|
||||||
|
user.setIsDelete(0);
|
||||||
|
when(userMapper.selectById(userId)).thenReturn(user);
|
||||||
|
|
||||||
|
assertThat(service.hasPermission(userId, "product:create")).isFalse();
|
||||||
|
|
||||||
|
verifyNoInteractions(userPermissionMapper);
|
||||||
|
verifyNoInteractions(userShopRoleMapper);
|
||||||
|
verifyNoInteractions(shopRolePermissionMapper);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void activeShopRolesAreScopedToCurrentShop() {
|
||||||
|
long userId = 10L;
|
||||||
|
long currentShopId = 301L;
|
||||||
|
long otherShopId = 302L;
|
||||||
|
long currentShopRoleId = 401L;
|
||||||
|
long otherShopRoleId = 402L;
|
||||||
|
long productCreateId = 101L;
|
||||||
|
long productViewId = 102L;
|
||||||
|
|
||||||
|
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||||
|
request.setAttribute(RequestShopContext.CURRENT_SHOP_ID_ATTRIBUTE, currentShopId);
|
||||||
|
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
|
||||||
|
|
||||||
|
UserDO user = new UserDO();
|
||||||
|
user.setId(userId);
|
||||||
|
user.setType(2);
|
||||||
|
user.setIsDelete(0);
|
||||||
|
when(userMapper.selectById(userId)).thenReturn(user);
|
||||||
|
|
||||||
|
UserShopRoleDO currentShopRole = roleBinding(userId, currentShopId, currentShopRoleId);
|
||||||
|
UserShopRoleDO otherShopRole = roleBinding(userId, otherShopId, otherShopRoleId);
|
||||||
|
when(userShopRoleMapper.selectList(any())).thenReturn(List.of(currentShopRole, otherShopRole));
|
||||||
|
|
||||||
|
ShopRolePermissionDO currentShopPermission = rolePermission(currentShopRoleId, productViewId);
|
||||||
|
ShopRolePermissionDO otherShopPermission = rolePermission(otherShopRoleId, productCreateId);
|
||||||
|
when(shopRolePermissionMapper.selectList(any())).thenReturn(List.of(currentShopPermission, otherShopPermission));
|
||||||
|
|
||||||
|
when(permissionMapper.selectOne(any()))
|
||||||
|
.thenReturn(permission(productCreateId, "product:create"))
|
||||||
|
.thenReturn(permission(productViewId, "product:view"));
|
||||||
|
|
||||||
|
assertThat(service.hasPermission(userId, "product:create")).isFalse();
|
||||||
|
assertThat(service.hasPermission(userId, "product:view")).isTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
private UserShopRoleDO roleBinding(long userId, long shopId, long roleId) {
|
||||||
|
UserShopRoleDO roleBinding = new UserShopRoleDO();
|
||||||
|
roleBinding.setUserId(userId);
|
||||||
|
roleBinding.setShopId(shopId);
|
||||||
|
roleBinding.setRoleId(roleId);
|
||||||
|
roleBinding.setStatus(1);
|
||||||
|
roleBinding.setIsDelete(0);
|
||||||
|
return roleBinding;
|
||||||
|
}
|
||||||
|
|
||||||
|
private ShopRolePermissionDO rolePermission(long roleId, long permissionId) {
|
||||||
|
ShopRolePermissionDO rolePermission = new ShopRolePermissionDO();
|
||||||
|
rolePermission.setRoleId(roleId);
|
||||||
|
rolePermission.setPermissionId(permissionId);
|
||||||
|
rolePermission.setIsDelete(0);
|
||||||
|
return rolePermission;
|
||||||
|
}
|
||||||
|
|
||||||
|
private PermissionDO permission(long id, String code) {
|
||||||
|
PermissionDO permission = new PermissionDO();
|
||||||
|
permission.setId(id);
|
||||||
|
permission.setPermissionCode(code);
|
||||||
|
permission.setPermissionName(code);
|
||||||
|
permission.setPermissionGroup("test");
|
||||||
|
permission.setIsDelete(0);
|
||||||
|
return permission;
|
||||||
|
}
|
||||||
|
}
|
||||||
+80
@@ -0,0 +1,80 @@
|
|||||||
|
package com.xiaowang.yuminailcore.service.impl;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
|
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||||
|
import com.xiaowang.yuminailcore.entity.SecurityAuditLogDO;
|
||||||
|
import com.xiaowang.yuminailcore.mapper.SecurityAuditLogMapper;
|
||||||
|
import com.xiaowang.yuminailcore.vo.PageResultVO;
|
||||||
|
import com.xiaowang.yuminailcore.vo.SecurityAuditLogVO;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.mockito.ArgumentCaptor;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.MockitoAnnotations;
|
||||||
|
import org.springframework.mock.web.MockHttpServletRequest;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
class SecurityAuditLogServiceImplTest {
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private SecurityAuditLogMapper auditLogMapper;
|
||||||
|
|
||||||
|
private SecurityAuditLogServiceImpl service;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
MockitoAnnotations.openMocks(this);
|
||||||
|
service = new SecurityAuditLogServiceImpl(auditLogMapper);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void recordTruncatesOversizedFieldsAndCapturesForwardedIp() {
|
||||||
|
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||||
|
request.addHeader("X-Forwarded-For", "10.0.0.1, 10.0.0.2");
|
||||||
|
|
||||||
|
service.record(1L, "a".repeat(100), "b".repeat(100), "SUCCESS", "c".repeat(600), request);
|
||||||
|
|
||||||
|
ArgumentCaptor<SecurityAuditLogDO> captor = ArgumentCaptor.forClass(SecurityAuditLogDO.class);
|
||||||
|
verify(auditLogMapper).insert(captor.capture());
|
||||||
|
SecurityAuditLogDO log = captor.getValue();
|
||||||
|
assertThat(log.getAccount()).hasSize(80);
|
||||||
|
assertThat(log.getAction()).hasSize(80);
|
||||||
|
assertThat(log.getReason()).hasSize(500);
|
||||||
|
assertThat(log.getIpAddress()).isEqualTo("10.0.0.1");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
void pageLogsFiltersAndMapsPagedResult() {
|
||||||
|
SecurityAuditLogDO log = new SecurityAuditLogDO();
|
||||||
|
log.setId(100L);
|
||||||
|
log.setUserId(1L);
|
||||||
|
log.setAccount("admin");
|
||||||
|
log.setAction("ORDER_PROCESS");
|
||||||
|
log.setResult("SUCCESS");
|
||||||
|
log.setReason("orderId=1");
|
||||||
|
log.setIpAddress("127.0.0.1");
|
||||||
|
log.setDeviceId("device-1");
|
||||||
|
log.setOperateTime(LocalDateTime.now());
|
||||||
|
Page<SecurityAuditLogDO> page = new Page<>(2, 5);
|
||||||
|
page.setRecords(List.of(log));
|
||||||
|
page.setTotal(11);
|
||||||
|
when(auditLogMapper.selectPage(any(Page.class), any(LambdaQueryWrapper.class))).thenReturn(page);
|
||||||
|
|
||||||
|
PageResultVO<SecurityAuditLogVO> result = service.pageLogs("admin", "ORDER_PROCESS", "SUCCESS",
|
||||||
|
LocalDateTime.now().minusDays(1), LocalDateTime.now(), 2, 5);
|
||||||
|
|
||||||
|
assertThat(result.getTotal()).isEqualTo(11);
|
||||||
|
assertThat(result.getPage()).isEqualTo(2);
|
||||||
|
assertThat(result.getSize()).isEqualTo(5);
|
||||||
|
assertThat(result.getList()).hasSize(1);
|
||||||
|
assertThat(result.getList().get(0).getAction()).isEqualTo("ORDER_PROCESS");
|
||||||
|
}
|
||||||
|
}
|
||||||
+102
@@ -0,0 +1,102 @@
|
|||||||
|
package com.xiaowang.yuminailcore.service.impl;
|
||||||
|
|
||||||
|
import com.xiaowang.yuminailcore.config.AppCacheProperties;
|
||||||
|
import com.xiaowang.yuminailcore.dto.ShopDTO;
|
||||||
|
import com.xiaowang.yuminailcore.entity.ShopDO;
|
||||||
|
import com.xiaowang.yuminailcore.mapper.CommentMapper;
|
||||||
|
import com.xiaowang.yuminailcore.mapper.CouponMapper;
|
||||||
|
import com.xiaowang.yuminailcore.mapper.ProductMapper;
|
||||||
|
import com.xiaowang.yuminailcore.mapper.ShopMapper;
|
||||||
|
import com.xiaowang.yuminailcore.mapper.TagMapper;
|
||||||
|
import com.xiaowang.yuminailcore.mapper.UserCouponMapper;
|
||||||
|
import com.xiaowang.yuminailcore.service.CouponService;
|
||||||
|
import com.xiaowang.yuminailcore.service.MapService;
|
||||||
|
import com.xiaowang.yuminailcore.support.UserShopBindingSupport;
|
||||||
|
import com.xiaowang.yuminailcore.support.cache.MultiLevelCacheService;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.MockitoAnnotations;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
|
import static org.mockito.Mockito.never;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.verifyNoInteractions;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
class ShopServiceImplTest {
|
||||||
|
@Mock
|
||||||
|
private ShopMapper shopMapper;
|
||||||
|
@Mock
|
||||||
|
private CouponService couponService;
|
||||||
|
@Mock
|
||||||
|
private CouponMapper couponMapper;
|
||||||
|
@Mock
|
||||||
|
private ProductMapper productMapper;
|
||||||
|
@Mock
|
||||||
|
private TagMapper tagMapper;
|
||||||
|
@Mock
|
||||||
|
private CommentMapper commentMapper;
|
||||||
|
@Mock
|
||||||
|
private UserCouponMapper userCouponMapper;
|
||||||
|
@Mock
|
||||||
|
private UserShopBindingSupport userShopBindingSupport;
|
||||||
|
@Mock
|
||||||
|
private MultiLevelCacheService multiLevelCacheService;
|
||||||
|
@Mock
|
||||||
|
private AppCacheProperties appCacheProperties;
|
||||||
|
@Mock
|
||||||
|
private MapService mapService;
|
||||||
|
|
||||||
|
private ShopServiceImpl service;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
MockitoAnnotations.openMocks(this);
|
||||||
|
service = new ShopServiceImpl(
|
||||||
|
shopMapper,
|
||||||
|
couponService,
|
||||||
|
couponMapper,
|
||||||
|
productMapper,
|
||||||
|
tagMapper,
|
||||||
|
commentMapper,
|
||||||
|
userCouponMapper,
|
||||||
|
userShopBindingSupport,
|
||||||
|
multiLevelCacheService,
|
||||||
|
appCacheProperties,
|
||||||
|
mapService
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void deleteShopRejectsBusinessDeleteWithoutCascadeSoftDelete() {
|
||||||
|
assertThatThrownBy(() -> service.deleteShop(1L))
|
||||||
|
.isInstanceOf(RuntimeException.class)
|
||||||
|
.hasMessage("店铺删除已停用,请使用停用封存");
|
||||||
|
|
||||||
|
verifyNoInteractions(
|
||||||
|
shopMapper,
|
||||||
|
couponMapper,
|
||||||
|
productMapper,
|
||||||
|
tagMapper,
|
||||||
|
commentMapper,
|
||||||
|
userCouponMapper,
|
||||||
|
userShopBindingSupport
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void updateShopRejectsDisabledArchivedShop() {
|
||||||
|
ShopDO disabledShop = new ShopDO();
|
||||||
|
disabledShop.setId(1L);
|
||||||
|
disabledShop.setStatus(0);
|
||||||
|
disabledShop.setIsDelete(0);
|
||||||
|
when(shopMapper.selectById(1L)).thenReturn(disabledShop);
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> service.updateShop(1L, new ShopDTO()))
|
||||||
|
.isInstanceOf(RuntimeException.class)
|
||||||
|
.hasMessage("停用店铺已封存,仅允许重新启用");
|
||||||
|
|
||||||
|
verify(shopMapper, never()).updateById(disabledShop);
|
||||||
|
}
|
||||||
|
}
|
||||||
+30
@@ -0,0 +1,30 @@
|
|||||||
|
package com.xiaowang.yuminailcore.support;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
|
|
||||||
|
class OrderStateMachineTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void allowsPendingOrderToCompleteOrCancel() {
|
||||||
|
assertThat(OrderStateMachine.isAllowedTransition(1, 2)).isTrue();
|
||||||
|
assertThat(OrderStateMachine.isAllowedTransition(1, 3)).isTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rejectsInvalidOrderTransition() {
|
||||||
|
assertThat(OrderStateMachine.isAllowedTransition(2, 3)).isFalse();
|
||||||
|
assertThatThrownBy(() -> OrderStateMachine.requireAllowedTransition(2, 3))
|
||||||
|
.isInstanceOf(RuntimeException.class)
|
||||||
|
.hasMessage("订单状态不允许处理");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rejectsUnknownTargetStatus() {
|
||||||
|
assertThatThrownBy(() -> OrderStatus.requireKnown(9))
|
||||||
|
.isInstanceOf(RuntimeException.class)
|
||||||
|
.hasMessage("无效的订单状态");
|
||||||
|
}
|
||||||
|
}
|
||||||
+19
-1
@@ -18,7 +18,7 @@ class PermissionCatalogTest {
|
|||||||
@Test
|
@Test
|
||||||
void platformOnlyPermissionsAreAvailableToAdminAndOverviewMode() {
|
void platformOnlyPermissionsAreAvailableToAdminAndOverviewMode() {
|
||||||
assertThat(PermissionCatalog.getDefaultPermissionCodes(4))
|
assertThat(PermissionCatalog.getDefaultPermissionCodes(4))
|
||||||
.contains("messagehub:config:manage", "legal_agreement:manage");
|
.contains("messagehub:config:manage", "security:audit:view", "legal_agreement:manage");
|
||||||
assertThat(PermissionCatalog.isAllowedForPlatformOverview("user:create")).isTrue();
|
assertThat(PermissionCatalog.isAllowedForPlatformOverview("user:create")).isTrue();
|
||||||
assertThat(PermissionCatalog.isAllowedForPlatformOverview("user:balance:manage")).isTrue();
|
assertThat(PermissionCatalog.isAllowedForPlatformOverview("user:balance:manage")).isTrue();
|
||||||
assertThat(PermissionCatalog.isAllowedForPlatformOverview("shop:delete")).isTrue();
|
assertThat(PermissionCatalog.isAllowedForPlatformOverview("shop:delete")).isTrue();
|
||||||
@@ -26,6 +26,7 @@ class PermissionCatalogTest {
|
|||||||
assertThat(PermissionCatalog.isAllowedForPlatformOverview("message:create")).isTrue();
|
assertThat(PermissionCatalog.isAllowedForPlatformOverview("message:create")).isTrue();
|
||||||
assertThat(PermissionCatalog.isAllowedForPlatformOverview("announcement:create")).isTrue();
|
assertThat(PermissionCatalog.isAllowedForPlatformOverview("announcement:create")).isTrue();
|
||||||
assertThat(PermissionCatalog.isAllowedForPlatformOverview("messagehub:config:manage")).isTrue();
|
assertThat(PermissionCatalog.isAllowedForPlatformOverview("messagehub:config:manage")).isTrue();
|
||||||
|
assertThat(PermissionCatalog.isAllowedForPlatformOverview("security:audit:view")).isTrue();
|
||||||
assertThat(PermissionCatalog.isAllowedForPlatformOverview("legal_agreement:manage")).isTrue();
|
assertThat(PermissionCatalog.isAllowedForPlatformOverview("legal_agreement:manage")).isTrue();
|
||||||
assertThat(PermissionCatalog.isAllowedForPlatformOverview("product:view")).isTrue();
|
assertThat(PermissionCatalog.isAllowedForPlatformOverview("product:view")).isTrue();
|
||||||
assertThat(PermissionCatalog.isAllowedForPlatformOverview("order:view")).isTrue();
|
assertThat(PermissionCatalog.isAllowedForPlatformOverview("order:view")).isTrue();
|
||||||
@@ -42,6 +43,23 @@ class PermissionCatalogTest {
|
|||||||
.containsAll(PermissionCatalog.getDefaultPermissionCodes(3));
|
.containsAll(PermissionCatalog.getDefaultPermissionCodes(3));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void nailArtistDefaultPermissionsAreWorkbenchOnly() {
|
||||||
|
assertThat(PermissionCatalog.getDefaultPermissionCodes(3))
|
||||||
|
.contains("product:view", "tag:view", "coupon:view", "order:view", "order:process", "order:artist-change")
|
||||||
|
.doesNotContain("product:create", "product:edit", "product:delete",
|
||||||
|
"tag:create", "tag:edit", "tag:delete",
|
||||||
|
"user:create", "user:edit", "coupon:create", "coupon:assign");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void artistChangePermissionIsGrantedToProductionRoles() {
|
||||||
|
assertChinesePermission("order:artist-change", "处理改派申请", "订单管理", "处理订单美甲师改派申请");
|
||||||
|
|
||||||
|
assertThat(PermissionCatalog.getDefaultPermissionCodes(2)).contains("order:artist-change");
|
||||||
|
assertThat(PermissionCatalog.getDefaultPermissionCodes(3)).contains("order:artist-change");
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void everyManagedDefaultPermissionUsesChineseDisplayText() {
|
void everyManagedDefaultPermissionUsesChineseDisplayText() {
|
||||||
PermissionCatalog.getManagedDefinitions().forEach(definition -> {
|
PermissionCatalog.getManagedDefinitions().forEach(definition -> {
|
||||||
|
|||||||
+47
@@ -0,0 +1,47 @@
|
|||||||
|
package com.xiaowang.yuminailcore.support;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
class YumiNailSqlSchemaTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void balanceTableDefinesUpdateTimeColumnBeforeSeedMigrations() throws Exception {
|
||||||
|
String sql = Files.readString(Path.of("src/main/resources/files/YumiNail.sql"));
|
||||||
|
|
||||||
|
assertThat(sql).containsPattern("(?is)create table t_balance\\s*\\([^;]*\\bupdate_time\\s+datetime");
|
||||||
|
assertThat(sql).contains("CALL sp_add_column_if_not_exists('t_balance', 'update_time'");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void orderArtistReviewAndChangeSchemasAreSeeded() throws Exception {
|
||||||
|
String sql = Files.readString(Path.of("src/main/resources/files/YumiNail.sql"));
|
||||||
|
|
||||||
|
assertThat(sql).contains("CREATE TABLE IF NOT EXISTS t_order_artist_review");
|
||||||
|
assertThat(sql).contains("CREATE TABLE IF NOT EXISTS t_order_artist_change_request");
|
||||||
|
assertThat(sql).contains("CALL sp_add_column_if_not_exists('t_system_message', 'business_type'");
|
||||||
|
assertThat(sql).contains("CALL sp_add_column_if_not_exists('t_system_message', 'business_id'");
|
||||||
|
assertThat(sql).contains("CALL sp_add_column_if_not_exists('t_system_message', 'action_path'");
|
||||||
|
assertThat(sql).contains("CALL sp_add_column_if_not_exists('t_system_message', 'idempotency_key'");
|
||||||
|
assertThat(sql).contains("CALL sp_add_unique_index_if_not_exists('t_system_message', 'uk_t_system_message_idempotency'");
|
||||||
|
assertThat(sql).contains("pending_key");
|
||||||
|
assertThat(sql).contains("EXPIRED");
|
||||||
|
assertThat(sql).contains("idx_order_artist_change_expire");
|
||||||
|
assertThat(sql).contains("CALL sp_add_unique_index_if_not_exists('t_order_artist_change_request', 'uk_order_artist_change_pending_key'");
|
||||||
|
assertThat(sql).contains("'order:artist-change'");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void businessEventOutboxAndSecurityAuditPermissionAreSeeded() throws Exception {
|
||||||
|
String sql = Files.readString(Path.of("src/main/resources/files/YumiNail.sql"));
|
||||||
|
|
||||||
|
assertThat(sql).contains("CREATE TABLE IF NOT EXISTS t_business_event_outbox");
|
||||||
|
assertThat(sql).contains("uk_business_event_outbox_event_key");
|
||||||
|
assertThat(sql).contains("idx_business_event_outbox_due");
|
||||||
|
assertThat(sql).contains("'security:audit:view'");
|
||||||
|
}
|
||||||
|
}
|
||||||
Generated
+925
-4
File diff suppressed because it is too large
Load Diff
@@ -6,7 +6,8 @@
|
|||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
"build": "vue-tsc -b && vite build",
|
"build": "vue-tsc -b && vite build",
|
||||||
"preview": "vite preview"
|
"preview": "vite preview",
|
||||||
|
"test:unit": "vitest run"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@element-plus/icons-vue": "^2.3.2",
|
"@element-plus/icons-vue": "^2.3.2",
|
||||||
@@ -22,13 +23,14 @@
|
|||||||
"@types/node": "^24.10.13",
|
"@types/node": "^24.10.13",
|
||||||
"@vitejs/plugin-vue": "^6.0.2",
|
"@vitejs/plugin-vue": "^6.0.2",
|
||||||
"@vue/tsconfig": "^0.8.1",
|
"@vue/tsconfig": "^0.8.1",
|
||||||
|
"jsdom": "^26.1.0",
|
||||||
"less": "^4.5.1",
|
"less": "^4.5.1",
|
||||||
"sass": "^1.97.3",
|
"sass": "^1.97.3",
|
||||||
"typescript": "~5.9.3",
|
"typescript": "~5.9.3",
|
||||||
"unplugin-auto-import": "^21.0.0",
|
"unplugin-auto-import": "^21.0.0",
|
||||||
"unplugin-vue-components": "^31.0.0",
|
"unplugin-vue-components": "^31.0.0",
|
||||||
"vite": "^7.3.1",
|
"vite": "^7.3.1",
|
||||||
|
"vitest": "^3.2.4",
|
||||||
"vue-tsc": "^3.1.5"
|
"vue-tsc": "^3.1.5"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -29,11 +29,13 @@ import SystemMessageCard from './components/SystemMessageCard.vue'
|
|||||||
import { cartApi } from './api/cart'
|
import { cartApi } from './api/cart'
|
||||||
import { userApi, type SystemMessageVO } from './api/user'
|
import { userApi, type SystemMessageVO } from './api/user'
|
||||||
import antdLocale from './config/antdv-locale'
|
import antdLocale from './config/antdv-locale'
|
||||||
|
import { useGlobalConfirmEnter } from './composables/useConfirmEnter'
|
||||||
import { useShopTheme } from './composables/useShopTheme'
|
import { useShopTheme } from './composables/useShopTheme'
|
||||||
|
|
||||||
const route = useRoute()
|
const route = useRoute()
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const { currentTheme, refreshShopTheme, resetShopTheme, setupShopThemeSync } = useShopTheme()
|
const { currentTheme, refreshShopTheme, resetShopTheme, setupShopThemeSync } = useShopTheme()
|
||||||
|
useGlobalConfirmEnter()
|
||||||
type ButtonPropsWithClass = ButtonProps & { class?: string }
|
type ButtonPropsWithClass = ButtonProps & { class?: string }
|
||||||
const popupMessageOkButtonProps: ButtonPropsWithClass = { class: 'popup-message-ok-button' }
|
const popupMessageOkButtonProps: ButtonPropsWithClass = { class: 'popup-message-ok-button' }
|
||||||
/** routerReady is a reactive state variable used by the template and event handlers. */
|
/** routerReady is a reactive state variable used by the template and event handlers. */
|
||||||
@@ -108,6 +110,22 @@ const updateCartCount = async () => {
|
|||||||
await loadCartCount()
|
await loadCartCount()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const resolveSystemMessageActionPath = (item: SystemMessageVO) => {
|
||||||
|
const actionPath = String(item.actionPath || '').trim()
|
||||||
|
if (!actionPath || !actionPath.startsWith('/') || actionPath.startsWith('//')) {
|
||||||
|
return ''
|
||||||
|
}
|
||||||
|
return actionPath
|
||||||
|
}
|
||||||
|
|
||||||
|
const openSystemMessageAction = async (item: SystemMessageVO) => {
|
||||||
|
const actionPath = resolveSystemMessageActionPath(item)
|
||||||
|
if (!actionPath) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
await router.push(actionPath)
|
||||||
|
}
|
||||||
|
|
||||||
/** showPopupMessage is a local helper used by this page script. */
|
/** showPopupMessage is a local helper used by this page script. */
|
||||||
const showPopupMessage = (item: SystemMessageVO) => {
|
const showPopupMessage = (item: SystemMessageVO) => {
|
||||||
return new Promise<void>((resolve) => {
|
return new Promise<void>((resolve) => {
|
||||||
@@ -142,6 +160,7 @@ const showPopupMessage = (item: SystemMessageVO) => {
|
|||||||
okButtonProps: popupMessageOkButtonProps,
|
okButtonProps: popupMessageOkButtonProps,
|
||||||
async onOk() {
|
async onOk() {
|
||||||
await markShownAndResolve()
|
await markShownAndResolve()
|
||||||
|
await openSystemMessageAction(item)
|
||||||
},
|
},
|
||||||
async afterClose() {
|
async afterClose() {
|
||||||
await markShownAndResolve()
|
await markShownAndResolve()
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import { ADMIN_API_BASE_URL } from '../config/api'
|
|||||||
import type { IdType } from '@/utils/id'
|
import type { IdType } from '@/utils/id'
|
||||||
import { clearAdminSessionStorage } from '@/utils/admin-session'
|
import { clearAdminSessionStorage } from '@/utils/admin-session'
|
||||||
import { attachRequestSignature } from '@/utils/request-signature'
|
import { attachRequestSignature } from '@/utils/request-signature'
|
||||||
|
import { isAdminApiAuthFreePath } from './auth-free-paths'
|
||||||
|
|
||||||
let lastErrorTime = 0
|
let lastErrorTime = 0
|
||||||
let lastErrorMessage = ''
|
let lastErrorMessage = ''
|
||||||
@@ -38,6 +39,25 @@ const processQueue = (error: any, token: string | null = null) => {
|
|||||||
failedQueue = []
|
failedQueue = []
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const getStoredAdminAccessToken = () => {
|
||||||
|
return localStorage.getItem('adminAccessToken') || sessionStorage.getItem('adminAccessToken')
|
||||||
|
}
|
||||||
|
|
||||||
|
const getRequestToken = (request: any) => {
|
||||||
|
if (request?._authToken) {
|
||||||
|
return request._authToken as string
|
||||||
|
}
|
||||||
|
const authHeader = request?.headers?.Authorization || request?.headers?.authorization
|
||||||
|
if (typeof authHeader !== 'string') {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
return authHeader.startsWith('Bearer ') ? authHeader.slice('Bearer '.length) : null
|
||||||
|
}
|
||||||
|
|
||||||
|
const isCurrentStoredAdminToken = (token: string | null) => {
|
||||||
|
return Boolean(token && token === getStoredAdminAccessToken())
|
||||||
|
}
|
||||||
|
|
||||||
const showError = (msg: string) => {
|
const showError = (msg: string) => {
|
||||||
const now = Date.now()
|
const now = Date.now()
|
||||||
if (now - lastErrorTime > ERROR_DEBOUNCE_TIME || msg !== lastErrorMessage) {
|
if (now - lastErrorTime > ERROR_DEBOUNCE_TIME || msg !== lastErrorMessage) {
|
||||||
@@ -48,10 +68,14 @@ const showError = (msg: string) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const isAuthFreePath = (url?: string) => {
|
const isAuthFreePath = (url?: string) => {
|
||||||
return Boolean(url?.includes('/auth/login') || url?.includes('/auth/login-shops/') || url?.includes('/auth/refresh'))
|
return isAdminApiAuthFreePath(url)
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleAdminTokenExpired = () => {
|
const handleAdminTokenExpired = (failedToken: string | null = null) => {
|
||||||
|
if (!isCurrentStoredAdminToken(failedToken)) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
clearAdminSessionStorage()
|
clearAdminSessionStorage()
|
||||||
|
|
||||||
if (Date.now() - lastErrorTime > ERROR_DEBOUNCE_TIME || lastErrorMessage !== '登录已过期,请重新登录') {
|
if (Date.now() - lastErrorTime > ERROR_DEBOUNCE_TIME || lastErrorMessage !== '登录已过期,请重新登录') {
|
||||||
@@ -67,14 +91,12 @@ adminApi.interceptors.request.use(
|
|||||||
async config => {
|
async config => {
|
||||||
let token: string | null = null
|
let token: string | null = null
|
||||||
if (!isAuthFreePath(config.url)) {
|
if (!isAuthFreePath(config.url)) {
|
||||||
token = localStorage.getItem('adminAccessToken')
|
token = getStoredAdminAccessToken()
|
||||||
if (!token) {
|
|
||||||
token = sessionStorage.getItem('adminAccessToken')
|
|
||||||
}
|
|
||||||
if (token) {
|
if (token) {
|
||||||
config.headers.Authorization = `Bearer ${token}`
|
config.headers.Authorization = `Bearer ${token}`
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
;(config as any)._authToken = token || null
|
||||||
return attachRequestSignature(config, token, {
|
return attachRequestSignature(config, token, {
|
||||||
authFree: isAuthFreePath(config.url)
|
authFree: isAuthFreePath(config.url)
|
||||||
})
|
})
|
||||||
@@ -100,6 +122,12 @@ adminApi.interceptors.response.use(
|
|||||||
const originalRequest = error.config as any
|
const originalRequest = error.config as any
|
||||||
|
|
||||||
if (error.response?.status === 401) {
|
if (error.response?.status === 401) {
|
||||||
|
const requestToken = getRequestToken(originalRequest)
|
||||||
|
|
||||||
|
if (!isCurrentStoredAdminToken(requestToken)) {
|
||||||
|
return Promise.reject(error)
|
||||||
|
}
|
||||||
|
|
||||||
if (!originalRequest?._retry && !isAuthFreePath(originalRequest?.url)) {
|
if (!originalRequest?._retry && !isAuthFreePath(originalRequest?.url)) {
|
||||||
if (isRefreshing) {
|
if (isRefreshing) {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
@@ -138,14 +166,14 @@ adminApi.interceptors.response.use(
|
|||||||
return adminApi(originalRequest)
|
return adminApi(originalRequest)
|
||||||
} catch (refreshError) {
|
} catch (refreshError) {
|
||||||
processQueue(refreshError, null)
|
processQueue(refreshError, null)
|
||||||
handleAdminTokenExpired()
|
handleAdminTokenExpired(requestToken)
|
||||||
return Promise.reject(refreshError)
|
return Promise.reject(refreshError)
|
||||||
} finally {
|
} finally {
|
||||||
isRefreshing = false
|
isRefreshing = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
handleAdminTokenExpired()
|
handleAdminTokenExpired(requestToken)
|
||||||
} else if (error.response?.status !== 403) {
|
} else if (error.response?.status !== 403) {
|
||||||
const errorMsg = (error.response?.data as any)?.message || error.message || '请求失败'
|
const errorMsg = (error.response?.data as any)?.message || error.message || '请求失败'
|
||||||
showError(errorMsg)
|
showError(errorMsg)
|
||||||
@@ -728,14 +756,6 @@ export const adminShopApi = {
|
|||||||
*/
|
*/
|
||||||
updateShopStatus: (id: IdType, status: number) => {
|
updateShopStatus: (id: IdType, status: number) => {
|
||||||
return adminApi.put<boolean>(`/shops/status/${id}`, { status })
|
return adminApi.put<boolean>(`/shops/status/${id}`, { status })
|
||||||
},
|
|
||||||
/**
|
|
||||||
* `deleteShop` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
|
|
||||||
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
|
|
||||||
* @param id: IdType caller-supplied value for `id: IdType`
|
|
||||||
*/
|
|
||||||
deleteShop: (id: IdType) => {
|
|
||||||
return adminApi.delete<boolean>(`/shops/delete/${id}`)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,56 @@
|
|||||||
|
export const WEB_API_AUTH_FREE_PATHS = [
|
||||||
|
'/user/login',
|
||||||
|
'/user/register',
|
||||||
|
'/user/check/',
|
||||||
|
'/user/refresh-token',
|
||||||
|
'/user/send-verification-code',
|
||||||
|
'/user/phone-login',
|
||||||
|
'/user/wechat-mini/',
|
||||||
|
'/user/reset-password-by-phone',
|
||||||
|
'/legal-agreement/current',
|
||||||
|
'/api/legal-agreement/current',
|
||||||
|
'/product/get/',
|
||||||
|
'/product/list/',
|
||||||
|
'/comment/list/product/',
|
||||||
|
'/shop/get/',
|
||||||
|
'/shop/list/public',
|
||||||
|
'/shop/list/simple',
|
||||||
|
'/tag/list/all',
|
||||||
|
'/file/get-signed-url/',
|
||||||
|
'/admin/auth/login',
|
||||||
|
'/admin/auth/login-shops/',
|
||||||
|
'/admin/auth/refresh'
|
||||||
|
] as const
|
||||||
|
|
||||||
|
export const ADMIN_API_AUTH_FREE_PATHS = [
|
||||||
|
'/auth/login',
|
||||||
|
'/auth/login-shops/',
|
||||||
|
'/auth/refresh'
|
||||||
|
] as const
|
||||||
|
|
||||||
|
const normalizePathname = (url?: string) => {
|
||||||
|
const raw = String(url || '')
|
||||||
|
const withoutHash = raw.split('#')[0] || ''
|
||||||
|
const withoutQuery = withoutHash.split('?')[0] || ''
|
||||||
|
try {
|
||||||
|
return new URL(withoutQuery, 'http://yuminail.local').pathname
|
||||||
|
} catch {
|
||||||
|
return withoutQuery.startsWith('/') ? withoutQuery : `/${withoutQuery}`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const matchesAuthFreePath = (url: string | undefined, path: string) => {
|
||||||
|
const pathname = normalizePathname(url)
|
||||||
|
if (path.endsWith('/')) {
|
||||||
|
return pathname === path.slice(0, -1) || pathname.startsWith(path)
|
||||||
|
}
|
||||||
|
return pathname === path
|
||||||
|
}
|
||||||
|
|
||||||
|
export const isApiAuthFreePath = (url?: string) => {
|
||||||
|
return WEB_API_AUTH_FREE_PATHS.some(path => matchesAuthFreePath(url, path))
|
||||||
|
}
|
||||||
|
|
||||||
|
export const isAdminApiAuthFreePath = (url?: string) => {
|
||||||
|
return ADMIN_API_AUTH_FREE_PATHS.some(path => matchesAuthFreePath(url, path))
|
||||||
|
}
|
||||||
@@ -11,6 +11,7 @@ import { API_BASE_URL } from '../config/api'
|
|||||||
import type { IdType } from '@/utils/id'
|
import type { IdType } from '@/utils/id'
|
||||||
import { clearAdminSessionStorage } from '@/utils/admin-session'
|
import { clearAdminSessionStorage } from '@/utils/admin-session'
|
||||||
import { attachRequestSignature } from '@/utils/request-signature'
|
import { attachRequestSignature } from '@/utils/request-signature'
|
||||||
|
import { isApiAuthFreePath } from './auth-free-paths'
|
||||||
|
|
||||||
// 防重复提示标志
|
// 防重复提示标志
|
||||||
let lastErrorTime = 0
|
let lastErrorTime = 0
|
||||||
@@ -31,6 +32,55 @@ let failedQueue: Array<{
|
|||||||
reject: (reason?: any) => void
|
reject: (reason?: any) => void
|
||||||
}> = []
|
}> = []
|
||||||
|
|
||||||
|
const getStoredAccessToken = (isAdmin = false) => {
|
||||||
|
return isAdmin
|
||||||
|
? (localStorage.getItem('adminAccessToken') || sessionStorage.getItem('adminAccessToken'))
|
||||||
|
: (localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken'))
|
||||||
|
}
|
||||||
|
|
||||||
|
const getStoredRefreshToken = (isAdmin = false) => {
|
||||||
|
return isAdmin
|
||||||
|
? (localStorage.getItem('adminRefreshToken') || sessionStorage.getItem('adminRefreshToken'))
|
||||||
|
: (localStorage.getItem('refreshToken') || sessionStorage.getItem('refreshToken'))
|
||||||
|
}
|
||||||
|
|
||||||
|
const getRequestToken = (request: any) => {
|
||||||
|
if (request?._authToken) {
|
||||||
|
return request._authToken as string
|
||||||
|
}
|
||||||
|
|
||||||
|
const authHeader = request?.headers?.Authorization || request?.headers?.authorization
|
||||||
|
if (typeof authHeader !== 'string') {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
return authHeader.startsWith('Bearer ') ? authHeader.slice('Bearer '.length) : null
|
||||||
|
}
|
||||||
|
|
||||||
|
const isCurrentStoredToken = (token: string | null, isAdmin = false) => {
|
||||||
|
return Boolean(token && token === getStoredAccessToken(isAdmin))
|
||||||
|
}
|
||||||
|
|
||||||
|
const getResponseMessage = (error: AxiosError) => {
|
||||||
|
return (error.response?.data as any)?.message || error.message || '请求失败'
|
||||||
|
}
|
||||||
|
|
||||||
|
const isTokenExpiredResponse = (error: AxiosError, requestToken: string | null) => {
|
||||||
|
const messageText = getResponseMessage(error)
|
||||||
|
return Boolean(
|
||||||
|
requestToken
|
||||||
|
&& (
|
||||||
|
messageText.includes('Token')
|
||||||
|
|| messageText.includes('token')
|
||||||
|
|| messageText.includes('登录态')
|
||||||
|
|| messageText.includes('登录已过期')
|
||||||
|
|| messageText.includes('未登录')
|
||||||
|
|| messageText.includes('认证')
|
||||||
|
|| messageText.includes('重新登录')
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
const processQueue = (error: any, token: string | null = null) => {
|
const processQueue = (error: any, token: string | null = null) => {
|
||||||
failedQueue.forEach(prom => {
|
failedQueue.forEach(prom => {
|
||||||
if (error) {
|
if (error) {
|
||||||
@@ -53,32 +103,14 @@ const showError = (msg: string) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const isAuthFreePath = (url?: string) => {
|
const isAuthFreePath = (url?: string) => {
|
||||||
return [
|
return isApiAuthFreePath(url)
|
||||||
'/user/login',
|
|
||||||
'/user/register',
|
|
||||||
'/user/check/',
|
|
||||||
'/user/refresh-token',
|
|
||||||
'/user/send-verification-code',
|
|
||||||
'/user/phone-login',
|
|
||||||
'/user/wechat-mini/',
|
|
||||||
'/user/reset-password-by-phone',
|
|
||||||
'/legal-agreement/current',
|
|
||||||
'/api/legal-agreement/current',
|
|
||||||
'/product/get/',
|
|
||||||
'/product/list/',
|
|
||||||
'/comment/list/product/',
|
|
||||||
'/shop/get/',
|
|
||||||
'/shop/list/public',
|
|
||||||
'/shop/list/simple',
|
|
||||||
'/tag/list/all',
|
|
||||||
'/file/get-signed-url/',
|
|
||||||
'/admin/auth/login',
|
|
||||||
'/admin/auth/login-shops/',
|
|
||||||
'/admin/auth/refresh'
|
|
||||||
].some(path => String(url || '').includes(path))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleTokenExpired = (isAdmin = false) => {
|
const handleTokenExpired = (isAdmin = false, failedToken: string | null = null) => {
|
||||||
|
if (!isCurrentStoredToken(failedToken, isAdmin)) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
// 清理token和用户信息
|
// 清理token和用户信息
|
||||||
if (isAdmin) {
|
if (isAdmin) {
|
||||||
// 清理后台管理的token
|
// 清理后台管理的token
|
||||||
@@ -89,6 +121,7 @@ const handleTokenExpired = (isAdmin = false) => {
|
|||||||
localStorage.removeItem('refreshToken')
|
localStorage.removeItem('refreshToken')
|
||||||
localStorage.removeItem('userInfo')
|
localStorage.removeItem('userInfo')
|
||||||
sessionStorage.removeItem('accessToken')
|
sessionStorage.removeItem('accessToken')
|
||||||
|
sessionStorage.removeItem('refreshToken')
|
||||||
}
|
}
|
||||||
|
|
||||||
// 显示错误提示
|
// 显示错误提示
|
||||||
@@ -124,6 +157,7 @@ api.interceptors.request.use(
|
|||||||
if (token) {
|
if (token) {
|
||||||
config.headers.Authorization = `Bearer ${token}`
|
config.headers.Authorization = `Bearer ${token}`
|
||||||
}
|
}
|
||||||
|
;(config as any)._authToken = token || null
|
||||||
return attachRequestSignature(config, token, {
|
return attachRequestSignature(config, token, {
|
||||||
authFree: isAuthFreePath(config.url)
|
authFree: isAuthFreePath(config.url)
|
||||||
})
|
})
|
||||||
@@ -149,28 +183,23 @@ api.interceptors.response.use(
|
|||||||
const originalRequest = error.config as any
|
const originalRequest = error.config as any
|
||||||
|
|
||||||
const isWhitelistedPath = (url: string) => {
|
const isWhitelistedPath = (url: string) => {
|
||||||
return url?.includes('/user/login') ||
|
return isApiAuthFreePath(url)
|
||||||
url?.includes('/user/register') ||
|
|
||||||
url?.includes('/user/check/') ||
|
|
||||||
url?.includes('/user/refresh-token') ||
|
|
||||||
url?.includes('/user/send-verification-code') ||
|
|
||||||
url?.includes('/user/phone-login') ||
|
|
||||||
url?.includes('/legal-agreement/current') ||
|
|
||||||
url?.includes('/product/get/') ||
|
|
||||||
url?.includes('/product/list/') ||
|
|
||||||
url?.includes('/comment/list/product/') ||
|
|
||||||
url?.includes('/shop/get/') ||
|
|
||||||
url?.includes('/shop/list/public') ||
|
|
||||||
url?.includes('/shop/list/simple') ||
|
|
||||||
url?.includes('/tag/list/all') ||
|
|
||||||
url?.includes('/file/get-signed-url/') ||
|
|
||||||
url?.includes('/admin/auth/login') ||
|
|
||||||
url?.includes('/admin/auth/refresh')
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (error.response?.status === 401) {
|
if (error.response?.status === 401) {
|
||||||
// 检查是否是后台管理的API请求
|
// 检查是否是后台管理的API请求
|
||||||
const isAdminRequest = originalRequest.url?.includes('/admin/') || originalRequest.url?.includes('/order/admin/')
|
const isAdminRequest = originalRequest.url?.includes('/admin/') || originalRequest.url?.includes('/order/admin/')
|
||||||
|
const requestToken = getRequestToken(originalRequest)
|
||||||
|
const isRealTokenExpired = isTokenExpiredResponse(error, requestToken)
|
||||||
|
|
||||||
|
if (!isRealTokenExpired) {
|
||||||
|
showError(getResponseMessage(error))
|
||||||
|
return Promise.reject(error)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isCurrentStoredToken(requestToken, isAdminRequest)) {
|
||||||
|
return Promise.reject(error)
|
||||||
|
}
|
||||||
|
|
||||||
if (!originalRequest._retry && !isWhitelistedPath(originalRequest.url)) {
|
if (!originalRequest._retry && !isWhitelistedPath(originalRequest.url)) {
|
||||||
if (isRefreshing) {
|
if (isRefreshing) {
|
||||||
@@ -179,6 +208,7 @@ api.interceptors.response.use(
|
|||||||
}).then(token => {
|
}).then(token => {
|
||||||
if (token) {
|
if (token) {
|
||||||
originalRequest.headers.Authorization = `Bearer ${token}`
|
originalRequest.headers.Authorization = `Bearer ${token}`
|
||||||
|
originalRequest._authToken = token
|
||||||
}
|
}
|
||||||
return api(originalRequest)
|
return api(originalRequest)
|
||||||
}).catch(err => {
|
}).catch(err => {
|
||||||
@@ -192,9 +222,9 @@ api.interceptors.response.use(
|
|||||||
try {
|
try {
|
||||||
let refreshToken
|
let refreshToken
|
||||||
if (isAdminRequest) {
|
if (isAdminRequest) {
|
||||||
refreshToken = localStorage.getItem('adminRefreshToken') || sessionStorage.getItem('adminRefreshToken')
|
refreshToken = getStoredRefreshToken(true)
|
||||||
} else {
|
} else {
|
||||||
refreshToken = localStorage.getItem('refreshToken') || sessionStorage.getItem('refreshToken')
|
refreshToken = getStoredRefreshToken(false)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!refreshToken) {
|
if (!refreshToken) {
|
||||||
@@ -217,21 +247,23 @@ api.interceptors.response.use(
|
|||||||
localStorage.setItem('accessToken', newToken)
|
localStorage.setItem('accessToken', newToken)
|
||||||
localStorage.setItem('refreshToken', newRefreshToken)
|
localStorage.setItem('refreshToken', newRefreshToken)
|
||||||
sessionStorage.setItem('accessToken', newToken)
|
sessionStorage.setItem('accessToken', newToken)
|
||||||
|
sessionStorage.setItem('refreshToken', newRefreshToken)
|
||||||
}
|
}
|
||||||
|
|
||||||
processQueue(null, newToken)
|
processQueue(null, newToken)
|
||||||
|
|
||||||
originalRequest.headers.Authorization = `Bearer ${newToken}`
|
originalRequest.headers.Authorization = `Bearer ${newToken}`
|
||||||
|
originalRequest._authToken = newToken
|
||||||
return api(originalRequest)
|
return api(originalRequest)
|
||||||
} catch (refreshError) {
|
} catch (refreshError) {
|
||||||
processQueue(refreshError, null)
|
processQueue(refreshError, null)
|
||||||
handleTokenExpired(isAdminRequest)
|
handleTokenExpired(isAdminRequest, requestToken)
|
||||||
return Promise.reject(refreshError)
|
return Promise.reject(refreshError)
|
||||||
} finally {
|
} finally {
|
||||||
isRefreshing = false
|
isRefreshing = false
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
handleTokenExpired(isAdminRequest)
|
handleTokenExpired(isAdminRequest, requestToken)
|
||||||
return Promise.reject(error)
|
return Promise.reject(error)
|
||||||
}
|
}
|
||||||
} else if (error.response?.status !== 403) { // 403权限不足不提示
|
} else if (error.response?.status !== 403) { // 403权限不足不提示
|
||||||
|
|||||||
@@ -40,6 +40,77 @@ export interface ArtistCalendarAppointment {
|
|||||||
durationMinutes: number
|
durationMinutes: number
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface OrderArtistReviewVO {
|
||||||
|
id: IdType
|
||||||
|
orderId: IdType
|
||||||
|
orderItemId: IdType
|
||||||
|
productId?: IdType
|
||||||
|
productTitle?: string
|
||||||
|
artistId?: IdType
|
||||||
|
artistName?: string
|
||||||
|
artistAvatar?: string
|
||||||
|
userId?: IdType
|
||||||
|
rating?: number
|
||||||
|
content?: string
|
||||||
|
imageFileIds?: IdType[]
|
||||||
|
status?: number
|
||||||
|
statusText?: string
|
||||||
|
submitTime?: string
|
||||||
|
createTime?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OrderArtistReviewSubmitRequest {
|
||||||
|
rating: number
|
||||||
|
content?: string
|
||||||
|
imageFileIds: IdType[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OrderArtistChangeOptionsVO {
|
||||||
|
orderId: IdType
|
||||||
|
orderItemId: IdType
|
||||||
|
currentArtistId?: IdType
|
||||||
|
currentArtistName?: string
|
||||||
|
artists: Array<{
|
||||||
|
artistId: IdType
|
||||||
|
artistName: string
|
||||||
|
artistAvatar?: string
|
||||||
|
userType?: number
|
||||||
|
participateProduction?: boolean
|
||||||
|
}>
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OrderArtistChangeRequestVO {
|
||||||
|
id: IdType
|
||||||
|
orderId: IdType
|
||||||
|
orderItemId: IdType
|
||||||
|
productId?: IdType
|
||||||
|
productTitle?: string
|
||||||
|
shopId?: IdType
|
||||||
|
userId?: IdType
|
||||||
|
originalArtistId?: IdType
|
||||||
|
originalArtistName?: string
|
||||||
|
requestedArtistId?: IdType
|
||||||
|
requestedArtistName?: string
|
||||||
|
status?: string
|
||||||
|
statusText?: string
|
||||||
|
reason?: string
|
||||||
|
rejectReason?: string
|
||||||
|
reviewerId?: IdType
|
||||||
|
reviewTime?: string
|
||||||
|
createTime?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OrderArtistChangeRequestSubmitRequest {
|
||||||
|
orderId: IdType
|
||||||
|
orderItemId: IdType
|
||||||
|
requestedArtistId: IdType
|
||||||
|
reason: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OrderArtistChangeRejectRequest {
|
||||||
|
rejectReason?: string
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* orderApi groups all API calls for this page domain.
|
* orderApi groups all API calls for this page domain.
|
||||||
* Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script.
|
* Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script.
|
||||||
@@ -59,6 +130,40 @@ export const orderApi = {
|
|||||||
getOrderList: async (): Promise<any[]> => {
|
getOrderList: async (): Promise<any[]> => {
|
||||||
return await api.get<any[]>('/order/list') as unknown as any[]
|
return await api.get<any[]>('/order/list') as unknown as any[]
|
||||||
},
|
},
|
||||||
|
|
||||||
|
getMyPendingReviews: async (): Promise<OrderArtistReviewVO[]> => {
|
||||||
|
return await api.get<OrderArtistReviewVO[]>('/order/review/my-pending') as unknown as OrderArtistReviewVO[]
|
||||||
|
},
|
||||||
|
|
||||||
|
getOrderReviews: async (orderId: IdType): Promise<OrderArtistReviewVO[]> => {
|
||||||
|
return await api.get<OrderArtistReviewVO[]>(`/order/${orderId}/reviews`) as unknown as OrderArtistReviewVO[]
|
||||||
|
},
|
||||||
|
|
||||||
|
submitArtistReview: async (reviewId: IdType, data: OrderArtistReviewSubmitRequest): Promise<OrderArtistReviewVO> => {
|
||||||
|
return await api.post<OrderArtistReviewVO>(`/order/review/${reviewId}/submit`, data) as unknown as OrderArtistReviewVO
|
||||||
|
},
|
||||||
|
|
||||||
|
getArtistChangeOptions: async (orderId: IdType, orderItemId: IdType): Promise<OrderArtistChangeOptionsVO> => {
|
||||||
|
return await api.get<OrderArtistChangeOptionsVO>(`/order/${orderId}/artist-change/options`, {
|
||||||
|
params: { orderItemId }
|
||||||
|
}) as unknown as OrderArtistChangeOptionsVO
|
||||||
|
},
|
||||||
|
|
||||||
|
requestArtistChange: async (data: OrderArtistChangeRequestSubmitRequest): Promise<OrderArtistChangeRequestVO> => {
|
||||||
|
return await api.post<OrderArtistChangeRequestVO>('/order/artist-change/request', data) as unknown as OrderArtistChangeRequestVO
|
||||||
|
},
|
||||||
|
|
||||||
|
getMyPendingArtistChangeRequests: async (): Promise<OrderArtistChangeRequestVO[]> => {
|
||||||
|
return await api.get<OrderArtistChangeRequestVO[]>('/order/artist-change/my-pending') as unknown as OrderArtistChangeRequestVO[]
|
||||||
|
},
|
||||||
|
|
||||||
|
approveArtistChange: async (requestId: IdType): Promise<OrderArtistChangeRequestVO> => {
|
||||||
|
return await api.put<OrderArtistChangeRequestVO>(`/order/artist-change/${requestId}/approve`) as unknown as OrderArtistChangeRequestVO
|
||||||
|
},
|
||||||
|
|
||||||
|
rejectArtistChange: async (requestId: IdType, data?: OrderArtistChangeRejectRequest): Promise<OrderArtistChangeRequestVO> => {
|
||||||
|
return await api.put<OrderArtistChangeRequestVO>(`/order/artist-change/${requestId}/reject`, data || {}) as unknown as OrderArtistChangeRequestVO
|
||||||
|
},
|
||||||
|
|
||||||
// 获取订单详情
|
// 获取订单详情
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -180,6 +180,9 @@ export interface SystemMessageVO {
|
|||||||
publisherName?: string
|
publisherName?: string
|
||||||
targetType?: string
|
targetType?: string
|
||||||
targetTypeName?: string
|
targetTypeName?: string
|
||||||
|
businessType?: string
|
||||||
|
businessId?: IdType
|
||||||
|
actionPath?: string
|
||||||
popupEnabled?: number
|
popupEnabled?: number
|
||||||
popupShown?: number
|
popupShown?: number
|
||||||
readStatus?: number
|
readStatus?: number
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
:title="title"
|
:title="title"
|
||||||
:width="mergedWidth"
|
:width="mergedWidth"
|
||||||
:centered="!isMobile"
|
:centered="!isMobile"
|
||||||
:wrap-class-name="isMobile ? 'admin-mobile-modal' : undefined"
|
:wrap-class-name="mergedWrapClassName"
|
||||||
:style="mergedStyle"
|
:style="mergedStyle"
|
||||||
:body-style="mergedBodyStyle"
|
:body-style="mergedBodyStyle"
|
||||||
@update:open="handleOpenChange"
|
@update:open="handleOpenChange"
|
||||||
@@ -25,18 +25,23 @@
|
|||||||
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
|
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
|
||||||
*/
|
*/
|
||||||
import type { CSSProperties } from 'vue'
|
import type { CSSProperties } from 'vue'
|
||||||
import { computed } from 'vue'
|
import { computed, useAttrs } from 'vue'
|
||||||
import { useAdminViewport } from '@/composables/useAdminViewport'
|
import { useAdminViewport } from '@/composables/useAdminViewport'
|
||||||
|
import { CONFIRM_ENTER_DISABLED_CLASS } from '@/composables/useConfirmEnter'
|
||||||
|
|
||||||
|
let modalInstanceSeed = 0
|
||||||
|
|
||||||
const props = withDefaults(defineProps<{
|
const props = withDefaults(defineProps<{
|
||||||
open: boolean
|
open: boolean
|
||||||
title?: string
|
title?: string
|
||||||
desktopWidth?: string | number
|
desktopWidth?: string | number
|
||||||
mobileBodyPadding?: string
|
mobileBodyPadding?: string
|
||||||
|
confirmOnEnter?: boolean
|
||||||
}>(), {
|
}>(), {
|
||||||
title: '',
|
title: '',
|
||||||
desktopWidth: 720,
|
desktopWidth: 720,
|
||||||
mobileBodyPadding: '16px 16px 104px'
|
mobileBodyPadding: '16px 16px 104px',
|
||||||
|
confirmOnEnter: true
|
||||||
})
|
})
|
||||||
|
|
||||||
const emit = defineEmits<{
|
const emit = defineEmits<{
|
||||||
@@ -46,6 +51,8 @@ const emit = defineEmits<{
|
|||||||
}>()
|
}>()
|
||||||
|
|
||||||
const { isMobile } = useAdminViewport()
|
const { isMobile } = useAdminViewport()
|
||||||
|
const attrs = useAttrs()
|
||||||
|
const modalInstanceClass = `admin-responsive-modal-${modalInstanceSeed++}`
|
||||||
|
|
||||||
/** mergedWidth is a reactive state variable used by the template and event handlers. */
|
/** mergedWidth is a reactive state variable used by the template and event handlers. */
|
||||||
const mergedWidth = computed(() => (isMobile.value ? '100vw' : props.desktopWidth))
|
const mergedWidth = computed(() => (isMobile.value ? '100vw' : props.desktopWidth))
|
||||||
@@ -59,6 +66,16 @@ const mergedStyle = computed(() => (
|
|||||||
}
|
}
|
||||||
: undefined
|
: undefined
|
||||||
))
|
))
|
||||||
|
const mergedWrapClassName = computed(() => (
|
||||||
|
[
|
||||||
|
attrs.wrapClassName || attrs['wrap-class-name'],
|
||||||
|
isMobile.value ? 'admin-mobile-modal' : '',
|
||||||
|
props.confirmOnEnter ? '' : CONFIRM_ENTER_DISABLED_CLASS,
|
||||||
|
modalInstanceClass
|
||||||
|
]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(' ')
|
||||||
|
))
|
||||||
/** mergedBodyStyle is a reactive state variable used by the template and event handlers. */
|
/** mergedBodyStyle is a reactive state variable used by the template and event handlers. */
|
||||||
const mergedBodyStyle = computed(() => (
|
const mergedBodyStyle = computed(() => (
|
||||||
isMobile.value
|
isMobile.value
|
||||||
|
|||||||
@@ -0,0 +1,238 @@
|
|||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
import { createApp } from 'vue'
|
||||||
|
import { useGlobalConfirmEnter } from './useConfirmEnter'
|
||||||
|
|
||||||
|
const visibleRects = [{
|
||||||
|
bottom: 100,
|
||||||
|
height: 100,
|
||||||
|
left: 0,
|
||||||
|
right: 100,
|
||||||
|
top: 0,
|
||||||
|
width: 100,
|
||||||
|
x: 0,
|
||||||
|
y: 0,
|
||||||
|
toJSON: () => ({})
|
||||||
|
}] as DOMRect[]
|
||||||
|
|
||||||
|
const makeVisible = (element: HTMLElement) => {
|
||||||
|
vi.spyOn(element, 'getClientRects').mockReturnValue(visibleRects as unknown as DOMRectList)
|
||||||
|
}
|
||||||
|
|
||||||
|
const setDesktopViewport = () => {
|
||||||
|
Object.defineProperty(window, 'innerWidth', {
|
||||||
|
configurable: true,
|
||||||
|
value: 1280
|
||||||
|
})
|
||||||
|
window.matchMedia = vi.fn().mockImplementation((query: string) => ({
|
||||||
|
matches: query === '(pointer: coarse)' ? false : false,
|
||||||
|
media: query,
|
||||||
|
onchange: null,
|
||||||
|
addEventListener: vi.fn(),
|
||||||
|
removeEventListener: vi.fn(),
|
||||||
|
addListener: vi.fn(),
|
||||||
|
removeListener: vi.fn(),
|
||||||
|
dispatchEvent: vi.fn()
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
const setMobileViewport = () => {
|
||||||
|
Object.defineProperty(window, 'innerWidth', {
|
||||||
|
configurable: true,
|
||||||
|
value: 640
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const setCoarsePointer = () => {
|
||||||
|
Object.defineProperty(window, 'innerWidth', {
|
||||||
|
configurable: true,
|
||||||
|
value: 1280
|
||||||
|
})
|
||||||
|
window.matchMedia = vi.fn().mockImplementation((query: string) => ({
|
||||||
|
matches: query === '(pointer: coarse)',
|
||||||
|
media: query,
|
||||||
|
onchange: null,
|
||||||
|
addEventListener: vi.fn(),
|
||||||
|
removeEventListener: vi.fn(),
|
||||||
|
addListener: vi.fn(),
|
||||||
|
removeListener: vi.fn(),
|
||||||
|
dispatchEvent: vi.fn()
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
const mountGlobalConfirmEnter = () => {
|
||||||
|
const host = document.createElement('div')
|
||||||
|
document.body.appendChild(host)
|
||||||
|
|
||||||
|
const app = createApp({
|
||||||
|
setup() {
|
||||||
|
useGlobalConfirmEnter()
|
||||||
|
return () => null
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
app.mount(host)
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
app.unmount()
|
||||||
|
host.remove()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const createModal = ({
|
||||||
|
zIndex = 1000,
|
||||||
|
buttonClass = '',
|
||||||
|
disabled = false,
|
||||||
|
ariaDisabled = false,
|
||||||
|
footerClass = 'ant-modal-footer'
|
||||||
|
}: {
|
||||||
|
zIndex?: number
|
||||||
|
buttonClass?: string
|
||||||
|
disabled?: boolean
|
||||||
|
ariaDisabled?: boolean
|
||||||
|
footerClass?: 'ant-modal-footer' | 'ant-modal-confirm-btns'
|
||||||
|
} = {}) => {
|
||||||
|
const wrap = document.createElement('div')
|
||||||
|
wrap.className = 'ant-modal-wrap'
|
||||||
|
wrap.style.zIndex = String(zIndex)
|
||||||
|
|
||||||
|
const footer = document.createElement('div')
|
||||||
|
footer.className = footerClass
|
||||||
|
|
||||||
|
const button = document.createElement('button')
|
||||||
|
button.type = 'button'
|
||||||
|
button.className = `ant-btn ant-btn-primary ${buttonClass}`.trim()
|
||||||
|
button.disabled = disabled
|
||||||
|
if (ariaDisabled) {
|
||||||
|
button.setAttribute('aria-disabled', 'true')
|
||||||
|
}
|
||||||
|
|
||||||
|
const onClick = vi.fn()
|
||||||
|
const click = vi.spyOn(button, 'click')
|
||||||
|
button.addEventListener('click', onClick)
|
||||||
|
|
||||||
|
footer.appendChild(button)
|
||||||
|
wrap.appendChild(footer)
|
||||||
|
document.body.appendChild(wrap)
|
||||||
|
makeVisible(wrap)
|
||||||
|
makeVisible(button)
|
||||||
|
|
||||||
|
return { wrap, button, click, onClick }
|
||||||
|
}
|
||||||
|
|
||||||
|
const createKeyboardEvent = () => new KeyboardEvent('keydown', {
|
||||||
|
key: 'Enter',
|
||||||
|
bubbles: true,
|
||||||
|
cancelable: true
|
||||||
|
})
|
||||||
|
|
||||||
|
const pressEnter = (target: EventTarget = document) => {
|
||||||
|
const event = createKeyboardEvent()
|
||||||
|
target.dispatchEvent(event)
|
||||||
|
return event
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('useGlobalConfirmEnter', () => {
|
||||||
|
let unmount: (() => void) | undefined
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
document.body.innerHTML = ''
|
||||||
|
setDesktopViewport()
|
||||||
|
unmount = mountGlobalConfirmEnter()
|
||||||
|
})
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
unmount?.()
|
||||||
|
document.body.innerHTML = ''
|
||||||
|
vi.restoreAllMocks()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('clicks the visible top modal primary ok button when PC users press Enter', () => {
|
||||||
|
const { onClick } = createModal()
|
||||||
|
|
||||||
|
const event = pressEnter()
|
||||||
|
|
||||||
|
expect(onClick).toHaveBeenCalledTimes(1)
|
||||||
|
expect(event.defaultPrevented).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not click the ok button when Enter starts inside textarea or contenteditable elements', () => {
|
||||||
|
const { onClick } = createModal()
|
||||||
|
|
||||||
|
const textarea = document.createElement('textarea')
|
||||||
|
document.body.appendChild(textarea)
|
||||||
|
pressEnter(textarea)
|
||||||
|
|
||||||
|
const editable = document.createElement('div')
|
||||||
|
editable.setAttribute('contenteditable', 'true')
|
||||||
|
document.body.appendChild(editable)
|
||||||
|
pressEnter(editable)
|
||||||
|
|
||||||
|
expect(onClick).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
'ant-select-dropdown',
|
||||||
|
'ant-picker-dropdown',
|
||||||
|
'ant-dropdown',
|
||||||
|
'ant-popover'
|
||||||
|
])('does not click the ok button while %s is open', (dropdownClass) => {
|
||||||
|
const { onClick } = createModal()
|
||||||
|
const popup = document.createElement('div')
|
||||||
|
popup.className = dropdownClass
|
||||||
|
document.body.appendChild(popup)
|
||||||
|
|
||||||
|
pressEnter()
|
||||||
|
|
||||||
|
expect(onClick).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not click disabled or loading ok buttons', () => {
|
||||||
|
const disabledModal = createModal({ disabled: true })
|
||||||
|
pressEnter()
|
||||||
|
expect(disabledModal.click).not.toHaveBeenCalled()
|
||||||
|
expect(disabledModal.onClick).not.toHaveBeenCalled()
|
||||||
|
disabledModal.wrap.remove()
|
||||||
|
|
||||||
|
const ariaDisabledModal = createModal({ ariaDisabled: true })
|
||||||
|
pressEnter()
|
||||||
|
expect(ariaDisabledModal.click).not.toHaveBeenCalled()
|
||||||
|
expect(ariaDisabledModal.onClick).not.toHaveBeenCalled()
|
||||||
|
ariaDisabledModal.wrap.remove()
|
||||||
|
|
||||||
|
const loadingModal = createModal({ buttonClass: 'ant-btn-loading' })
|
||||||
|
pressEnter()
|
||||||
|
expect(loadingModal.click).not.toHaveBeenCalled()
|
||||||
|
expect(loadingModal.onClick).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not click the ok button on mobile width or coarse pointer devices', () => {
|
||||||
|
const mobileModal = createModal()
|
||||||
|
setMobileViewport()
|
||||||
|
pressEnter()
|
||||||
|
expect(mobileModal.onClick).not.toHaveBeenCalled()
|
||||||
|
mobileModal.wrap.remove()
|
||||||
|
|
||||||
|
const coarsePointerModal = createModal()
|
||||||
|
setCoarsePointer()
|
||||||
|
pressEnter()
|
||||||
|
expect(coarsePointerModal.onClick).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('clicks only the z-index and DOM-top modal when multiple modals are visible', () => {
|
||||||
|
const firstModal = createModal({ zIndex: 1000 })
|
||||||
|
const secondModal = createModal({ zIndex: 1000 })
|
||||||
|
const topZIndexModal = createModal({ zIndex: 1200 })
|
||||||
|
|
||||||
|
pressEnter()
|
||||||
|
|
||||||
|
expect(firstModal.onClick).not.toHaveBeenCalled()
|
||||||
|
expect(secondModal.onClick).not.toHaveBeenCalled()
|
||||||
|
expect(topZIndexModal.onClick).toHaveBeenCalledTimes(1)
|
||||||
|
|
||||||
|
topZIndexModal.wrap.remove()
|
||||||
|
pressEnter()
|
||||||
|
|
||||||
|
expect(firstModal.onClick).not.toHaveBeenCalled()
|
||||||
|
expect(secondModal.onClick).toHaveBeenCalledTimes(1)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,179 @@
|
|||||||
|
import { computed, onBeforeUnmount, onMounted, type ComputedRef } from 'vue'
|
||||||
|
|
||||||
|
interface UseConfirmEnterOptions {
|
||||||
|
enabled: ComputedRef<boolean>
|
||||||
|
onConfirm: (event: KeyboardEvent) => void
|
||||||
|
isConfirmDisabled?: () => boolean
|
||||||
|
isTopLayer?: () => boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export const CONFIRM_ENTER_DISABLED_CLASS = 'confirm-enter-disabled'
|
||||||
|
const DESKTOP_MIN_WIDTH = 960
|
||||||
|
|
||||||
|
const isEditableTarget = (target: EventTarget | null) => {
|
||||||
|
if (!(target instanceof HTMLElement)) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
if (target.isContentEditable) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
return target.tagName.toLowerCase() === 'textarea' || Boolean(target.closest('[contenteditable="true"]'))
|
||||||
|
}
|
||||||
|
|
||||||
|
const hasOpenPickerOrDropdown = () => {
|
||||||
|
return Boolean(document.querySelector([
|
||||||
|
'.ant-select-dropdown:not(.ant-select-dropdown-hidden)',
|
||||||
|
'.ant-picker-dropdown:not(.ant-picker-dropdown-hidden)',
|
||||||
|
'.ant-cascader-dropdown:not(.ant-cascader-dropdown-hidden)',
|
||||||
|
'.ant-dropdown:not(.ant-dropdown-hidden)',
|
||||||
|
'.ant-popover:not(.ant-popover-hidden)'
|
||||||
|
].join(',')))
|
||||||
|
}
|
||||||
|
|
||||||
|
const isDesktopViewport = () => {
|
||||||
|
if (typeof window === 'undefined') {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
const coarsePointer = window.matchMedia?.('(pointer: coarse)').matches ?? false
|
||||||
|
return window.innerWidth > DESKTOP_MIN_WIDTH && !coarsePointer
|
||||||
|
}
|
||||||
|
|
||||||
|
const isVisibleElement = (element: Element) => {
|
||||||
|
if (!(element instanceof HTMLElement)) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
const style = window.getComputedStyle(element)
|
||||||
|
return style.display !== 'none'
|
||||||
|
&& style.visibility !== 'hidden'
|
||||||
|
&& style.opacity !== '0'
|
||||||
|
&& element.getClientRects().length > 0
|
||||||
|
}
|
||||||
|
|
||||||
|
const isDisabledButton = (button: HTMLButtonElement) => {
|
||||||
|
return button.disabled
|
||||||
|
|| button.getAttribute('aria-disabled') === 'true'
|
||||||
|
|| button.classList.contains('ant-btn-loading')
|
||||||
|
|| button.classList.contains('ant-btn-disabled')
|
||||||
|
}
|
||||||
|
|
||||||
|
const getTopModalWrap = () => {
|
||||||
|
const modals = Array.from(document.querySelectorAll<HTMLElement>('.ant-modal-wrap'))
|
||||||
|
.filter(isVisibleElement)
|
||||||
|
|
||||||
|
if (!modals.length) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
const sortedModals = modals
|
||||||
|
.map((modal, index) => {
|
||||||
|
const zIndex = Number.parseInt(window.getComputedStyle(modal).zIndex || '0', 10)
|
||||||
|
return {
|
||||||
|
modal,
|
||||||
|
index,
|
||||||
|
zIndex: Number.isNaN(zIndex) ? 0 : zIndex
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.sort((left, right) => left.zIndex - right.zIndex || left.index - right.index)
|
||||||
|
|
||||||
|
return sortedModals[sortedModals.length - 1]?.modal ?? null
|
||||||
|
}
|
||||||
|
|
||||||
|
const getTopModalConfirmButton = () => {
|
||||||
|
const topModal = getTopModalWrap()
|
||||||
|
if (!topModal || topModal.classList.contains(CONFIRM_ENTER_DISABLED_CLASS)) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
const button = topModal.querySelector<HTMLButtonElement>([
|
||||||
|
'.ant-modal-confirm-btns .ant-btn-primary',
|
||||||
|
'.ant-modal-footer .ant-btn-primary'
|
||||||
|
].join(','))
|
||||||
|
|
||||||
|
if (!button || !isVisibleElement(button) || isDisabledButton(button)) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
return button
|
||||||
|
}
|
||||||
|
|
||||||
|
export const useConfirmEnter = ({
|
||||||
|
enabled,
|
||||||
|
onConfirm,
|
||||||
|
isConfirmDisabled,
|
||||||
|
isTopLayer
|
||||||
|
}: UseConfirmEnterOptions) => {
|
||||||
|
const canConfirm = computed(() => (
|
||||||
|
enabled.value
|
||||||
|
&& !(isConfirmDisabled?.() ?? false)
|
||||||
|
&& (isTopLayer?.() ?? true)
|
||||||
|
))
|
||||||
|
|
||||||
|
const handleKeydown = (event: KeyboardEvent) => {
|
||||||
|
if (
|
||||||
|
event.key !== 'Enter'
|
||||||
|
|| event.defaultPrevented
|
||||||
|
|| event.shiftKey
|
||||||
|
|| event.ctrlKey
|
||||||
|
|| event.altKey
|
||||||
|
|| event.metaKey
|
||||||
|
|| event.isComposing
|
||||||
|
|| !canConfirm.value
|
||||||
|
|| isEditableTarget(event.target)
|
||||||
|
|| hasOpenPickerOrDropdown()
|
||||||
|
) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
event.preventDefault()
|
||||||
|
onConfirm(event)
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
document.addEventListener('keydown', handleKeydown)
|
||||||
|
})
|
||||||
|
|
||||||
|
onBeforeUnmount(() => {
|
||||||
|
document.removeEventListener('keydown', handleKeydown)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export const useGlobalConfirmEnter = () => {
|
||||||
|
const handleKeydown = (event: KeyboardEvent) => {
|
||||||
|
if (
|
||||||
|
event.key !== 'Enter'
|
||||||
|
|| event.defaultPrevented
|
||||||
|
|| event.shiftKey
|
||||||
|
|| event.ctrlKey
|
||||||
|
|| event.altKey
|
||||||
|
|| event.metaKey
|
||||||
|
|| event.isComposing
|
||||||
|
|| (event as KeyboardEvent & { keyCode?: number }).keyCode === 229
|
||||||
|
|| !isDesktopViewport()
|
||||||
|
|| isEditableTarget(event.target)
|
||||||
|
|| hasOpenPickerOrDropdown()
|
||||||
|
) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const confirmButton = getTopModalConfirmButton()
|
||||||
|
if (!confirmButton) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
event.preventDefault()
|
||||||
|
event.stopImmediatePropagation()
|
||||||
|
confirmButton.click()
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
document.addEventListener('keydown', handleKeydown)
|
||||||
|
})
|
||||||
|
|
||||||
|
onBeforeUnmount(() => {
|
||||||
|
document.removeEventListener('keydown', handleKeydown)
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -75,6 +75,13 @@
|
|||||||
<div class="title">{{ item.productTitle }}</div>
|
<div class="title">{{ item.productTitle }}</div>
|
||||||
<div class="line">¥{{ item.price.toFixed(2) }} x {{ item.quantity }}</div>
|
<div class="line">¥{{ item.price.toFixed(2) }} x {{ item.quantity }}</div>
|
||||||
<div v-if="item.appointmentTime" class="line appointment">预约时间:{{ item.appointmentTime }}</div>
|
<div v-if="item.appointmentTime" class="line appointment">预约时间:{{ item.appointmentTime }}</div>
|
||||||
|
<div v-if="pendingArtistChangeForItem(order, item)" class="change-status">
|
||||||
|
改派申请处理中:{{ pendingArtistChangeForItem(order, item)?.requestedArtistName || '新美甲师' }}
|
||||||
|
</div>
|
||||||
|
<div v-else-if="canRequestArtistChange(order, item)" class="change-action">
|
||||||
|
<span>需要更换服务美甲师</span>
|
||||||
|
<a-button size="small" @click="openArtistChangeModal(order, item)">申请改派</a-button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -86,6 +93,38 @@
|
|||||||
</div>
|
</div>
|
||||||
</a-card>
|
</a-card>
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
|
<a-modal
|
||||||
|
v-model:open="artistChangeModalOpen"
|
||||||
|
title="申请改派"
|
||||||
|
:confirm-loading="artistChangeSubmitting"
|
||||||
|
@ok="submitArtistChangeRequest"
|
||||||
|
@cancel="closeArtistChangeModal"
|
||||||
|
>
|
||||||
|
<a-form layout="vertical">
|
||||||
|
<a-form-item label="当前美甲师">
|
||||||
|
<span>{{ artistChangeOptions?.currentArtistName || activeArtistChangeItem?.artistName || '未分配' }}</span>
|
||||||
|
</a-form-item>
|
||||||
|
<a-form-item label="新美甲师" required>
|
||||||
|
<a-select
|
||||||
|
v-model:value="artistChangeForm.requestedArtistId"
|
||||||
|
:loading="artistChangeOptionsLoading"
|
||||||
|
placeholder="请选择新的美甲师"
|
||||||
|
>
|
||||||
|
<a-select-option
|
||||||
|
v-for="artist in selectableArtistOptions"
|
||||||
|
:key="String(artist.artistId)"
|
||||||
|
:value="artist.artistId"
|
||||||
|
>
|
||||||
|
{{ artist.artistName }}
|
||||||
|
</a-select-option>
|
||||||
|
</a-select>
|
||||||
|
</a-form-item>
|
||||||
|
<a-form-item label="改派原因" required>
|
||||||
|
<a-textarea v-model:value="artistChangeForm.reason" :rows="4" :maxlength="300" placeholder="请说明申请改派的原因" />
|
||||||
|
</a-form-item>
|
||||||
|
</a-form>
|
||||||
|
</a-modal>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
@@ -101,6 +140,7 @@ import { message, Modal } from 'ant-design-vue'
|
|||||||
import { userApi } from '@/api/user'
|
import { userApi } from '@/api/user'
|
||||||
import { fileApi } from '../api/index'
|
import { fileApi } from '../api/index'
|
||||||
import { orderApi } from '../api/order'
|
import { orderApi } from '../api/order'
|
||||||
|
import type { OrderArtistChangeOptionsVO, OrderArtistChangeRequestVO } from '../api/order'
|
||||||
import type { IdType } from '@/utils/id'
|
import type { IdType } from '@/utils/id'
|
||||||
import { runWithGlobalLoading } from '@/utils/action-loading'
|
import { runWithGlobalLoading } from '@/utils/action-loading'
|
||||||
|
|
||||||
@@ -110,6 +150,13 @@ const orders = ref<any[]>([])
|
|||||||
const imageIdCache = ref<Record<string, string>>({})
|
const imageIdCache = ref<Record<string, string>>({})
|
||||||
const orderRefs = ref<Record<string, any>>({})
|
const orderRefs = ref<Record<string, any>>({})
|
||||||
const showCalendarEntry = ref(false)
|
const showCalendarEntry = ref(false)
|
||||||
|
const currentUserId = ref<IdType>()
|
||||||
|
const artistChangeModalOpen = ref(false)
|
||||||
|
const artistChangeSubmitting = ref(false)
|
||||||
|
const artistChangeOptionsLoading = ref(false)
|
||||||
|
const artistChangeOptions = ref<OrderArtistChangeOptionsVO | null>(null)
|
||||||
|
const activeArtistChangeOrder = ref<any | null>(null)
|
||||||
|
const activeArtistChangeItem = ref<any | null>(null)
|
||||||
const filters = reactive({
|
const filters = reactive({
|
||||||
keyword: '',
|
keyword: '',
|
||||||
source: 'all',
|
source: 'all',
|
||||||
@@ -118,6 +165,10 @@ const filters = reactive({
|
|||||||
minAmount: undefined as number | undefined,
|
minAmount: undefined as number | undefined,
|
||||||
maxAmount: undefined as number | undefined
|
maxAmount: undefined as number | undefined
|
||||||
})
|
})
|
||||||
|
const artistChangeForm = reactive({
|
||||||
|
requestedArtistId: undefined as IdType | undefined,
|
||||||
|
reason: ''
|
||||||
|
})
|
||||||
|
|
||||||
/** filteredOrders is a reactive state variable used by the template and event handlers. */
|
/** filteredOrders is a reactive state variable used by the template and event handlers. */
|
||||||
const filteredOrders = computed(() => {
|
const filteredOrders = computed(() => {
|
||||||
@@ -182,11 +233,33 @@ const sourceClass = (source?: string) => {
|
|||||||
return 'source-service'
|
return 'source-service'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const sameId = (left: unknown, right: unknown) => {
|
||||||
|
return left !== undefined && left !== null && right !== undefined && right !== null && String(left) === String(right)
|
||||||
|
}
|
||||||
|
|
||||||
|
const pendingArtistChangeForItem = (order: any, item: any): OrderArtistChangeRequestVO | undefined => {
|
||||||
|
const itemValue = item?.pendingArtistChangeRequest as OrderArtistChangeRequestVO | undefined
|
||||||
|
if (itemValue) return itemValue
|
||||||
|
const orderValue = order?.pendingArtistChangeRequest as OrderArtistChangeRequestVO | undefined
|
||||||
|
if (!orderValue) return undefined
|
||||||
|
return sameId(orderValue.orderItemId, item.id) || (order.items || []).length === 1 ? orderValue : undefined
|
||||||
|
}
|
||||||
|
|
||||||
/** canComplete is a local helper used by this page script. */
|
/** canComplete is a local helper used by this page script. */
|
||||||
const canComplete = (order: any) => {
|
const canComplete = (order: any) => {
|
||||||
return order.status === 1 && order.artistOrderSource !== 'SELF'
|
return order.status === 1 && order.artistOrderSource !== 'SELF'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const canRequestArtistChange = (order: any, item: any) => {
|
||||||
|
const assignedToCurrentUser = !currentUserId.value || !item.artistId || sameId(item.artistId, currentUserId.value)
|
||||||
|
return order.status === 1 && item.id && assignedToCurrentUser && !pendingArtistChangeForItem(order, item)
|
||||||
|
}
|
||||||
|
|
||||||
|
const selectableArtistOptions = computed(() => {
|
||||||
|
const options = artistChangeOptions.value?.artists || []
|
||||||
|
return options.filter(artist => !sameId(artist.artistId, artistChangeOptions.value?.currentArtistId))
|
||||||
|
})
|
||||||
|
|
||||||
/** resetFilters is a local helper used by this page script. */
|
/** resetFilters is a local helper used by this page script. */
|
||||||
const resetFilters = () => {
|
const resetFilters = () => {
|
||||||
filters.keyword = ''
|
filters.keyword = ''
|
||||||
@@ -225,6 +298,7 @@ const loadCalendarAccess = async () => {
|
|||||||
showCalendarEntry.value = false
|
showCalendarEntry.value = false
|
||||||
try {
|
try {
|
||||||
const currentUser = await userApi.getUserInfo()
|
const currentUser = await userApi.getUserInfo()
|
||||||
|
currentUserId.value = currentUser.id
|
||||||
if (currentUser.type === 3) {
|
if (currentUser.type === 3) {
|
||||||
showCalendarEntry.value = true
|
showCalendarEntry.value = true
|
||||||
return
|
return
|
||||||
@@ -234,6 +308,7 @@ const loadCalendarAccess = async () => {
|
|||||||
showCalendarEntry.value = Number(artistInfo?.participateProduction) === 1
|
showCalendarEntry.value = Number(artistInfo?.participateProduction) === 1
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
|
currentUserId.value = undefined
|
||||||
showCalendarEntry.value = false
|
showCalendarEntry.value = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -243,6 +318,70 @@ const handleRefreshClick = async () => {
|
|||||||
await runWithGlobalLoading(() => loadOrders())
|
await runWithGlobalLoading(() => loadOrders())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const openArtistChangeModal = async (order: any, item: any) => {
|
||||||
|
if (!canRequestArtistChange(order, item)) return
|
||||||
|
activeArtistChangeOrder.value = order
|
||||||
|
activeArtistChangeItem.value = item
|
||||||
|
artistChangeOptions.value = null
|
||||||
|
artistChangeForm.requestedArtistId = undefined
|
||||||
|
artistChangeForm.reason = ''
|
||||||
|
artistChangeModalOpen.value = true
|
||||||
|
artistChangeOptionsLoading.value = true
|
||||||
|
try {
|
||||||
|
artistChangeOptions.value = await orderApi.getArtistChangeOptions(order.id, item.id)
|
||||||
|
if (!selectableArtistOptions.value.length) {
|
||||||
|
message.warning('暂无可改派的美甲师')
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
message.error('获取可改派美甲师失败')
|
||||||
|
closeArtistChangeModal()
|
||||||
|
} finally {
|
||||||
|
artistChangeOptionsLoading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const closeArtistChangeModal = () => {
|
||||||
|
artistChangeModalOpen.value = false
|
||||||
|
activeArtistChangeOrder.value = null
|
||||||
|
activeArtistChangeItem.value = null
|
||||||
|
artistChangeOptions.value = null
|
||||||
|
artistChangeForm.requestedArtistId = undefined
|
||||||
|
artistChangeForm.reason = ''
|
||||||
|
}
|
||||||
|
|
||||||
|
const submitArtistChangeRequest = async () => {
|
||||||
|
if (!activeArtistChangeOrder.value || !activeArtistChangeItem.value) return
|
||||||
|
if (!artistChangeForm.requestedArtistId) {
|
||||||
|
message.warning('请选择新的美甲师')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const reason = artistChangeForm.reason.trim()
|
||||||
|
if (!reason) {
|
||||||
|
message.warning('请填写改派原因')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (sameId(artistChangeForm.requestedArtistId, artistChangeOptions.value?.currentArtistId)) {
|
||||||
|
message.warning('新美甲师不能与当前美甲师相同')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
artistChangeSubmitting.value = true
|
||||||
|
try {
|
||||||
|
await orderApi.requestArtistChange({
|
||||||
|
orderId: activeArtistChangeOrder.value.id,
|
||||||
|
orderItemId: activeArtistChangeItem.value.id,
|
||||||
|
requestedArtistId: artistChangeForm.requestedArtistId,
|
||||||
|
reason
|
||||||
|
})
|
||||||
|
message.success('改派申请已提交')
|
||||||
|
closeArtistChangeModal()
|
||||||
|
await loadOrders()
|
||||||
|
} catch {
|
||||||
|
message.error('提交改派申请失败')
|
||||||
|
} finally {
|
||||||
|
artistChangeSubmitting.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** completeOrder is a local helper used by this page script. */
|
/** completeOrder is a local helper used by this page script. */
|
||||||
const completeOrder = (orderId: IdType) => {
|
const completeOrder = (orderId: IdType) => {
|
||||||
Modal.confirm({
|
Modal.confirm({
|
||||||
@@ -298,6 +437,8 @@ onMounted(async () => {
|
|||||||
.title { font-weight: 600; color: var(--text-primary); }
|
.title { font-weight: 600; color: var(--text-primary); }
|
||||||
.line { margin-top: 4px; color: var(--text-secondary); font-size: 13px; }
|
.line { margin-top: 4px; color: var(--text-secondary); font-size: 13px; }
|
||||||
.appointment { color: var(--theme-primary); }
|
.appointment { color: var(--theme-primary); }
|
||||||
|
.change-status { margin-top: 8px; padding: 8px 10px; border-radius: 8px; background: var(--theme-primary-soft); color: var(--theme-primary); font-size: 13px; }
|
||||||
|
.change-action { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-top: 8px; padding: 8px 10px; border-radius: 8px; background: var(--theme-primary-soft); color: var(--theme-primary); font-size: 13px; }
|
||||||
|
|
||||||
:deep(.ant-btn-primary) { background: var(--theme-primary); border-color: var(--theme-primary); }
|
:deep(.ant-btn-primary) { background: var(--theme-primary); border-color: var(--theme-primary); }
|
||||||
:deep(.ant-btn-link) { color: var(--theme-primary); }
|
:deep(.ant-btn-link) { color: var(--theme-primary); }
|
||||||
|
|||||||
@@ -925,6 +925,7 @@ const handleSubmit = async () => {
|
|||||||
localStorage.setItem('refreshToken', loginData.refreshToken)
|
localStorage.setItem('refreshToken', loginData.refreshToken)
|
||||||
localStorage.setItem('userInfo', JSON.stringify(loginData.userInfo))
|
localStorage.setItem('userInfo', JSON.stringify(loginData.userInfo))
|
||||||
sessionStorage.setItem('accessToken', loginData.accessToken)
|
sessionStorage.setItem('accessToken', loginData.accessToken)
|
||||||
|
sessionStorage.setItem('refreshToken', loginData.refreshToken)
|
||||||
notifyShopThemeChanged()
|
notifyShopThemeChanged()
|
||||||
|
|
||||||
if (loginData.needSetPassword) {
|
if (loginData.needSetPassword) {
|
||||||
@@ -1110,6 +1111,7 @@ const handleAdminLogin = () => {
|
|||||||
localStorage.removeItem('adminRefreshToken')
|
localStorage.removeItem('adminRefreshToken')
|
||||||
localStorage.removeItem('adminUserInfo')
|
localStorage.removeItem('adminUserInfo')
|
||||||
sessionStorage.removeItem('accessToken')
|
sessionStorage.removeItem('accessToken')
|
||||||
|
sessionStorage.removeItem('refreshToken')
|
||||||
sessionStorage.removeItem('adminAccessToken')
|
sessionStorage.removeItem('adminAccessToken')
|
||||||
|
|
||||||
window.setTimeout(() => {
|
window.setTimeout(() => {
|
||||||
|
|||||||
@@ -56,6 +56,22 @@ const currentMessage = ref<SystemMessageVO | null>(null)
|
|||||||
/** unreadCount is a reactive state variable used by the template and event handlers. */
|
/** unreadCount is a reactive state variable used by the template and event handlers. */
|
||||||
const unreadCount = computed(() => messages.value.filter(item => item.readStatus !== 1).length)
|
const unreadCount = computed(() => messages.value.filter(item => item.readStatus !== 1).length)
|
||||||
|
|
||||||
|
const resolveSystemMessageActionPath = (item: SystemMessageVO) => {
|
||||||
|
const actionPath = String(item.actionPath || '').trim()
|
||||||
|
if (!actionPath || !actionPath.startsWith('/') || actionPath.startsWith('//')) {
|
||||||
|
return ''
|
||||||
|
}
|
||||||
|
return actionPath
|
||||||
|
}
|
||||||
|
|
||||||
|
const markMessageReadIfNeeded = async (item: SystemMessageVO) => {
|
||||||
|
if (item.readStatus === 1) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
await userApi.markMessageRead(item.id)
|
||||||
|
item.readStatus = 1
|
||||||
|
}
|
||||||
|
|
||||||
/** loadMessages is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
|
/** loadMessages is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
|
||||||
const loadMessages = async () => {
|
const loadMessages = async () => {
|
||||||
loading.value = true
|
loading.value = true
|
||||||
@@ -70,12 +86,21 @@ const loadMessages = async () => {
|
|||||||
|
|
||||||
/** openMessage is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
|
/** openMessage is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
|
||||||
const openMessage = async (item: SystemMessageVO) => {
|
const openMessage = async (item: SystemMessageVO) => {
|
||||||
|
try {
|
||||||
|
await markMessageReadIfNeeded(item)
|
||||||
|
} catch (error: any) {
|
||||||
|
message.error(error?.message || '标记已读失败')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const actionPath = resolveSystemMessageActionPath(item)
|
||||||
|
if (actionPath) {
|
||||||
|
await router.push(actionPath)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
currentMessage.value = item
|
currentMessage.value = item
|
||||||
detailVisible.value = true
|
detailVisible.value = true
|
||||||
if (item.readStatus !== 1) {
|
|
||||||
await userApi.markMessageRead(item.id)
|
|
||||||
item.readStatus = 1
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
onMounted(loadMessages)
|
onMounted(loadMessages)
|
||||||
|
|||||||
@@ -53,6 +53,28 @@
|
|||||||
<div class="line">¥{{ item.price.toFixed(2) }} x {{ item.quantity }}</div>
|
<div class="line">¥{{ item.price.toFixed(2) }} x {{ item.quantity }}</div>
|
||||||
<div v-if="item.artistName" class="line">美甲师:{{ item.artistName }}</div>
|
<div v-if="item.artistName" class="line">美甲师:{{ item.artistName }}</div>
|
||||||
<div v-if="item.appointmentTime" class="line appointment">预约时间:{{ item.appointmentTime }}</div>
|
<div v-if="item.appointmentTime" class="line appointment">预约时间:{{ item.appointmentTime }}</div>
|
||||||
|
<div v-if="submittedReviewForItem(order, item)" class="review-summary">
|
||||||
|
已评价:{{ formatRating(submittedReviewForItem(order, item)?.rating) }} 分
|
||||||
|
<span v-if="submittedReviewForItem(order, item)?.content"> · {{ submittedReviewForItem(order, item)?.content }}</span>
|
||||||
|
</div>
|
||||||
|
<div v-else-if="pendingReviewForItem(order, item)" class="review-action">
|
||||||
|
<span>待评价:{{ pendingReviewForItem(order, item)?.artistName || item.artistName || '美甲师' }}</span>
|
||||||
|
<a-button size="small" type="primary" @click="openReviewModal(pendingReviewForItem(order, item))">评价美甲师</a-button>
|
||||||
|
</div>
|
||||||
|
<div v-if="pendingChangeRequestForItem(order, item)" class="change-request">
|
||||||
|
<div class="change-info">
|
||||||
|
<strong>待处理改派申请</strong>
|
||||||
|
<span>
|
||||||
|
{{ pendingChangeRequestForItem(order, item)?.originalArtistName || item.artistName || '原美甲师' }}
|
||||||
|
→ {{ pendingChangeRequestForItem(order, item)?.requestedArtistName || '新美甲师' }}
|
||||||
|
</span>
|
||||||
|
<span v-if="pendingChangeRequestForItem(order, item)?.reason">原因:{{ pendingChangeRequestForItem(order, item)?.reason }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="change-actions">
|
||||||
|
<a-button size="small" type="primary" @click="approveArtistChange(pendingChangeRequestForItem(order, item))">同意</a-button>
|
||||||
|
<a-button size="small" danger @click="openRejectArtistChange(pendingChangeRequestForItem(order, item))">拒绝</a-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -62,6 +84,44 @@
|
|||||||
</div>
|
</div>
|
||||||
</a-card>
|
</a-card>
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
|
<a-modal
|
||||||
|
v-model:open="reviewModalOpen"
|
||||||
|
title="评价美甲师"
|
||||||
|
:confirm-loading="reviewSubmitting"
|
||||||
|
@ok="submitReview"
|
||||||
|
@cancel="closeReviewModal"
|
||||||
|
>
|
||||||
|
<a-form layout="vertical">
|
||||||
|
<a-form-item label="评分" required>
|
||||||
|
<a-input-number
|
||||||
|
v-model:value="reviewForm.rating"
|
||||||
|
class="rating-input"
|
||||||
|
:min="0.5"
|
||||||
|
:max="5"
|
||||||
|
:step="0.5"
|
||||||
|
placeholder="0.5-5 分"
|
||||||
|
/>
|
||||||
|
</a-form-item>
|
||||||
|
<a-form-item label="评价内容">
|
||||||
|
<a-textarea v-model:value="reviewForm.content" :rows="4" :maxlength="500" placeholder="写下这次服务体验" />
|
||||||
|
</a-form-item>
|
||||||
|
</a-form>
|
||||||
|
</a-modal>
|
||||||
|
|
||||||
|
<a-modal
|
||||||
|
v-model:open="rejectModalOpen"
|
||||||
|
title="拒绝改派申请"
|
||||||
|
:confirm-loading="changeProcessing"
|
||||||
|
@ok="submitRejectArtistChange"
|
||||||
|
@cancel="closeRejectArtistChange"
|
||||||
|
>
|
||||||
|
<a-form layout="vertical">
|
||||||
|
<a-form-item label="拒绝原因">
|
||||||
|
<a-textarea v-model:value="rejectForm.rejectReason" :rows="3" :maxlength="300" placeholder="可选,请填写拒绝原因" />
|
||||||
|
</a-form-item>
|
||||||
|
</a-form>
|
||||||
|
</a-modal>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
@@ -76,6 +136,7 @@ import { LeftOutlined } from '@ant-design/icons-vue'
|
|||||||
import { message, Modal } from 'ant-design-vue'
|
import { message, Modal } from 'ant-design-vue'
|
||||||
import { fileApi } from '../api/index'
|
import { fileApi } from '../api/index'
|
||||||
import { orderApi } from '../api/order'
|
import { orderApi } from '../api/order'
|
||||||
|
import type { OrderArtistChangeRequestVO, OrderArtistReviewVO } from '../api/order'
|
||||||
import { userApi } from '@/api/user'
|
import { userApi } from '@/api/user'
|
||||||
import type { IdType } from '@/utils/id'
|
import type { IdType } from '@/utils/id'
|
||||||
import { runWithGlobalLoading } from '@/utils/action-loading'
|
import { runWithGlobalLoading } from '@/utils/action-loading'
|
||||||
@@ -83,6 +144,15 @@ import { runWithGlobalLoading } from '@/utils/action-loading'
|
|||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const orders = ref<any[]>([])
|
const orders = ref<any[]>([])
|
||||||
const imageIdCache = ref<Record<string, string>>({})
|
const imageIdCache = ref<Record<string, string>>({})
|
||||||
|
const pendingReviews = ref<OrderArtistReviewVO[]>([])
|
||||||
|
const orderReviews = ref<Record<string, OrderArtistReviewVO[]>>({})
|
||||||
|
const pendingChangeRequests = ref<OrderArtistChangeRequestVO[]>([])
|
||||||
|
const reviewModalOpen = ref(false)
|
||||||
|
const reviewSubmitting = ref(false)
|
||||||
|
const activeReview = ref<OrderArtistReviewVO | null>(null)
|
||||||
|
const rejectModalOpen = ref(false)
|
||||||
|
const changeProcessing = ref(false)
|
||||||
|
const activeChangeRequest = ref<OrderArtistChangeRequestVO | null>(null)
|
||||||
const filters = reactive({
|
const filters = reactive({
|
||||||
keyword: '',
|
keyword: '',
|
||||||
status: 'all' as 'all' | number,
|
status: 'all' as 'all' | number,
|
||||||
@@ -90,6 +160,13 @@ const filters = reactive({
|
|||||||
minAmount: undefined as number | undefined,
|
minAmount: undefined as number | undefined,
|
||||||
maxAmount: undefined as number | undefined
|
maxAmount: undefined as number | undefined
|
||||||
})
|
})
|
||||||
|
const reviewForm = reactive({
|
||||||
|
rating: undefined as number | undefined,
|
||||||
|
content: ''
|
||||||
|
})
|
||||||
|
const rejectForm = reactive({
|
||||||
|
rejectReason: ''
|
||||||
|
})
|
||||||
|
|
||||||
/** filteredOrders is a reactive state variable used by the template and event handlers. */
|
/** filteredOrders is a reactive state variable used by the template and event handlers. */
|
||||||
const filteredOrders = computed(() => {
|
const filteredOrders = computed(() => {
|
||||||
@@ -124,6 +201,40 @@ const statusClass = (status: number) => {
|
|||||||
return 'cancelled'
|
return 'cancelled'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const sameId = (left: unknown, right: unknown) => {
|
||||||
|
return left !== undefined && left !== null && right !== undefined && right !== null && String(left) === String(right)
|
||||||
|
}
|
||||||
|
|
||||||
|
const embeddedForItem = <T extends { orderItemId?: IdType }>(order: any, item: any, field: string): T | undefined => {
|
||||||
|
const itemValue = item?.[field] as T | undefined
|
||||||
|
if (itemValue) return itemValue
|
||||||
|
const orderValue = order?.[field] as T | undefined
|
||||||
|
if (!orderValue) return undefined
|
||||||
|
return sameId(orderValue.orderItemId, item.id) || (order.items || []).length === 1 ? orderValue : undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
const pendingReviewForItem = (order: any, item: any): OrderArtistReviewVO | undefined => {
|
||||||
|
const embedded = embeddedForItem<OrderArtistReviewVO>(order, item, 'pendingReview')
|
||||||
|
if (embedded) return embedded
|
||||||
|
return pendingReviews.value.find(review => sameId(review.orderId, order.id) && sameId(review.orderItemId, item.id))
|
||||||
|
}
|
||||||
|
|
||||||
|
const submittedReviewForItem = (order: any, item: any): OrderArtistReviewVO | undefined => {
|
||||||
|
const embedded = embeddedForItem<OrderArtistReviewVO>(order, item, 'reviewSummary')
|
||||||
|
if (embedded) return embedded
|
||||||
|
return (orderReviews.value[String(order.id)] || []).find(review => sameId(review.orderItemId, item.id) && Number(review.status) === 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
const pendingChangeRequestForItem = (order: any, item: any): OrderArtistChangeRequestVO | undefined => {
|
||||||
|
const embedded = embeddedForItem<OrderArtistChangeRequestVO>(order, item, 'pendingArtistChangeRequest')
|
||||||
|
if (embedded) return embedded
|
||||||
|
return pendingChangeRequests.value.find(request => sameId(request.orderId, order.id) && sameId(request.orderItemId, item.id))
|
||||||
|
}
|
||||||
|
|
||||||
|
const formatRating = (rating?: number) => {
|
||||||
|
return Number(rating || 0).toFixed(1)
|
||||||
|
}
|
||||||
|
|
||||||
/** resetFilters is a local helper used by this page script. */
|
/** resetFilters is a local helper used by this page script. */
|
||||||
const resetFilters = () => {
|
const resetFilters = () => {
|
||||||
filters.keyword = ''
|
filters.keyword = ''
|
||||||
@@ -142,13 +253,49 @@ const copyOrderNo = async (orderNo: string) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const loadPendingReviews = async () => {
|
||||||
|
try {
|
||||||
|
pendingReviews.value = (await orderApi.getMyPendingReviews()) || []
|
||||||
|
} catch {
|
||||||
|
pendingReviews.value = []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const loadOrderReviews = async () => {
|
||||||
|
const orderIds = orders.value.map(order => order.id).filter(Boolean)
|
||||||
|
const entries = await Promise.all(orderIds.map(async (orderId) => {
|
||||||
|
try {
|
||||||
|
return [String(orderId), await orderApi.getOrderReviews(orderId)] as const
|
||||||
|
} catch {
|
||||||
|
return [String(orderId), []] as const
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
orderReviews.value = Object.fromEntries(entries)
|
||||||
|
}
|
||||||
|
|
||||||
|
const loadPendingArtistChangeRequests = async () => {
|
||||||
|
try {
|
||||||
|
pendingChangeRequests.value = (await orderApi.getMyPendingArtistChangeRequests()) || []
|
||||||
|
} catch {
|
||||||
|
pendingChangeRequests.value = []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const refreshOrderExtensions = async () => {
|
||||||
|
await Promise.all([
|
||||||
|
loadPendingReviews(),
|
||||||
|
loadOrderReviews(),
|
||||||
|
loadPendingArtistChangeRequests()
|
||||||
|
])
|
||||||
|
}
|
||||||
|
|
||||||
/** loadOrders is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
|
/** loadOrders is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
|
||||||
const loadOrders = async () => {
|
const loadOrders = async () => {
|
||||||
try {
|
try {
|
||||||
const userInfo = await userApi.getUserInfo()
|
const userInfo = await userApi.getUserInfo()
|
||||||
if (userInfo.type === 2 || userInfo.type === 3) {
|
if (userInfo.type === 2 || userInfo.type === 3) {
|
||||||
router.replace('/artist-orders')
|
router.replace('/artist-orders')
|
||||||
return
|
return false
|
||||||
}
|
}
|
||||||
orders.value = (await orderApi.getOrderList() as unknown as any[]) || []
|
orders.value = (await orderApi.getOrderList() as unknown as any[]) || []
|
||||||
for (const order of orders.value) {
|
for (const order of orders.value) {
|
||||||
@@ -164,8 +311,104 @@ const loadOrders = async () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
await refreshOrderExtensions()
|
||||||
|
return true
|
||||||
} catch {
|
} catch {
|
||||||
message.error('获取订单列表失败')
|
message.error('获取订单列表失败')
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const openReviewModal = (review?: OrderArtistReviewVO) => {
|
||||||
|
if (!review) return
|
||||||
|
activeReview.value = review
|
||||||
|
reviewForm.rating = review.rating ? Number(review.rating) : undefined
|
||||||
|
reviewForm.content = review.content || ''
|
||||||
|
reviewModalOpen.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
const closeReviewModal = () => {
|
||||||
|
reviewModalOpen.value = false
|
||||||
|
activeReview.value = null
|
||||||
|
reviewForm.rating = undefined
|
||||||
|
reviewForm.content = ''
|
||||||
|
}
|
||||||
|
|
||||||
|
const submitReview = async () => {
|
||||||
|
if (!activeReview.value) return
|
||||||
|
const rating = Number(reviewForm.rating)
|
||||||
|
if (!rating || rating < 0.5 || rating > 5) {
|
||||||
|
message.warning('请填写 0.5-5 分的评分')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const normalizedRating = Math.round(rating * 2) / 2
|
||||||
|
if (Math.abs(normalizedRating - rating) > 0.001) {
|
||||||
|
message.warning('评分请按 0.5 分递增')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
reviewSubmitting.value = true
|
||||||
|
try {
|
||||||
|
await orderApi.submitArtistReview(activeReview.value.id, {
|
||||||
|
rating: normalizedRating,
|
||||||
|
content: reviewForm.content.trim() || undefined,
|
||||||
|
imageFileIds: []
|
||||||
|
})
|
||||||
|
message.success('评价已提交')
|
||||||
|
closeReviewModal()
|
||||||
|
await Promise.all([loadPendingReviews(), loadOrderReviews()])
|
||||||
|
} catch {
|
||||||
|
message.error('提交评价失败')
|
||||||
|
} finally {
|
||||||
|
reviewSubmitting.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const approveArtistChange = (request?: OrderArtistChangeRequestVO) => {
|
||||||
|
if (!request) return
|
||||||
|
Modal.confirm({
|
||||||
|
title: '同意改派申请',
|
||||||
|
content: `确定同意改派给「${request.requestedArtistName || '新美甲师'}」吗?`,
|
||||||
|
onOk: async () => {
|
||||||
|
try {
|
||||||
|
await runWithGlobalLoading(async () => {
|
||||||
|
await orderApi.approveArtistChange(request.id)
|
||||||
|
await loadOrders()
|
||||||
|
})
|
||||||
|
message.success('已同意改派')
|
||||||
|
} catch {
|
||||||
|
message.error('处理改派申请失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const openRejectArtistChange = (request?: OrderArtistChangeRequestVO) => {
|
||||||
|
if (!request) return
|
||||||
|
activeChangeRequest.value = request
|
||||||
|
rejectForm.rejectReason = ''
|
||||||
|
rejectModalOpen.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
const closeRejectArtistChange = () => {
|
||||||
|
rejectModalOpen.value = false
|
||||||
|
activeChangeRequest.value = null
|
||||||
|
rejectForm.rejectReason = ''
|
||||||
|
}
|
||||||
|
|
||||||
|
const submitRejectArtistChange = async () => {
|
||||||
|
if (!activeChangeRequest.value) return
|
||||||
|
changeProcessing.value = true
|
||||||
|
try {
|
||||||
|
await orderApi.rejectArtistChange(activeChangeRequest.value.id, {
|
||||||
|
rejectReason: rejectForm.rejectReason.trim() || undefined
|
||||||
|
})
|
||||||
|
message.success('已拒绝改派')
|
||||||
|
closeRejectArtistChange()
|
||||||
|
await loadOrders()
|
||||||
|
} catch {
|
||||||
|
message.error('拒绝改派申请失败')
|
||||||
|
} finally {
|
||||||
|
changeProcessing.value = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -215,6 +458,13 @@ onMounted(loadOrders)
|
|||||||
.title { font-weight: 600; color: var(--text-primary); }
|
.title { font-weight: 600; color: var(--text-primary); }
|
||||||
.line { margin-top: 4px; color: var(--text-secondary); font-size: 13px; }
|
.line { margin-top: 4px; color: var(--text-secondary); font-size: 13px; }
|
||||||
.appointment { color: var(--theme-primary); }
|
.appointment { color: var(--theme-primary); }
|
||||||
|
.review-summary { margin-top: 8px; padding: 8px 10px; border-radius: 8px; background: var(--theme-primary-soft); color: var(--theme-primary); font-size: 13px; }
|
||||||
|
.review-action { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-top: 8px; padding: 8px 10px; border-radius: 8px; background: var(--theme-primary-soft); color: var(--theme-primary); font-size: 13px; }
|
||||||
|
.change-request { display: grid; gap: 8px; margin-top: 8px; padding: 10px; border: 1px solid var(--theme-border); border-radius: 8px; background: rgba(255, 255, 255, 0.72); }
|
||||||
|
.change-info { display: grid; gap: 4px; color: var(--text-secondary); font-size: 13px; }
|
||||||
|
.change-info strong { color: var(--text-primary); }
|
||||||
|
.change-actions { display: flex; gap: 8px; justify-content: flex-end; }
|
||||||
|
.rating-input { width: 100%; }
|
||||||
|
|
||||||
:deep(.ant-btn-primary) { background: var(--theme-primary); border-color: var(--theme-primary); }
|
:deep(.ant-btn-primary) { background: var(--theme-primary); border-color: var(--theme-primary); }
|
||||||
:deep(.ant-btn-link) { color: var(--theme-primary); }
|
:deep(.ant-btn-link) { color: var(--theme-primary); }
|
||||||
|
|||||||
@@ -125,15 +125,6 @@
|
|||||||
<a-button v-if="hasPermission('shop:edit')" type="link" size="small" @click="showEditModal(record)">
|
<a-button v-if="hasPermission('shop:edit')" type="link" size="small" @click="showEditModal(record)">
|
||||||
编辑
|
编辑
|
||||||
</a-button>
|
</a-button>
|
||||||
<a-popconfirm
|
|
||||||
v-if="hasPermission('shop:delete')"
|
|
||||||
title="确定要删除这个店铺吗?"
|
|
||||||
@confirm="handleDelete(record)"
|
|
||||||
>
|
|
||||||
<a-button type="link" size="small" danger>
|
|
||||||
删除
|
|
||||||
</a-button>
|
|
||||||
</a-popconfirm>
|
|
||||||
</a-space>
|
</a-space>
|
||||||
</template>
|
</template>
|
||||||
</template>
|
</template>
|
||||||
@@ -166,7 +157,14 @@
|
|||||||
<div class="admin-mobile-card__actions">
|
<div class="admin-mobile-card__actions">
|
||||||
<a-button size="small" @click="showViewModal(item)">查看</a-button>
|
<a-button size="small" @click="showViewModal(item)">查看</a-button>
|
||||||
<a-button v-if="hasPermission('shop:edit')" size="small" @click="showEditModal(item)">编辑</a-button>
|
<a-button v-if="hasPermission('shop:edit')" size="small" @click="showEditModal(item)">编辑</a-button>
|
||||||
<a-button v-if="hasPermission('shop:delete')" size="small" danger @click="handleDelete(item)">删除</a-button>
|
<a-button
|
||||||
|
v-if="hasPermission('shop:edit')"
|
||||||
|
size="small"
|
||||||
|
:disabled="!isAdmin"
|
||||||
|
@click="handleStatusChange(item, item.status === 0)"
|
||||||
|
>
|
||||||
|
{{ item.status === 0 ? '启用' : '停用' }}
|
||||||
|
</a-button>
|
||||||
</div>
|
</div>
|
||||||
</article>
|
</article>
|
||||||
</template>
|
</template>
|
||||||
@@ -2103,20 +2101,6 @@ const handleModalCancel = () => {
|
|||||||
syncUploadedThemeBackgroundId('')
|
syncUploadedThemeBackgroundId('')
|
||||||
}
|
}
|
||||||
|
|
||||||
/** handleDelete is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
|
|
||||||
const handleDelete = async (record: Shop | Record<string, any>) => {
|
|
||||||
try {
|
|
||||||
await runWithGlobalLoading(async () => {
|
|
||||||
const shopId = 'id' in record ? record.id : (record as any).id
|
|
||||||
await adminShopApi.deleteShop(shopId)
|
|
||||||
message.success('删除成功')
|
|
||||||
await fetchShopList()
|
|
||||||
})
|
|
||||||
} catch (error) {
|
|
||||||
message.error('删除失败')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** handleStatusChange is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
|
/** handleStatusChange is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
|
||||||
const handleStatusChange = async (record: Shop | Record<string, any>, enabled: boolean) => {
|
const handleStatusChange = async (record: Shop | Record<string, any>, enabled: boolean) => {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -0,0 +1,112 @@
|
|||||||
|
// @vitest-environment jsdom
|
||||||
|
|
||||||
|
import { AxiosError, type AxiosAdapter, type AxiosResponse, type InternalAxiosRequestConfig } from 'axios'
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
|
||||||
|
const messageError = vi.hoisted(() => vi.fn())
|
||||||
|
|
||||||
|
vi.mock('ant-design-vue', () => ({
|
||||||
|
message: {
|
||||||
|
error: messageError
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
|
||||||
|
import adminApi from '../../src/api/admin'
|
||||||
|
|
||||||
|
function createTokenExpiredError(config: InternalAxiosRequestConfig) {
|
||||||
|
const response = {
|
||||||
|
data: {
|
||||||
|
code: 401,
|
||||||
|
message: 'Token expired'
|
||||||
|
},
|
||||||
|
status: 401,
|
||||||
|
statusText: 'Unauthorized',
|
||||||
|
headers: {},
|
||||||
|
config,
|
||||||
|
request: {}
|
||||||
|
} as AxiosResponse
|
||||||
|
|
||||||
|
return new AxiosError(
|
||||||
|
'Request failed with status code 401',
|
||||||
|
AxiosError.ERR_BAD_REQUEST,
|
||||||
|
config,
|
||||||
|
{},
|
||||||
|
response
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('admin api stale token handling', () => {
|
||||||
|
const originalAdapter = adminApi.defaults.adapter
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.useFakeTimers()
|
||||||
|
messageError.mockClear()
|
||||||
|
window.history.replaceState(null, '', '/admin')
|
||||||
|
localStorage.clear()
|
||||||
|
sessionStorage.clear()
|
||||||
|
})
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
adminApi.defaults.adapter = originalAdapter
|
||||||
|
localStorage.clear()
|
||||||
|
sessionStorage.clear()
|
||||||
|
vi.useRealTimers()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps a newer admin session when an old-token request returns 401', async () => {
|
||||||
|
localStorage.setItem('adminAccessToken', 'old-admin-token')
|
||||||
|
localStorage.setItem('adminRefreshToken', 'old-admin-refresh')
|
||||||
|
sessionStorage.setItem('adminAccessToken', 'old-admin-token')
|
||||||
|
|
||||||
|
const requests: Array<{ url?: string, authorization?: string }> = []
|
||||||
|
let markRequestStarted!: () => void
|
||||||
|
let releaseStale401!: () => void
|
||||||
|
const requestStarted = new Promise<void>(resolve => {
|
||||||
|
markRequestStarted = resolve
|
||||||
|
})
|
||||||
|
|
||||||
|
adminApi.defaults.adapter = ((config: InternalAxiosRequestConfig) => {
|
||||||
|
if (config.url !== '/user/info') {
|
||||||
|
return Promise.reject(new Error(`Unexpected request: ${config.url}`))
|
||||||
|
}
|
||||||
|
requests.push({
|
||||||
|
url: config.url,
|
||||||
|
authorization: String(config.headers.Authorization || '')
|
||||||
|
})
|
||||||
|
markRequestStarted()
|
||||||
|
return new Promise((_resolve, reject) => {
|
||||||
|
releaseStale401 = () => reject(createTokenExpiredError(config))
|
||||||
|
})
|
||||||
|
}) as AxiosAdapter
|
||||||
|
|
||||||
|
const staleRequest = adminApi.get('/user/info')
|
||||||
|
|
||||||
|
await requestStarted
|
||||||
|
expect(requests).toEqual([
|
||||||
|
{
|
||||||
|
url: '/user/info',
|
||||||
|
authorization: 'Bearer old-admin-token'
|
||||||
|
}
|
||||||
|
])
|
||||||
|
|
||||||
|
localStorage.setItem('adminAccessToken', 'new-admin-token')
|
||||||
|
localStorage.setItem('adminRefreshToken', 'new-admin-refresh')
|
||||||
|
sessionStorage.setItem('adminAccessToken', 'new-admin-token')
|
||||||
|
const hrefBefore401 = window.location.href
|
||||||
|
|
||||||
|
releaseStale401()
|
||||||
|
|
||||||
|
await expect(staleRequest).rejects.toMatchObject({
|
||||||
|
response: {
|
||||||
|
status: 401
|
||||||
|
}
|
||||||
|
})
|
||||||
|
await vi.runAllTimersAsync()
|
||||||
|
|
||||||
|
expect(localStorage.getItem('adminAccessToken')).toBe('new-admin-token')
|
||||||
|
expect(localStorage.getItem('adminRefreshToken')).toBe('new-admin-refresh')
|
||||||
|
expect(sessionStorage.getItem('adminAccessToken')).toBe('new-admin-token')
|
||||||
|
expect(window.location.href).toBe(hrefBefore401)
|
||||||
|
expect(messageError).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import { isApiAuthFreePath, WEB_API_AUTH_FREE_PATHS } from '@/api/auth-free-paths'
|
||||||
|
|
||||||
|
describe('auth-free API contract', () => {
|
||||||
|
it('covers public paths and rejects protected business APIs', () => {
|
||||||
|
expect(isApiAuthFreePath('/comment/list/product/1')).toBe(true)
|
||||||
|
expect(isApiAuthFreePath('/user/wechat-mini/auto-login')).toBe(true)
|
||||||
|
expect(isApiAuthFreePath('/admin/auth/login-shops/1')).toBe(true)
|
||||||
|
|
||||||
|
expect(isApiAuthFreePath('/order/list')).toBe(false)
|
||||||
|
expect(isApiAuthFreePath('/shop/delete/1')).toBe(false)
|
||||||
|
expect(isApiAuthFreePath('/permission/list')).toBe(false)
|
||||||
|
expect(isApiAuthFreePath('/order/list?next=/user/login')).toBe(false)
|
||||||
|
expect(isApiAuthFreePath('/user/profile/admin/auth/refresh')).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps auth-free path constants unique', () => {
|
||||||
|
expect(new Set(WEB_API_AUTH_FREE_PATHS).size).toBe(WEB_API_AUTH_FREE_PATHS.length)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
// @vitest-environment jsdom
|
||||||
|
|
||||||
|
import { AxiosError, type AxiosAdapter, type AxiosResponse, type InternalAxiosRequestConfig } from 'axios'
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
|
||||||
|
const messageError = vi.hoisted(() => vi.fn())
|
||||||
|
|
||||||
|
vi.mock('ant-design-vue', () => ({
|
||||||
|
message: {
|
||||||
|
error: messageError
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
|
||||||
|
import api from '../../src/api'
|
||||||
|
|
||||||
|
function createTokenExpiredError(config: InternalAxiosRequestConfig) {
|
||||||
|
const response = {
|
||||||
|
data: {
|
||||||
|
code: 401,
|
||||||
|
message: 'Token expired'
|
||||||
|
},
|
||||||
|
status: 401,
|
||||||
|
statusText: 'Unauthorized',
|
||||||
|
headers: {},
|
||||||
|
config,
|
||||||
|
request: {}
|
||||||
|
} as AxiosResponse
|
||||||
|
|
||||||
|
return new AxiosError(
|
||||||
|
'Request failed with status code 401',
|
||||||
|
AxiosError.ERR_BAD_REQUEST,
|
||||||
|
config,
|
||||||
|
{},
|
||||||
|
response
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('api stale token handling', () => {
|
||||||
|
const originalAdapter = api.defaults.adapter
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.useFakeTimers()
|
||||||
|
messageError.mockClear()
|
||||||
|
window.history.replaceState(null, '', '/profile')
|
||||||
|
localStorage.clear()
|
||||||
|
sessionStorage.clear()
|
||||||
|
})
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
api.defaults.adapter = originalAdapter
|
||||||
|
localStorage.clear()
|
||||||
|
sessionStorage.clear()
|
||||||
|
vi.useRealTimers()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps a newer login session when an old-token request returns 401', async () => {
|
||||||
|
localStorage.setItem('accessToken', 'old-token')
|
||||||
|
sessionStorage.setItem('accessToken', 'old-token')
|
||||||
|
|
||||||
|
const requests: Array<{ url?: string, authorization?: string }> = []
|
||||||
|
let markRequestStarted!: () => void
|
||||||
|
let releaseStale401!: () => void
|
||||||
|
const requestStarted = new Promise<void>(resolve => {
|
||||||
|
markRequestStarted = resolve
|
||||||
|
})
|
||||||
|
|
||||||
|
api.defaults.adapter = ((config: InternalAxiosRequestConfig) => {
|
||||||
|
if (config.url !== '/user/info') {
|
||||||
|
return Promise.reject(new Error(`Unexpected request: ${config.url}`))
|
||||||
|
}
|
||||||
|
|
||||||
|
requests.push({
|
||||||
|
url: config.url,
|
||||||
|
authorization: String(config.headers.Authorization || '')
|
||||||
|
})
|
||||||
|
markRequestStarted()
|
||||||
|
|
||||||
|
return new Promise((_resolve, reject) => {
|
||||||
|
releaseStale401 = () => reject(createTokenExpiredError(config))
|
||||||
|
})
|
||||||
|
}) as AxiosAdapter
|
||||||
|
|
||||||
|
const staleRequest = api.get('/user/info')
|
||||||
|
|
||||||
|
await requestStarted
|
||||||
|
expect(requests).toEqual([
|
||||||
|
{
|
||||||
|
url: '/user/info',
|
||||||
|
authorization: 'Bearer old-token'
|
||||||
|
}
|
||||||
|
])
|
||||||
|
|
||||||
|
localStorage.setItem('accessToken', 'new-token')
|
||||||
|
localStorage.setItem('refreshToken', 'new-refresh')
|
||||||
|
localStorage.setItem('userInfo', JSON.stringify({ id: 2, nickname: 'new-user' }))
|
||||||
|
sessionStorage.setItem('accessToken', 'new-token')
|
||||||
|
sessionStorage.setItem('refreshToken', 'new-refresh')
|
||||||
|
const hrefBefore401 = window.location.href
|
||||||
|
|
||||||
|
releaseStale401()
|
||||||
|
|
||||||
|
await expect(staleRequest).rejects.toMatchObject({
|
||||||
|
response: {
|
||||||
|
status: 401
|
||||||
|
}
|
||||||
|
})
|
||||||
|
await vi.runAllTimersAsync()
|
||||||
|
|
||||||
|
expect(requests).toHaveLength(1)
|
||||||
|
expect(localStorage.getItem('accessToken')).toBe('new-token')
|
||||||
|
expect(localStorage.getItem('refreshToken')).toBe('new-refresh')
|
||||||
|
expect(localStorage.getItem('userInfo')).toBe(JSON.stringify({ id: 2, nickname: 'new-user' }))
|
||||||
|
expect(sessionStorage.getItem('accessToken')).toBe('new-token')
|
||||||
|
expect(sessionStorage.getItem('refreshToken')).toBe('new-refresh')
|
||||||
|
expect(window.location.href).toBe(hrefBefore401)
|
||||||
|
expect(messageError).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { defineConfig } from 'vitest/config'
|
||||||
|
import path from 'node:path'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
environment: 'jsdom',
|
||||||
|
globals: false
|
||||||
|
},
|
||||||
|
resolve: {
|
||||||
|
alias: {
|
||||||
|
'@': path.resolve(__dirname, './src')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
+53
-52
@@ -17,46 +17,14 @@ import org.springframework.web.server.ServerWebExchange;
|
|||||||
import reactor.core.publisher.Mono;
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.LinkedHashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
/**
|
|
||||||
* 全局认证过滤器
|
|
||||||
* 负责 Token 校验和白名单过滤
|
|
||||||
*
|
|
||||||
* @author xiaowang
|
|
||||||
* @date 2026-02-12
|
|
||||||
*/
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Component
|
@Component
|
||||||
public class AuthGlobalFilter implements GlobalFilter, Ordered {
|
public class AuthGlobalFilter implements GlobalFilter, Ordered {
|
||||||
|
|
||||||
private static final List<String> DEFAULT_WHITELIST = List.of(
|
private static final List<String> DEFAULT_WHITELIST = AuthWhitelist.defaultPatterns();
|
||||||
"/api/user/login",
|
|
||||||
"/api/user/register",
|
|
||||||
"/api/user/check/**",
|
|
||||||
"/api/user/refresh-token",
|
|
||||||
"/api/user/send-verification-code",
|
|
||||||
"/api/user/phone-login",
|
|
||||||
"/api/user/wechat-mini/**",
|
|
||||||
"/api/user/reset-password-by-phone",
|
|
||||||
"/api/legal-agreement/current",
|
|
||||||
"/api/legal-agreement/current/**",
|
|
||||||
"/api/product/get/**",
|
|
||||||
"/api/product/list/**",
|
|
||||||
"/api/shop/get/**",
|
|
||||||
"/api/shop/list/public",
|
|
||||||
"/api/shop/list/simple",
|
|
||||||
"/api/tag/list/all",
|
|
||||||
"/api/file/get-signed-url/**",
|
|
||||||
"/api/admin/auth/login",
|
|
||||||
"/api/admin/auth/login-shops/**",
|
|
||||||
"/api/admin/auth/refresh",
|
|
||||||
"/admin/api/auth/login",
|
|
||||||
"/admin/api/auth/login-shops/**",
|
|
||||||
"/admin/api/auth/refresh",
|
|
||||||
"/api/health/**",
|
|
||||||
"/api/error"
|
|
||||||
);
|
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private GatewayConfig gatewayConfig;
|
private GatewayConfig gatewayConfig;
|
||||||
@@ -92,37 +60,70 @@ public class AuthGlobalFilter implements GlobalFilter, Ordered {
|
|||||||
return chain.filter(exchange);
|
return chain.filter(exchange);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 判断是否在白名单中
|
|
||||||
*/
|
|
||||||
private boolean isWhitelist(String path) {
|
private boolean isWhitelist(String path) {
|
||||||
if (gatewayConfig.getWhitelist() != null) {
|
return AuthWhitelist.effectivePatterns(gatewayConfig).stream()
|
||||||
for (String whitelistPath : gatewayConfig.getWhitelist()) {
|
.anyMatch(pattern -> pathMatcher.match(pattern, path));
|
||||||
if (pathMatcher.match(whitelistPath, path)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return DEFAULT_WHITELIST.stream().anyMatch(pattern -> pathMatcher.match(pattern, path));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 无权限响应处理
|
|
||||||
*/
|
|
||||||
private Mono<Void> unAuthorized(ServerWebExchange exchange, String msg) {
|
private Mono<Void> unAuthorized(ServerWebExchange exchange, String msg) {
|
||||||
ServerHttpResponse response = exchange.getResponse();
|
ServerHttpResponse response = exchange.getResponse();
|
||||||
response.setStatusCode(HttpStatus.UNAUTHORIZED);
|
response.setStatusCode(HttpStatus.UNAUTHORIZED);
|
||||||
response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
|
response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
|
||||||
|
|
||||||
String result = "{\"code\": 401, \"message\": \"" + msg + "\", \"data\": null}";
|
String result = "{\"code\": 401, \"message\": \"" + msg + "\", \"data\": null}";
|
||||||
DataBuffer buffer = response.bufferFactory().wrap(result.getBytes(StandardCharsets.UTF_8));
|
DataBuffer buffer = response.bufferFactory().wrap(result.getBytes(StandardCharsets.UTF_8));
|
||||||
|
|
||||||
return response.writeWith(Mono.just(buffer));
|
return response.writeWith(Mono.just(buffer));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int getOrder() {
|
public int getOrder() {
|
||||||
return -1; // 优先级最高
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static final class AuthWhitelist {
|
||||||
|
|
||||||
|
private AuthWhitelist() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<String> defaultPatterns() {
|
||||||
|
return List.of(
|
||||||
|
"/api/user/login",
|
||||||
|
"/api/user/register",
|
||||||
|
"/api/user/check/**",
|
||||||
|
"/api/user/refresh-token",
|
||||||
|
"/api/user/send-verification-code",
|
||||||
|
"/api/user/phone-login",
|
||||||
|
"/api/user/wechat-mini/**",
|
||||||
|
"/api/user/reset-password-by-phone",
|
||||||
|
"/api/legal-agreement/current",
|
||||||
|
"/api/legal-agreement/current/**",
|
||||||
|
"/api/product/get/**",
|
||||||
|
"/api/product/list/**",
|
||||||
|
"/api/comment/list/product/**",
|
||||||
|
"/api/shop/get/**",
|
||||||
|
"/api/shop/list/public",
|
||||||
|
"/api/shop/list/simple",
|
||||||
|
"/api/tag/list/all",
|
||||||
|
"/api/file/get-signed-url/**",
|
||||||
|
"/api/admin/auth/login",
|
||||||
|
"/api/admin/auth/login-shops/**",
|
||||||
|
"/api/admin/auth/refresh",
|
||||||
|
"/admin/api/auth/login",
|
||||||
|
"/admin/api/auth/login-shops/**",
|
||||||
|
"/admin/api/auth/refresh",
|
||||||
|
"/api/health/**",
|
||||||
|
"/api/error"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<String> effectivePatterns(GatewayConfig gatewayConfig) {
|
||||||
|
if (gatewayConfig == null || gatewayConfig.getWhitelist() == null || gatewayConfig.getWhitelist().isEmpty()) {
|
||||||
|
return defaultPatterns();
|
||||||
|
}
|
||||||
|
LinkedHashSet<String> patterns = new LinkedHashSet<>(gatewayConfig.getWhitelist());
|
||||||
|
patterns.addAll(DEFAULT_WHITELIST);
|
||||||
|
return List.copyOf(patterns);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+38
@@ -0,0 +1,38 @@
|
|||||||
|
package com.xiaowang.yumitailgateway.filter;
|
||||||
|
|
||||||
|
import com.xiaowang.yumitailgateway.config.GatewayConfig;
|
||||||
|
import com.xiaowang.yumitailgateway.filter.AuthGlobalFilter.AuthWhitelist;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.util.AntPathMatcher;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
class AuthGlobalFilterWhitelistTest {
|
||||||
|
|
||||||
|
private final AntPathMatcher pathMatcher = new AntPathMatcher();
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void effectiveWhitelistCoversPublicCommentListAndRejectsOrderApi() {
|
||||||
|
GatewayConfig config = new GatewayConfig();
|
||||||
|
config.setWhitelist(List.of("/api/user/login"));
|
||||||
|
|
||||||
|
List<String> patterns = AuthWhitelist.effectivePatterns(config);
|
||||||
|
|
||||||
|
assertThat(matches(patterns, "/api/comment/list/product/1")).isTrue();
|
||||||
|
assertThat(matches(patterns, "/api/order/list")).isFalse();
|
||||||
|
assertThat(matches(patterns, "/api/admin/user/list")).isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void defaultWhitelistIncludesOnlyExpectedPublicBusinessAreas() {
|
||||||
|
assertThat(AuthWhitelist.defaultPatterns())
|
||||||
|
.contains("/api/user/login", "/api/comment/list/product/**", "/api/admin/auth/login")
|
||||||
|
.doesNotContain("/api/order/**", "/api/shop/delete/**", "/api/permission/**");
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean matches(List<String> patterns, String path) {
|
||||||
|
return patterns.stream().anyMatch(pattern -> pathMatcher.match(pattern, path));
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user