diff --git a/WeChatProgram/api/order.js b/WeChatProgram/api/order.js index b90e01c6..72ac197b 100644 --- a/WeChatProgram/api/order.js +++ b/WeChatProgram/api/order.js @@ -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) { return request({ url: `/order/cancel/${orderId}`, diff --git a/WeChatProgram/pages/notifications/index.js b/WeChatProgram/pages/notifications/index.js index 1e722332..2cf5c92c 100644 --- a/WeChatProgram/pages/notifications/index.js +++ b/WeChatProgram/pages/notifications/index.js @@ -54,6 +54,24 @@ Page({ if (!item) { 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({ currentMessage: item, detailVisible: true diff --git a/WeChatProgram/pages/orders/index.js b/WeChatProgram/pages/orders/index.js index 4198edce..80b2fe31 100644 --- a/WeChatProgram/pages/orders/index.js +++ b/WeChatProgram/pages/orders/index.js @@ -7,21 +7,157 @@ const { resolveLegacyImage } = require('../../utils/file') const { formatDateTime, formatPrice, getOrderStatusClass, getOrderStatusText } = require('../../utils/format') const { runWithLoading } = require('../../utils/loading') -/** - * orders page logic. - * Call guide: page data drives the WXML template, and each method is called by user events or lifecycle callbacks. - */ +const REVIEW_SCORE_OPTIONS = [0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5] + +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({ data: Object.assign(theme.pageThemeData(getApp().globalData.shopTheme), { loading: 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() { this.loadOrders() }, @@ -33,10 +169,6 @@ Page({ 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) { this.setData({ orders: [], @@ -47,19 +179,34 @@ Page({ try { 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 => ({ ...order, statusText: getOrderStatusText(order), statusClass: getOrderStatusClass(order), shopNameText: order.shopName ? `所属店铺:${order.shopName}` : '', actualAmountText: `\u00a5${formatPrice(order.actualAmount)}`, - items: await Promise.all((order.items || []).map(async item => ({ - ...item, - productImageUrl: await resolveLegacyImage(item.productImage), - priceText: `\u00a5${formatPrice(item.price)}`, - appointmentText: formatDateTime(item.appointmentTime) - }))) + items: await Promise.all(safeList(order.items).map(async item => { + const itemId = toId(item.id) + const inlinePendingReview = resolveRelatedRecord(item.pendingReview || order.pendingReview, item.id) + const inlineReviewSummary = resolveRelatedRecord(item.reviewSummary || order.reviewSummary, item.id) + 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({ @@ -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() { 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() { 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) { 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) { 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) { return } diff --git a/WeChatProgram/pages/orders/index.wxml b/WeChatProgram/pages/orders/index.wxml index c5edcdeb..fb5bd97c 100644 --- a/WeChatProgram/pages/orders/index.wxml +++ b/WeChatProgram/pages/orders/index.wxml @@ -35,6 +35,50 @@ + + 评价状态 + {{orderItem.reviewSummary.displayText}} + {{orderItem.reviewSummary.contentText}} + + + + + 评价美甲师 + 评分必填,文字可选 + + + {{score}} + + + 提交评价 + + + + 待确认改派 + {{orderItem.pendingArtistChangeRequest.displayText}} + 原因:{{orderItem.pendingArtistChangeRequest.reasonText}} + + 同意改派 + 拒绝 + + + 总计:{{item.actualAmountText}} 取消订单 diff --git a/WeChatProgram/pages/orders/index.wxss b/WeChatProgram/pages/orders/index.wxss index 96d845c2..947cb20c 100644 --- a/WeChatProgram/pages/orders/index.wxss +++ b/WeChatProgram/pages/orders/index.wxss @@ -131,3 +131,129 @@ font-size: 24rpx; 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; +} diff --git a/WeChatProgram/pages/profile/index.js b/WeChatProgram/pages/profile/index.js index fced5c16..488c99e7 100644 --- a/WeChatProgram/pages/profile/index.js +++ b/WeChatProgram/pages/profile/index.js @@ -194,6 +194,10 @@ Page({ }) }) await userApi.markMessagePopupShown(item.id) + const opened = await navigation.openActionPath(item.actionPath) + if (opened) { + break + } } } catch (error) { console.error('加载待弹窗消息失败', error) diff --git a/WeChatProgram/utils/navigation.js b/WeChatProgram/utils/navigation.js index 36f6c8f5..44f5cca1 100644 --- a/WeChatProgram/utils/navigation.js +++ b/WeChatProgram/utils/navigation.js @@ -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) { const pages = getCurrentPages() if (pages.length > 1) { @@ -186,6 +225,8 @@ module.exports = { isTabPage, navigate, switchTab, + normalizeActionPath, + openActionPath, goBack, redirectAfterLogin, openAuth, diff --git a/YumiNail-Admin-Program/api/order.js b/YumiNail-Admin-Program/api/order.js index e2060e1b..f322190d 100644 --- a/YumiNail-Admin-Program/api/order.js +++ b/YumiNail-Admin-Program/api/order.js @@ -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) { return request({ url: `/order/update-status/${id}`, diff --git a/YumiNail-Admin-Program/pages/orders/index.js b/YumiNail-Admin-Program/pages/orders/index.js index 885fb364..880aa11e 100644 --- a/YumiNail-Admin-Program/pages/orders/index.js +++ b/YumiNail-Admin-Program/pages/orders/index.js @@ -12,6 +12,212 @@ const STATUS_OPTIONS = [ { 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({ data: { keyword: '', @@ -29,8 +235,9 @@ Page({ return } + const userInfo = getApp().globalData.userInfo this.setData({ - userInfo: getApp().globalData.userInfo + userInfo }) if (!this.data.initialized || consumeDirty('admin-orders')) { @@ -73,16 +280,15 @@ Page({ status: this.data.status === '' ? undefined : this.data.status }) + const rawList = safeList(result && result.list) + const assistData = await loadAssistData(rawList) + if (requestId !== this._loadRequestId) { return } this.setData({ - list: (Array.isArray(result && result.list) ? result.list : []).map(item => ({ - ...item, - displayStatusText: format.getOrderStatusText(item), - displayCreateTime: format.formatDateTime(item.createTime) - })), + list: rawList.map(item => formatOrder(item, this.data.userInfo, assistData)), total: Number(result && result.total) || 0, initialized: true }) @@ -119,6 +325,54 @@ Page({ }).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) { const order = event.currentTarget.dataset.order if (!order) { diff --git a/YumiNail-Admin-Program/pages/orders/index.wxml b/YumiNail-Admin-Program/pages/orders/index.wxml index 2e3d97c8..60ffee2f 100644 --- a/YumiNail-Admin-Program/pages/orders/index.wxml +++ b/YumiNail-Admin-Program/pages/orders/index.wxml @@ -33,7 +33,7 @@ 订单金额 - ¥{{item.payAmount}} + ¥{{item.displayPayAmount}} 所属门店 @@ -48,6 +48,27 @@ {{item.displayCreateTime}} + + + + + {{orderItem.productTitle || '订单项目'}} + 美甲师:{{orderItem.artistName || '--'}} + 预约时间:{{orderItem.displayAppointmentTime}} + {{orderItem.reviewStatusText}} + 评价内容:{{orderItem.reviewSummary.contentText}} + + 改派申请待处理 + {{orderItem.pendingArtistChangeRequest.displayText}} + 原因:{{orderItem.pendingArtistChangeRequest.reasonText}} + + + 申请改派 + + + + {{item.reviewStatusText}} + 查看详情 处理订单 diff --git a/YumiNail-Admin-Program/pages/orders/index.wxss b/YumiNail-Admin-Program/pages/orders/index.wxss index 09b20ffe..b654fb00 100644 --- a/YumiNail-Admin-Program/pages/orders/index.wxss +++ b/YumiNail-Admin-Program/pages/orders/index.wxss @@ -1,3 +1,82 @@ .page-shell { 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; +} diff --git a/YumiNail-Admin-Program/pages/shops/index.js b/YumiNail-Admin-Program/pages/shops/index.js index f866ecf6..acebff86 100644 --- a/YumiNail-Admin-Program/pages/shops/index.js +++ b/YumiNail-Admin-Program/pages/shops/index.js @@ -111,31 +111,5 @@ Page({ 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' - }) - } - } - }) } }) diff --git a/YumiNail-Admin-Program/pages/shops/index.wxml b/YumiNail-Admin-Program/pages/shops/index.wxml index f2d235e6..dbf33a36 100644 --- a/YumiNail-Admin-Program/pages/shops/index.wxml +++ b/YumiNail-Admin-Program/pages/shops/index.wxml @@ -32,7 +32,6 @@ 编辑 {{item.status === 0 ? '启用' : '停用'}} - 删除 diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/YumiNailCoreApplication.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/YumiNailCoreApplication.java index d6c8614e..395b22ea 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/YumiNailCoreApplication.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/YumiNailCoreApplication.java @@ -3,8 +3,10 @@ package com.xiaowang.yuminailcore; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.scheduling.annotation.EnableScheduling; @EnableDiscoveryClient +@EnableScheduling @SpringBootApplication public class YumiNailCoreApplication { diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminPermissionController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminPermissionController.java index 14363999..5c302b81 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminPermissionController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminPermissionController.java @@ -9,6 +9,8 @@ import com.xiaowang.yuminailcore.entity.UserDO; import com.xiaowang.yuminailcore.service.PermissionService; import com.xiaowang.yuminailcore.service.UserService; 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 lombok.RequiredArgsConstructor; 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. */ private final AdminScopeHelper adminScopeHelper; + private final SecurityAuditSupport securityAuditSupport; @PostMapping("/create") @RequirePermission("permission:create") @@ -50,8 +53,14 @@ public class AdminPermissionController { public Result createPermission(HttpServletRequest request, @RequestBody PermissionDTO permissionDTO) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以维护权限定义"); - Long id = permissionService.createPermission(permissionDTO); - return Result.success(id); + try { + 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}") @@ -68,8 +77,14 @@ public class AdminPermissionController { public Result updatePermission(HttpServletRequest request, @PathVariable Long id, @RequestBody PermissionDTO permissionDTO) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以维护权限定义"); - boolean success = permissionService.updatePermission(id, permissionDTO); - return Result.success(success); + try { + 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}") @@ -85,8 +100,14 @@ public class AdminPermissionController { public Result deletePermission(HttpServletRequest request, @PathVariable Long id) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以维护权限定义"); - boolean success = permissionService.deletePermission(id); - return Result.success(success); + try { + 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}") @@ -199,7 +220,13 @@ public class AdminPermissionController { } Long currentUserId = (Long) request.getAttribute("userId"); userPermissionDTO.setUserId(userId); - boolean success = permissionService.assignPermissions(userPermissionDTO, currentUserId); - return Result.success(success); + try { + 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; + } } } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminSecurityAuditController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminSecurityAuditController.java new file mode 100644 index 00000000..1c9b95ff --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminSecurityAuditController.java @@ -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> 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()); + } + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminShopController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminShopController.java index 7bd4f283..61b30656 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminShopController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminShopController.java @@ -7,6 +7,8 @@ import com.xiaowang.yuminailcore.dto.ShopDTO; import com.xiaowang.yuminailcore.entity.UserDO; import com.xiaowang.yuminailcore.service.ShopService; 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.ShopVO; 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. */ private final AdminScopeHelper adminScopeHelper; + private final SecurityAuditSupport securityAuditSupport; @GetMapping("/list") @RequirePermission("shop:view") @@ -103,8 +106,14 @@ public class AdminShopController { public Result deleteShop(HttpServletRequest request, @PathVariable Long id) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以删除店铺"); - boolean success = shopService.deleteShop(id); - return Result.success(success); + try { + 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}") @@ -121,8 +130,14 @@ public class AdminShopController { public Result updateShopStatus(HttpServletRequest request, @PathVariable Long id, @RequestBody StatusRequest statusRequest) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); adminScopeHelper.requirePlatformAdmin(currentUser, "只有平台管理员可以启停店铺"); - boolean success = shopService.updateShopStatus(id, statusRequest.getStatus()); - return Result.success(success); + try { + 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") diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminUserController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminUserController.java index c0db8643..796098e9 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminUserController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/AdminUserController.java @@ -13,6 +13,8 @@ import com.xiaowang.yuminailcore.service.UserService; import com.xiaowang.yuminailcore.service.ShopRoleService; import com.xiaowang.yuminailcore.support.AdminScopeHelper; 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.PageResultVO; 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. */ private final BookableArtistSupport bookableArtistSupport; + private final SecurityAuditSupport securityAuditSupport; @GetMapping("/list") @RequirePermission("user:view") @@ -214,8 +217,14 @@ public class AdminUserController { */ throw new RuntimeException("管理员账号不允许停用"); } - boolean success = userService.updateUserStatus(id, request.getStatus()); - return Result.success(success); + try { + 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}") @@ -236,8 +245,14 @@ public class AdminUserController { } adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, "无权重置其他店铺用户密码"); Long currentUserId = (Long) request.getAttribute("userId"); - boolean success = userService.resetPassword(userId, currentUserId); - return Result.success(success); + try { + 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}") @@ -265,8 +280,14 @@ public class AdminUserController { */ throw new RuntimeException("管理员账号不允许删除"); } - boolean success = userService.deleteUser(id); - return Result.success(success); + try { + 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}") @@ -295,8 +316,14 @@ public class AdminUserController { */ throw new RuntimeException("管理员账号不允许解绑"); } - boolean success = userService.unbindUserInShopWithOperator(id, currentUser.getShopId(), currentUser.getType()); - return Result.success(success); + try { + 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") @@ -341,8 +368,14 @@ public class AdminUserController { ) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); UserVO targetUser = requireAccessibleUser(currentUser, id, "无权调整其他店铺用户余额"); - UserAssetVO assetVO = userAssetService.changeBalance(currentUser.getId(), targetUser.getId(), balanceChangeDTO); - return Result.success(assetVO); + try { + 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") @@ -355,8 +388,14 @@ public class AdminUserController { ) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); UserVO targetUser = requireAccessibleUser(currentUser, id, "无权调整其他店铺用户 VIP"); - UserAssetVO assetVO = userAssetService.overrideVip(currentUser.getId(), targetUser.getId(), vipOverrideDTO); - return Result.success(assetVO); + try { + 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") @@ -372,8 +411,14 @@ public class AdminUserController { public Result recalculateUserVip(HttpServletRequest request, @PathVariable Long id) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); UserVO targetUser = requireAccessibleUser(currentUser, id, "无权重算其他店铺用户 VIP"); - UserAssetVO assetVO = userAssetService.recalculateVip(currentUser.getId(), targetUser.getId()); - return Result.success(assetVO); + try { + 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") diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/FrontendFileController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/FrontendFileController.java index 154f0a09..d316651f 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/FrontendFileController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/FrontendFileController.java @@ -1,6 +1,9 @@ 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; @@ -31,6 +34,9 @@ public class FrontendFileController { * Variable `objectStorageUrlSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ 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) { return Result.error("文件不存在"); } + if (!Integer.valueOf(1).equals(fileVO.getStatus()) || !isPublicFileReference(fileId)) { + return Result.error("文件不可公开访问"); + } String objectName = objectStorageUrlSupport.extractObjectName(fileVO.getFileUrl()); if (objectName == null || objectName.isEmpty()) { @@ -60,4 +69,17 @@ public class FrontendFileController { 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; + } } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/OrderController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/OrderController.java index 50f54eda..b06ad977 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/OrderController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/OrderController.java @@ -4,8 +4,16 @@ import com.xiaowang.yuminailcore.annotation.OperationGuard; import com.xiaowang.yuminailcore.annotation.RequirePermission; import com.xiaowang.yuminailcore.common.Result; 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.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.UserVO; import org.springframework.format.annotation.DateTimeFormat; @@ -30,6 +38,9 @@ public class OrderController { @Resource private UserService userService; + @Resource + private SecurityAuditSupport securityAuditSupport; + @PostMapping("/create") @OperationGuard(action = "order-create", ttlSeconds = 15, message = "订单正在提交中,请勿重复点击") /** @@ -145,8 +156,14 @@ public class OrderController { */ throw new RuntimeException("美甲师只能完成属于自己的订单"); } - orderService.completeArtistOrder(orderId, userId); - return Result.success(); + try { + 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)) { UserVO currentUser = userService.getUserById(userId); @@ -171,8 +188,14 @@ public class OrderController { throw new RuntimeException("无权处理其他店铺订单"); } } - orderService.processOrder(orderId, status); - return Result.success(); + try { + 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("仅美甲师可完成自己的订单"); } - orderService.completeArtistOrder(orderId, userId); - return Result.success(); + try { + 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> listMyPendingReviews(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + return Result.success(orderService.listMyPendingReviews(userId)); + } + + @GetMapping("/{orderId}/reviews") + public Result> 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 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 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 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> 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 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 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; + } } } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/OrderArtistChangeRejectDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/OrderArtistChangeRejectDTO.java new file mode 100644 index 00000000..0e765a1d --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/OrderArtistChangeRejectDTO.java @@ -0,0 +1,8 @@ +package com.xiaowang.yuminailcore.dto; + +import lombok.Data; + +@Data +public class OrderArtistChangeRejectDTO { + private String rejectReason; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/OrderArtistChangeRequestDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/OrderArtistChangeRequestDTO.java new file mode 100644 index 00000000..8c3ef23c --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/OrderArtistChangeRequestDTO.java @@ -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; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/OrderArtistReviewSubmitDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/OrderArtistReviewSubmitDTO.java new file mode 100644 index 00000000..0a0c160d --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/OrderArtistReviewSubmitDTO.java @@ -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 imageFileIds; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/SystemMessageCreateDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/SystemMessageCreateDTO.java index 82a3925b..72c23b77 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/SystemMessageCreateDTO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/SystemMessageCreateDTO.java @@ -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. */ private Integer popupEnabled = 1; + + private String businessType; + + private Long businessId; + + private String actionPath; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/BusinessEventOutboxDO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/BusinessEventOutboxDO.java new file mode 100644 index 00000000..8e034c5d --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/BusinessEventOutboxDO.java @@ -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; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/OrderArtistChangeRequestDO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/OrderArtistChangeRequestDO.java new file mode 100644 index 00000000..114aee69 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/OrderArtistChangeRequestDO.java @@ -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; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/OrderArtistReviewDO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/OrderArtistReviewDO.java new file mode 100644 index 00000000..cbe31fc8 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/OrderArtistReviewDO.java @@ -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; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/SystemMessageDO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/SystemMessageDO.java index cb61e78e..39ba2624 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/SystemMessageDO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/SystemMessageDO.java @@ -65,6 +65,18 @@ public class SystemMessageDO extends BaseEntity { */ 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") /** * Field `popupEnabled` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/BusinessEventOutboxMapper.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/BusinessEventOutboxMapper.java new file mode 100644 index 00000000..460d1f37 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/BusinessEventOutboxMapper.java @@ -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 { + + @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 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); +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/EffectDiagramMapper.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/EffectDiagramMapper.java index 9e32368d..1d781796 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/EffectDiagramMapper.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/EffectDiagramMapper.java @@ -2,6 +2,8 @@ package com.xiaowang.yuminailcore.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.xiaowang.yuminailcore.entity.EffectDiagramDO; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; /** * 商品效果图信息表 Mapper @@ -11,4 +13,7 @@ import com.xiaowang.yuminailcore.entity.EffectDiagramDO; * @date 2026-02-13 */ public interface EffectDiagramMapper extends BaseMapper { + + @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); } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/OrderArtistChangeRequestMapper.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/OrderArtistChangeRequestMapper.java new file mode 100644 index 00000000..349644a0 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/OrderArtistChangeRequestMapper.java @@ -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 { + + @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 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 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 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); +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/OrderArtistReviewMapper.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/OrderArtistReviewMapper.java new file mode 100644 index 00000000..d005b774 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/OrderArtistReviewMapper.java @@ -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 { + + @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 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 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); +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/OrderItemMapper.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/OrderItemMapper.java index 9b3ca350..20643878 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/OrderItemMapper.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/OrderItemMapper.java @@ -18,6 +18,9 @@ public interface OrderItemMapper extends BaseMapper { @Select("SELECT * FROM t_order_item WHERE order_id = #{orderId}") List 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 " + "INNER JOIN t_order o ON o.id = oi.order_id " + "WHERE oi.artist_id = #{artistId} " + diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/OrderMapper.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/OrderMapper.java index 07cf1959..87c7fe82 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/OrderMapper.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/OrderMapper.java @@ -5,6 +5,7 @@ import com.xiaowang.yuminailcore.entity.OrderDO; 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.util.List; @@ -25,4 +26,9 @@ public interface OrderMapper extends BaseMapper { "WHERE oi.artist_id = #{artistId} AND o.is_delete = 0 " + "ORDER BY o.create_time DESC") List selectByArtistId(@Param("artistId") Long artistId); -} \ No newline at end of file + + @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); +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/ProductMapper.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/ProductMapper.java index bb7fc603..3a77df55 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/ProductMapper.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/ProductMapper.java @@ -3,6 +3,7 @@ package com.xiaowang.yuminailcore.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.xiaowang.yuminailcore.entity.ProductDO; import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; /** @@ -49,4 +50,7 @@ public interface ProductMapper extends BaseMapper { */ @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); + + @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); } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/ShopMapper.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/ShopMapper.java index c8634701..69545f15 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/ShopMapper.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/ShopMapper.java @@ -2,6 +2,8 @@ package com.xiaowang.yuminailcore.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.xiaowang.yuminailcore.entity.ShopDO; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; /** * 店铺信息表 Mapper @@ -11,4 +13,7 @@ import com.xiaowang.yuminailcore.entity.ShopDO; * @date 2026-02-13 */ public interface ShopMapper extends BaseMapper { + + @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); } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/BusinessEventOutboxService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/BusinessEventOutboxService.java new file mode 100644 index 00000000..98add903 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/BusinessEventOutboxService.java @@ -0,0 +1,8 @@ +package com.xiaowang.yuminailcore.service; + +public interface BusinessEventOutboxService { + + void enqueueOrderCompleted(Long orderId); + + void processDueEvents(); +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/OrderService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/OrderService.java index 485eb4d8..89a2e564 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/OrderService.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/OrderService.java @@ -1,7 +1,13 @@ package com.xiaowang.yuminailcore.service; 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.OrderArtistChangeOptionsVO; +import com.xiaowang.yuminailcore.vo.OrderArtistChangeRequestVO; +import com.xiaowang.yuminailcore.vo.OrderArtistReviewVO; import com.xiaowang.yuminailcore.vo.OrderVO; import java.time.LocalDate; @@ -93,4 +99,20 @@ public interface OrderService { * @return List result consumed by the caller or returned to the frontend */ List getArtistCalendarDay(Long userId, Integer userType, LocalDate date); + + List listMyPendingReviews(Long userId); + + List 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 listMyPendingArtistChangeRequests(Long userId, Integer userType); + + OrderArtistChangeRequestVO approveArtistChange(Long requestId, Long userId, Integer userType); + + OrderArtistChangeRequestVO rejectArtistChange(Long requestId, Long userId, Integer userType, OrderArtistChangeRejectDTO dto); } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/SecurityAuditLogService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/SecurityAuditLogService.java index 6539ceac..9ab7fdd8 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/SecurityAuditLogService.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/SecurityAuditLogService.java @@ -1,8 +1,20 @@ package com.xiaowang.yuminailcore.service; import javax.servlet.http.HttpServletRequest; +import java.time.LocalDateTime; + +import com.xiaowang.yuminailcore.vo.PageResultVO; +import com.xiaowang.yuminailcore.vo.SecurityAuditLogVO; public interface SecurityAuditLogService { void record(Long userId, String account, String action, String result, String reason, HttpServletRequest request); + + PageResultVO pageLogs(String account, + String action, + String result, + LocalDateTime startTime, + LocalDateTime endTime, + Integer page, + Integer size); } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/BusinessEventOutboxProcessor.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/BusinessEventOutboxProcessor.java new file mode 100644 index 00000000..2eed4fdd --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/BusinessEventOutboxProcessor.java @@ -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 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)); + } + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/BusinessEventOutboxServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/BusinessEventOutboxServiceImpl.java new file mode 100644 index 00000000..cd101c95 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/BusinessEventOutboxServiceImpl.java @@ -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); + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/OrderServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/OrderServiceImpl.java index 4bc7f683..aa1e440f 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/OrderServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/OrderServiceImpl.java @@ -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.LambdaQueryWrapper; 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.entity.CartDO; import com.xiaowang.yuminailcore.entity.CouponDO; 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.ShopDO; +import com.xiaowang.yuminailcore.entity.SystemMessageDO; import com.xiaowang.yuminailcore.entity.UserCouponDO; import com.xiaowang.yuminailcore.entity.UserDO; import com.xiaowang.yuminailcore.mapper.CartMapper; import com.xiaowang.yuminailcore.mapper.CouponMapper; 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.ShopMapper; +import com.xiaowang.yuminailcore.mapper.SystemMessageMapper; import com.xiaowang.yuminailcore.mapper.UserCouponMapper; import com.xiaowang.yuminailcore.mapper.UserMapper; +import com.xiaowang.yuminailcore.service.BusinessEventOutboxService; import com.xiaowang.yuminailcore.service.CouponService; import com.xiaowang.yuminailcore.service.OrderService; import com.xiaowang.yuminailcore.service.TagService; import com.xiaowang.yuminailcore.support.BookableArtistSupport; 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.UserShopBindingSupport; 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.OrderVO; import com.xiaowang.yuminailcore.vo.TagVO; import com.xiaowang.yuminailcore.vo.UserCouponVO; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.script.DefaultRedisScript; +import org.springframework.dao.DuplicateKeyException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionTemplate; @@ -44,6 +60,7 @@ import org.springframework.util.StringUtils; import javax.annotation.Resource; import javax.annotation.PreDestroy; import java.math.BigDecimal; +import java.math.RoundingMode; import java.time.Duration; import java.time.LocalDate; import java.time.LocalDateTime; @@ -59,6 +76,7 @@ import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.UUID; import java.util.regex.Matcher; @@ -68,6 +86,7 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; @Service /** @@ -81,6 +100,16 @@ public class OrderServiceImpl implements OrderService { private static final String COUPON_SOURCE_NONE = "NONE"; private static final String COUPON_SOURCE_USER = "USER_COUPON"; 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_ARTIST_LOCK_PREFIX = "order:create:artist:"; private static final Duration ORDER_CREATE_LOCK_TTL = Duration.ofSeconds(15); @@ -123,6 +152,12 @@ public class OrderServiceImpl implements OrderService { @Resource private OrderItemMapper orderItemMapper; + @Resource + private OrderArtistReviewMapper orderArtistReviewMapper; + + @Resource + private OrderArtistChangeRequestMapper orderArtistChangeRequestMapper; + @Resource private CartMapper cartMapper; @@ -144,6 +179,9 @@ public class OrderServiceImpl implements OrderService { @Resource private ShopMapper shopMapper; + @Resource + private SystemMessageMapper systemMessageMapper; + @Resource private CouponService couponService; @@ -156,6 +194,9 @@ public class OrderServiceImpl implements OrderService { @Resource private BookableArtistSupport bookableArtistSupport; + @Resource + private BusinessEventOutboxService businessEventOutboxService; + @Resource private TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; @@ -629,6 +670,7 @@ public class OrderServiceImpl implements OrderService { */ throw new RuntimeException("无效的订单状态"); } + OrderStatus targetStatus = OrderStatus.requireKnown(status); if (order.getStatus() != 1) { /** * Run business method `RuntimeException`. @@ -638,9 +680,15 @@ public class OrderServiceImpl implements OrderService { throw new RuntimeException("订单状态不允许处理"); } + OrderStateMachine.requireAllowedTransition(order.getStatus(), status); + if (orderMapper.updateStatusIfCurrent(order.getId(), order.getStatus(), status) == 0) { + throw new RuntimeException("订单状态已变化,请刷新后重试"); + } order.setStatus(status); - orderMapper.updateById(order); - if (status == 3) { + if (targetStatus == OrderStatus.COMPLETED) { + businessEventOutboxService.enqueueOrderCompleted(order.getId()); + } + if (targetStatus == OrderStatus.CANCELLED) { restoreUserCoupon(order, order.getUserId()); } } @@ -694,8 +742,12 @@ public class OrderServiceImpl implements OrderService { throw new RuntimeException("只能完成全部由自己承接的订单"); } - order.setStatus(2); - orderMapper.updateById(order); + OrderStateMachine.requireAllowedTransition(order.getStatus(), OrderStatus.COMPLETED.getCode()); + if (orderMapper.updateStatusIfCurrent(order.getId(), order.getStatus(), OrderStatus.COMPLETED.getCode()) == 0) { + throw new RuntimeException("订单状态已变化,请刷新后重试"); + } + order.setStatus(OrderStatus.COMPLETED.getCode()); + businessEventOutboxService.enqueueOrderCompleted(order.getId()); } @Override @@ -818,6 +870,710 @@ public class OrderServiceImpl implements OrderService { return listArtistCalendarAppointments(userId, targetDate.atStartOfDay(), targetDate.plusDays(1).atStartOfDay()); } + @Override + public List listMyPendingReviews(Long userId) { + return orderArtistReviewMapper.selectPendingByUserId(userId).stream() + .map(this::buildArtistReviewVO) + .toList(); + } + + @Override + public List 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 listMyPendingArtistChangeRequests(Long userId, Integer userType) { + expireDueArtistChangeRequests(); + List 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 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 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 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 parseIdSet(String rawIds) { + if (!StringUtils.hasText(rawIds)) { + return Collections.emptySet(); + } + LinkedHashSet 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() + .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() + .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`. * 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); } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/PermissionServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/PermissionServiceImpl.java index 22dba1ad..fdf501a3 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/PermissionServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/PermissionServiceImpl.java @@ -193,6 +193,17 @@ public class PermissionServiceImpl extends ServiceImpl listUserPermissions(Long userId) { UserDO userDO = userMapper.selectById(userId); + if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { + return List.of(); + } + + List activeShopRoles = listActiveShopRoles(userId); + if (usesShopRoleEffectivePermissions(userDO, activeShopRoles)) { + return listPermissionsByIds(listPermissionIdsByShopRoles(activeShopRoles)).stream() + .filter(permission -> isPermissionAllowedForUserType(userDO, permission.getPermissionCode())) + .collect(Collectors.toList()); + } + List userPermissions = userPermissionMapper.selectList( Wrappers.lambdaQuery(UserPermissionDO.class) .eq(UserPermissionDO::getUserId, userId) @@ -224,7 +235,9 @@ public class PermissionServiceImpl extends ServiceImpl isPermissionAllowedForUserType(userDO, permission.getPermissionCode())) + .collect(Collectors.toList()); } @Override @@ -440,6 +453,21 @@ public class PermissionServiceImpl extends ServiceImpl activeShopRoles = listActiveShopRoles(userId); + if (usesShopRoleEffectivePermissions(userDO, activeShopRoles)) { + return hasShopRolePermission(activeShopRoles, permissionCode); + } + List userPermissions = userPermissionMapper.selectList( Wrappers.lambdaQuery(UserPermissionDO.class) .eq(UserPermissionDO::getUserId, userId) @@ -463,50 +491,14 @@ public class PermissionServiceImpl extends ServiceImpl 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 roleIds = roles.stream().map(UserShopRoleDO::getRoleId).filter(Objects::nonNull).distinct().collect(Collectors.toList()); - if (roleIds.isEmpty()) { - return false; - } - List 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()); + private boolean hasShopRolePermission(List activeShopRoles, String permissionCode) { + List permissionIds = listPermissionIdsByShopRoles(activeShopRoles); if (permissionIds.isEmpty()) { return false; } @@ -555,21 +547,58 @@ public class PermissionServiceImpl extends ServiceImpl result consumed by the caller or returned to the frontend */ private Set listPermissionCodesByUserId(Long userId) { - List userPermissions = userPermissionMapper.selectList( - Wrappers.lambdaQuery(UserPermissionDO.class) - .eq(UserPermissionDO::getUserId, userId) - ); - if (userPermissions.isEmpty()) { - return Collections.emptySet(); + return listUserPermissions(userId).stream() + .map(PermissionVO::getPermissionCode) + .collect(Collectors.toSet()); + } + + private List listActiveShopRoles(Long userId) { + if (userId == null) { + return List.of(); } - List permissionIds = userPermissions.stream() - .map(UserPermissionDO::getPermissionId) + Long currentShopId = RequestShopContext.getCurrentShopId(); + List 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 listPermissionIdsByShopRoles(List activeShopRoles) { + if (activeShopRoles == null || activeShopRoles.isEmpty()) { + return List.of(); + } + + List roleIds = activeShopRoles.stream() + .map(UserShopRoleDO::getRoleId) .filter(Objects::nonNull) .distinct() .collect(Collectors.toList()); - if (permissionIds.isEmpty()) { - return Collections.emptySet(); + if (roleIds.isEmpty()) { + 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 listPermissionsByIds(List permissionIds) { + if (permissionIds == null || permissionIds.isEmpty()) { + return List.of(); } return permissionMapper.selectList( @@ -577,8 +606,26 @@ public class PermissionServiceImpl extends ServiceImpl 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()); } /** diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/SecurityAuditLogServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/SecurityAuditLogServiceImpl.java index 64bbeb42..a52b8042 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/SecurityAuditLogServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/SecurityAuditLogServiceImpl.java @@ -1,9 +1,13 @@ 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.service.SecurityAuditLogService; import com.xiaowang.yuminailcore.support.security.RequestThrottleService; +import com.xiaowang.yuminailcore.vo.PageResultVO; +import com.xiaowang.yuminailcore.vo.SecurityAuditLogVO; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; @@ -35,6 +39,57 @@ public class SecurityAuditLogServiceImpl implements SecurityAuditLogService { } } + @Override + public PageResultVO 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 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 logPage = auditLogMapper.selectPage(new Page<>(pageNo, pageSize), wrapper); + + PageResultVO 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) { if (request == null) { return null; diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/ShopServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/ShopServiceImpl.java index 73a92d9d..c7fa86be 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/ShopServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/ShopServiceImpl.java @@ -50,6 +50,8 @@ import java.util.stream.Collectors; public class ShopServiceImpl extends ServiceImpl implements ShopService { 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_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. */ @@ -134,6 +136,9 @@ public class ShopServiceImpl extends ServiceImpl implements if (shopDO == null) { return false; } + if (Integer.valueOf(0).equals(normalizeStatus(shopDO.getStatus()))) { + throw new RuntimeException(DISABLED_SHOP_ARCHIVED_MESSAGE); + } shopDO.setShopName(shopDTO.getShopName()); shopDO.setDescription(shopDTO.getDescription()); shopDO.setAddress(shopDTO.getAddress()); @@ -170,53 +175,7 @@ public class ShopServiceImpl extends ServiceImpl implements * @return boolean result consumed by the caller or returned to the frontend */ public boolean deleteShop(Long id) { - ShopDO shopDO = shopMapper.selectById(id); - if (shopDO == null || Integer.valueOf(1).equals(shopDO.getIsDelete())) { - return false; - } - List 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; + throw new RuntimeException(SHOP_DELETE_DISABLED_MESSAGE); } @Override diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/SystemMessageServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/SystemMessageServiceImpl.java index 7c2d781e..72d92861 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/SystemMessageServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/SystemMessageServiceImpl.java @@ -134,6 +134,9 @@ public class SystemMessageServiceImpl extends ServiceImpl(parseIds(message.getTargetIds()))); + vo.setBusinessType(message.getBusinessType()); + vo.setBusinessId(message.getBusinessId()); + vo.setActionPath(message.getActionPath()); vo.setPopupEnabled(message.getPopupEnabled()); vo.setStatus(message.getStatus()); vo.setPublishTime(message.getPublishTime()); @@ -775,6 +781,13 @@ public class SystemMessageServiceImpl extends ServiceImpl Integer.valueOf(status.code).equals(code)) + .findFirst() + .orElseThrow(() -> new RuntimeException("无效的订单状态")); + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/PermissionCatalog.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/PermissionCatalog.java index 17685be3..f3ab5ddc 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/PermissionCatalog.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/PermissionCatalog.java @@ -26,11 +26,12 @@ public final class PermissionCatalog { "tag:view", "tag:create", "tag:edit", "tag:delete", "tag:assign", "coupon:view", "coupon:create", "coupon:edit", "coupon:delete", "coupon:assign", "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", "message:view", "message:create", "message:delete", "announcement:view", "announcement:create", "announcement:delete", "messagehub:config:manage", + "security:audit:view", "legal_agreement:manage" ); @@ -46,7 +47,7 @@ public final class PermissionCatalog { "tag:view", "tag:create", "tag:edit", "tag:delete", "tag:assign", "coupon:view", "coupon:create", "coupon:edit", "coupon:delete", "coupon:assign", "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", "message:view", "message:create", "announcement:view", "announcement:create" @@ -54,14 +55,14 @@ public final class PermissionCatalog { private static final List NAIL_ARTIST_DEFAULT_PERMISSION_CODES = List.of( "home:view", - "user:view", "user:create", + "user:view", "user:balance:view", - "product:view", "product:create", + "product:view", "shop:view", - "tag:view", "tag:create", + "tag:view", "coupon:view", "comment:view", - "order:view", "order:process" + "order:view", "order:process", "order:artist-change" ); private static final Set PLATFORM_OVERVIEW_PREFIXES = Set.of( @@ -74,6 +75,7 @@ public final class PermissionCatalog { private static final Set PLATFORM_OVERVIEW_PERMISSIONS = Set.of( "messagehub:config:manage", + "security:audit:view", "legal_agreement:manage" ); @@ -202,6 +204,7 @@ public final class PermissionCatalog { put(definitions, "order:process", "处理订单", "订单管理", "处理订单状态或由美甲师完结订单"); put(definitions, "order:edit", "编辑订单", "订单管理", "编辑订单信息的预留权限"); put(definitions, "order:delete", "删除订单", "订单管理", "删除订单的预留权限"); + put(definitions, "order:artist-change", "处理改派申请", "订单管理", "处理订单美甲师改派申请"); put(definitions, "nail_artist:view", "查看美甲师", "美甲师管理", "查看美甲师信息与排班入口"); put(definitions, "nail_artist:edit", "编辑美甲师", "美甲师管理", "编辑美甲师信息"); put(definitions, "message:view", "查看消息", "消息管理", "查看站内消息发布与通知"); @@ -211,6 +214,7 @@ public final class PermissionCatalog { put(definitions, "announcement:create", "发布公告", "公告管理", "发布公告"); put(definitions, "announcement:delete", "撤回公告", "公告管理", "撤回已发布公告"); put(definitions, "messagehub:config:manage", "管理消息参数", "参数管理", "管理地图 Key、短信 MessageHub 等平台参数"); + put(definitions, "security:audit:view", "查看安全审计", "安全审计", "查看高危操作和登录安全审计日志"); put(definitions, "legal_agreement:manage", "管理协议", "协议管理", "管理用户协议和隐私政策版本"); return Map.copyOf(definitions); } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/SecurityAuditActions.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/SecurityAuditActions.java new file mode 100644 index 00000000..82680e8e --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/SecurityAuditActions.java @@ -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() { + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/SecurityAuditSupport.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/SecurityAuditSupport.java new file mode 100644 index 00000000..cc9decdb --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/support/SecurityAuditSupport.java @@ -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); + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/OrderArtistChangeOptionsVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/OrderArtistChangeOptionsVO.java new file mode 100644 index 00000000..b3863c4e --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/OrderArtistChangeOptionsVO.java @@ -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 artists; + + @Data + public static class ArtistOptionVO { + private Long artistId; + private String artistName; + private String artistAvatar; + private Integer userType; + private Boolean participateProduction; + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/OrderArtistChangeRequestVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/OrderArtistChangeRequestVO.java new file mode 100644 index 00000000..e110dfa7 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/OrderArtistChangeRequestVO.java @@ -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; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/OrderArtistReviewVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/OrderArtistReviewVO.java new file mode 100644 index 00000000..06bb8895 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/OrderArtistReviewVO.java @@ -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 imageFileIds; + private Integer status; + private String statusText; + private Long reminderMessageId; + private LocalDateTime submitTime; + private LocalDateTime submittedAt; + private LocalDateTime createTime; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/OrderItemVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/OrderItemVO.java index 25550e7f..a4bd5f27 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/OrderItemVO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/OrderItemVO.java @@ -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. */ private String appointmentTime; + private OrderArtistReviewVO pendingReview; + private OrderArtistReviewVO reviewSummary; + private OrderArtistChangeRequestVO pendingArtistChangeRequest; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/SecurityAuditLogVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/SecurityAuditLogVO.java new file mode 100644 index 00000000..6cb72243 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/SecurityAuditLogVO.java @@ -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; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/SystemMessageVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/SystemMessageVO.java index 3d55b60a..2d4192de 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/SystemMessageVO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/SystemMessageVO.java @@ -55,6 +55,9 @@ public class SystemMessageVO { * Field `targetIds` (List): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. */ private List 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. */ diff --git a/YumiNail-Core/src/main/resources/files/YumiNail.sql b/YumiNail-Core/src/main/resources/files/YumiNail.sql index f1a1d4ba..7912bfca 100644 --- a/YumiNail-Core/src/main/resources/files/YumiNail.sql +++ b/YumiNail-Core/src/main/resources/files/YumiNail.sql @@ -19,6 +19,7 @@ create table t_balance last_recharge_time datetime 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 '最近一次更新时间', + update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间', constraint uk_user_id unique (user_id) comment '用户余额唯一索引(一个用户对应一条余额记录)' ) @@ -336,6 +337,75 @@ create index idx_order_id on t_order_item (order_id) 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 create table t_permission ( @@ -572,6 +642,10 @@ create table if not exists t_system_message 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_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-不弹窗', status tinyint unsigned default 1 not null comment '状态:1-已发布,0-已撤回', 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 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 ( 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', '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 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_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` ( `id` bigint unsigned NOT NULL COMMENT '主键ID', `scene_code` varchar(80) NOT NULL COMMENT '业务场景编码', @@ -1312,6 +1483,15 @@ ON DUPLICATE KEY UPDATE update_time = NOW(), 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 ( shop_id, nickname, @@ -1396,6 +1576,7 @@ INNER JOIN t_permission p 'comment:delete', 'order:view', 'order:process', + 'order:artist-change', 'order:edit', 'order:delete', 'nail_artist:view', @@ -1456,6 +1637,7 @@ INNER JOIN t_permission p 'comment:delete', 'order:view', 'order:process', + 'order:artist-change', 'order:edit', 'order:delete', 'nail_artist:view', @@ -1482,17 +1664,15 @@ INNER JOIN t_permission p AND p.permission_code IN ( 'home:view', 'user:view', - 'user:create', 'user:balance:view', 'product:view', - 'product:create', 'shop:view', 'tag:view', - 'tag:create', 'coupon:view', 'comment:view', 'order:view', - 'order:process' + 'order:process', + 'order:artist-change' ) WHERE u.is_delete = 0 AND u.type = 3 @@ -1884,3 +2064,13 @@ ON DUPLICATE KEY UPDATE is_delete = 0, update_by = VALUES(update_by), 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(); diff --git a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/controller/AdminSecurityAuditControllerTest.java b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/controller/AdminSecurityAuditControllerTest.java new file mode 100644 index 00000000..747e5040 --- /dev/null +++ b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/controller/AdminSecurityAuditControllerTest.java @@ -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 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> 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)); + } +} diff --git a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/controller/FrontendFileControllerTest.java b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/controller/FrontendFileControllerTest.java new file mode 100644 index 00000000..309abd17 --- /dev/null +++ b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/controller/FrontendFileControllerTest.java @@ -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 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 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; + } +} diff --git a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/service/impl/BusinessEventOutboxServiceTest.java b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/service/impl/BusinessEventOutboxServiceTest.java new file mode 100644 index 00000000..4c1ceac7 --- /dev/null +++ b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/service/impl/BusinessEventOutboxServiceTest.java @@ -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 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)); + } +} diff --git a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/service/impl/OrderServiceImplReviewChangeTest.java b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/service/impl/OrderServiceImplReviewChangeTest.java new file mode 100644 index 00000000..7c2fe0c4 --- /dev/null +++ b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/service/impl/OrderServiceImplReviewChangeTest.java @@ -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 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 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 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 messageCaptor = ArgumentCaptor.forClass(SystemMessageDO.class); + verify(systemMessageMapper).insert(messageCaptor.capture()); + assertThat(messageCaptor.getValue().getIdempotencyKey()).isEqualTo("ORDER_ARTIST_REVIEW:1001:2"); + ArgumentCaptor 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 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; + } +} diff --git a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/service/impl/PermissionServiceImplTest.java b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/service/impl/PermissionServiceImplTest.java new file mode 100644 index 00000000..5e8b3aeb --- /dev/null +++ b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/service/impl/PermissionServiceImplTest.java @@ -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 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; + } +} diff --git a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/service/impl/SecurityAuditLogServiceImplTest.java b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/service/impl/SecurityAuditLogServiceImplTest.java new file mode 100644 index 00000000..806da7ae --- /dev/null +++ b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/service/impl/SecurityAuditLogServiceImplTest.java @@ -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 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 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 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"); + } +} diff --git a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/service/impl/ShopServiceImplTest.java b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/service/impl/ShopServiceImplTest.java new file mode 100644 index 00000000..3a29a79f --- /dev/null +++ b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/service/impl/ShopServiceImplTest.java @@ -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); + } +} diff --git a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/support/OrderStateMachineTest.java b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/support/OrderStateMachineTest.java new file mode 100644 index 00000000..beb3402b --- /dev/null +++ b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/support/OrderStateMachineTest.java @@ -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("无效的订单状态"); + } +} diff --git a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/support/PermissionCatalogTest.java b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/support/PermissionCatalogTest.java index f408e464..2645f44b 100644 --- a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/support/PermissionCatalogTest.java +++ b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/support/PermissionCatalogTest.java @@ -18,7 +18,7 @@ class PermissionCatalogTest { @Test void platformOnlyPermissionsAreAvailableToAdminAndOverviewMode() { 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:balance:manage")).isTrue(); assertThat(PermissionCatalog.isAllowedForPlatformOverview("shop:delete")).isTrue(); @@ -26,6 +26,7 @@ class PermissionCatalogTest { assertThat(PermissionCatalog.isAllowedForPlatformOverview("message:create")).isTrue(); assertThat(PermissionCatalog.isAllowedForPlatformOverview("announcement:create")).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("product:view")).isTrue(); assertThat(PermissionCatalog.isAllowedForPlatformOverview("order:view")).isTrue(); @@ -42,6 +43,23 @@ class PermissionCatalogTest { .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 void everyManagedDefaultPermissionUsesChineseDisplayText() { PermissionCatalog.getManagedDefinitions().forEach(definition -> { diff --git a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/support/YumiNailSqlSchemaTest.java b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/support/YumiNailSqlSchemaTest.java new file mode 100644 index 00000000..ff440a16 --- /dev/null +++ b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/support/YumiNailSqlSchemaTest.java @@ -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'"); + } +} diff --git a/YumiNail-Frontend/package-lock.json b/YumiNail-Frontend/package-lock.json index 8297b8ea..12380bf9 100644 --- a/YumiNail-Frontend/package-lock.json +++ b/YumiNail-Frontend/package-lock.json @@ -21,12 +21,14 @@ "@types/node": "^24.10.13", "@vitejs/plugin-vue": "^6.0.2", "@vue/tsconfig": "^0.8.1", + "jsdom": "^26.1.0", "less": "^4.5.1", "sass": "^1.97.3", "typescript": "~5.9.3", "unplugin-auto-import": "^21.0.0", "unplugin-vue-components": "^31.0.0", "vite": "^7.3.1", + "vitest": "^3.2.4", "vue-tsc": "^3.1.5" } }, @@ -58,6 +60,20 @@ "vue": ">=3.0.3" } }, + "node_modules/@asamuzakjp/css-color": { + "version": "3.2.0", + "resolved": "https://registry.npmmirror.com/@asamuzakjp/css-color/-/css-color-3.2.0.tgz", + "integrity": "sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@csstools/css-calc": "^2.1.3", + "@csstools/css-color-parser": "^3.0.9", + "@csstools/css-parser-algorithms": "^3.0.4", + "@csstools/css-tokenizer": "^3.0.3", + "lru-cache": "^10.4.3" + } + }, "node_modules/@babel/helper-string-parser": { "version": "7.27.1", "resolved": "https://registry.npmmirror.com/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz", @@ -113,6 +129,121 @@ "node": ">=6.9.0" } }, + "node_modules/@csstools/color-helpers": { + "version": "5.1.0", + "resolved": "https://registry.npmmirror.com/@csstools/color-helpers/-/color-helpers-5.1.0.tgz", + "integrity": "sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "engines": { + "node": ">=18" + } + }, + "node_modules/@csstools/css-calc": { + "version": "2.1.4", + "resolved": "https://registry.npmmirror.com/@csstools/css-calc/-/css-calc-2.1.4.tgz", + "integrity": "sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-color-parser": { + "version": "3.1.0", + "resolved": "https://registry.npmmirror.com/@csstools/css-color-parser/-/css-color-parser-3.1.0.tgz", + "integrity": "sha512-nbtKwh3a6xNVIp/VRuXV64yTKnb1IjTAEEh3irzS+HkKjAOYLTGNb9pmVNntZ8iVBHcWDA2Dof0QtPgFI1BaTA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "dependencies": { + "@csstools/color-helpers": "^5.1.0", + "@csstools/css-calc": "^2.1.4" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-parser-algorithms": { + "version": "3.0.5", + "resolved": "https://registry.npmmirror.com/@csstools/css-parser-algorithms/-/css-parser-algorithms-3.0.5.tgz", + "integrity": "sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-tokenizer": { + "version": "3.0.4", + "resolved": "https://registry.npmmirror.com/@csstools/css-tokenizer/-/css-tokenizer-3.0.4.tgz", + "integrity": "sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/@ctrl/tinycolor": { "version": "3.6.1", "resolved": "https://registry.npmmirror.com/@ctrl/tinycolor/-/tinycolor-3.6.1.tgz", @@ -1368,6 +1499,24 @@ "nanopop": "^2.1.0" } }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmmirror.com/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmmirror.com/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/estree": { "version": "1.0.8", "resolved": "https://registry.npmmirror.com/@types/estree/-/estree-1.0.8.tgz", @@ -1423,6 +1572,131 @@ "vue": "^3.2.25" } }, + "node_modules/@vitest/expect": { + "version": "3.2.4", + "resolved": "https://registry.npmmirror.com/@vitest/expect/-/expect-3.2.4.tgz", + "integrity": "sha512-Io0yyORnB6sikFlt8QW5K7slY4OjqNX9jmJQ02QDda8lyM6B5oNgVWoSoKPac8/kgnCUzuHQKrSLtu/uOqqrig==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/spy": "3.2.4", + "@vitest/utils": "3.2.4", + "chai": "^5.2.0", + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/mocker": { + "version": "3.2.4", + "resolved": "https://registry.npmmirror.com/@vitest/mocker/-/mocker-3.2.4.tgz", + "integrity": "sha512-46ryTE9RZO/rfDd7pEqFl7etuyzekzEhUbTW3BvmeO/BcCMEgq59BKhek3dXDWgAj4oMK6OZi+vRr1wPW6qjEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/spy": "3.2.4", + "estree-walker": "^3.0.3", + "magic-string": "^0.30.17" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/mocker/node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmmirror.com/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/@vitest/pretty-format": { + "version": "3.2.4", + "resolved": "https://registry.npmmirror.com/@vitest/pretty-format/-/pretty-format-3.2.4.tgz", + "integrity": "sha512-IVNZik8IVRJRTr9fxlitMKeJeXFFFN0JaB9PHPGQ8NKQbGpfjlTx9zO4RefN8gp7eqjNy8nyK3NZmBzOPeIxtA==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { + "version": "3.2.4", + "resolved": "https://registry.npmmirror.com/@vitest/runner/-/runner-3.2.4.tgz", + "integrity": "sha512-oukfKT9Mk41LreEW09vt45f8wx7DordoWUZMYdY/cyAk7w5TWkTRCNZYF7sX7n2wB7jyGAl74OxgwhPgKaqDMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/utils": "3.2.4", + "pathe": "^2.0.3", + "strip-literal": "^3.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot": { + "version": "3.2.4", + "resolved": "https://registry.npmmirror.com/@vitest/snapshot/-/snapshot-3.2.4.tgz", + "integrity": "sha512-dEYtS7qQP2CjU27QBC5oUOxLE/v5eLkGqPE0ZKEIDGMs4vKWe7IjgLOeauHsR0D5YuuycGRO5oSRXnwnmA78fQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "3.2.4", + "magic-string": "^0.30.17", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/spy": { + "version": "3.2.4", + "resolved": "https://registry.npmmirror.com/@vitest/spy/-/spy-3.2.4.tgz", + "integrity": "sha512-vAfasCOe6AIK70iP5UD11Ac4siNUNJ9i/9PZ3NKx07sG6sUxeag1LWdNrMWeKKYBLlzuK+Gn65Yd5nyL6ds+nw==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyspy": "^4.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils": { + "version": "3.2.4", + "resolved": "https://registry.npmmirror.com/@vitest/utils/-/utils-3.2.4.tgz", + "integrity": "sha512-fB2V0JFrQSMsCo9HiSq3Ezpdv4iYaXRG1Sx8edX3MwxfyNn83mKiGzOcH+Fkxt4MHxr3y42fQi1oeAInqgX2QA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "3.2.4", + "loupe": "^3.1.4", + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, "node_modules/@volar/language-core": { "version": "2.4.27", "resolved": "https://registry.npmmirror.com/@volar/language-core/-/language-core-2.4.27.tgz", @@ -1721,6 +1995,16 @@ "node": ">=0.4.0" } }, + "node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmmirror.com/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, "node_modules/alien-signals": { "version": "3.1.2", "resolved": "https://registry.npmmirror.com/alien-signals/-/alien-signals-3.1.2.tgz", @@ -1774,6 +2058,16 @@ "integrity": "sha512-4ROwICNlNw/Hqa9v+rk5h22KjmzB1JGTMVKP2AKJBOCgb0yL0ASf0+YvCcLNNwquOHNX48jkeZIJ3a+oOQqKcw==", "license": "MIT" }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmmirror.com/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, "node_modules/async-validator": { "version": "4.2.5", "resolved": "https://registry.npmmirror.com/async-validator/-/async-validator-4.2.5.tgz", @@ -1806,6 +2100,16 @@ "url": "https://github.com/sponsors/antfu" } }, + "node_modules/cac": { + "version": "6.7.14", + "resolved": "https://registry.npmmirror.com/cac/-/cac-6.7.14.tgz", + "integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/call-bind-apply-helpers": { "version": "1.0.2", "resolved": "https://registry.npmmirror.com/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", @@ -1819,6 +2123,33 @@ "node": ">= 0.4" } }, + "node_modules/chai": { + "version": "5.3.3", + "resolved": "https://registry.npmmirror.com/chai/-/chai-5.3.3.tgz", + "integrity": "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "assertion-error": "^2.0.1", + "check-error": "^2.1.1", + "deep-eql": "^5.0.1", + "loupe": "^3.1.0", + "pathval": "^2.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/check-error": { + "version": "2.1.3", + "resolved": "https://registry.npmmirror.com/check-error/-/check-error-2.1.3.tgz", + "integrity": "sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 16" + } + }, "node_modules/chokidar": { "version": "4.0.3", "resolved": "https://registry.npmmirror.com/chokidar/-/chokidar-4.0.3.tgz", @@ -1886,18 +2217,81 @@ "url": "https://opencollective.com/core-js" } }, + "node_modules/cssstyle": { + "version": "4.6.0", + "resolved": "https://registry.npmmirror.com/cssstyle/-/cssstyle-4.6.0.tgz", + "integrity": "sha512-2z+rWdzbbSZv6/rhtvzvqeZQHrBaqgogqt85sqFNbabZOuFbCVFb8kPeEtZjiKkbrm395irpNKiYeFeLiQnFPg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@asamuzakjp/css-color": "^3.2.0", + "rrweb-cssom": "^0.8.0" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/csstype": { "version": "3.2.3", "resolved": "https://registry.npmmirror.com/csstype/-/csstype-3.2.3.tgz", "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", "license": "MIT" }, + "node_modules/data-urls": { + "version": "5.0.0", + "resolved": "https://registry.npmmirror.com/data-urls/-/data-urls-5.0.0.tgz", + "integrity": "sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-mimetype": "^4.0.0", + "whatwg-url": "^14.0.0" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/dayjs": { "version": "1.11.19", "resolved": "https://registry.npmmirror.com/dayjs/-/dayjs-1.11.19.tgz", "integrity": "sha512-t5EcLVS6QPBNqM2z8fakk/NKel+Xzshgt8FFKAn+qwlD1pzZWxh0nVCrvFK7ZDb6XucZeF9z8C7CBWTRIVApAw==", "license": "MIT" }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmmirror.com/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decimal.js": { + "version": "10.6.0", + "resolved": "https://registry.npmmirror.com/decimal.js/-/decimal.js-10.6.0.tgz", + "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==", + "dev": true, + "license": "MIT" + }, + "node_modules/deep-eql": { + "version": "5.0.2", + "resolved": "https://registry.npmmirror.com/deep-eql/-/deep-eql-5.0.2.tgz", + "integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/delayed-stream": { "version": "1.0.0", "resolved": "https://registry.npmmirror.com/delayed-stream/-/delayed-stream-1.0.0.tgz", @@ -2013,6 +2407,13 @@ "node": ">= 0.4" } }, + "node_modules/es-module-lexer": { + "version": "1.7.0", + "resolved": "https://registry.npmmirror.com/es-module-lexer/-/es-module-lexer-1.7.0.tgz", + "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==", + "dev": true, + "license": "MIT" + }, "node_modules/es-object-atoms": { "version": "1.1.1", "resolved": "https://registry.npmmirror.com/es-object-atoms/-/es-object-atoms-1.1.1.tgz", @@ -2101,6 +2502,16 @@ "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", "license": "MIT" }, + "node_modules/expect-type": { + "version": "1.3.0", + "resolved": "https://registry.npmmirror.com/expect-type/-/expect-type-1.3.0.tgz", + "integrity": "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, "node_modules/exsolve": { "version": "1.0.8", "resolved": "https://registry.npmmirror.com/exsolve/-/exsolve-1.0.8.tgz", @@ -2288,13 +2699,53 @@ "integrity": "sha512-Yc+BQe8SvoXH1643Qez1zqLRmbA5rCL+sSmk6TVos0LWVfNIB7PGncdlId77WzLGSIB5KaWgTaNTs2lNVEI6VQ==", "license": "MIT" }, + "node_modules/html-encoding-sniffer": { + "version": "4.0.0", + "resolved": "https://registry.npmmirror.com/html-encoding-sniffer/-/html-encoding-sniffer-4.0.0.tgz", + "integrity": "sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-encoding": "^3.1.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/http-proxy-agent": { + "version": "7.0.2", + "resolved": "https://registry.npmmirror.com/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", + "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.0", + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmmirror.com/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, "node_modules/iconv-lite": { "version": "0.6.3", "resolved": "https://registry.npmmirror.com/iconv-lite/-/iconv-lite-0.6.3.tgz", "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", "dev": true, "license": "MIT", - "optional": true, "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" }, @@ -2357,6 +2808,13 @@ "node": ">=0.10.0" } }, + "node_modules/is-potential-custom-element-name": { + "version": "1.0.1", + "resolved": "https://registry.npmmirror.com/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", + "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", + "dev": true, + "license": "MIT" + }, "node_modules/is-what": { "version": "5.5.0", "resolved": "https://registry.npmmirror.com/is-what/-/is-what-5.5.0.tgz", @@ -2376,6 +2834,46 @@ "dev": true, "license": "MIT" }, + "node_modules/jsdom": { + "version": "26.1.0", + "resolved": "https://registry.npmmirror.com/jsdom/-/jsdom-26.1.0.tgz", + "integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cssstyle": "^4.2.1", + "data-urls": "^5.0.0", + "decimal.js": "^10.5.0", + "html-encoding-sniffer": "^4.0.0", + "http-proxy-agent": "^7.0.2", + "https-proxy-agent": "^7.0.6", + "is-potential-custom-element-name": "^1.0.1", + "nwsapi": "^2.2.16", + "parse5": "^7.2.1", + "rrweb-cssom": "^0.8.0", + "saxes": "^6.0.0", + "symbol-tree": "^3.2.4", + "tough-cookie": "^5.1.1", + "w3c-xmlserializer": "^5.0.0", + "webidl-conversions": "^7.0.0", + "whatwg-encoding": "^3.1.1", + "whatwg-mimetype": "^4.0.0", + "whatwg-url": "^14.1.1", + "ws": "^8.18.0", + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "canvas": "^3.0.0" + }, + "peerDependenciesMeta": { + "canvas": { + "optional": true + } + } + }, "node_modules/less": { "version": "4.5.1", "resolved": "https://registry.npmmirror.com/less/-/less-4.5.1.tgz", @@ -2483,6 +2981,20 @@ "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", "license": "MIT" }, + "node_modules/loupe": { + "version": "3.2.1", + "resolved": "https://registry.npmmirror.com/loupe/-/loupe-3.2.1.tgz", + "integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/lru-cache": { + "version": "10.4.3", + "resolved": "https://registry.npmmirror.com/lru-cache/-/lru-cache-10.4.3.tgz", + "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", + "dev": true, + "license": "ISC" + }, "node_modules/magic-string": { "version": "0.30.21", "resolved": "https://registry.npmmirror.com/magic-string/-/magic-string-0.30.21.tgz", @@ -2595,6 +3107,13 @@ "pathe": "^2.0.1" } }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmmirror.com/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, "node_modules/muggle-string": { "version": "0.4.1", "resolved": "https://registry.npmmirror.com/muggle-string/-/muggle-string-0.4.1.tgz", @@ -2658,6 +3177,13 @@ "integrity": "sha512-Wj7+EJQ8mSuXr2iWfnujrimU35R2W4FAErEyTmJoJ7ucwTn2hOUSsRehMb5RSYkxXGTM7Y9QpvPmp++w5ftoJw==", "license": "BSD-3-Clause" }, + "node_modules/nwsapi": { + "version": "2.2.23", + "resolved": "https://registry.npmmirror.com/nwsapi/-/nwsapi-2.2.23.tgz", + "integrity": "sha512-7wfH4sLbt4M0gCDzGE6vzQBo0bfTKjU7Sfpqy/7gs1qBfYz2vEJH6vXcBKpO3+6Yu1telwd0t9HpyOoLEQQbIQ==", + "dev": true, + "license": "MIT" + }, "node_modules/obug": { "version": "2.1.1", "resolved": "https://registry.npmmirror.com/obug/-/obug-2.1.1.tgz", @@ -2679,6 +3205,32 @@ "node": ">= 0.10" } }, + "node_modules/parse5": { + "version": "7.3.0", + "resolved": "https://registry.npmmirror.com/parse5/-/parse5-7.3.0.tgz", + "integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "entities": "^6.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/parse5/node_modules/entities": { + "version": "6.0.1", + "resolved": "https://registry.npmmirror.com/entities/-/entities-6.0.1.tgz", + "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, "node_modules/path-browserify": { "version": "1.0.1", "resolved": "https://registry.npmmirror.com/path-browserify/-/path-browserify-1.0.1.tgz", @@ -2693,6 +3245,16 @@ "dev": true, "license": "MIT" }, + "node_modules/pathval": { + "version": "2.0.1", + "resolved": "https://registry.npmmirror.com/pathval/-/pathval-2.0.1.tgz", + "integrity": "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14.16" + } + }, "node_modules/perfect-debounce": { "version": "1.0.0", "resolved": "https://registry.npmmirror.com/perfect-debounce/-/perfect-debounce-1.0.0.tgz", @@ -2804,6 +3366,16 @@ "license": "MIT", "optional": true }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmmirror.com/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/quansync": { "version": "0.2.11", "resolved": "https://registry.npmmirror.com/quansync/-/quansync-0.2.11.tgz", @@ -2892,13 +3464,19 @@ "fsevents": "~2.3.2" } }, + "node_modules/rrweb-cssom": { + "version": "0.8.0", + "resolved": "https://registry.npmmirror.com/rrweb-cssom/-/rrweb-cssom-0.8.0.tgz", + "integrity": "sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw==", + "dev": true, + "license": "MIT" + }, "node_modules/safer-buffer": { "version": "2.1.2", "resolved": "https://registry.npmmirror.com/safer-buffer/-/safer-buffer-2.1.2.tgz", "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", "dev": true, - "license": "MIT", - "optional": true + "license": "MIT" }, "node_modules/sass": { "version": "1.97.3", @@ -2932,6 +3510,19 @@ "node": ">=11.0.0" } }, + "node_modules/saxes": { + "version": "6.0.0", + "resolved": "https://registry.npmmirror.com/saxes/-/saxes-6.0.0.tgz", + "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", + "dev": true, + "license": "ISC", + "dependencies": { + "xmlchars": "^2.2.0" + }, + "engines": { + "node": ">=v12.22.7" + } + }, "node_modules/scroll-into-view-if-needed": { "version": "2.2.31", "resolved": "https://registry.npmmirror.com/scroll-into-view-if-needed/-/scroll-into-view-if-needed-2.2.31.tgz", @@ -2965,6 +3556,13 @@ "integrity": "sha512-S4vJDjHHMBaiZuT9NPb616CSmLf618jawtv3sufLl6ivK8WocjAo58cXwbRV1cgqxH0Qbv+iUt6m05eqEa2IRA==", "license": "MIT" }, + "node_modules/siginfo": { + "version": "2.0.0", + "resolved": "https://registry.npmmirror.com/siginfo/-/siginfo-2.0.0.tgz", + "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", + "dev": true, + "license": "ISC" + }, "node_modules/source-map": { "version": "0.6.1", "resolved": "https://registry.npmmirror.com/source-map/-/source-map-0.6.1.tgz", @@ -2994,6 +3592,20 @@ "node": ">=0.10.0" } }, + "node_modules/stackback": { + "version": "0.0.2", + "resolved": "https://registry.npmmirror.com/stackback/-/stackback-0.0.2.tgz", + "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", + "dev": true, + "license": "MIT" + }, + "node_modules/std-env": { + "version": "3.10.0", + "resolved": "https://registry.npmmirror.com/std-env/-/std-env-3.10.0.tgz", + "integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==", + "dev": true, + "license": "MIT" + }, "node_modules/strip-literal": { "version": "3.1.0", "resolved": "https://registry.npmmirror.com/strip-literal/-/strip-literal-3.1.0.tgz", @@ -3025,6 +3637,13 @@ "node": ">=16" } }, + "node_modules/symbol-tree": { + "version": "3.2.4", + "resolved": "https://registry.npmmirror.com/symbol-tree/-/symbol-tree-3.2.4.tgz", + "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", + "dev": true, + "license": "MIT" + }, "node_modules/throttle-debounce": { "version": "5.0.2", "resolved": "https://registry.npmmirror.com/throttle-debounce/-/throttle-debounce-5.0.2.tgz", @@ -3034,6 +3653,20 @@ "node": ">=12.22" } }, + "node_modules/tinybench": { + "version": "2.9.0", + "resolved": "https://registry.npmmirror.com/tinybench/-/tinybench-2.9.0.tgz", + "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyexec": { + "version": "0.3.2", + "resolved": "https://registry.npmmirror.com/tinyexec/-/tinyexec-0.3.2.tgz", + "integrity": "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==", + "dev": true, + "license": "MIT" + }, "node_modules/tinyglobby": { "version": "0.2.15", "resolved": "https://registry.npmmirror.com/tinyglobby/-/tinyglobby-0.2.15.tgz", @@ -3051,6 +3684,82 @@ "url": "https://github.com/sponsors/SuperchupuDev" } }, + "node_modules/tinypool": { + "version": "1.1.1", + "resolved": "https://registry.npmmirror.com/tinypool/-/tinypool-1.1.1.tgz", + "integrity": "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.0.0 || >=20.0.0" + } + }, + "node_modules/tinyrainbow": { + "version": "2.0.0", + "resolved": "https://registry.npmmirror.com/tinyrainbow/-/tinyrainbow-2.0.0.tgz", + "integrity": "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tinyspy": { + "version": "4.0.4", + "resolved": "https://registry.npmmirror.com/tinyspy/-/tinyspy-4.0.4.tgz", + "integrity": "sha512-azl+t0z7pw/z958Gy9svOTuzqIk6xq+NSheJzn5MMWtWTFywIacg2wUlzKFGtt3cthx0r2SxMK0yzJOR0IES7Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tldts": { + "version": "6.1.86", + "resolved": "https://registry.npmmirror.com/tldts/-/tldts-6.1.86.tgz", + "integrity": "sha512-WMi/OQ2axVTf/ykqCQgXiIct+mSQDFdH2fkwhPwgEwvJ1kSzZRiinb0zF2Xb8u4+OqPChmyI6MEu4EezNJz+FQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "tldts-core": "^6.1.86" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "6.1.86", + "resolved": "https://registry.npmmirror.com/tldts-core/-/tldts-core-6.1.86.tgz", + "integrity": "sha512-Je6p7pkk+KMzMv2XXKmAE3McmolOQFdxkKw0R8EYNr7sELW46JqnNeTX8ybPiQgvg1ymCoF8LXs5fzFaZvJPTA==", + "dev": true, + "license": "MIT" + }, + "node_modules/tough-cookie": { + "version": "5.1.2", + "resolved": "https://registry.npmmirror.com/tough-cookie/-/tough-cookie-5.1.2.tgz", + "integrity": "sha512-FVDYdxtnj0G6Qm/DhNPSb8Ju59ULcup3tuJxkFb5K8Bv2pUXILbf0xZWU8PX8Ov19OXljbUyveOFwRMwkXzO+A==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "tldts": "^6.1.32" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/tr46": { + "version": "5.1.1", + "resolved": "https://registry.npmmirror.com/tr46/-/tr46-5.1.1.tgz", + "integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==", + "dev": true, + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/tslib": { "version": "2.8.1", "resolved": "https://registry.npmmirror.com/tslib/-/tslib-2.8.1.tgz", @@ -3326,6 +4035,102 @@ } } }, + "node_modules/vite-node": { + "version": "3.2.4", + "resolved": "https://registry.npmmirror.com/vite-node/-/vite-node-3.2.4.tgz", + "integrity": "sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cac": "^6.7.14", + "debug": "^4.4.1", + "es-module-lexer": "^1.7.0", + "pathe": "^2.0.3", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" + }, + "bin": { + "vite-node": "vite-node.mjs" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/vitest": { + "version": "3.2.4", + "resolved": "https://registry.npmmirror.com/vitest/-/vitest-3.2.4.tgz", + "integrity": "sha512-LUCP5ev3GURDysTWiP47wRRUpLKMOfPh+yKTx3kVIEiu5KOMeqzpnYNsKyOoVrULivR8tLcks4+lga33Whn90A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/expect": "3.2.4", + "@vitest/mocker": "3.2.4", + "@vitest/pretty-format": "^3.2.4", + "@vitest/runner": "3.2.4", + "@vitest/snapshot": "3.2.4", + "@vitest/spy": "3.2.4", + "@vitest/utils": "3.2.4", + "chai": "^5.2.0", + "debug": "^4.4.1", + "expect-type": "^1.2.1", + "magic-string": "^0.30.17", + "pathe": "^2.0.3", + "picomatch": "^4.0.2", + "std-env": "^3.9.0", + "tinybench": "^2.9.0", + "tinyexec": "^0.3.2", + "tinyglobby": "^0.2.14", + "tinypool": "^1.1.1", + "tinyrainbow": "^2.0.0", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0", + "vite-node": "3.2.4", + "why-is-node-running": "^2.3.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@types/debug": "^4.1.12", + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "@vitest/browser": "3.2.4", + "@vitest/ui": "3.2.4", + "happy-dom": "*", + "jsdom": "*" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@types/debug": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + } + } + }, "node_modules/vscode-uri": { "version": "3.1.0", "resolved": "https://registry.npmmirror.com/vscode-uri/-/vscode-uri-3.1.0.tgz", @@ -3407,6 +4212,19 @@ "vue": "^3.0.0" } }, + "node_modules/w3c-xmlserializer": { + "version": "5.0.0", + "resolved": "https://registry.npmmirror.com/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz", + "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==", + "dev": true, + "license": "MIT", + "dependencies": { + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/warning": { "version": "4.0.3", "resolved": "https://registry.npmmirror.com/warning/-/warning-4.0.3.tgz", @@ -3416,13 +4234,116 @@ "loose-envify": "^1.0.0" } }, + "node_modules/webidl-conversions": { + "version": "7.0.0", + "resolved": "https://registry.npmmirror.com/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + } + }, "node_modules/webpack-virtual-modules": { "version": "0.6.2", "resolved": "https://registry.npmmirror.com/webpack-virtual-modules/-/webpack-virtual-modules-0.6.2.tgz", "integrity": "sha512-66/V2i5hQanC51vBQKPH4aI8NMAcBW59FVBs+rC7eGHupMyfn34q7rZIE+ETlJ+XTevqfUhVVBgSUNSW2flEUQ==", "dev": true, "license": "MIT" + }, + "node_modules/whatwg-encoding": { + "version": "3.1.1", + "resolved": "https://registry.npmmirror.com/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz", + "integrity": "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==", + "deprecated": "Use @exodus/bytes instead for a more spec-conformant and faster implementation", + "dev": true, + "license": "MIT", + "dependencies": { + "iconv-lite": "0.6.3" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-mimetype": { + "version": "4.0.0", + "resolved": "https://registry.npmmirror.com/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz", + "integrity": "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-url": { + "version": "14.2.0", + "resolved": "https://registry.npmmirror.com/whatwg-url/-/whatwg-url-14.2.0.tgz", + "integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "tr46": "^5.1.0", + "webidl-conversions": "^7.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/why-is-node-running": { + "version": "2.3.0", + "resolved": "https://registry.npmmirror.com/why-is-node-running/-/why-is-node-running-2.3.0.tgz", + "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "siginfo": "^2.0.0", + "stackback": "0.0.2" + }, + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/ws": { + "version": "8.20.1", + "resolved": "https://registry.npmmirror.com/ws/-/ws-8.20.1.tgz", + "integrity": "sha512-It4dO0K5v//JtTXuPkfEOaI3uUN87iYPnqo/ZzqCoG3g8uhA66QUMs/SrM0YK7/NAu+r4LMh/9dq2A7k+rHs+w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/xml-name-validator": { + "version": "5.0.0", + "resolved": "https://registry.npmmirror.com/xml-name-validator/-/xml-name-validator-5.0.0.tgz", + "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/xmlchars": { + "version": "2.2.0", + "resolved": "https://registry.npmmirror.com/xmlchars/-/xmlchars-2.2.0.tgz", + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "dev": true, + "license": "MIT" } } } - diff --git a/YumiNail-Frontend/package.json b/YumiNail-Frontend/package.json index fa950050..d2601af9 100644 --- a/YumiNail-Frontend/package.json +++ b/YumiNail-Frontend/package.json @@ -6,7 +6,8 @@ "scripts": { "dev": "vite", "build": "vue-tsc -b && vite build", - "preview": "vite preview" + "preview": "vite preview", + "test:unit": "vitest run" }, "dependencies": { "@element-plus/icons-vue": "^2.3.2", @@ -22,13 +23,14 @@ "@types/node": "^24.10.13", "@vitejs/plugin-vue": "^6.0.2", "@vue/tsconfig": "^0.8.1", + "jsdom": "^26.1.0", "less": "^4.5.1", "sass": "^1.97.3", "typescript": "~5.9.3", "unplugin-auto-import": "^21.0.0", "unplugin-vue-components": "^31.0.0", "vite": "^7.3.1", + "vitest": "^3.2.4", "vue-tsc": "^3.1.5" } } - diff --git a/YumiNail-Frontend/src/App.vue b/YumiNail-Frontend/src/App.vue index 30d70227..c1008796 100644 --- a/YumiNail-Frontend/src/App.vue +++ b/YumiNail-Frontend/src/App.vue @@ -29,11 +29,13 @@ import SystemMessageCard from './components/SystemMessageCard.vue' import { cartApi } from './api/cart' import { userApi, type SystemMessageVO } from './api/user' import antdLocale from './config/antdv-locale' +import { useGlobalConfirmEnter } from './composables/useConfirmEnter' import { useShopTheme } from './composables/useShopTheme' const route = useRoute() const router = useRouter() const { currentTheme, refreshShopTheme, resetShopTheme, setupShopThemeSync } = useShopTheme() +useGlobalConfirmEnter() type ButtonPropsWithClass = ButtonProps & { class?: string } const popupMessageOkButtonProps: ButtonPropsWithClass = { class: 'popup-message-ok-button' } /** routerReady is a reactive state variable used by the template and event handlers. */ @@ -108,6 +110,22 @@ const updateCartCount = async () => { 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. */ const showPopupMessage = (item: SystemMessageVO) => { return new Promise((resolve) => { @@ -142,6 +160,7 @@ const showPopupMessage = (item: SystemMessageVO) => { okButtonProps: popupMessageOkButtonProps, async onOk() { await markShownAndResolve() + await openSystemMessageAction(item) }, async afterClose() { await markShownAndResolve() diff --git a/YumiNail-Frontend/src/api/admin.ts b/YumiNail-Frontend/src/api/admin.ts index 7e7d3e5a..d88b0d62 100644 --- a/YumiNail-Frontend/src/api/admin.ts +++ b/YumiNail-Frontend/src/api/admin.ts @@ -8,6 +8,7 @@ import { ADMIN_API_BASE_URL } from '../config/api' import type { IdType } from '@/utils/id' import { clearAdminSessionStorage } from '@/utils/admin-session' import { attachRequestSignature } from '@/utils/request-signature' +import { isAdminApiAuthFreePath } from './auth-free-paths' let lastErrorTime = 0 let lastErrorMessage = '' @@ -38,6 +39,25 @@ const processQueue = (error: any, token: string | null = null) => { 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 now = Date.now() if (now - lastErrorTime > ERROR_DEBOUNCE_TIME || msg !== lastErrorMessage) { @@ -48,10 +68,14 @@ const showError = (msg: 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() if (Date.now() - lastErrorTime > ERROR_DEBOUNCE_TIME || lastErrorMessage !== '登录已过期,请重新登录') { @@ -67,14 +91,12 @@ adminApi.interceptors.request.use( async config => { let token: string | null = null if (!isAuthFreePath(config.url)) { - token = localStorage.getItem('adminAccessToken') - if (!token) { - token = sessionStorage.getItem('adminAccessToken') - } + token = getStoredAdminAccessToken() if (token) { config.headers.Authorization = `Bearer ${token}` } } + ;(config as any)._authToken = token || null return attachRequestSignature(config, token, { authFree: isAuthFreePath(config.url) }) @@ -100,6 +122,12 @@ adminApi.interceptors.response.use( const originalRequest = error.config as any if (error.response?.status === 401) { + const requestToken = getRequestToken(originalRequest) + + if (!isCurrentStoredAdminToken(requestToken)) { + return Promise.reject(error) + } + if (!originalRequest?._retry && !isAuthFreePath(originalRequest?.url)) { if (isRefreshing) { return new Promise((resolve, reject) => { @@ -138,14 +166,14 @@ adminApi.interceptors.response.use( return adminApi(originalRequest) } catch (refreshError) { processQueue(refreshError, null) - handleAdminTokenExpired() + handleAdminTokenExpired(requestToken) return Promise.reject(refreshError) } finally { isRefreshing = false } } - handleAdminTokenExpired() + handleAdminTokenExpired(requestToken) } else if (error.response?.status !== 403) { const errorMsg = (error.response?.data as any)?.message || error.message || '请求失败' showError(errorMsg) @@ -728,14 +756,6 @@ export const adminShopApi = { */ updateShopStatus: (id: IdType, status: number) => { return adminApi.put(`/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(`/shops/delete/${id}`) } } diff --git a/YumiNail-Frontend/src/api/auth-free-paths.ts b/YumiNail-Frontend/src/api/auth-free-paths.ts new file mode 100644 index 00000000..7ce403d0 --- /dev/null +++ b/YumiNail-Frontend/src/api/auth-free-paths.ts @@ -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)) +} diff --git a/YumiNail-Frontend/src/api/index.ts b/YumiNail-Frontend/src/api/index.ts index 908357dc..d805103a 100644 --- a/YumiNail-Frontend/src/api/index.ts +++ b/YumiNail-Frontend/src/api/index.ts @@ -11,6 +11,7 @@ import { API_BASE_URL } from '../config/api' import type { IdType } from '@/utils/id' import { clearAdminSessionStorage } from '@/utils/admin-session' import { attachRequestSignature } from '@/utils/request-signature' +import { isApiAuthFreePath } from './auth-free-paths' // 防重复提示标志 let lastErrorTime = 0 @@ -31,6 +32,55 @@ let failedQueue: Array<{ 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) => { failedQueue.forEach(prom => { if (error) { @@ -53,32 +103,14 @@ const showError = (msg: string) => { } const isAuthFreePath = (url?: string) => { - return [ - '/user/login', - '/user/register', - '/user/check/', - '/user/refresh-token', - '/user/send-verification-code', - '/user/phone-login', - '/user/wechat-mini/', - '/user/reset-password-by-phone', - '/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)) + return isApiAuthFreePath(url) } -const handleTokenExpired = (isAdmin = false) => { +const handleTokenExpired = (isAdmin = false, failedToken: string | null = null) => { + if (!isCurrentStoredToken(failedToken, isAdmin)) { + return + } + // 清理token和用户信息 if (isAdmin) { // 清理后台管理的token @@ -89,6 +121,7 @@ const handleTokenExpired = (isAdmin = false) => { localStorage.removeItem('refreshToken') localStorage.removeItem('userInfo') sessionStorage.removeItem('accessToken') + sessionStorage.removeItem('refreshToken') } // 显示错误提示 @@ -124,6 +157,7 @@ api.interceptors.request.use( if (token) { config.headers.Authorization = `Bearer ${token}` } + ;(config as any)._authToken = token || null return attachRequestSignature(config, token, { authFree: isAuthFreePath(config.url) }) @@ -149,28 +183,23 @@ api.interceptors.response.use( const originalRequest = error.config as any const isWhitelistedPath = (url: string) => { - return url?.includes('/user/login') || - 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') + return isApiAuthFreePath(url) } if (error.response?.status === 401) { // 检查是否是后台管理的API请求 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 (isRefreshing) { @@ -179,6 +208,7 @@ api.interceptors.response.use( }).then(token => { if (token) { originalRequest.headers.Authorization = `Bearer ${token}` + originalRequest._authToken = token } return api(originalRequest) }).catch(err => { @@ -192,9 +222,9 @@ api.interceptors.response.use( try { let refreshToken if (isAdminRequest) { - refreshToken = localStorage.getItem('adminRefreshToken') || sessionStorage.getItem('adminRefreshToken') + refreshToken = getStoredRefreshToken(true) } else { - refreshToken = localStorage.getItem('refreshToken') || sessionStorage.getItem('refreshToken') + refreshToken = getStoredRefreshToken(false) } if (!refreshToken) { @@ -217,21 +247,23 @@ api.interceptors.response.use( localStorage.setItem('accessToken', newToken) localStorage.setItem('refreshToken', newRefreshToken) sessionStorage.setItem('accessToken', newToken) + sessionStorage.setItem('refreshToken', newRefreshToken) } processQueue(null, newToken) originalRequest.headers.Authorization = `Bearer ${newToken}` + originalRequest._authToken = newToken return api(originalRequest) } catch (refreshError) { processQueue(refreshError, null) - handleTokenExpired(isAdminRequest) + handleTokenExpired(isAdminRequest, requestToken) return Promise.reject(refreshError) } finally { isRefreshing = false } } else { - handleTokenExpired(isAdminRequest) + handleTokenExpired(isAdminRequest, requestToken) return Promise.reject(error) } } else if (error.response?.status !== 403) { // 403权限不足不提示 diff --git a/YumiNail-Frontend/src/api/order.ts b/YumiNail-Frontend/src/api/order.ts index 048d8822..1e2c3746 100644 --- a/YumiNail-Frontend/src/api/order.ts +++ b/YumiNail-Frontend/src/api/order.ts @@ -40,6 +40,77 @@ export interface ArtistCalendarAppointment { 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. * 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 => { return await api.get('/order/list') as unknown as any[] }, + + getMyPendingReviews: async (): Promise => { + return await api.get('/order/review/my-pending') as unknown as OrderArtistReviewVO[] + }, + + getOrderReviews: async (orderId: IdType): Promise => { + return await api.get(`/order/${orderId}/reviews`) as unknown as OrderArtistReviewVO[] + }, + + submitArtistReview: async (reviewId: IdType, data: OrderArtistReviewSubmitRequest): Promise => { + return await api.post(`/order/review/${reviewId}/submit`, data) as unknown as OrderArtistReviewVO + }, + + getArtistChangeOptions: async (orderId: IdType, orderItemId: IdType): Promise => { + return await api.get(`/order/${orderId}/artist-change/options`, { + params: { orderItemId } + }) as unknown as OrderArtistChangeOptionsVO + }, + + requestArtistChange: async (data: OrderArtistChangeRequestSubmitRequest): Promise => { + return await api.post('/order/artist-change/request', data) as unknown as OrderArtistChangeRequestVO + }, + + getMyPendingArtistChangeRequests: async (): Promise => { + return await api.get('/order/artist-change/my-pending') as unknown as OrderArtistChangeRequestVO[] + }, + + approveArtistChange: async (requestId: IdType): Promise => { + return await api.put(`/order/artist-change/${requestId}/approve`) as unknown as OrderArtistChangeRequestVO + }, + + rejectArtistChange: async (requestId: IdType, data?: OrderArtistChangeRejectRequest): Promise => { + return await api.put(`/order/artist-change/${requestId}/reject`, data || {}) as unknown as OrderArtistChangeRequestVO + }, // 获取订单详情 /** diff --git a/YumiNail-Frontend/src/api/user.ts b/YumiNail-Frontend/src/api/user.ts index bb7907e4..00e4627f 100644 --- a/YumiNail-Frontend/src/api/user.ts +++ b/YumiNail-Frontend/src/api/user.ts @@ -180,6 +180,9 @@ export interface SystemMessageVO { publisherName?: string targetType?: string targetTypeName?: string + businessType?: string + businessId?: IdType + actionPath?: string popupEnabled?: number popupShown?: number readStatus?: number diff --git a/YumiNail-Frontend/src/components/admin/AdminResponsiveModal.vue b/YumiNail-Frontend/src/components/admin/AdminResponsiveModal.vue index 977462d6..622457aa 100644 --- a/YumiNail-Frontend/src/components/admin/AdminResponsiveModal.vue +++ b/YumiNail-Frontend/src/components/admin/AdminResponsiveModal.vue @@ -5,7 +5,7 @@ :title="title" :width="mergedWidth" :centered="!isMobile" - :wrap-class-name="isMobile ? 'admin-mobile-modal' : undefined" + :wrap-class-name="mergedWrapClassName" :style="mergedStyle" :body-style="mergedBodyStyle" @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. */ import type { CSSProperties } from 'vue' -import { computed } from 'vue' +import { computed, useAttrs } from 'vue' import { useAdminViewport } from '@/composables/useAdminViewport' +import { CONFIRM_ENTER_DISABLED_CLASS } from '@/composables/useConfirmEnter' + +let modalInstanceSeed = 0 const props = withDefaults(defineProps<{ open: boolean title?: string desktopWidth?: string | number mobileBodyPadding?: string + confirmOnEnter?: boolean }>(), { title: '', desktopWidth: 720, - mobileBodyPadding: '16px 16px 104px' + mobileBodyPadding: '16px 16px 104px', + confirmOnEnter: true }) const emit = defineEmits<{ @@ -46,6 +51,8 @@ const emit = defineEmits<{ }>() 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. */ const mergedWidth = computed(() => (isMobile.value ? '100vw' : props.desktopWidth)) @@ -59,6 +66,16 @@ const mergedStyle = computed(() => ( } : 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. */ const mergedBodyStyle = computed(() => ( isMobile.value diff --git a/YumiNail-Frontend/src/composables/useConfirmEnter.test.ts b/YumiNail-Frontend/src/composables/useConfirmEnter.test.ts new file mode 100644 index 00000000..928b1742 --- /dev/null +++ b/YumiNail-Frontend/src/composables/useConfirmEnter.test.ts @@ -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) + }) +}) diff --git a/YumiNail-Frontend/src/composables/useConfirmEnter.ts b/YumiNail-Frontend/src/composables/useConfirmEnter.ts new file mode 100644 index 00000000..0b5abb50 --- /dev/null +++ b/YumiNail-Frontend/src/composables/useConfirmEnter.ts @@ -0,0 +1,179 @@ +import { computed, onBeforeUnmount, onMounted, type ComputedRef } from 'vue' + +interface UseConfirmEnterOptions { + enabled: ComputedRef + 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('.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([ + '.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) + }) +} diff --git a/YumiNail-Frontend/src/views/ArtistOrderView.vue b/YumiNail-Frontend/src/views/ArtistOrderView.vue index 9ef16c06..cac0d540 100644 --- a/YumiNail-Frontend/src/views/ArtistOrderView.vue +++ b/YumiNail-Frontend/src/views/ArtistOrderView.vue @@ -75,6 +75,13 @@
{{ item.productTitle }}
¥{{ item.price.toFixed(2) }} x {{ item.quantity }}
预约时间:{{ item.appointmentTime }}
+
+ 改派申请处理中:{{ pendingArtistChangeForItem(order, item)?.requestedArtistName || '新美甲师' }} +
+
+ 需要更换服务美甲师 + 申请改派 +
@@ -86,6 +93,38 @@ + + + + + {{ artistChangeOptions?.currentArtistName || activeArtistChangeItem?.artistName || '未分配' }} + + + + + {{ artist.artistName }} + + + + + + + + @@ -101,6 +140,7 @@ import { message, Modal } from 'ant-design-vue' import { userApi } from '@/api/user' import { fileApi } from '../api/index' import { orderApi } from '../api/order' +import type { OrderArtistChangeOptionsVO, OrderArtistChangeRequestVO } from '../api/order' import type { IdType } from '@/utils/id' import { runWithGlobalLoading } from '@/utils/action-loading' @@ -110,6 +150,13 @@ const orders = ref([]) const imageIdCache = ref>({}) const orderRefs = ref>({}) const showCalendarEntry = ref(false) +const currentUserId = ref() +const artistChangeModalOpen = ref(false) +const artistChangeSubmitting = ref(false) +const artistChangeOptionsLoading = ref(false) +const artistChangeOptions = ref(null) +const activeArtistChangeOrder = ref(null) +const activeArtistChangeItem = ref(null) const filters = reactive({ keyword: '', source: 'all', @@ -118,6 +165,10 @@ const filters = reactive({ minAmount: 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. */ const filteredOrders = computed(() => { @@ -182,11 +233,33 @@ const sourceClass = (source?: string) => { 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. */ const canComplete = (order: any) => { 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. */ const resetFilters = () => { filters.keyword = '' @@ -225,6 +298,7 @@ const loadCalendarAccess = async () => { showCalendarEntry.value = false try { const currentUser = await userApi.getUserInfo() + currentUserId.value = currentUser.id if (currentUser.type === 3) { showCalendarEntry.value = true return @@ -234,6 +308,7 @@ const loadCalendarAccess = async () => { showCalendarEntry.value = Number(artistInfo?.participateProduction) === 1 } } catch { + currentUserId.value = undefined showCalendarEntry.value = false } } @@ -243,6 +318,70 @@ const handleRefreshClick = async () => { 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. */ const completeOrder = (orderId: IdType) => { Modal.confirm({ @@ -298,6 +437,8 @@ onMounted(async () => { .title { font-weight: 600; color: var(--text-primary); } .line { margin-top: 4px; color: var(--text-secondary); font-size: 13px; } .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-link) { color: var(--theme-primary); } diff --git a/YumiNail-Frontend/src/views/AuthView.vue b/YumiNail-Frontend/src/views/AuthView.vue index 0eccd352..e4ebca02 100644 --- a/YumiNail-Frontend/src/views/AuthView.vue +++ b/YumiNail-Frontend/src/views/AuthView.vue @@ -925,6 +925,7 @@ const handleSubmit = async () => { localStorage.setItem('refreshToken', loginData.refreshToken) localStorage.setItem('userInfo', JSON.stringify(loginData.userInfo)) sessionStorage.setItem('accessToken', loginData.accessToken) + sessionStorage.setItem('refreshToken', loginData.refreshToken) notifyShopThemeChanged() if (loginData.needSetPassword) { @@ -1110,6 +1111,7 @@ const handleAdminLogin = () => { localStorage.removeItem('adminRefreshToken') localStorage.removeItem('adminUserInfo') sessionStorage.removeItem('accessToken') + sessionStorage.removeItem('refreshToken') sessionStorage.removeItem('adminAccessToken') window.setTimeout(() => { diff --git a/YumiNail-Frontend/src/views/NotificationsView.vue b/YumiNail-Frontend/src/views/NotificationsView.vue index 410b4b65..160d002c 100644 --- a/YumiNail-Frontend/src/views/NotificationsView.vue +++ b/YumiNail-Frontend/src/views/NotificationsView.vue @@ -56,6 +56,22 @@ const currentMessage = ref(null) /** 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 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. */ const loadMessages = async () => { 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. */ 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 detailVisible.value = true - if (item.readStatus !== 1) { - await userApi.markMessageRead(item.id) - item.readStatus = 1 - } } onMounted(loadMessages) diff --git a/YumiNail-Frontend/src/views/OrderView.vue b/YumiNail-Frontend/src/views/OrderView.vue index 465e038c..b4c0e937 100644 --- a/YumiNail-Frontend/src/views/OrderView.vue +++ b/YumiNail-Frontend/src/views/OrderView.vue @@ -53,6 +53,28 @@
¥{{ item.price.toFixed(2) }} x {{ item.quantity }}
美甲师:{{ item.artistName }}
预约时间:{{ item.appointmentTime }}
+
+ 已评价:{{ formatRating(submittedReviewForItem(order, item)?.rating) }} 分 + · {{ submittedReviewForItem(order, item)?.content }} +
+
+ 待评价:{{ pendingReviewForItem(order, item)?.artistName || item.artistName || '美甲师' }} + 评价美甲师 +
+
+
+ 待处理改派申请 + + {{ pendingChangeRequestForItem(order, item)?.originalArtistName || item.artistName || '原美甲师' }} + → {{ pendingChangeRequestForItem(order, item)?.requestedArtistName || '新美甲师' }} + + 原因:{{ pendingChangeRequestForItem(order, item)?.reason }} +
+
+ 同意 + 拒绝 +
+
@@ -62,6 +84,44 @@ + + + + + + + + + + + + + + + + + + + @@ -76,6 +136,7 @@ import { LeftOutlined } from '@ant-design/icons-vue' import { message, Modal } from 'ant-design-vue' import { fileApi } from '../api/index' import { orderApi } from '../api/order' +import type { OrderArtistChangeRequestVO, OrderArtistReviewVO } from '../api/order' import { userApi } from '@/api/user' import type { IdType } from '@/utils/id' import { runWithGlobalLoading } from '@/utils/action-loading' @@ -83,6 +144,15 @@ import { runWithGlobalLoading } from '@/utils/action-loading' const router = useRouter() const orders = ref([]) const imageIdCache = ref>({}) +const pendingReviews = ref([]) +const orderReviews = ref>({}) +const pendingChangeRequests = ref([]) +const reviewModalOpen = ref(false) +const reviewSubmitting = ref(false) +const activeReview = ref(null) +const rejectModalOpen = ref(false) +const changeProcessing = ref(false) +const activeChangeRequest = ref(null) const filters = reactive({ keyword: '', status: 'all' as 'all' | number, @@ -90,6 +160,13 @@ const filters = reactive({ minAmount: 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. */ const filteredOrders = computed(() => { @@ -124,6 +201,40 @@ const statusClass = (status: number) => { return 'cancelled' } +const sameId = (left: unknown, right: unknown) => { + return left !== undefined && left !== null && right !== undefined && right !== null && String(left) === String(right) +} + +const embeddedForItem = (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(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(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(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. */ const resetFilters = () => { 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. */ const loadOrders = async () => { try { const userInfo = await userApi.getUserInfo() if (userInfo.type === 2 || userInfo.type === 3) { router.replace('/artist-orders') - return + return false } orders.value = (await orderApi.getOrderList() as unknown as any[]) || [] for (const order of orders.value) { @@ -164,8 +311,104 @@ const loadOrders = async () => { } } } + await refreshOrderExtensions() + return true } catch { 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); } .line { margin-top: 4px; color: var(--text-secondary); font-size: 13px; } .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-link) { color: var(--theme-primary); } diff --git a/YumiNail-Frontend/src/views/admin/ShopsView.vue b/YumiNail-Frontend/src/views/admin/ShopsView.vue index a510eb56..2ec406b4 100644 --- a/YumiNail-Frontend/src/views/admin/ShopsView.vue +++ b/YumiNail-Frontend/src/views/admin/ShopsView.vue @@ -125,15 +125,6 @@ 编辑 - - - 删除 - - @@ -166,7 +157,14 @@
查看 编辑 - 删除 + + {{ item.status === 0 ? '启用' : '停用' }} +
@@ -2103,20 +2101,6 @@ const handleModalCancel = () => { 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) => { - 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. */ const handleStatusChange = async (record: Shop | Record, enabled: boolean) => { try { diff --git a/YumiNail-Frontend/tests/api/admin.stale-token.test.ts b/YumiNail-Frontend/tests/api/admin.stale-token.test.ts new file mode 100644 index 00000000..378a93af --- /dev/null +++ b/YumiNail-Frontend/tests/api/admin.stale-token.test.ts @@ -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(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() + }) +}) diff --git a/YumiNail-Frontend/tests/api/auth-free-paths.test.ts b/YumiNail-Frontend/tests/api/auth-free-paths.test.ts new file mode 100644 index 00000000..4c1dcdf3 --- /dev/null +++ b/YumiNail-Frontend/tests/api/auth-free-paths.test.ts @@ -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) + }) +}) diff --git a/YumiNail-Frontend/tests/api/index.stale-token.test.ts b/YumiNail-Frontend/tests/api/index.stale-token.test.ts new file mode 100644 index 00000000..0daf3689 --- /dev/null +++ b/YumiNail-Frontend/tests/api/index.stale-token.test.ts @@ -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(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() + }) +}) diff --git a/YumiNail-Frontend/vitest.config.ts b/YumiNail-Frontend/vitest.config.ts new file mode 100644 index 00000000..d99b14cd --- /dev/null +++ b/YumiNail-Frontend/vitest.config.ts @@ -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') + } + } +}) diff --git a/YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/filter/AuthGlobalFilter.java b/YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/filter/AuthGlobalFilter.java index 306a7ede..d0547fde 100644 --- a/YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/filter/AuthGlobalFilter.java +++ b/YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/filter/AuthGlobalFilter.java @@ -17,46 +17,14 @@ import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono; import java.nio.charset.StandardCharsets; +import java.util.LinkedHashSet; import java.util.List; -/** - * 全局认证过滤器 - * 负责 Token 校验和白名单过滤 - * - * @author xiaowang - * @date 2026-02-12 - */ @Slf4j @Component public class AuthGlobalFilter implements GlobalFilter, Ordered { - private static final List DEFAULT_WHITELIST = 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/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" - ); + private static final List DEFAULT_WHITELIST = AuthWhitelist.defaultPatterns(); @Autowired private GatewayConfig gatewayConfig; @@ -92,37 +60,70 @@ public class AuthGlobalFilter implements GlobalFilter, Ordered { return chain.filter(exchange); } - /** - * 判断是否在白名单中 - */ private boolean isWhitelist(String path) { - if (gatewayConfig.getWhitelist() != null) { - for (String whitelistPath : gatewayConfig.getWhitelist()) { - if (pathMatcher.match(whitelistPath, path)) { - return true; - } - } - } - - return DEFAULT_WHITELIST.stream().anyMatch(pattern -> pathMatcher.match(pattern, path)); + return AuthWhitelist.effectivePatterns(gatewayConfig).stream() + .anyMatch(pattern -> pathMatcher.match(pattern, path)); } - /** - * 无权限响应处理 - */ private Mono unAuthorized(ServerWebExchange exchange, String msg) { ServerHttpResponse response = exchange.getResponse(); response.setStatusCode(HttpStatus.UNAUTHORIZED); response.getHeaders().add("Content-Type", "application/json;charset=UTF-8"); - + String result = "{\"code\": 401, \"message\": \"" + msg + "\", \"data\": null}"; DataBuffer buffer = response.bufferFactory().wrap(result.getBytes(StandardCharsets.UTF_8)); - + return response.writeWith(Mono.just(buffer)); } @Override public int getOrder() { - return -1; // 优先级最高 + return -1; + } + + public static final class AuthWhitelist { + + private AuthWhitelist() { + } + + public static List 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 effectivePatterns(GatewayConfig gatewayConfig) { + if (gatewayConfig == null || gatewayConfig.getWhitelist() == null || gatewayConfig.getWhitelist().isEmpty()) { + return defaultPatterns(); + } + LinkedHashSet patterns = new LinkedHashSet<>(gatewayConfig.getWhitelist()); + patterns.addAll(DEFAULT_WHITELIST); + return List.copyOf(patterns); + } } } diff --git a/YumiNail-Gateway/src/test/java/com/xiaowang/yumitailgateway/filter/AuthGlobalFilterWhitelistTest.java b/YumiNail-Gateway/src/test/java/com/xiaowang/yumitailgateway/filter/AuthGlobalFilterWhitelistTest.java new file mode 100644 index 00000000..974c9411 --- /dev/null +++ b/YumiNail-Gateway/src/test/java/com/xiaowang/yumitailgateway/filter/AuthGlobalFilterWhitelistTest.java @@ -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 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 patterns, String path) { + return patterns.stream().anyMatch(pattern -> pathMatcher.match(pattern, path)); + } +}