功能:更新消息中心和 YumiNail 模块
This commit is contained in:
@@ -256,6 +256,10 @@ build/Release
|
||||
node_modules/
|
||||
jspm_packages/
|
||||
|
||||
# Mini program local overrides
|
||||
WeChatProgram/utils/config.local.js
|
||||
YumiNail-Admin-Program/utils/config.local.js
|
||||
|
||||
# Snowpack dependency directory (https://snowpack.dev/)
|
||||
web_modules/
|
||||
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
// API配置文件
|
||||
// 提取域名和端口,方便后续修改
|
||||
export const API_CONFIG = {
|
||||
domain: 'http://127.0.0.1',
|
||||
port: '80',
|
||||
basePath: '/api',
|
||||
adminBasePath: '/admin/api'
|
||||
}
|
||||
|
||||
export const API_BASE_URL = `${API_CONFIG.domain}:${API_CONFIG.port}${API_CONFIG.basePath}`
|
||||
export const ADMIN_API_BASE_URL = `${API_CONFIG.domain}:${API_CONFIG.port}${API_CONFIG.adminBasePath}`
|
||||
@@ -1,50 +0,0 @@
|
||||
import { permissionApi } from '@/api/permission'
|
||||
import { ref, computed } from 'vue'
|
||||
|
||||
const userPermissions = ref<string[]>([])
|
||||
const loadingPermissions = ref(false)
|
||||
|
||||
export const usePermission = () => {
|
||||
const hasPermission = (permissionCode: string) => {
|
||||
return userPermissions.value.includes(permissionCode)
|
||||
}
|
||||
|
||||
const hasAnyPermission = (permissionCodes: string[]) => {
|
||||
return permissionCodes.some(code => userPermissions.value.includes(code))
|
||||
}
|
||||
|
||||
const hasAllPermissions = (permissionCodes: string[]) => {
|
||||
return permissionCodes.every(code => userPermissions.value.includes(code))
|
||||
}
|
||||
|
||||
const loadUserPermissions = async () => {
|
||||
loadingPermissions.value = true
|
||||
try {
|
||||
const permissions = await permissionApi.getUserPermissions()
|
||||
userPermissions.value = permissions && Array.isArray(permissions) ? permissions.map(p => p.permissionCode) : []
|
||||
// 存储权限到本地存储,供路由守卫使用
|
||||
localStorage.setItem('userPermissions', JSON.stringify(userPermissions.value))
|
||||
} catch (error) {
|
||||
console.error('加载用户权限失败:', error)
|
||||
userPermissions.value = []
|
||||
localStorage.setItem('userPermissions', JSON.stringify([]))
|
||||
} finally {
|
||||
loadingPermissions.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const clearPermissions = () => {
|
||||
userPermissions.value = []
|
||||
localStorage.removeItem('userPermissions')
|
||||
}
|
||||
|
||||
return {
|
||||
userPermissions: computed(() => userPermissions.value),
|
||||
loadingPermissions: computed(() => loadingPermissions.value),
|
||||
hasPermission,
|
||||
hasAnyPermission,
|
||||
hasAllPermissions,
|
||||
loadUserPermissions,
|
||||
clearPermissions
|
||||
}
|
||||
}
|
||||
@@ -1,879 +0,0 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<header class="header">
|
||||
<a-button type="text" @click="router.back()">
|
||||
<LeftOutlined :style="{ fontSize: '20px' }" />
|
||||
</a-button>
|
||||
<h1>购物车</h1>
|
||||
<a-button type="text" @click="editing = !editing">
|
||||
{{ editing ? '完成' : '批量删除' }}
|
||||
</a-button>
|
||||
</header>
|
||||
|
||||
<main class="content">
|
||||
<a-empty v-if="!cartItems.length" description="购物车还是空的">
|
||||
<a-button type="primary" @click="router.push('/products')">去逛作品</a-button>
|
||||
</a-empty>
|
||||
|
||||
<a-alert
|
||||
v-if="selectedCount && checkoutIssues.length && !editing"
|
||||
class="issue-alert"
|
||||
type="warning"
|
||||
show-icon
|
||||
:message="`还有 ${checkoutIssues.length} 项待完善`"
|
||||
:description="checkoutIssues.map(issue => issue.message).join(';')"
|
||||
>
|
||||
<template #action>
|
||||
<a-button size="small" @click="focusFirstIssue">定位问题</a-button>
|
||||
</template>
|
||||
</a-alert>
|
||||
|
||||
<a-card
|
||||
v-for="item in cartItems"
|
||||
:key="item.id"
|
||||
:ref="element => setItemRef(item.id, element)"
|
||||
class="item-card"
|
||||
:class="{ 'issue-card': item.selected && hasItemIssue(item) }"
|
||||
>
|
||||
<div class="item-row">
|
||||
<a-checkbox v-model:checked="item.selected" @change="loadAvailableCoupons" />
|
||||
<div class="thumb" @click="openProduct(item)">
|
||||
<img v-if="item.productImage" :src="item.productImage" :alt="item.productTitle" />
|
||||
<span v-else>{{ item.productTitle[0] }}</span>
|
||||
</div>
|
||||
<div class="item-main">
|
||||
<div class="title" @click="openProduct(item)">{{ item.productTitle }}</div>
|
||||
<div class="price">¥{{ Number(item.price || 0).toFixed(2) }}</div>
|
||||
|
||||
<div class="selector" :class="{ issue: item.selected && !item.artistId }" @click="openBookingModal(item)">
|
||||
<span class="label">美甲师</span>
|
||||
<span class="value">{{ item.artist?.name || '请选择美甲师' }}</span>
|
||||
<RightOutlined />
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="selector"
|
||||
:class="{ issue: item.selected && (!item.appointmentTime || isPastAppointment(item.appointmentTime)) }"
|
||||
@click="openBookingModal(item)"
|
||||
>
|
||||
<span class="label">预约时间</span>
|
||||
<span class="value">
|
||||
{{ item.appointmentTime ? formatAppointmentDisplay(item.appointmentTime) : (item.artistId ? '请选择预约时间' : '先选择美甲师') }}
|
||||
</span>
|
||||
<RightOutlined />
|
||||
</div>
|
||||
|
||||
<div v-if="item.approximateDuration" class="duration">预计时长:{{ item.approximateDuration }}</div>
|
||||
|
||||
<div class="actions">
|
||||
<div class="qty">
|
||||
<a-button size="small" :disabled="item.quantity <= 1" @click="changeQuantity(item, -1)">-</a-button>
|
||||
<span>{{ item.quantity }}</span>
|
||||
<a-button size="small" :disabled="item.quantity >= 99" @click="changeQuantity(item, 1)">+</a-button>
|
||||
</div>
|
||||
<a-popconfirm title="确认删除这件作品吗?" ok-text="确认" cancel-text="取消" @confirm="removeItem(item)">
|
||||
<a-button type="text" danger size="small">
|
||||
<DeleteOutlined />
|
||||
</a-button>
|
||||
</a-popconfirm>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</a-card>
|
||||
|
||||
<a-card v-if="selectedCount && !editing" class="coupon-card" @click="openCouponModal">
|
||||
<div class="coupon-row">
|
||||
<span>优惠方式</span>
|
||||
<span>{{ selectedCoupon ? formatCouponDisplay(selectedCoupon) : '不使用优惠' }}</span>
|
||||
</div>
|
||||
<div v-if="selectedCoupon" class="coupon-extra">
|
||||
<span>{{ selectedCoupon.sourceType === 'SYSTEM_VIP' ? '当前为 VIP 自动折扣,不会消耗用户券。' : '当前为用户券,只有下单成功才会消耗。' }}</span>
|
||||
<strong>-¥{{ discountAmount.toFixed(2) }}</strong>
|
||||
</div>
|
||||
</a-card>
|
||||
|
||||
<a-card v-if="cartItems.length && !editing" class="summary-card">
|
||||
<div class="summary-row"><span>选中项目</span><span>{{ selectedCount }} 项</span></div>
|
||||
<div class="summary-row"><span>作品数量</span><span>{{ totalQuantity }} 件</span></div>
|
||||
<div class="summary-row"><span>小计</span><span>¥{{ subtotal.toFixed(2) }}</span></div>
|
||||
<div v-if="selectedCoupon" class="summary-row"><span>优惠</span><span>-¥{{ discountAmount.toFixed(2) }}</span></div>
|
||||
<div class="summary-row total"><span>合计</span><span>¥{{ totalAmount.toFixed(2) }}</span></div>
|
||||
</a-card>
|
||||
</main>
|
||||
|
||||
<footer v-if="cartItems.length" class="footer">
|
||||
<a-button
|
||||
v-if="editing"
|
||||
danger
|
||||
size="large"
|
||||
block
|
||||
@click="removeSelectedItems"
|
||||
>
|
||||
删除已选中的 {{ selectedCount }} 项
|
||||
</a-button>
|
||||
<a-button
|
||||
v-else
|
||||
type="primary"
|
||||
size="large"
|
||||
block
|
||||
@click="checkout"
|
||||
>
|
||||
结算 {{ selectedCount }} 项,预计金额 ¥{{ totalAmount.toFixed(2) }}
|
||||
</a-button>
|
||||
</footer>
|
||||
|
||||
<a-modal v-model:open="showCouponModal" title="选择优惠方式" @ok="applyCouponSelection" @cancel="showCouponModal = false">
|
||||
<a-radio-group v-model:value="couponSelectionKey" class="coupon-options">
|
||||
<a-radio :value="NO_COUPON_KEY">不使用优惠</a-radio>
|
||||
<a-radio v-for="coupon in availableCoupons" :key="getCouponKey(coupon)" :value="getCouponKey(coupon)">
|
||||
{{ formatCouponDisplay(coupon) }}
|
||||
</a-radio>
|
||||
</a-radio-group>
|
||||
<div class="coupon-tip">
|
||||
系统只会默认预选最佳 VIP 自动券,普通用户券需要你手动选择后才会在下单时使用。
|
||||
</div>
|
||||
</a-modal>
|
||||
|
||||
<a-modal v-model:open="showBookingModal" :title="bookingTitle" @ok="confirmBooking" @cancel="closeBookingModal">
|
||||
<div class="modal-section">
|
||||
<div class="section-title">美甲师</div>
|
||||
<div v-if="availableArtists.length" class="artist-list">
|
||||
<button
|
||||
v-for="artist in availableArtists"
|
||||
:key="artist.id"
|
||||
type="button"
|
||||
class="artist-option"
|
||||
:class="{ active: sameId(draftArtistId, artist.id) }"
|
||||
@click="draftArtistId = artist.id"
|
||||
>
|
||||
<img v-if="artist.avatar" :src="artist.avatar" :alt="artist.name" />
|
||||
<span>{{ artist.name }}</span>
|
||||
</button>
|
||||
</div>
|
||||
<a-empty v-else description="暂无可预约美甲师" />
|
||||
</div>
|
||||
|
||||
<div class="modal-section">
|
||||
<div class="section-title">预约时间</div>
|
||||
<a-date-picker
|
||||
v-model:value="draftAppointmentTime"
|
||||
class="time-picker"
|
||||
style="width: 100%"
|
||||
format="YYYY-MM-DD HH:mm:ss"
|
||||
value-format="YYYY-MM-DD HH:mm:ss"
|
||||
input-read-only
|
||||
:disabled-date="disablePastAppointmentDate"
|
||||
:disabled-time="disablePastAppointmentTime"
|
||||
:show-time="{ minuteStep: 30, secondStep: 60, hideDisabledOptions: true }"
|
||||
placeholder="请选择预约时间"
|
||||
/>
|
||||
<div class="helper">{{ bookingHelperText }}</div>
|
||||
</div>
|
||||
</a-modal>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, inject, onMounted, ref, watch } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { DeleteOutlined, LeftOutlined, RightOutlined } from '@ant-design/icons-vue'
|
||||
import { message } from 'ant-design-vue'
|
||||
import { cartApi } from '../api/cart'
|
||||
import { couponApi, type UserCoupon } from '../api/coupon'
|
||||
import { fileApi } from '../api/index'
|
||||
import { orderApi } from '../api/order'
|
||||
import { shopApi } from '../api/shop'
|
||||
import type { IdType } from '@/utils/id'
|
||||
import { sameId, toOptionalIdString } from '@/utils/id'
|
||||
|
||||
const router = useRouter()
|
||||
const updateCartCount = inject<() => Promise<void>>('updateCartCount', async () => {})
|
||||
|
||||
const NO_COUPON_KEY = 'NONE'
|
||||
|
||||
interface ArtistOption {
|
||||
id: IdType
|
||||
name: string
|
||||
avatar?: string
|
||||
}
|
||||
|
||||
interface CartItem {
|
||||
id: IdType
|
||||
productId: IdType
|
||||
shopId?: IdType
|
||||
productTitle: string
|
||||
productImage: string
|
||||
originalProductImage?: string
|
||||
price: number
|
||||
quantity: number
|
||||
totalPrice: number
|
||||
tags: string
|
||||
tagNames?: string
|
||||
approximateDuration?: string
|
||||
bookableArtists?: string
|
||||
availableBookableArtistCount?: number
|
||||
bookableArtistRestricted?: boolean
|
||||
availableArtists?: ArtistOption[]
|
||||
appointmentTime?: string
|
||||
selected: boolean
|
||||
artistId?: IdType
|
||||
artist?: ArtistOption
|
||||
}
|
||||
|
||||
interface CheckoutIssue {
|
||||
key: string
|
||||
message: string
|
||||
itemId?: IdType
|
||||
}
|
||||
|
||||
const cartItems = ref<CartItem[]>([])
|
||||
const imageIdCache = ref<Record<string, string>>({})
|
||||
const itemRefs = ref<Record<string, HTMLElement>>({})
|
||||
const availableCoupons = ref<UserCoupon[]>([])
|
||||
const selectedCoupon = ref<UserCoupon | null>(null)
|
||||
const couponSelectionKey = ref(NO_COUPON_KEY)
|
||||
const couponSelectionTouched = ref(false)
|
||||
const showCouponModal = ref(false)
|
||||
const showBookingModal = ref(false)
|
||||
const currentItem = ref<CartItem | null>(null)
|
||||
const availableArtists = ref<ArtistOption[]>([])
|
||||
const draftArtistId = ref<IdType>()
|
||||
const draftAppointmentTime = ref('')
|
||||
const currentShopHours = ref('')
|
||||
const editing = ref(false)
|
||||
|
||||
const selectedItems = computed(() => cartItems.value.filter(item => item.selected))
|
||||
const selectedCount = computed(() => selectedItems.value.length)
|
||||
const totalQuantity = computed(() => selectedItems.value.reduce((sum, item) => sum + item.quantity, 0))
|
||||
const subtotal = computed(() => selectedItems.value.reduce((sum, item) => sum + Number(item.price || 0) * item.quantity, 0))
|
||||
const discountAmount = computed(() => calculateCouponDiscount(selectedCoupon.value, subtotal.value))
|
||||
const totalAmount = computed(() => Math.max(0, subtotal.value - discountAmount.value))
|
||||
const bookingTitle = computed(() => currentItem.value ? `为 ${currentItem.value.productTitle} 选择预约信息` : '选择预约信息')
|
||||
const bookingHelperText = computed(() => {
|
||||
const texts: string[] = []
|
||||
if (currentShopHours.value) texts.push(`门店营业时间:${currentShopHours.value}`)
|
||||
if (currentItem.value?.approximateDuration) texts.push(`预计时长:${currentItem.value.approximateDuration}`)
|
||||
return texts.join(' · ') || '请选择至少晚于当前 5 分钟的预约时间'
|
||||
})
|
||||
|
||||
const getMinAppointmentDate = () => {
|
||||
const date = new Date()
|
||||
date.setSeconds(0, 0)
|
||||
date.setMinutes(date.getMinutes() + 5)
|
||||
return date
|
||||
}
|
||||
|
||||
const getDayBoundary = (date: Date) => {
|
||||
const boundary = new Date(date)
|
||||
boundary.setHours(0, 0, 0, 0)
|
||||
return boundary.getTime()
|
||||
}
|
||||
|
||||
const getCouponKey = (coupon: UserCoupon) => `${coupon.sourceType || 'USER_COUPON'}:${coupon.id}`
|
||||
|
||||
const setItemRef = (itemId: IdType, element: unknown) => {
|
||||
const refKey = toOptionalIdString(itemId)
|
||||
if (!refKey) {
|
||||
return
|
||||
}
|
||||
if (element && (element as any).$el) {
|
||||
itemRefs.value[refKey] = (element as any).$el as HTMLElement
|
||||
return
|
||||
}
|
||||
if (element instanceof HTMLElement) {
|
||||
itemRefs.value[refKey] = element
|
||||
return
|
||||
}
|
||||
delete itemRefs.value[refKey]
|
||||
}
|
||||
|
||||
const formatCouponDisplay = (coupon: UserCoupon) => {
|
||||
const badge = coupon.sourceType === 'SYSTEM_VIP' ? '[VIP 自动券]' : '[用户券]'
|
||||
const benefit = coupon.couponType === 1
|
||||
? `${coupon.discountValue} 折`
|
||||
: `满 ${coupon.minAmount} 减 ${coupon.reduceAmount}`
|
||||
return `${badge} ${coupon.couponName} ${benefit}`
|
||||
}
|
||||
|
||||
const calculateCouponDiscount = (coupon: UserCoupon | null, amount: number) => {
|
||||
if (!coupon || amount <= 0) {
|
||||
return 0
|
||||
}
|
||||
if (coupon.couponType === 1) {
|
||||
const discountValue = Number(coupon.discountValue || 0)
|
||||
return discountValue ? amount - amount * discountValue / 10 : 0
|
||||
}
|
||||
if (coupon.couponType === 2) {
|
||||
return Number(coupon.reduceAmount || 0)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
const findBestSystemVipCoupon = (coupons: UserCoupon[]) => {
|
||||
return coupons
|
||||
.filter(coupon => coupon.sourceType === 'SYSTEM_VIP')
|
||||
.sort((left, right) => calculateCouponDiscount(right, subtotal.value) - calculateCouponDiscount(left, subtotal.value))[0] || null
|
||||
}
|
||||
|
||||
const formatAppointmentDisplay = (value?: string) => value ? value.replace('T', ' ').slice(0, 16) : '未选择预约时间'
|
||||
const isPastAppointment = (value?: string) => !!value && new Date(value.replace(' ', 'T')).getTime() < getMinAppointmentDate().getTime()
|
||||
|
||||
const hasItemIssue = (item: CartItem) => !item.artistId || !item.appointmentTime || isPastAppointment(item.appointmentTime)
|
||||
|
||||
// 购物车结算口径要求单店铺、单美甲师、完整预约信息,避免后端拆单和排班出现歧义。
|
||||
const checkoutIssues = computed<CheckoutIssue[]>(() => {
|
||||
const items = selectedItems.value
|
||||
const issues: CheckoutIssue[] = []
|
||||
const firstMissingArtist = items.find(item => !item.artistId)
|
||||
if (firstMissingArtist) {
|
||||
issues.push({ key: 'artist', message: `请先为“${firstMissingArtist.productTitle}”选择美甲师`, itemId: firstMissingArtist.id })
|
||||
}
|
||||
|
||||
const firstMissingTime = items.find(item => !item.appointmentTime)
|
||||
if (firstMissingTime) {
|
||||
issues.push({ key: 'time', message: `请先为“${firstMissingTime.productTitle}”选择预约时间`, itemId: firstMissingTime.id })
|
||||
}
|
||||
|
||||
const firstExpiredTime = items.find(item => isPastAppointment(item.appointmentTime))
|
||||
if (firstExpiredTime) {
|
||||
issues.push({ key: 'expired', message: `“${firstExpiredTime.productTitle}”的预约时间已过期,请重新选择`, itemId: firstExpiredTime.id })
|
||||
}
|
||||
|
||||
const selectedShopIds = new Set(
|
||||
items
|
||||
.map(item => toOptionalIdString(item.shopId))
|
||||
.filter((shopId): shopId is string => Boolean(shopId))
|
||||
)
|
||||
if (selectedShopIds.size > 1) {
|
||||
issues.push({ key: 'shop', message: '跨店铺项目请分开结算', itemId: items[0]?.id })
|
||||
}
|
||||
|
||||
const selectedArtistIds = new Set(
|
||||
items
|
||||
.map(item => toOptionalIdString(item.artistId))
|
||||
.filter((artistId): artistId is string => Boolean(artistId))
|
||||
)
|
||||
if (selectedArtistIds.size > 1) {
|
||||
issues.push({ key: 'artist-mix', message: '不同美甲师的项目请分开结算', itemId: items[0]?.id })
|
||||
}
|
||||
|
||||
return issues
|
||||
})
|
||||
|
||||
const scrollToIssue = (issue?: CheckoutIssue) => {
|
||||
const itemId = toOptionalIdString(issue?.itemId)
|
||||
if (!itemId) {
|
||||
return
|
||||
}
|
||||
const target = itemRefs.value[itemId]
|
||||
if (target) {
|
||||
target.scrollIntoView({ behavior: 'smooth', block: 'center' })
|
||||
}
|
||||
}
|
||||
|
||||
const focusFirstIssue = () => {
|
||||
scrollToIssue(checkoutIssues.value[0])
|
||||
}
|
||||
|
||||
const loadCartItems = async () => {
|
||||
const response = await cartApi.getCartList() as unknown as any[]
|
||||
cartItems.value = (response || []).map(item => ({
|
||||
...item,
|
||||
selected: true,
|
||||
originalProductImage: item.productImage,
|
||||
productImage: '',
|
||||
appointmentTime: item.appointmentTime
|
||||
}))
|
||||
couponSelectionTouched.value = false
|
||||
couponSelectionKey.value = NO_COUPON_KEY
|
||||
selectedCoupon.value = null
|
||||
editing.value = false
|
||||
await Promise.all([loadProductImages(), loadAvailableCoupons()])
|
||||
}
|
||||
|
||||
const loadProductImages = async () => {
|
||||
for (const item of cartItems.value) {
|
||||
if (!item.originalProductImage) continue
|
||||
const match = item.originalProductImage.replace(/<[^>]*>/g, '').match(/\/api\/file\/get\/(\d+)/)
|
||||
if (!match?.[1]) continue
|
||||
const imageId = match[1]
|
||||
try {
|
||||
if (!imageIdCache.value[imageId]) {
|
||||
imageIdCache.value[imageId] = await fileApi.getSignedUrl(imageId) as any
|
||||
}
|
||||
item.productImage = imageIdCache.value[imageId] || ''
|
||||
} catch {
|
||||
item.productImage = ''
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const loadAvailableCoupons = async () => {
|
||||
if (editing.value) {
|
||||
return
|
||||
}
|
||||
|
||||
const currentSelectedKey = selectedCoupon.value ? getCouponKey(selectedCoupon.value) : couponSelectionKey.value
|
||||
const selectedShopId = selectedItems.value[0]?.shopId
|
||||
|
||||
if (!selectedItems.value.length || subtotal.value <= 0) {
|
||||
availableCoupons.value = []
|
||||
selectedCoupon.value = null
|
||||
couponSelectionKey.value = NO_COUPON_KEY
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
// 这里只做“最佳 VIP 自动券”兜底预选,普通用户券必须显式点选后才会消耗。
|
||||
const tags = new Set<string>()
|
||||
selectedItems.value.forEach(item => {
|
||||
item.tagNames?.split(',').map(tag => tag.trim()).forEach(tag => {
|
||||
if (tag) {
|
||||
tags.add(tag)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
const data = await couponApi.getAvailableCoupons(Array.from(tags).join(','), subtotal.value, selectedShopId) as unknown as UserCoupon[]
|
||||
availableCoupons.value = Array.isArray(data) ? data : []
|
||||
|
||||
const matchedCoupon = availableCoupons.value.find(coupon => getCouponKey(coupon) === currentSelectedKey) || null
|
||||
if (matchedCoupon) {
|
||||
selectedCoupon.value = matchedCoupon
|
||||
couponSelectionKey.value = getCouponKey(matchedCoupon)
|
||||
return
|
||||
}
|
||||
|
||||
if (couponSelectionTouched.value && currentSelectedKey === NO_COUPON_KEY) {
|
||||
selectedCoupon.value = null
|
||||
couponSelectionKey.value = NO_COUPON_KEY
|
||||
return
|
||||
}
|
||||
|
||||
couponSelectionTouched.value = false
|
||||
const defaultVipCoupon = findBestSystemVipCoupon(availableCoupons.value)
|
||||
if (defaultVipCoupon) {
|
||||
selectedCoupon.value = defaultVipCoupon
|
||||
couponSelectionKey.value = getCouponKey(defaultVipCoupon)
|
||||
} else {
|
||||
selectedCoupon.value = null
|
||||
couponSelectionKey.value = NO_COUPON_KEY
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取可用优惠失败:', error)
|
||||
availableCoupons.value = []
|
||||
selectedCoupon.value = null
|
||||
couponSelectionKey.value = NO_COUPON_KEY
|
||||
}
|
||||
}
|
||||
|
||||
const changeQuantity = async (item: CartItem, delta: number) => {
|
||||
const next = item.quantity + delta
|
||||
if (next < 1 || next > 99) return
|
||||
item.quantity = next
|
||||
try {
|
||||
await cartApi.updateCartQuantity({ productId: item.productId, quantity: next })
|
||||
await Promise.all([loadAvailableCoupons(), updateCartCount()])
|
||||
} catch {
|
||||
item.quantity -= delta
|
||||
message.error('更新数量失败')
|
||||
}
|
||||
}
|
||||
|
||||
const removeItem = async (item: CartItem) => {
|
||||
try {
|
||||
await cartApi.removeFromCart(item.productId)
|
||||
cartItems.value = cartItems.value.filter(current => !sameId(current.id, item.id))
|
||||
await Promise.all([loadAvailableCoupons(), updateCartCount()])
|
||||
message.success('作品已删除')
|
||||
} catch {
|
||||
message.error('删除作品失败')
|
||||
}
|
||||
}
|
||||
|
||||
const removeSelectedItems = async () => {
|
||||
if (!selectedItems.value.length) {
|
||||
message.warning('请先勾选要删除的作品')
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
await Promise.all(selectedItems.value.map(item => cartApi.removeFromCart(item.productId)))
|
||||
await Promise.all([loadCartItems(), updateCartCount()])
|
||||
message.success('已删除选中的作品')
|
||||
} catch (error) {
|
||||
console.error('批量删除失败:', error)
|
||||
message.error('批量删除失败,请稍后重试')
|
||||
}
|
||||
}
|
||||
|
||||
const openProduct = (item: CartItem) => {
|
||||
router.push('/product/' + item.productId)
|
||||
}
|
||||
|
||||
const openBookingModal = async (item: CartItem) => {
|
||||
currentItem.value = item
|
||||
draftArtistId.value = item.artistId
|
||||
draftAppointmentTime.value = item.appointmentTime || ''
|
||||
showBookingModal.value = true
|
||||
await Promise.all([loadArtists(item), loadShopHours(item.shopId)])
|
||||
}
|
||||
|
||||
const loadArtists = async (item: CartItem) => {
|
||||
// 购物车里保存的是后端已经按作品可约范围裁剪过的美甲师列表,这里只做前端展示和 ID 保真。
|
||||
availableArtists.value = Array.isArray(item.availableArtists)
|
||||
? item.availableArtists
|
||||
.filter(artist => artist && artist.id !== undefined && artist.id !== null)
|
||||
.map(artist => ({
|
||||
id: artist.id,
|
||||
name: artist.name,
|
||||
avatar: artist.avatar
|
||||
}))
|
||||
: []
|
||||
|
||||
if (draftArtistId.value && !availableArtists.value.some(artist => sameId(artist.id, draftArtistId.value))) {
|
||||
draftArtistId.value = undefined
|
||||
}
|
||||
}
|
||||
|
||||
const loadShopHours = async (shopId?: IdType) => {
|
||||
currentShopHours.value = ''
|
||||
if (!shopId) return
|
||||
try {
|
||||
const shop = await shopApi.getShopById(shopId) as any
|
||||
currentShopHours.value = shop?.businessHours || ''
|
||||
} catch {
|
||||
currentShopHours.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
const disablePastAppointmentDate = (current: any) => {
|
||||
if (!current) return false
|
||||
return current.valueOf() < getDayBoundary(new Date())
|
||||
}
|
||||
|
||||
const disablePastAppointmentTime = (current: any) => {
|
||||
if (!current || typeof current.format !== 'function') {
|
||||
return {}
|
||||
}
|
||||
const minDate = getMinAppointmentDate()
|
||||
const minDateText = [
|
||||
minDate.getFullYear(),
|
||||
String(minDate.getMonth() + 1).padStart(2, '0'),
|
||||
String(minDate.getDate()).padStart(2, '0')
|
||||
].join('-')
|
||||
if (current.format('YYYY-MM-DD') !== minDateText) {
|
||||
return {}
|
||||
}
|
||||
const minHour = minDate.getHours()
|
||||
const minMinute = minDate.getMinutes()
|
||||
return {
|
||||
disabledHours: () => Array.from({ length: minHour }, (_, index) => index),
|
||||
disabledMinutes: (selectedHour: number) => selectedHour === minHour
|
||||
? Array.from({ length: minMinute }, (_, index) => index)
|
||||
: [],
|
||||
disabledSeconds: () => []
|
||||
}
|
||||
}
|
||||
|
||||
const closeBookingModal = () => {
|
||||
showBookingModal.value = false
|
||||
currentItem.value = null
|
||||
draftArtistId.value = undefined
|
||||
draftAppointmentTime.value = ''
|
||||
availableArtists.value = []
|
||||
currentShopHours.value = ''
|
||||
}
|
||||
|
||||
const confirmBooking = () => {
|
||||
if (!currentItem.value) return closeBookingModal()
|
||||
if (!draftArtistId.value) return message.warning('请先选择美甲师')
|
||||
if (!draftAppointmentTime.value) return message.warning('请选择预约时间')
|
||||
if (isPastAppointment(draftAppointmentTime.value)) return message.warning('预约时间至少需要晚于当前 5 分钟')
|
||||
currentItem.value.artistId = draftArtistId.value
|
||||
currentItem.value.artist = availableArtists.value.find(artist => sameId(artist.id, draftArtistId.value))
|
||||
currentItem.value.appointmentTime = draftAppointmentTime.value
|
||||
closeBookingModal()
|
||||
}
|
||||
|
||||
const openCouponModal = () => {
|
||||
couponSelectionKey.value = selectedCoupon.value ? getCouponKey(selectedCoupon.value) : NO_COUPON_KEY
|
||||
showCouponModal.value = true
|
||||
}
|
||||
|
||||
const applyCouponSelection = () => {
|
||||
couponSelectionTouched.value = true
|
||||
if (couponSelectionKey.value === NO_COUPON_KEY) {
|
||||
selectedCoupon.value = null
|
||||
} else {
|
||||
selectedCoupon.value = availableCoupons.value.find(coupon => getCouponKey(coupon) === couponSelectionKey.value) || null
|
||||
}
|
||||
showCouponModal.value = false
|
||||
}
|
||||
|
||||
const checkout = async () => {
|
||||
const items = selectedItems.value
|
||||
if (!items.length) {
|
||||
return message.warning('请先选择要结算的作品')
|
||||
}
|
||||
|
||||
const firstIssue = checkoutIssues.value[0]
|
||||
if (firstIssue) {
|
||||
message.warning(firstIssue.message)
|
||||
scrollToIssue(firstIssue)
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
await orderApi.createOrder({
|
||||
couponId: selectedCoupon.value?.id,
|
||||
couponSourceType: selectedCoupon.value?.sourceType || (couponSelectionTouched.value && !selectedCoupon.value ? NO_COUPON_KEY : undefined),
|
||||
items: items.map(item => ({
|
||||
productId: item.productId,
|
||||
quantity: item.quantity,
|
||||
artistId: item.artistId,
|
||||
appointmentTime: item.appointmentTime
|
||||
}))
|
||||
})
|
||||
await Promise.all([loadCartItems(), updateCartCount()])
|
||||
message.success('订单创建成功')
|
||||
router.push('/orders')
|
||||
} catch (error: any) {
|
||||
console.error('创建订单失败:', error)
|
||||
message.error(error?.message || '创建订单失败')
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => cartItems.value.map(item => `${item.id}-${item.selected}-${item.quantity}`).join('|'),
|
||||
() => {
|
||||
void loadAvailableCoupons()
|
||||
}
|
||||
)
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
await loadCartItems()
|
||||
} catch {
|
||||
message.error('获取购物车数据失败')
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.page {
|
||||
min-height: 100vh;
|
||||
padding-top: 60px;
|
||||
background: #f5f5f5;
|
||||
}
|
||||
|
||||
.header,
|
||||
.footer {
|
||||
position: fixed;
|
||||
left: 0;
|
||||
right: 0;
|
||||
background: #fff;
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
.header {
|
||||
top: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 10px 15px;
|
||||
border-bottom: 1px solid #f0f0f0;
|
||||
}
|
||||
|
||||
.header h1 {
|
||||
margin: 0;
|
||||
font-size: 18px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.content {
|
||||
max-width: 980px;
|
||||
margin: 0 auto;
|
||||
padding: 16px 16px 140px;
|
||||
}
|
||||
|
||||
.issue-alert {
|
||||
margin-bottom: 16px;
|
||||
border-radius: 16px;
|
||||
}
|
||||
|
||||
.item-card,
|
||||
.coupon-card,
|
||||
.summary-card {
|
||||
margin-bottom: 12px;
|
||||
border-radius: 16px;
|
||||
}
|
||||
|
||||
.issue-card {
|
||||
border-color: #faad14;
|
||||
box-shadow: 0 8px 24px rgba(250, 173, 20, 0.12);
|
||||
}
|
||||
|
||||
.item-row {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
.thumb {
|
||||
width: 84px;
|
||||
height: 84px;
|
||||
border-radius: 12px;
|
||||
overflow: hidden;
|
||||
background: #eef3ff;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.thumb img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.item-main {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.title {
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.price {
|
||||
margin: 6px 0 10px;
|
||||
color: #ff4d4f;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.selector {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 10px 12px;
|
||||
margin-bottom: 10px;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 10px;
|
||||
background: #f8f9ff;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.selector.issue {
|
||||
border-color: #faad14;
|
||||
background: #fff7e6;
|
||||
}
|
||||
|
||||
.selector .label {
|
||||
min-width: 56px;
|
||||
color: #666;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.selector .value {
|
||||
flex: 1;
|
||||
color: #1677ff;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.duration,
|
||||
.coupon-tip,
|
||||
.helper {
|
||||
color: #666;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.actions,
|
||||
.qty,
|
||||
.coupon-row,
|
||||
.summary-row,
|
||||
.coupon-extra {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.qty {
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.coupon-extra {
|
||||
margin-top: 10px;
|
||||
color: #666;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.summary-row {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.summary-row.total {
|
||||
margin-bottom: 0;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.footer {
|
||||
bottom: 60px;
|
||||
padding: 15px;
|
||||
border-top: 1px solid #f0f0f0;
|
||||
box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.06);
|
||||
}
|
||||
|
||||
.coupon-options {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.modal-section + .modal-section {
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
margin-bottom: 8px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.artist-list {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.artist-option {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 8px 12px;
|
||||
border: 1px solid #d9d9d9;
|
||||
border-radius: 999px;
|
||||
background: #fff;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.artist-option.active {
|
||||
border-color: #1677ff;
|
||||
color: #1677ff;
|
||||
background: #f0f9ff;
|
||||
}
|
||||
|
||||
.artist-option img {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border-radius: 50%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
@media (max-width: 767px) {
|
||||
.content {
|
||||
padding: 15px 15px 140px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,397 +0,0 @@
|
||||
<template>
|
||||
<div class="admin-layout">
|
||||
<a-layout>
|
||||
<a-layout-sider
|
||||
v-model:collapsed="collapsed"
|
||||
:trigger="null"
|
||||
collapsible
|
||||
class="sider"
|
||||
width="240"
|
||||
>
|
||||
<div class="logo">
|
||||
<h1 v-if="!collapsed">后台管理</h1>
|
||||
<h1 v-else>后台</h1>
|
||||
</div>
|
||||
<a-menu
|
||||
:selectedKeys="selectedKeys"
|
||||
mode="inline"
|
||||
theme="dark"
|
||||
@click="handleMenuClick"
|
||||
>
|
||||
<a-menu-item
|
||||
v-for="item in filteredMenuItems"
|
||||
:key="item.key"
|
||||
>
|
||||
<template #icon>
|
||||
<component :is="item.icon" />
|
||||
</template>
|
||||
<span>{{ item.label }}</span>
|
||||
</a-menu-item>
|
||||
</a-menu>
|
||||
</a-layout-sider>
|
||||
|
||||
<a-layout>
|
||||
<a-layout-header class="header">
|
||||
<div class="header-shell">
|
||||
<div class="header-left">
|
||||
<MenuUnfoldOutlined v-if="collapsed" class="trigger" @click="toggleCollapsed" />
|
||||
<MenuFoldOutlined v-else class="trigger" @click="toggleCollapsed" />
|
||||
|
||||
<div v-if="isBootstrapAdmin" class="shop-hint">
|
||||
<span>当前暂无可用门店,请先前往店铺管理创建</span>
|
||||
<a-button type="link" @click="router.push('/admin/shops')">去创建</a-button>
|
||||
</div>
|
||||
|
||||
<div v-else-if="shopOptions.length > 1" class="shop-switcher">
|
||||
<span class="shop-switcher-label">当前门店</span>
|
||||
<a-select
|
||||
v-model:value="selectedShopId"
|
||||
class="shop-select"
|
||||
:options="shopSelectOptions"
|
||||
:loading="shopSwitchLoading"
|
||||
@change="handleShopChange"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div v-else class="shop-pill">
|
||||
<ShopOutlined />
|
||||
<span>{{ currentShopName }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="header-right">
|
||||
<a-dropdown>
|
||||
<a class="user-dropdown" @click.prevent>
|
||||
<a-avatar :size="32" :src="userInfo?.avatar || DEFAULT_AVATAR" />
|
||||
<span class="username">{{ userInfo?.nickname || '管理员' }}</span>
|
||||
<DownOutlined />
|
||||
</a>
|
||||
<template #overlay>
|
||||
<a-menu>
|
||||
<a-menu-item key="home" @click="router.push('/admin')">
|
||||
<template #icon>
|
||||
<UserOutlined />
|
||||
</template>
|
||||
工作台
|
||||
</a-menu-item>
|
||||
<a-menu-divider />
|
||||
<a-menu-item key="logout" @click="handleLogout">
|
||||
<template #icon>
|
||||
<LogoutOutlined />
|
||||
</template>
|
||||
退出登录
|
||||
</a-menu-item>
|
||||
</a-menu>
|
||||
</template>
|
||||
</a-dropdown>
|
||||
</div>
|
||||
</div>
|
||||
</a-layout-header>
|
||||
|
||||
<a-layout-content class="content">
|
||||
<div class="content-shell">
|
||||
<router-view />
|
||||
</div>
|
||||
</a-layout-content>
|
||||
</a-layout>
|
||||
</a-layout>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import {
|
||||
DashboardOutlined,
|
||||
DownOutlined,
|
||||
GiftOutlined,
|
||||
HomeOutlined,
|
||||
LogoutOutlined,
|
||||
MenuFoldOutlined,
|
||||
MenuUnfoldOutlined,
|
||||
SafetyCertificateOutlined,
|
||||
ShopOutlined,
|
||||
ShoppingOutlined,
|
||||
TagOutlined,
|
||||
TeamOutlined,
|
||||
UserOutlined
|
||||
} from '@ant-design/icons-vue'
|
||||
import { message, Modal } from 'ant-design-vue'
|
||||
import { adminAuthApi, type UserVO } from '@/api/admin'
|
||||
import { DEFAULT_AVATAR } from '@/constants'
|
||||
import { usePermission } from '@/utils/permission'
|
||||
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
|
||||
const collapsed = ref(false)
|
||||
const userInfo = ref<UserVO | null>(null)
|
||||
const selectedKeys = ref<string[]>([route.path])
|
||||
const selectedShopId = ref<string>()
|
||||
const shopSwitchLoading = ref(false)
|
||||
const { loadUserPermissions, hasPermission, clearPermissions, userPermissions } = usePermission()
|
||||
|
||||
const menuItems = [
|
||||
{ key: '/admin', icon: HomeOutlined, label: '首页', permissionCode: '' },
|
||||
{ key: '/admin/dashboard', icon: DashboardOutlined, label: '仪表盘', permissionCode: 'dashboard:view' },
|
||||
{ key: '/admin/users', icon: UserOutlined, label: '用户管理', permissionCode: 'user:view' },
|
||||
{ key: '/admin/products', icon: ShopOutlined, label: '作品管理', permissionCode: 'product:view' },
|
||||
{ key: '/admin/coupons', icon: GiftOutlined, label: '优惠券管理', permissionCode: 'coupon:view' },
|
||||
{ key: '/admin/shops', icon: HomeOutlined, label: '店铺管理', permissionCode: 'shop:view' },
|
||||
{ key: '/admin/permissions', icon: SafetyCertificateOutlined, label: '权限管理', permissionCode: 'permission:view' },
|
||||
{ key: '/admin/tags', icon: TagOutlined, label: '标签管理', permissionCode: 'tag:view' },
|
||||
{ key: '/admin/orders', icon: ShoppingOutlined, label: '订单管理', permissionCode: 'order:view' },
|
||||
{ key: '/admin/nail-artists', icon: TeamOutlined, label: '美甲师管理', permissionCode: 'nail_artist:view' }
|
||||
]
|
||||
|
||||
const isBootstrapAdmin = computed(() => userInfo.value?.type === 4 && !userInfo.value?.shopId)
|
||||
const shopOptions = computed(() => {
|
||||
const ids = userInfo.value?.shopIds || []
|
||||
const names = userInfo.value?.shopNames || []
|
||||
return ids.map((id, index) => ({
|
||||
id: String(id),
|
||||
name: names[index] || `门店 ${id}`
|
||||
}))
|
||||
})
|
||||
const shopSelectOptions = computed(() => shopOptions.value.map(shop => ({ label: shop.name, value: shop.id })))
|
||||
const currentShopName = computed(() => userInfo.value?.shopName || '未选择门店')
|
||||
|
||||
const filteredMenuItems = computed(() => {
|
||||
userPermissions.value
|
||||
let visibleItems = menuItems.filter(item => !item.permissionCode || hasPermission(item.permissionCode))
|
||||
if (isBootstrapAdmin.value) {
|
||||
visibleItems = visibleItems.filter(item => item.key === '/admin' || item.key === '/admin/shops')
|
||||
}
|
||||
return visibleItems
|
||||
})
|
||||
|
||||
const persistAdminSession = (payload: any) => {
|
||||
localStorage.setItem('adminAccessToken', payload.accessToken)
|
||||
localStorage.setItem('adminRefreshToken', payload.refreshToken)
|
||||
localStorage.setItem('adminUserInfo', JSON.stringify(payload.userInfo))
|
||||
sessionStorage.setItem('adminAccessToken', payload.accessToken)
|
||||
}
|
||||
|
||||
const toggleCollapsed = () => {
|
||||
collapsed.value = !collapsed.value
|
||||
}
|
||||
|
||||
const handleMenuClick = (info: any) => {
|
||||
router.push(info.key)
|
||||
}
|
||||
|
||||
const handleLogout = () => {
|
||||
Modal.confirm({
|
||||
title: '确认退出登录',
|
||||
content: '退出后需要重新登录后台。',
|
||||
okText: '确认',
|
||||
cancelText: '取消',
|
||||
onOk: async () => {
|
||||
try {
|
||||
await adminAuthApi.logout()
|
||||
} catch (error) {
|
||||
console.error('退出失败:', error)
|
||||
} finally {
|
||||
localStorage.removeItem('adminAccessToken')
|
||||
localStorage.removeItem('adminRefreshToken')
|
||||
localStorage.removeItem('adminUserInfo')
|
||||
localStorage.removeItem('accessToken')
|
||||
localStorage.removeItem('refreshToken')
|
||||
localStorage.removeItem('userInfo')
|
||||
sessionStorage.removeItem('adminAccessToken')
|
||||
sessionStorage.removeItem('accessToken')
|
||||
clearPermissions()
|
||||
message.success('已退出登录')
|
||||
window.location.href = '/admin/login'
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const fetchUserInfo = async () => {
|
||||
try {
|
||||
const cache = localStorage.getItem('adminUserInfo')
|
||||
if (cache) {
|
||||
userInfo.value = JSON.parse(cache)
|
||||
}
|
||||
if (!userInfo.value) {
|
||||
return
|
||||
}
|
||||
selectedShopId.value = userInfo.value.shopId ? String(userInfo.value.shopId) : undefined
|
||||
} catch (error) {
|
||||
console.error('获取后台用户信息失败:', error)
|
||||
}
|
||||
}
|
||||
|
||||
const handleShopChange = async (shopId: unknown) => {
|
||||
if (typeof shopId !== 'string' && typeof shopId !== 'number') {
|
||||
return
|
||||
}
|
||||
const normalizedShopId = String(shopId)
|
||||
if (!normalizedShopId || normalizedShopId === String(userInfo.value?.shopId || '')) {
|
||||
return
|
||||
}
|
||||
shopSwitchLoading.value = true
|
||||
try {
|
||||
const response = await adminAuthApi.switchShop(normalizedShopId)
|
||||
persistAdminSession(response as any)
|
||||
await fetchUserInfo()
|
||||
await loadUserPermissions()
|
||||
message.success('门店上下文已切换')
|
||||
window.location.reload()
|
||||
} catch (error: any) {
|
||||
console.error('切换门店失败:', error)
|
||||
selectedShopId.value = userInfo.value?.shopId ? String(userInfo.value.shopId) : undefined
|
||||
message.error(error?.message || '切换门店失败')
|
||||
} finally {
|
||||
shopSwitchLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => route.path,
|
||||
newPath => {
|
||||
selectedKeys.value = [newPath]
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
onMounted(async () => {
|
||||
await fetchUserInfo()
|
||||
await loadUserPermissions()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.admin-layout {
|
||||
height: 100vh;
|
||||
}
|
||||
|
||||
.sider {
|
||||
background: #001529;
|
||||
overflow: auto;
|
||||
height: 100vh;
|
||||
position: fixed;
|
||||
left: 0;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
z-index: 1000;
|
||||
}
|
||||
|
||||
.logo {
|
||||
height: 64px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
|
||||
.logo h1 {
|
||||
margin: 0;
|
||||
color: white;
|
||||
font-size: 18px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.header {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 100;
|
||||
padding: 0 24px;
|
||||
background: white;
|
||||
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
|
||||
}
|
||||
|
||||
.header-shell {
|
||||
width: 100%;
|
||||
max-width: var(--admin-content-max-width);
|
||||
margin: 0 auto;
|
||||
min-height: 64px;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.header-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.trigger {
|
||||
font-size: 18px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.shop-hint,
|
||||
.shop-switcher,
|
||||
.shop-pill {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
min-height: 40px;
|
||||
padding: 0 14px;
|
||||
border-radius: 999px;
|
||||
background: #f5f7fb;
|
||||
color: #334155;
|
||||
}
|
||||
|
||||
.shop-hint {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.shop-switcher-label {
|
||||
font-size: 13px;
|
||||
color: #64748b;
|
||||
}
|
||||
|
||||
.shop-select {
|
||||
min-width: 220px;
|
||||
}
|
||||
|
||||
.shop-pill {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.header-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.user-dropdown {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 8px 12px;
|
||||
border-radius: 10px;
|
||||
transition: background 0.2s ease;
|
||||
}
|
||||
|
||||
.user-dropdown:hover {
|
||||
background: #f8fafc;
|
||||
}
|
||||
|
||||
.username {
|
||||
color: #1f2937;
|
||||
}
|
||||
|
||||
.content {
|
||||
margin-left: 240px;
|
||||
min-height: calc(100vh - 64px);
|
||||
padding: 24px;
|
||||
background: #f0f2f5;
|
||||
transition: margin-left 0.2s;
|
||||
}
|
||||
|
||||
.content-shell {
|
||||
width: 100%;
|
||||
max-width: var(--admin-content-max-width);
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.admin-layout :deep(.ant-layout-sider-collapsed) + .ant-layout .content {
|
||||
margin-left: 80px;
|
||||
}
|
||||
</style>
|
||||
@@ -1,334 +0,0 @@
|
||||
<template>
|
||||
<div class="home">
|
||||
<a-page-header title="欢迎使用后台管理系统" :sub-title="welcomeMessage" />
|
||||
|
||||
<a-alert
|
||||
v-if="isBootstrapAdmin"
|
||||
class="bootstrap-alert"
|
||||
type="warning"
|
||||
show-icon
|
||||
message="当前处于建店引导态"
|
||||
description="系统里还没有可用店铺。当前账号已允许登录后台先创建第一家店铺,其他后台模块会保持不可用,创建完成后请重新登录并选择店铺。"
|
||||
/>
|
||||
|
||||
<a-card class="time-card">
|
||||
<a-statistic title="当前时间" :value="currentTime" />
|
||||
</a-card>
|
||||
|
||||
<a-card class="info-card">
|
||||
<a-descriptions bordered>
|
||||
<a-descriptions-item label="用户信息">
|
||||
<div class="user-info">
|
||||
<a-avatar :size="64" :src="userInfo?.avatar || DEFAULT_AVATAR" />
|
||||
<div class="user-details">
|
||||
<h3>{{ userInfo?.nickname || '管理员' }}</h3>
|
||||
<p>{{ getUserTypeText(userInfo?.type) }}</p>
|
||||
<p v-if="userInfo?.shopName">所属店铺: {{ userInfo?.shopName }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</a-descriptions-item>
|
||||
</a-descriptions>
|
||||
</a-card>
|
||||
|
||||
<a-card class="permissions-card">
|
||||
<template #title>
|
||||
<div class="card-title">
|
||||
<SafetyCertificateOutlined class="title-icon" />
|
||||
<span>我的权限</span>
|
||||
</div>
|
||||
</template>
|
||||
<div class="permissions-content" v-if="userPermissions.length > 0">
|
||||
<div v-for="(group, groupName) in groupedPermissions" :key="groupName" class="permission-group">
|
||||
<div class="group-title">{{ groupName }}</div>
|
||||
<div class="permission-tags">
|
||||
<a-tag v-for="permission in group" :key="permission.id" color="blue" class="permission-tag">
|
||||
{{ permission.permissionName }}
|
||||
</a-tag>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="no-permissions" v-else>
|
||||
暂无权限信息
|
||||
</div>
|
||||
</a-card>
|
||||
|
||||
<a-card class="quick-actions">
|
||||
<template #title>
|
||||
快捷操作
|
||||
</template>
|
||||
<a-grid :columns="3" :colGap="16" :rowGap="16">
|
||||
<a-grid-item v-for="item in quickActions" :key="item.key">
|
||||
<a-card hoverable @click="navigateTo(item.path, item.permissionCode)">
|
||||
<template #cover>
|
||||
<div class="action-icon">
|
||||
<component :is="item.icon" />
|
||||
</div>
|
||||
</template>
|
||||
<template #title>
|
||||
{{ item.title }}
|
||||
</template>
|
||||
</a-card>
|
||||
</a-grid-item>
|
||||
</a-grid>
|
||||
</a-card>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, onMounted } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { DashboardOutlined, UserOutlined, ShopOutlined, SafetyCertificateOutlined, HomeOutlined } from '@ant-design/icons-vue'
|
||||
import { userApi, type UserVO } from '@/api/admin'
|
||||
import { permissionApi, type PermissionVO } from '@/api/permission'
|
||||
import { DEFAULT_AVATAR } from '@/constants'
|
||||
import { message } from 'ant-design-vue'
|
||||
|
||||
const router = useRouter()
|
||||
const currentTime = ref('')
|
||||
const userInfo = ref<UserVO | null>(null)
|
||||
const userPermissions = ref<PermissionVO[]>([])
|
||||
|
||||
const welcomeMessage = computed(() => {
|
||||
const hour = new Date().getHours()
|
||||
if (hour < 12) {
|
||||
return '早上好!'
|
||||
} else if (hour < 18) {
|
||||
return '下午好!'
|
||||
} else {
|
||||
return '晚上好!'
|
||||
}
|
||||
})
|
||||
|
||||
const isBootstrapAdmin = computed(() => userInfo.value?.type === 4 && !userInfo.value?.shopId)
|
||||
|
||||
const groupedPermissions = computed(() => {
|
||||
const groups: Record<string, PermissionVO[]> = {}
|
||||
userPermissions.value.forEach(permission => {
|
||||
const groupName = permission.permissionGroup
|
||||
if (!groups[groupName]) {
|
||||
groups[groupName] = []
|
||||
}
|
||||
groups[groupName]!.push(permission)
|
||||
})
|
||||
return groups
|
||||
})
|
||||
|
||||
const quickActions = computed(() => {
|
||||
const actions = [
|
||||
{
|
||||
key: 'dashboard',
|
||||
title: '仪表盘',
|
||||
path: '/admin/dashboard',
|
||||
icon: DashboardOutlined,
|
||||
permissionCode: 'dashboard:view'
|
||||
},
|
||||
{
|
||||
key: 'users',
|
||||
title: '用户管理',
|
||||
path: '/admin/users',
|
||||
icon: UserOutlined,
|
||||
permissionCode: 'user:view'
|
||||
},
|
||||
{
|
||||
key: 'products',
|
||||
title: '作品管理',
|
||||
path: '/admin/products',
|
||||
icon: ShopOutlined,
|
||||
permissionCode: 'product:view'
|
||||
},
|
||||
{
|
||||
key: 'shops',
|
||||
title: '店铺管理',
|
||||
path: '/admin/shops',
|
||||
icon: HomeOutlined,
|
||||
permissionCode: 'shop:view'
|
||||
},
|
||||
{
|
||||
key: 'permissions',
|
||||
title: '权限管理',
|
||||
path: '/admin/permissions',
|
||||
icon: SafetyCertificateOutlined,
|
||||
permissionCode: 'permission:view'
|
||||
}
|
||||
]
|
||||
|
||||
const grantedPermissions = new Set(userPermissions.value.map(permission => permission.permissionCode))
|
||||
return actions.filter(item => grantedPermissions.has(item.permissionCode))
|
||||
})
|
||||
|
||||
const getUserTypeText = (type: number | undefined) => {
|
||||
switch (type) {
|
||||
case 4:
|
||||
return '管理员'
|
||||
case 2:
|
||||
return '店长'
|
||||
case 3:
|
||||
return '美甲师'
|
||||
default:
|
||||
return '普通用户'
|
||||
}
|
||||
}
|
||||
|
||||
const updateCurrentTime = () => {
|
||||
const now = new Date()
|
||||
currentTime.value = now.toLocaleString('zh-CN', {
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit'
|
||||
})
|
||||
}
|
||||
|
||||
const fetchUserInfo = async () => {
|
||||
try {
|
||||
const adminUserInfoStr = localStorage.getItem('adminUserInfo')
|
||||
if (adminUserInfoStr) {
|
||||
userInfo.value = JSON.parse(adminUserInfoStr)
|
||||
} else {
|
||||
const res = await userApi.getUserInfo()
|
||||
userInfo.value = res as unknown as UserVO
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取用户信息失败:', error)
|
||||
}
|
||||
}
|
||||
|
||||
const fetchUserPermissions = async () => {
|
||||
try {
|
||||
const res = await permissionApi.getUserPermissions()
|
||||
userPermissions.value = res as unknown as PermissionVO[]
|
||||
} catch (error) {
|
||||
console.error('获取用户权限失败:', error)
|
||||
}
|
||||
}
|
||||
|
||||
const navigateTo = (path: string, permissionCode?: string) => {
|
||||
// 检查是否需要权限
|
||||
if (permissionCode) {
|
||||
const hasPermission = userPermissions.value.some(p => p.permissionCode === permissionCode)
|
||||
if (!hasPermission) {
|
||||
message.warning('您没有该操作的权限')
|
||||
return
|
||||
}
|
||||
}
|
||||
router.push(path)
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
updateCurrentTime()
|
||||
setInterval(updateCurrentTime, 1000)
|
||||
fetchUserInfo()
|
||||
fetchUserPermissions()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.home {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.time-card {
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.bootstrap-alert {
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.info-card {
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.permissions-card {
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.user-info {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.user-details {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.user-details h3 {
|
||||
margin: 0 0 8px 0;
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.user-details p {
|
||||
margin: 4px 0;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.card-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: #1a1a2e;
|
||||
}
|
||||
|
||||
.title-icon {
|
||||
font-size: 20px;
|
||||
color: #667eea;
|
||||
}
|
||||
|
||||
.permissions-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.permission-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.group-title {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: #667eea;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.permission-tags {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.permission-tag {
|
||||
font-size: 13px;
|
||||
padding: 4px 12px;
|
||||
border-radius: 12px;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.no-permissions {
|
||||
text-align: center;
|
||||
padding: 20px;
|
||||
color: #999;
|
||||
}
|
||||
|
||||
.quick-actions {
|
||||
margin-top: 24px;
|
||||
}
|
||||
|
||||
.action-icon {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 80px;
|
||||
font-size: 32px;
|
||||
color: #1890ff;
|
||||
background: #f0f2f5;
|
||||
}
|
||||
</style>
|
||||
@@ -1,160 +0,0 @@
|
||||
<template>
|
||||
<div class="orders">
|
||||
<a-page-header title="订单管理" sub-title="管理系统订单" />
|
||||
|
||||
<a-card :bordered="false">
|
||||
<a-table :columns="columns" :data-source="orders" :loading="loading" row-key="id">
|
||||
<template #bodyCell="{ column, record }">
|
||||
<template v-if="column.key === 'status'">
|
||||
<a-tag :color="statusColor(record.status)">{{ record.statusText }}</a-tag>
|
||||
</template>
|
||||
<template v-else-if="column.key === 'totalAmount'">
|
||||
¥{{ record.totalAmount.toFixed(2) }}
|
||||
</template>
|
||||
<template v-else-if="column.key === 'actualAmount'">
|
||||
¥{{ record.actualAmount.toFixed(2) }}
|
||||
</template>
|
||||
<template v-else-if="column.key === 'actions'">
|
||||
<a-space>
|
||||
<a-button type="link" size="small" @click="currentOrder = record">查看</a-button>
|
||||
<a-button
|
||||
v-if="record.status === 1 && canProcessOrders"
|
||||
type="primary"
|
||||
size="small"
|
||||
@click="process(record.id, 2)"
|
||||
>
|
||||
确认完成
|
||||
</a-button>
|
||||
<a-button
|
||||
v-if="record.status === 1 && canProcessOrders && !isArtist"
|
||||
danger
|
||||
size="small"
|
||||
@click="process(record.id, 3)"
|
||||
>
|
||||
取消订单
|
||||
</a-button>
|
||||
</a-space>
|
||||
</template>
|
||||
</template>
|
||||
</a-table>
|
||||
</a-card>
|
||||
|
||||
<a-modal v-model:open="detailVisible" title="订单详情" width="860px" @cancel="currentOrder = null">
|
||||
<template v-if="currentOrder">
|
||||
<a-descriptions :column="2">
|
||||
<a-descriptions-item label="订单编号">{{ currentOrder.orderNo }}</a-descriptions-item>
|
||||
<a-descriptions-item label="用户ID">{{ currentOrder.userId }}</a-descriptions-item>
|
||||
<a-descriptions-item label="订单总额">¥{{ currentOrder.totalAmount.toFixed(2) }}</a-descriptions-item>
|
||||
<a-descriptions-item label="实付金额">¥{{ currentOrder.actualAmount.toFixed(2) }}</a-descriptions-item>
|
||||
<a-descriptions-item label="优惠券">{{ currentOrder.couponName || '无' }}</a-descriptions-item>
|
||||
<a-descriptions-item label="订单状态">{{ currentOrder.statusText }}</a-descriptions-item>
|
||||
<a-descriptions-item label="创建时间" :span="2">{{ currentOrder.createTime }}</a-descriptions-item>
|
||||
</a-descriptions>
|
||||
|
||||
<a-divider>订单项目</a-divider>
|
||||
<a-table :columns="itemColumns" :data-source="currentOrder.items" row-key="id" :pagination="false">
|
||||
<template #bodyCell="{ column, record }">
|
||||
<template v-if="column.key === 'price'">¥{{ record.price.toFixed(2) }}</template>
|
||||
<template v-else-if="column.key === 'totalPrice'">¥{{ (record.price * record.quantity).toFixed(2) }}</template>
|
||||
</template>
|
||||
</a-table>
|
||||
</template>
|
||||
</a-modal>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { message } from 'ant-design-vue'
|
||||
import { orderApi } from '../../api/order'
|
||||
import { usePermission } from '@/utils/permission'
|
||||
import type { IdType } from '@/utils/id'
|
||||
import { sameId } from '@/utils/id'
|
||||
|
||||
const orders = ref<any[]>([])
|
||||
const loading = ref(false)
|
||||
const currentOrder = ref<any | null>(null)
|
||||
const currentUserType = ref<number | null>(null)
|
||||
const { hasPermission, loadUserPermissions } = usePermission()
|
||||
const detailVisible = computed({
|
||||
get: () => !!currentOrder.value,
|
||||
set: value => { if (!value) currentOrder.value = null }
|
||||
})
|
||||
const canProcessOrders = computed(() => hasPermission('order:process'))
|
||||
const isArtist = computed(() => currentUserType.value === 3)
|
||||
|
||||
const columns = [
|
||||
{ title: '订单编号', dataIndex: 'orderNo', key: 'orderNo' },
|
||||
{ title: '用户ID', dataIndex: 'userId', key: 'userId', width: 100 },
|
||||
{ title: '订单总额', key: 'totalAmount', width: 120 },
|
||||
{ title: '实付金额', key: 'actualAmount', width: 120 },
|
||||
{ title: '优惠券', dataIndex: 'couponName', key: 'couponName', width: 140 },
|
||||
{ title: '状态', key: 'status', width: 100 },
|
||||
{ title: '创建时间', dataIndex: 'createTime', key: 'createTime', width: 180 },
|
||||
{ title: '操作', key: 'actions', width: 180 }
|
||||
]
|
||||
|
||||
const itemColumns = [
|
||||
{ title: '商品ID', dataIndex: 'productId', key: 'productId', width: 100 },
|
||||
{ title: '商品名称', dataIndex: 'productTitle', key: 'productTitle' },
|
||||
{ title: '美甲师', dataIndex: 'artistName', key: 'artistName', width: 120 },
|
||||
{ title: '预约时间', dataIndex: 'appointmentTime', key: 'appointmentTime', width: 180 },
|
||||
{ title: '单价', key: 'price', width: 100 },
|
||||
{ title: '数量', dataIndex: 'quantity', key: 'quantity', width: 80 },
|
||||
{ title: '总价', key: 'totalPrice', width: 100 }
|
||||
]
|
||||
|
||||
const statusColor = (status: number) => {
|
||||
if (status === 1) return 'orange'
|
||||
if (status === 2) return 'green'
|
||||
if (status === 3) return 'red'
|
||||
return 'default'
|
||||
}
|
||||
|
||||
const resolveCurrentUserType = () => {
|
||||
const cached = localStorage.getItem('adminUserInfo') || sessionStorage.getItem('adminUserInfo')
|
||||
if (!cached) {
|
||||
currentUserType.value = null
|
||||
return
|
||||
}
|
||||
try {
|
||||
currentUserType.value = JSON.parse(cached)?.type ?? null
|
||||
} catch {
|
||||
currentUserType.value = null
|
||||
}
|
||||
}
|
||||
|
||||
const loadOrders = async () => {
|
||||
loading.value = true
|
||||
try {
|
||||
orders.value = await orderApi.getAllOrders() as unknown as any[]
|
||||
} catch {
|
||||
message.error('获取订单列表失败')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const process = async (orderId: IdType, status: number) => {
|
||||
try {
|
||||
await orderApi.processOrder(orderId, status)
|
||||
message.success('操作成功')
|
||||
await loadOrders()
|
||||
if (sameId(currentOrder.value?.id, orderId)) {
|
||||
currentOrder.value = orders.value.find(order => sameId(order.id, orderId)) || null
|
||||
}
|
||||
} catch {
|
||||
message.error('操作失败')
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
resolveCurrentUserType()
|
||||
await loadUserPermissions()
|
||||
await loadOrders()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.orders { padding: 0; }
|
||||
</style>
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,60 +0,0 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
import path from 'path'
|
||||
import AutoImport from 'unplugin-auto-import/vite'
|
||||
import Components from 'unplugin-vue-components/vite'
|
||||
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
|
||||
import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers'
|
||||
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
// 配置服务器中间件
|
||||
plugins: [
|
||||
vue(),
|
||||
AutoImport({
|
||||
resolvers: [ElementPlusResolver()],
|
||||
imports: ['vue', 'vue-router', 'pinia'],
|
||||
dts: 'src/auto-import.d.ts',
|
||||
}),
|
||||
Components({
|
||||
resolvers: [ElementPlusResolver(), AntDesignVueResolver({ importStyle: 'less' })],
|
||||
dts: 'src/components.d.ts',
|
||||
}),
|
||||
// 添加 IP 访问控制中间件
|
||||
{
|
||||
name: 'ip-access-control',
|
||||
configureServer(server) {
|
||||
// 暂时禁用 IP 访问控制,允许所有 IP 访问
|
||||
// 生产环境应该重新启用并配置正确的 IP 列表
|
||||
server.middlewares.use((_req, _res, next) => {
|
||||
// 直接允许所有 IP 访问
|
||||
next()
|
||||
})
|
||||
},
|
||||
},
|
||||
],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': path.resolve(__dirname, './src'),
|
||||
},
|
||||
},
|
||||
server: {
|
||||
port: 3000,
|
||||
host: true,
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'http://wcy111.top:8088', // 代理到 Gateway
|
||||
changeOrigin: true,
|
||||
rewrite: (path) => path.replace(/^\/api/, ''),
|
||||
},
|
||||
},
|
||||
// 配置允许的主机名
|
||||
allowedHosts: [
|
||||
'localhost',
|
||||
'127.0.0.1',
|
||||
'2666.online', // 允许通过 2666.online 访问
|
||||
'wcy111.top', // 允许通过 wcy111.top 访问
|
||||
// 可以添加更多允许的域名
|
||||
],
|
||||
},
|
||||
})
|
||||
@@ -16,6 +16,8 @@ public class MessageChannelProperties {
|
||||
|
||||
private Mock mock = new Mock();
|
||||
|
||||
private Retry retry = new Retry();
|
||||
|
||||
@Data
|
||||
public static class Security {
|
||||
private String encryptionKey = "MessageHub-Change-Me-2026";
|
||||
@@ -26,4 +28,12 @@ public class MessageChannelProperties {
|
||||
private boolean autoBootstrap = true;
|
||||
private List<String> profiles = new ArrayList<>(List.of("dev", "local", "test"));
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class Retry {
|
||||
private int maxAttempts = 3;
|
||||
private long initialDelayMillis = 1000L;
|
||||
private double multiplier = 2.0D;
|
||||
private long maxDelayMillis = 30000L;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,12 +19,21 @@ public class RabbitMQConfig {
|
||||
public static final String SMS_QUEUE = "smsQueue";
|
||||
// 定义邮件队列名称常量
|
||||
public static final String EMAIL_QUEUE = "emailQueue";
|
||||
public static final String QQ_QUEUE = "qqQueue";
|
||||
// 定义统一消息交换机名称常量
|
||||
public static final String MESSAGE_EXCHANGE = "messageExchange";
|
||||
public static final String DEAD_LETTER_EXCHANGE = "messageDeadLetterExchange";
|
||||
public static final String SMS_DEAD_LETTER_QUEUE = "smsDeadLetterQueue";
|
||||
public static final String EMAIL_DEAD_LETTER_QUEUE = "emailDeadLetterQueue";
|
||||
public static final String QQ_DEAD_LETTER_QUEUE = "qqDeadLetterQueue";
|
||||
public static final String SMS_DEAD_LETTER_ROUTING_KEY = "dead.sms";
|
||||
public static final String EMAIL_DEAD_LETTER_ROUTING_KEY = "dead.email";
|
||||
public static final String QQ_DEAD_LETTER_ROUTING_KEY = "dead.qq";
|
||||
// 定义短信路由键常量
|
||||
public static final String SMS_ROUTING_KEY = "sms.#";
|
||||
// 定义邮件路由键常量
|
||||
public static final String EMAIL_ROUTING_KEY = "email.#";
|
||||
public static final String QQ_ROUTING_KEY = "qq.#";
|
||||
|
||||
/**
|
||||
* 配置短信队列
|
||||
@@ -44,6 +53,11 @@ public class RabbitMQConfig {
|
||||
return QueueBuilder.durable(EMAIL_QUEUE).build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Queue qqQueue() {
|
||||
return QueueBuilder.durable(QQ_QUEUE).build();
|
||||
}
|
||||
|
||||
/**
|
||||
* 配置统一消息交换机
|
||||
* @return 持久化的、自动删除的、不自动声明的主题交换机
|
||||
@@ -53,6 +67,26 @@ public class RabbitMQConfig {
|
||||
return new TopicExchange(MESSAGE_EXCHANGE, true, false);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DirectExchange deadLetterExchange() {
|
||||
return new DirectExchange(DEAD_LETTER_EXCHANGE, true, false);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Queue smsDeadLetterQueue() {
|
||||
return QueueBuilder.durable(SMS_DEAD_LETTER_QUEUE).build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Queue emailDeadLetterQueue() {
|
||||
return QueueBuilder.durable(EMAIL_DEAD_LETTER_QUEUE).build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Queue qqDeadLetterQueue() {
|
||||
return QueueBuilder.durable(QQ_DEAD_LETTER_QUEUE).build();
|
||||
}
|
||||
|
||||
/**
|
||||
* 配置短信队列与交换机的绑定关系
|
||||
* @return 绑定对象,将短信队列绑定到统一消息交换机,并设置路由键
|
||||
@@ -71,6 +105,26 @@ public class RabbitMQConfig {
|
||||
return BindingBuilder.bind(emailQueue()).to(messageExchange()).with(EMAIL_ROUTING_KEY);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Binding qqBinding() {
|
||||
return BindingBuilder.bind(qqQueue()).to(messageExchange()).with(QQ_ROUTING_KEY);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Binding smsDeadLetterBinding() {
|
||||
return BindingBuilder.bind(smsDeadLetterQueue()).to(deadLetterExchange()).with(SMS_DEAD_LETTER_ROUTING_KEY);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Binding emailDeadLetterBinding() {
|
||||
return BindingBuilder.bind(emailDeadLetterQueue()).to(deadLetterExchange()).with(EMAIL_DEAD_LETTER_ROUTING_KEY);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Binding qqDeadLetterBinding() {
|
||||
return BindingBuilder.bind(qqDeadLetterQueue()).to(deadLetterExchange()).with(QQ_DEAD_LETTER_ROUTING_KEY);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SimpleRabbitListenerContainerFactory manualAckRabbitListenerContainerFactory(
|
||||
SimpleRabbitListenerContainerFactoryConfigurer configurer,
|
||||
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.xiaowang.messagehub.controller;
|
||||
|
||||
import com.xiaowang.messagehub.dto.admin.EmailAttachmentPolicyRequest;
|
||||
import com.xiaowang.messagehub.dto.admin.EmailAttachmentPolicyView;
|
||||
import com.xiaowang.messagehub.dto.admin.EmailAttachmentView;
|
||||
import com.xiaowang.messagehub.dto.common.ApiResponse;
|
||||
import com.xiaowang.messagehub.service.email.AttachmentStorageService;
|
||||
import com.xiaowang.messagehub.service.email.EmailAttachmentPolicyService;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.validation.Valid;
|
||||
|
||||
@Validated
|
||||
@RestController
|
||||
public class EmailAttachmentAdminController {
|
||||
|
||||
private final AttachmentStorageService attachmentStorageService;
|
||||
private final EmailAttachmentPolicyService policyService;
|
||||
|
||||
public EmailAttachmentAdminController(AttachmentStorageService attachmentStorageService,
|
||||
EmailAttachmentPolicyService policyService) {
|
||||
this.attachmentStorageService = attachmentStorageService;
|
||||
this.policyService = policyService;
|
||||
}
|
||||
|
||||
@PostMapping("/admin/api/email-attachments")
|
||||
public ApiResponse<EmailAttachmentView> uploadAttachment(@RequestParam("file") MultipartFile file) {
|
||||
return ApiResponse.success("附件上传成功", attachmentStorageService.upload(file));
|
||||
}
|
||||
|
||||
@GetMapping("/admin/api/email-attachment-policies")
|
||||
public ApiResponse<EmailAttachmentPolicyView> getPolicy() {
|
||||
return ApiResponse.success(policyService.getPolicy());
|
||||
}
|
||||
|
||||
@PutMapping("/admin/api/email-attachment-policies")
|
||||
public ApiResponse<EmailAttachmentPolicyView> updatePolicy(@Valid @RequestBody EmailAttachmentPolicyRequest request) {
|
||||
return ApiResponse.success("附件策略更新成功", policyService.updatePolicy(request));
|
||||
}
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package com.xiaowang.messagehub.controller;
|
||||
|
||||
import com.xiaowang.messagehub.dto.admin.EmailTemplateSaveRequest;
|
||||
import com.xiaowang.messagehub.dto.admin.EmailTemplateStatusUpdateRequest;
|
||||
import com.xiaowang.messagehub.dto.admin.EmailTemplateView;
|
||||
import com.xiaowang.messagehub.dto.common.ApiResponse;
|
||||
import com.xiaowang.messagehub.service.email.EmailTemplateService;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import java.util.List;
|
||||
|
||||
@Validated
|
||||
@RestController
|
||||
@RequestMapping("/admin/api/email-templates")
|
||||
public class EmailTemplateAdminController {
|
||||
|
||||
private final EmailTemplateService emailTemplateService;
|
||||
|
||||
public EmailTemplateAdminController(EmailTemplateService emailTemplateService) {
|
||||
this.emailTemplateService = emailTemplateService;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public ApiResponse<List<EmailTemplateView>> listTemplates() {
|
||||
return ApiResponse.success(emailTemplateService.listTemplates());
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public ApiResponse<EmailTemplateView> createTemplate(@Valid @RequestBody EmailTemplateSaveRequest request) {
|
||||
return ApiResponse.success("邮件模板创建成功", emailTemplateService.createTemplate(request));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public ApiResponse<EmailTemplateView> updateTemplate(@PathVariable Long id,
|
||||
@Valid @RequestBody EmailTemplateSaveRequest request) {
|
||||
return ApiResponse.success("邮件模板更新成功", emailTemplateService.updateTemplate(id, request));
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/status")
|
||||
public ApiResponse<EmailTemplateView> updateTemplateStatus(@PathVariable Long id,
|
||||
@Valid @RequestBody EmailTemplateStatusUpdateRequest request) {
|
||||
return ApiResponse.success("邮件模板状态更新成功", emailTemplateService.updateTemplateStatus(id, request.getEnabled()));
|
||||
}
|
||||
}
|
||||
+24
@@ -43,6 +43,11 @@ public class MessageChannelAdminController {
|
||||
return ApiResponse.success(messageChannelService.listSmsTemplates());
|
||||
}
|
||||
|
||||
@GetMapping("/qq-templates")
|
||||
public ApiResponse<List<ChannelSmsTemplateView>> listQqTemplates() {
|
||||
return ApiResponse.success(messageChannelService.listQqTemplates());
|
||||
}
|
||||
|
||||
@PostMapping("/sms-templates")
|
||||
public ApiResponse<ChannelSmsTemplateView> createSmsTemplate(
|
||||
@Valid @RequestBody ChannelSmsTemplateSaveRequest request) {
|
||||
@@ -62,6 +67,25 @@ public class MessageChannelAdminController {
|
||||
return ApiResponse.success("模板状态更新成功", messageChannelService.updateSmsTemplateStatus(id, request.getEnabled()));
|
||||
}
|
||||
|
||||
@PostMapping("/qq-templates")
|
||||
public ApiResponse<ChannelSmsTemplateView> createQqTemplate(
|
||||
@Valid @RequestBody ChannelSmsTemplateSaveRequest request) {
|
||||
return ApiResponse.success("QQ template created", messageChannelService.createQqTemplate(request));
|
||||
}
|
||||
|
||||
@PutMapping("/qq-templates/{id}")
|
||||
public ApiResponse<ChannelSmsTemplateView> updateQqTemplate(@PathVariable Long id,
|
||||
@Valid @RequestBody ChannelSmsTemplateSaveRequest request) {
|
||||
return ApiResponse.success("QQ template updated", messageChannelService.updateQqTemplate(id, request));
|
||||
}
|
||||
|
||||
@PostMapping("/qq-templates/{id}/status")
|
||||
public ApiResponse<ChannelSmsTemplateView> updateQqTemplateStatus(
|
||||
@PathVariable Long id,
|
||||
@Valid @RequestBody ChannelSmsTemplateStatusUpdateRequest request) {
|
||||
return ApiResponse.success("QQ template status updated", messageChannelService.updateQqTemplateStatus(id, request.getEnabled()));
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public ApiResponse<ChannelConfigView> getChannel(@PathVariable Long id) {
|
||||
return ApiResponse.success(messageChannelService.getChannel(id));
|
||||
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package com.xiaowang.messagehub.controller;
|
||||
|
||||
import com.xiaowang.messagehub.dto.admin.PushLogView;
|
||||
import com.xiaowang.messagehub.dto.common.ApiResponse;
|
||||
import com.xiaowang.messagehub.service.admin.PushLogAdminService;
|
||||
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.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/admin/api/push-logs")
|
||||
public class PushLogAdminController {
|
||||
|
||||
private final PushLogAdminService pushLogAdminService;
|
||||
|
||||
public PushLogAdminController(PushLogAdminService pushLogAdminService) {
|
||||
this.pushLogAdminService = pushLogAdminService;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public ApiResponse<List<PushLogView>> listLogs(@RequestParam(required = false) String sourceSystem,
|
||||
@RequestParam(required = false) String channelType,
|
||||
@RequestParam(required = false) Integer status,
|
||||
@RequestParam(required = false) String keyword,
|
||||
@RequestParam(required = false) Boolean deadLetter,
|
||||
@RequestParam(defaultValue = "50") int limit) {
|
||||
return ApiResponse.success(pushLogAdminService.listLogs(sourceSystem, channelType, status, keyword, deadLetter, limit));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.xiaowang.messagehub.dto;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public class EmailMessageDTO extends MessageDTO {
|
||||
|
||||
private String subject;
|
||||
|
||||
private String content;
|
||||
|
||||
private String bodyType;
|
||||
|
||||
private String emailTemplateCode;
|
||||
|
||||
private List<Long> attachmentIds = new ArrayList<>();
|
||||
}
|
||||
@@ -20,7 +20,7 @@ public class MessageDTO {
|
||||
private String receiver;
|
||||
|
||||
@NotBlank(message = "通道类型不能为空")
|
||||
@Pattern(regexp = "^(EMAIL|SMS|PUSH|WECHAT)$", message = "通道类型必须是 EMAIL、SMS、PUSH 或 WECHAT")
|
||||
@Pattern(regexp = "^(EMAIL|SMS|QQ|PUSH|WECHAT)$", message = "通道类型必须是 EMAIL、SMS、QQ、PUSH 或 WECHAT")
|
||||
private String channelType;
|
||||
|
||||
@NotBlank(message = "消息类型不能为空")
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.xiaowang.messagehub.dto;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public class QqMessageDTO extends MessageDTO {
|
||||
|
||||
private String targetType;
|
||||
|
||||
private String content;
|
||||
|
||||
private String contentMode;
|
||||
}
|
||||
+10
@@ -4,7 +4,9 @@ import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Data
|
||||
@@ -20,7 +22,15 @@ public class ChannelConfigTestRequest {
|
||||
|
||||
private String content;
|
||||
|
||||
private String bodyType;
|
||||
|
||||
private String targetType;
|
||||
|
||||
private String contentMode;
|
||||
|
||||
private String templateCode;
|
||||
|
||||
private Map<String, Object> templateParams = new LinkedHashMap<>();
|
||||
|
||||
private List<Long> attachmentIds = new ArrayList<>();
|
||||
}
|
||||
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.xiaowang.messagehub.dto.admin;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.Min;
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
@Data
|
||||
public class EmailAttachmentPolicyRequest {
|
||||
|
||||
@NotNull(message = "单文件大小限制不能为空")
|
||||
@Min(value = 1, message = "单文件大小限制必须大于 0")
|
||||
private Long maxSingleFileSize;
|
||||
|
||||
@NotNull(message = "总附件大小限制不能为空")
|
||||
@Min(value = 1, message = "总附件大小限制必须大于 0")
|
||||
private Long maxTotalFileSize;
|
||||
|
||||
@NotNull(message = "附件数量限制不能为空")
|
||||
@Min(value = 1, message = "附件数量限制必须大于 0")
|
||||
private Integer maxFileCount;
|
||||
|
||||
private String allowedExtensions;
|
||||
|
||||
private String allowedMimeTypes;
|
||||
|
||||
@NotNull(message = "附件保留天数不能为空")
|
||||
@Min(value = 1, message = "附件保留天数必须大于 0")
|
||||
private Integer retentionDays;
|
||||
|
||||
@NotNull(message = "读取超时时间不能为空")
|
||||
@Min(value = 1000, message = "读取超时时间不能小于 1000 毫秒")
|
||||
private Integer readTimeoutMillis;
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.xiaowang.messagehub.dto.admin;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
public class EmailAttachmentPolicyView {
|
||||
|
||||
private Long maxSingleFileSize;
|
||||
|
||||
private Long maxTotalFileSize;
|
||||
|
||||
private Integer maxFileCount;
|
||||
|
||||
private String allowedExtensions;
|
||||
|
||||
private String allowedMimeTypes;
|
||||
|
||||
private Integer retentionDays;
|
||||
|
||||
private Integer readTimeoutMillis;
|
||||
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.xiaowang.messagehub.dto.admin;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
public class EmailAttachmentView {
|
||||
|
||||
private Long id;
|
||||
|
||||
private String originalFileName;
|
||||
|
||||
private String contentType;
|
||||
|
||||
private String fileExtension;
|
||||
|
||||
private Long fileSize;
|
||||
|
||||
private String status;
|
||||
|
||||
private LocalDateTime expireTime;
|
||||
|
||||
private LocalDateTime createTime;
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package com.xiaowang.messagehub.dto.admin;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.Size;
|
||||
|
||||
@Data
|
||||
public class EmailTemplateSaveRequest {
|
||||
|
||||
@Size(max = 64, message = "邮件模板编码不能超过 64 个字符")
|
||||
private String templateCode;
|
||||
|
||||
@NotBlank(message = "邮件模板名称不能为空")
|
||||
@Size(max = 100, message = "邮件模板名称不能超过 100 个字符")
|
||||
private String templateName;
|
||||
|
||||
@NotBlank(message = "邮件主题模板不能为空")
|
||||
private String subjectPattern;
|
||||
|
||||
@NotBlank(message = "邮件正文类型不能为空")
|
||||
private String bodyType;
|
||||
|
||||
@NotBlank(message = "邮件正文模板不能为空")
|
||||
private String bodyPattern;
|
||||
|
||||
private Long channelId;
|
||||
|
||||
private Boolean enabled = Boolean.TRUE;
|
||||
|
||||
@Size(max = 255, message = "描述不能超过 255 个字符")
|
||||
private String description;
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.xiaowang.messagehub.dto.admin;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
@Data
|
||||
public class EmailTemplateStatusUpdateRequest {
|
||||
|
||||
@NotNull(message = "启用状态不能为空")
|
||||
private Boolean enabled;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.xiaowang.messagehub.dto.admin;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class EmailTemplateView {
|
||||
|
||||
private Long id;
|
||||
|
||||
private String templateCode;
|
||||
|
||||
private String templateName;
|
||||
|
||||
private String subjectPattern;
|
||||
|
||||
private String bodyType;
|
||||
|
||||
private String bodyPattern;
|
||||
|
||||
private Long channelId;
|
||||
|
||||
private String channelName;
|
||||
|
||||
private boolean enabled;
|
||||
|
||||
private String description;
|
||||
|
||||
private List<String> placeholders = new ArrayList<>();
|
||||
|
||||
private LocalDateTime createTime;
|
||||
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.xiaowang.messagehub.dto.admin;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
public class PushLogView {
|
||||
|
||||
private String id;
|
||||
|
||||
private String sourceSystem;
|
||||
|
||||
private String uniqueId;
|
||||
|
||||
private String receiver;
|
||||
|
||||
private String channelType;
|
||||
|
||||
private Long channelId;
|
||||
|
||||
private String providerCode;
|
||||
|
||||
private String msgType;
|
||||
|
||||
private String templateCode;
|
||||
|
||||
private String finalContent;
|
||||
|
||||
private Integer status;
|
||||
|
||||
private Integer retryCount;
|
||||
|
||||
private LocalDateTime nextRetryTime;
|
||||
|
||||
private String failReason;
|
||||
|
||||
private String deadLetterReason;
|
||||
|
||||
private LocalDateTime sendTime;
|
||||
|
||||
private LocalDateTime createTime;
|
||||
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
+2
@@ -24,4 +24,6 @@ public class SourceSystemSaveRequest {
|
||||
private Long defaultSmsChannelId;
|
||||
|
||||
private Long defaultEmailChannelId;
|
||||
|
||||
private Long defaultQqChannelId;
|
||||
}
|
||||
|
||||
@@ -25,6 +25,10 @@ public class SourceSystemView {
|
||||
|
||||
private String defaultEmailChannelName;
|
||||
|
||||
private Long defaultQqChannelId;
|
||||
|
||||
private String defaultQqChannelName;
|
||||
|
||||
private LocalDateTime createTime;
|
||||
|
||||
private LocalDateTime updateTime;
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.xiaowang.messagehub.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@TableName("email_attachment")
|
||||
public class EmailAttachmentDO {
|
||||
|
||||
@TableId(value = "id", type = IdType.ASSIGN_ID)
|
||||
private Long id;
|
||||
|
||||
@TableField("original_file_name")
|
||||
private String originalFileName;
|
||||
|
||||
@TableField("stored_file_name")
|
||||
private String storedFileName;
|
||||
|
||||
@TableField("storage_path")
|
||||
private String storagePath;
|
||||
|
||||
@TableField("content_type")
|
||||
private String contentType;
|
||||
|
||||
@TableField("file_extension")
|
||||
private String fileExtension;
|
||||
|
||||
@TableField("file_size")
|
||||
private Long fileSize;
|
||||
|
||||
@TableField("status")
|
||||
private String status;
|
||||
|
||||
@TableField("expire_time")
|
||||
private LocalDateTime expireTime;
|
||||
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.xiaowang.messagehub.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@TableName("email_attachment_policy")
|
||||
public class EmailAttachmentPolicyDO {
|
||||
|
||||
@TableId(value = "id", type = IdType.INPUT)
|
||||
private Long id;
|
||||
|
||||
@TableField("max_single_file_size")
|
||||
private Long maxSingleFileSize;
|
||||
|
||||
@TableField("max_total_file_size")
|
||||
private Long maxTotalFileSize;
|
||||
|
||||
@TableField("max_file_count")
|
||||
private Integer maxFileCount;
|
||||
|
||||
@TableField("allowed_extensions")
|
||||
private String allowedExtensions;
|
||||
|
||||
@TableField("allowed_mime_types")
|
||||
private String allowedMimeTypes;
|
||||
|
||||
@TableField("retention_days")
|
||||
private Integer retentionDays;
|
||||
|
||||
@TableField("read_timeout_millis")
|
||||
private Integer readTimeoutMillis;
|
||||
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.xiaowang.messagehub.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@TableName("email_template")
|
||||
public class EmailTemplateDO {
|
||||
|
||||
@TableId(value = "id", type = IdType.ASSIGN_ID)
|
||||
private Long id;
|
||||
|
||||
@TableField("template_code")
|
||||
private String templateCode;
|
||||
|
||||
@TableField("template_name")
|
||||
private String templateName;
|
||||
|
||||
@TableField("subject_pattern")
|
||||
private String subjectPattern;
|
||||
|
||||
@TableField("body_type")
|
||||
private String bodyType;
|
||||
|
||||
@TableField("body_pattern")
|
||||
private String bodyPattern;
|
||||
|
||||
@TableField("channel_id")
|
||||
private Long channelId;
|
||||
|
||||
@TableField("is_enable")
|
||||
private Integer isEnable;
|
||||
|
||||
@TableField("description")
|
||||
private String description;
|
||||
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
@@ -29,6 +29,12 @@ public class PushLogDO {
|
||||
@TableField("channel_type")
|
||||
private String channelType; // 推送渠道类型,如短信、邮件等
|
||||
|
||||
@TableField("channel_id")
|
||||
private Long channelId;
|
||||
|
||||
@TableField("provider_code")
|
||||
private String providerCode;
|
||||
|
||||
@TableField("msg_type")
|
||||
private String msgType; // 消息类型,如通知、验证码等
|
||||
|
||||
@@ -47,12 +53,27 @@ public class PushLogDO {
|
||||
@TableField("retry_count")
|
||||
private Integer retryCount; // 重试次数
|
||||
|
||||
@TableField("next_retry_time")
|
||||
private LocalDateTime nextRetryTime;
|
||||
|
||||
@TableField("fail_reason")
|
||||
private String failReason; // 失败原因描述
|
||||
|
||||
@TableField("dead_letter_reason")
|
||||
private String deadLetterReason;
|
||||
|
||||
@TableField("request_payload")
|
||||
private String requestPayload;
|
||||
|
||||
@TableField("provider_response")
|
||||
private String providerResponse;
|
||||
|
||||
@TableField("send_time")
|
||||
private LocalDateTime sendTime; // 消息发送时间
|
||||
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT) // 自动填充字段,插入时自动设置当前时间
|
||||
private LocalDateTime createTime; // 记录创建时间
|
||||
|
||||
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
|
||||
+10
-1
@@ -11,7 +11,16 @@ public enum ChannelProviderCodeEnum {
|
||||
MOCK_SMS("MOCK_SMS", ChannelTypeEnum.SMS.getCode(), "开发Mock短信"),
|
||||
GMAIL("GMAIL", ChannelTypeEnum.EMAIL.getCode(), "Gmail SMTP"),
|
||||
QQMAIL("QQMAIL", ChannelTypeEnum.EMAIL.getCode(), "QQ邮箱 SMTP"),
|
||||
MOCK_EMAIL("MOCK_EMAIL", ChannelTypeEnum.EMAIL.getCode(), "开发Mock邮件");
|
||||
NETEASE_163("NETEASE_163", ChannelTypeEnum.EMAIL.getCode(), "网易 163 邮箱 SMTP"),
|
||||
NETEASE_126("NETEASE_126", ChannelTypeEnum.EMAIL.getCode(), "网易 126 邮箱 SMTP"),
|
||||
OUTLOOK("OUTLOOK", ChannelTypeEnum.EMAIL.getCode(), "Outlook SMTP"),
|
||||
HOTMAIL("HOTMAIL", ChannelTypeEnum.EMAIL.getCode(), "Hotmail SMTP"),
|
||||
ALIYUN_ENTERPRISE("ALIYUN_ENTERPRISE", ChannelTypeEnum.EMAIL.getCode(), "阿里企业邮箱 SMTP"),
|
||||
TENCENT_ENTERPRISE("TENCENT_ENTERPRISE", ChannelTypeEnum.EMAIL.getCode(), "腾讯企业邮箱 SMTP"),
|
||||
SMTP_GENERIC("SMTP_GENERIC", ChannelTypeEnum.EMAIL.getCode(), "通用 SMTP"),
|
||||
MOCK_EMAIL("MOCK_EMAIL", ChannelTypeEnum.EMAIL.getCode(), "开发Mock邮件"),
|
||||
QQAUTO("QQAUTO", ChannelTypeEnum.QQ.getCode(), "QQAuto"),
|
||||
MOCK_QQ("MOCK_QQ", ChannelTypeEnum.QQ.getCode(), "开发Mock QQ");
|
||||
|
||||
private final String code;
|
||||
|
||||
|
||||
@@ -8,7 +8,8 @@ import lombok.Getter;
|
||||
public enum ChannelTypeEnum {
|
||||
|
||||
SMS("SMS", "短信"),
|
||||
EMAIL("EMAIL", "邮件");
|
||||
EMAIL("EMAIL", "邮件"),
|
||||
QQ("QQ", "QQ");
|
||||
|
||||
private final String code;
|
||||
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.xiaowang.messagehub.enums;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
public enum EmailBodyTypeEnum {
|
||||
|
||||
TEXT,
|
||||
HTML;
|
||||
|
||||
public static EmailBodyTypeEnum fromCode(String code) {
|
||||
if (code == null || code.trim().isEmpty()) {
|
||||
return TEXT;
|
||||
}
|
||||
return valueOf(code.trim().toUpperCase(Locale.ROOT));
|
||||
}
|
||||
}
|
||||
@@ -2,13 +2,17 @@ package com.xiaowang.messagehub.listener;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.rabbitmq.client.Channel;
|
||||
import com.xiaowang.messagehub.dto.MessageDTO;
|
||||
import com.xiaowang.messagehub.config.RabbitMQConfig;
|
||||
import com.xiaowang.messagehub.dto.EmailMessageDTO;
|
||||
import com.xiaowang.messagehub.model.EmailDispatchRequest;
|
||||
import com.xiaowang.messagehub.model.ManagedChannelConfig;
|
||||
import com.xiaowang.messagehub.service.EmailSendService;
|
||||
import com.xiaowang.messagehub.service.impl.MessageHandleService;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.amqp.core.Message;
|
||||
import org.springframework.amqp.rabbit.annotation.RabbitListener;
|
||||
import org.springframework.amqp.rabbit.core.RabbitTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
@@ -21,13 +25,16 @@ public class EmailQueueListener {
|
||||
private final EmailSendService emailSendService;
|
||||
private final MessageHandleService messageHandleService;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final RabbitTemplate rabbitTemplate;
|
||||
|
||||
public EmailQueueListener(EmailSendService emailSendService,
|
||||
MessageHandleService messageHandleService,
|
||||
ObjectMapper objectMapper) {
|
||||
ObjectMapper objectMapper,
|
||||
RabbitTemplate rabbitTemplate) {
|
||||
this.emailSendService = emailSendService;
|
||||
this.messageHandleService = messageHandleService;
|
||||
this.objectMapper = objectMapper;
|
||||
this.rabbitTemplate = rabbitTemplate;
|
||||
}
|
||||
|
||||
@RabbitListener(queues = "emailQueue", containerFactory = "manualAckRabbitListenerContainerFactory")
|
||||
@@ -44,31 +51,29 @@ public class EmailQueueListener {
|
||||
log.info("消息内容: {}", messageBody);
|
||||
log.info("========================================");
|
||||
|
||||
MessageDTO messageDTO = objectMapper.readValue(messageBody, MessageDTO.class);
|
||||
EmailMessageDTO messageDTO = objectMapper.readValue(messageBody, EmailMessageDTO.class);
|
||||
MessageHandleService.MessageLogDecision decision =
|
||||
messageHandleService.validateAndPrepareLog(messageDTO, messageId, sendTime);
|
||||
messageHandleService.validateAndPrepareLog(messageDTO, messageId, sendTime, messageBody);
|
||||
if (!decision.shouldProcess()) {
|
||||
log.warn("邮件消息无需继续处理,消息ID: {}, reason: {}", messageId, decision.reason());
|
||||
acknowledge(channel, deliveryTag);
|
||||
return;
|
||||
}
|
||||
|
||||
String subject = buildSubject(messageDTO);
|
||||
String content = buildContent(messageDTO);
|
||||
emailSendService.sendEmail(
|
||||
messageDTO.getReceiver(),
|
||||
subject,
|
||||
content,
|
||||
messageDTO.getChannelId(),
|
||||
messageDTO.getSourceSystem()
|
||||
EmailDispatchRequest request = buildDispatchRequest(messageDTO);
|
||||
ManagedChannelConfig dispatchChannel = emailSendService.sendEmail(request);
|
||||
messageHandleService.markDispatchChannel(
|
||||
messageId,
|
||||
dispatchChannel.entity().getId(),
|
||||
dispatchChannel.entity().getProviderCode()
|
||||
);
|
||||
messageHandleService.markSendSuccess(messageId, content);
|
||||
messageHandleService.markSendSuccess(messageId, request.getContent());
|
||||
|
||||
log.info("========================================");
|
||||
log.info("邮件消息处理完成");
|
||||
log.info("消息ID: {}", messageId);
|
||||
log.info("收件人: {}", messageDTO.getReceiver());
|
||||
log.info("主题: {}", subject);
|
||||
log.info("主题: {}", request.getSubject());
|
||||
log.info("========================================");
|
||||
acknowledge(channel, deliveryTag);
|
||||
} catch (JsonProcessingException exception) {
|
||||
@@ -87,19 +92,24 @@ public class EmailQueueListener {
|
||||
}
|
||||
|
||||
messageHandleService.markMessageRejected(messageId, "EMAIL", sendTime, retryDecision.failReason());
|
||||
reject(channel, deliveryTag);
|
||||
publishDeadLetter(message, RabbitMQConfig.EMAIL_DEAD_LETTER_ROUTING_KEY, retryDecision.failReason());
|
||||
acknowledge(channel, deliveryTag);
|
||||
}
|
||||
}
|
||||
|
||||
private String buildSubject(MessageDTO messageDTO) {
|
||||
if (messageDTO.getTemplateCode() != null && !messageDTO.getTemplateCode().isEmpty()) {
|
||||
return "[" + messageDTO.getTemplateCode() + "] " + messageDTO.getMsgType();
|
||||
}
|
||||
return messageDTO.getMsgType();
|
||||
}
|
||||
|
||||
private String buildContent(MessageDTO messageDTO) {
|
||||
return messageHandleService.buildFinalContent(messageDTO.getTemplateCode(), messageDTO.getTemplateParams());
|
||||
private EmailDispatchRequest buildDispatchRequest(EmailMessageDTO messageDTO) {
|
||||
EmailDispatchRequest request = new EmailDispatchRequest();
|
||||
request.setReceiver(messageDTO.getReceiver());
|
||||
request.setSubject(messageDTO.getSubject());
|
||||
request.setContent(messageDTO.getContent());
|
||||
request.setBodyType(messageDTO.getBodyType());
|
||||
request.setEmailTemplateCode(messageDTO.getEmailTemplateCode());
|
||||
request.setLegacyTemplateCode(messageDTO.getTemplateCode());
|
||||
request.setTemplateParams(messageDTO.getTemplateParams());
|
||||
request.setChannelId(messageDTO.getChannelId());
|
||||
request.setSourceSystem(messageDTO.getSourceSystem());
|
||||
request.setAttachmentIds(messageDTO.getAttachmentIds());
|
||||
return request;
|
||||
}
|
||||
|
||||
private void acknowledge(Channel channel, long deliveryTag) {
|
||||
@@ -125,4 +135,13 @@ public class EmailQueueListener {
|
||||
log.error("邮件消息拒绝失败", rejectException);
|
||||
}
|
||||
}
|
||||
|
||||
private void publishDeadLetter(Message message, String routingKey, String reason) {
|
||||
try {
|
||||
message.getMessageProperties().setHeader("x-messagehub-dead-letter-reason", reason);
|
||||
rabbitTemplate.send(RabbitMQConfig.DEAD_LETTER_EXCHANGE, routingKey, message);
|
||||
} catch (Exception exception) {
|
||||
log.error("邮件消息投递死信队列失败", exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
package com.xiaowang.messagehub.listener;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.rabbitmq.client.Channel;
|
||||
import com.xiaowang.messagehub.config.RabbitMQConfig;
|
||||
import com.xiaowang.messagehub.dto.QqMessageDTO;
|
||||
import com.xiaowang.messagehub.model.QqDispatchRequest;
|
||||
import com.xiaowang.messagehub.service.QqSendService;
|
||||
import com.xiaowang.messagehub.service.impl.MessageHandleService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.amqp.core.Message;
|
||||
import org.springframework.amqp.rabbit.annotation.RabbitListener;
|
||||
import org.springframework.amqp.rabbit.core.RabbitTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.LinkedHashMap;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
public class QqQueueListener {
|
||||
|
||||
private final QqSendService qqSendService;
|
||||
private final MessageHandleService messageHandleService;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final RabbitTemplate rabbitTemplate;
|
||||
|
||||
public QqQueueListener(QqSendService qqSendService,
|
||||
MessageHandleService messageHandleService,
|
||||
ObjectMapper objectMapper,
|
||||
RabbitTemplate rabbitTemplate) {
|
||||
this.qqSendService = qqSendService;
|
||||
this.messageHandleService = messageHandleService;
|
||||
this.objectMapper = objectMapper;
|
||||
this.rabbitTemplate = rabbitTemplate;
|
||||
}
|
||||
|
||||
@RabbitListener(queues = "qqQueue", containerFactory = "manualAckRabbitListenerContainerFactory")
|
||||
public void handleQqMessage(Message message, Channel channel) {
|
||||
String messageId = message.getMessageProperties().getMessageId();
|
||||
LocalDateTime sendTime = LocalDateTime.now();
|
||||
long deliveryTag = message.getMessageProperties().getDeliveryTag();
|
||||
|
||||
try {
|
||||
String messageBody = new String(message.getBody(), StandardCharsets.UTF_8);
|
||||
log.info("Received QQ message, messageId: {}, body: {}", messageId, messageBody);
|
||||
|
||||
QqMessageDTO messageDTO = objectMapper.readValue(messageBody, QqMessageDTO.class);
|
||||
MessageHandleService.MessageLogDecision decision =
|
||||
messageHandleService.validateAndPrepareLog(messageDTO, messageId, sendTime, messageBody);
|
||||
if (!decision.shouldProcess()) {
|
||||
log.warn("QQ message skipped, messageId: {}, reason: {}", messageId, decision.reason());
|
||||
acknowledge(channel, deliveryTag);
|
||||
return;
|
||||
}
|
||||
|
||||
QqSendService.QqDispatchResult dispatchResult = qqSendService.sendQq(buildDispatchRequest(messageDTO));
|
||||
messageHandleService.markDispatchChannel(
|
||||
messageId,
|
||||
dispatchResult.channelConfig().entity().getId(),
|
||||
dispatchResult.channelConfig().entity().getProviderCode()
|
||||
);
|
||||
if (dispatchResult.sendResult() != null) {
|
||||
messageHandleService.markProviderResponse(messageId, dispatchResult.sendResult().getRawResponse());
|
||||
}
|
||||
messageHandleService.markSendSuccess(messageId, dispatchResult.finalContent());
|
||||
acknowledge(channel, deliveryTag);
|
||||
} catch (JsonProcessingException exception) {
|
||||
log.error("QQ message JSON parse failed, messageId: {}", messageId, exception);
|
||||
messageHandleService.markMessageRejected(messageId, "QQ", sendTime, "Message body parse failed: " + exception.getOriginalMessage());
|
||||
reject(channel, deliveryTag);
|
||||
} catch (Exception exception) {
|
||||
log.error("QQ message handling failed, messageId: {}", messageId, exception);
|
||||
MessageHandleService.MessageRetryDecision retryDecision =
|
||||
messageHandleService.recordSendFailure(messageId, "QQ", sendTime, exception);
|
||||
if (retryDecision.shouldRetry()) {
|
||||
log.warn("QQ message will retry, messageId: {}, retryCount: {}, reason: {}",
|
||||
messageId, retryDecision.retryCount(), retryDecision.failReason());
|
||||
requeue(channel, deliveryTag);
|
||||
return;
|
||||
}
|
||||
|
||||
messageHandleService.markMessageRejected(messageId, "QQ", sendTime, retryDecision.failReason());
|
||||
publishDeadLetter(message, RabbitMQConfig.QQ_DEAD_LETTER_ROUTING_KEY, retryDecision.failReason());
|
||||
acknowledge(channel, deliveryTag);
|
||||
}
|
||||
}
|
||||
|
||||
private QqDispatchRequest buildDispatchRequest(QqMessageDTO messageDTO) {
|
||||
QqDispatchRequest request = new QqDispatchRequest();
|
||||
request.setReceiver(messageDTO.getReceiver());
|
||||
request.setTargetType(messageDTO.getTargetType());
|
||||
request.setContent(messageDTO.getContent());
|
||||
request.setContentMode(messageDTO.getContentMode());
|
||||
request.setTemplateCode(messageDTO.getTemplateCode());
|
||||
request.setTemplateParams(messageDTO.getTemplateParams() == null ? new LinkedHashMap<>() : new LinkedHashMap<>(messageDTO.getTemplateParams()));
|
||||
request.setChannelId(messageDTO.getChannelId());
|
||||
request.setSourceSystem(messageDTO.getSourceSystem());
|
||||
return request;
|
||||
}
|
||||
|
||||
private void acknowledge(Channel channel, long deliveryTag) {
|
||||
try {
|
||||
channel.basicAck(deliveryTag, false);
|
||||
} catch (Exception ackException) {
|
||||
log.error("QQ message ack failed", ackException);
|
||||
}
|
||||
}
|
||||
|
||||
private void requeue(Channel channel, long deliveryTag) {
|
||||
try {
|
||||
channel.basicNack(deliveryTag, false, true);
|
||||
} catch (Exception nackException) {
|
||||
log.error("QQ message requeue failed", nackException);
|
||||
}
|
||||
}
|
||||
|
||||
private void reject(Channel channel, long deliveryTag) {
|
||||
try {
|
||||
channel.basicReject(deliveryTag, false);
|
||||
} catch (Exception rejectException) {
|
||||
log.error("QQ message reject failed", rejectException);
|
||||
}
|
||||
}
|
||||
|
||||
private void publishDeadLetter(Message message, String routingKey, String reason) {
|
||||
try {
|
||||
message.getMessageProperties().setHeader("x-messagehub-dead-letter-reason", reason);
|
||||
rabbitTemplate.send(RabbitMQConfig.DEAD_LETTER_EXCHANGE, routingKey, message);
|
||||
} catch (Exception exception) {
|
||||
log.error("QQ message dead-letter publish failed", exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package com.xiaowang.messagehub.listener;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.rabbitmq.client.Channel;
|
||||
import com.xiaowang.messagehub.config.RabbitMQConfig;
|
||||
import com.xiaowang.messagehub.dto.SmsMessageDTO;
|
||||
import com.xiaowang.messagehub.service.SmsSendService;
|
||||
import com.xiaowang.messagehub.service.impl.MessageHandleService;
|
||||
@@ -10,6 +11,7 @@ import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.amqp.core.Message;
|
||||
import org.springframework.amqp.rabbit.annotation.RabbitListener;
|
||||
import org.springframework.amqp.rabbit.core.RabbitTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
@@ -23,13 +25,16 @@ public class SmsQueueListener {
|
||||
private final ObjectMapper objectMapper;
|
||||
private final SmsSendService smsSendService;
|
||||
private final MessageHandleService messageHandleService;
|
||||
private final RabbitTemplate rabbitTemplate;
|
||||
|
||||
public SmsQueueListener(ObjectMapper objectMapper,
|
||||
SmsSendService smsSendService,
|
||||
MessageHandleService messageHandleService) {
|
||||
MessageHandleService messageHandleService,
|
||||
RabbitTemplate rabbitTemplate) {
|
||||
this.objectMapper = objectMapper;
|
||||
this.smsSendService = smsSendService;
|
||||
this.messageHandleService = messageHandleService;
|
||||
this.rabbitTemplate = rabbitTemplate;
|
||||
}
|
||||
|
||||
@RabbitListener(queues = "smsQueue", containerFactory = "manualAckRabbitListenerContainerFactory")
|
||||
@@ -85,7 +90,8 @@ public class SmsQueueListener {
|
||||
}
|
||||
|
||||
messageHandleService.markMessageRejected(messageId, "SMS", sendTime, retryDecision.failReason());
|
||||
reject(channel, deliveryTag);
|
||||
publishDeadLetter(message, RabbitMQConfig.SMS_DEAD_LETTER_ROUTING_KEY, retryDecision.failReason());
|
||||
acknowledge(channel, deliveryTag);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,4 +118,13 @@ public class SmsQueueListener {
|
||||
logger.error("短信消息拒绝失败", rejectException);
|
||||
}
|
||||
}
|
||||
|
||||
private void publishDeadLetter(Message message, String routingKey, String reason) {
|
||||
try {
|
||||
message.getMessageProperties().setHeader("x-messagehub-dead-letter-reason", reason);
|
||||
rabbitTemplate.send(RabbitMQConfig.DEAD_LETTER_EXCHANGE, routingKey, message);
|
||||
} catch (Exception exception) {
|
||||
logger.error("短信消息投递死信队列失败", exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.xiaowang.messagehub.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.xiaowang.messagehub.entity.EmailAttachmentDO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface EmailAttachmentMapper extends BaseMapper<EmailAttachmentDO> {
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.xiaowang.messagehub.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.xiaowang.messagehub.entity.EmailAttachmentPolicyDO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface EmailAttachmentPolicyMapper extends BaseMapper<EmailAttachmentPolicyDO> {
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.xiaowang.messagehub.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.xiaowang.messagehub.entity.EmailTemplateDO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Mapper
|
||||
public interface EmailTemplateMapper extends BaseMapper<EmailTemplateDO> {
|
||||
|
||||
@Select("SELECT * FROM email_template WHERE template_code = #{templateCode} LIMIT 1")
|
||||
EmailTemplateDO selectByTemplateCode(@Param("templateCode") String templateCode);
|
||||
|
||||
@Select("SELECT * FROM email_template ORDER BY create_time DESC")
|
||||
List<EmailTemplateDO> selectAllTemplates();
|
||||
|
||||
@Select("SELECT * FROM email_template WHERE is_enable = 1 ORDER BY create_time DESC")
|
||||
List<EmailTemplateDO> selectEnabledTemplates();
|
||||
}
|
||||
@@ -75,6 +75,9 @@ public interface PushLogMapper extends BaseMapper<PushLogDO> {
|
||||
@Select("SELECT * FROM push_log WHERE unique_id = #{uniqueId} ORDER BY create_time DESC LIMIT 1")
|
||||
PushLogDO selectByUniqueId(@Param("uniqueId") String uniqueId);
|
||||
|
||||
@Select("SELECT * FROM push_log WHERE source_system = #{sourceSystem} AND unique_id = #{uniqueId} ORDER BY create_time DESC LIMIT 1")
|
||||
PushLogDO selectBySourceSystemAndUniqueId(@Param("sourceSystem") String sourceSystem, @Param("uniqueId") String uniqueId);
|
||||
|
||||
/**
|
||||
* 更新推送日志的重试状态
|
||||
* @param ID 日志ID
|
||||
@@ -82,8 +85,12 @@ public interface PushLogMapper extends BaseMapper<PushLogDO> {
|
||||
* @param failReason 失败原因
|
||||
* @return 更新的记录数
|
||||
*/
|
||||
@Update("UPDATE push_log SET status = #{status}, retry_count = retry_count + 1, fail_reason = #{failReason} WHERE id = #{id}")
|
||||
int updateRetryStatus(@Param("id") String id, @Param("status") Integer status, @Param("failReason") String failReason);
|
||||
@Update("UPDATE push_log SET status = #{status}, retry_count = retry_count + 1, fail_reason = #{failReason}, next_retry_time = #{nextRetryTime}, dead_letter_reason = #{deadLetterReason} WHERE id = #{id}")
|
||||
int updateRetryStatus(@Param("id") String id,
|
||||
@Param("status") Integer status,
|
||||
@Param("failReason") String failReason,
|
||||
@Param("nextRetryTime") LocalDateTime nextRetryTime,
|
||||
@Param("deadLetterReason") String deadLetterReason);
|
||||
|
||||
/**
|
||||
* 更新推送日志的最终内容
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.xiaowang.messagehub.model;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
public record EmailAttachmentResource(
|
||||
Long id,
|
||||
String originalFileName,
|
||||
String contentType,
|
||||
long fileSize,
|
||||
Path storagePath
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.xiaowang.messagehub.model;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Data
|
||||
public class EmailDispatchRequest {
|
||||
|
||||
private String receiver;
|
||||
|
||||
private String subject;
|
||||
|
||||
private String content;
|
||||
|
||||
private String bodyType;
|
||||
|
||||
private String emailTemplateCode;
|
||||
|
||||
private String legacyTemplateCode;
|
||||
|
||||
private Map<String, Object> templateParams = new LinkedHashMap<>();
|
||||
|
||||
private Long channelId;
|
||||
|
||||
private String sourceSystem;
|
||||
|
||||
private List<Long> attachmentIds = new ArrayList<>();
|
||||
|
||||
private List<EmailAttachmentResource> attachments = new ArrayList<>();
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.xiaowang.messagehub.model;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
public class EmailRenderResult {
|
||||
|
||||
private String subject;
|
||||
|
||||
private String content;
|
||||
|
||||
private String bodyType;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.xiaowang.messagehub.model;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Data
|
||||
public class QqDispatchRequest {
|
||||
|
||||
private String receiver;
|
||||
|
||||
private String targetType;
|
||||
|
||||
private String content;
|
||||
|
||||
private String contentMode;
|
||||
|
||||
private String templateCode;
|
||||
|
||||
private Map<String, Object> templateParams = new LinkedHashMap<>();
|
||||
|
||||
private Long channelId;
|
||||
|
||||
private String sourceSystem;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.xiaowang.messagehub.model;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class QqSendResult {
|
||||
|
||||
private String requestId;
|
||||
|
||||
private String messageId;
|
||||
|
||||
private String message;
|
||||
|
||||
private String rawResponse;
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.xiaowang.messagehub.service;
|
||||
|
||||
import com.xiaowang.messagehub.model.EmailDispatchRequest;
|
||||
import com.xiaowang.messagehub.model.ManagedChannelConfig;
|
||||
import com.xiaowang.messagehub.service.channel.MessageChannelService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -28,4 +30,14 @@ public class EmailSendService {
|
||||
to, subject, channelId, sourceSystem);
|
||||
messageChannelService.sendEmail(to, subject, content, channelId, sourceSystem);
|
||||
}
|
||||
|
||||
public ManagedChannelConfig sendEmail(EmailDispatchRequest request) {
|
||||
log.info("Preparing email dispatch, receiver: {}, subject: {}, channelId: {}, sourceSystem: {}, attachments: {}",
|
||||
request.getReceiver(),
|
||||
request.getSubject(),
|
||||
request.getChannelId(),
|
||||
request.getSourceSystem(),
|
||||
request.getAttachmentIds());
|
||||
return messageChannelService.sendEmail(request);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.xiaowang.messagehub.service;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xiaowang.messagehub.config.RabbitMQConfig;
|
||||
import com.xiaowang.messagehub.dto.MessageDTO;
|
||||
import com.xiaowang.messagehub.dto.QqMessageDTO;
|
||||
import com.xiaowang.messagehub.dto.SmsMessageDTO;
|
||||
import com.xiaowang.messagehub.support.id.TimeOrderedSnowflakeIdGenerator;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -91,6 +92,36 @@ public class MessageProducerService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送 QQ 消息。
|
||||
*/
|
||||
public void sendQqMessage(QqMessageDTO messageDTO) {
|
||||
try {
|
||||
String messageId = snowflakeIdGenerator.nextIdString();
|
||||
ensureUniqueId(messageDTO, messageId);
|
||||
|
||||
String messageBody = objectMapper.writeValueAsString(messageDTO);
|
||||
Message message = MessageBuilder
|
||||
.withBody(messageBody.getBytes())
|
||||
.setContentType(MessageProperties.CONTENT_TYPE_JSON)
|
||||
.setMessageId(messageId)
|
||||
.setTimestamp(new java.util.Date())
|
||||
.build();
|
||||
|
||||
rabbitTemplate.send(
|
||||
RabbitMQConfig.MESSAGE_EXCHANGE,
|
||||
"qq." + messageDTO.getMsgType().toLowerCase(),
|
||||
message
|
||||
);
|
||||
|
||||
log.info("QQ message sent to queue, messageId: {}, receiver: {}, msgType: {}",
|
||||
messageId, messageDTO.getReceiver(), messageDTO.getMsgType());
|
||||
} catch (Exception exception) {
|
||||
log.error("Failed to send QQ message", exception);
|
||||
throw new RuntimeException("Failed to send QQ message: " + exception.getMessage(), exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送微信消息。
|
||||
*/
|
||||
@@ -174,6 +205,8 @@ public class MessageProducerService {
|
||||
routingKey = "sms." + messageDTO.getMsgType().toLowerCase();
|
||||
} else if ("EMAIL".equalsIgnoreCase(channelType)) {
|
||||
routingKey = "email." + messageDTO.getMsgType().toLowerCase();
|
||||
} else if ("QQ".equalsIgnoreCase(channelType)) {
|
||||
routingKey = "qq." + messageDTO.getMsgType().toLowerCase();
|
||||
} else if ("WECHAT".equalsIgnoreCase(channelType)) {
|
||||
routingKey = "wechat." + messageDTO.getMsgType().toLowerCase();
|
||||
} else if ("PUSH".equalsIgnoreCase(channelType)) {
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.xiaowang.messagehub.service;
|
||||
|
||||
import com.xiaowang.messagehub.model.ManagedChannelConfig;
|
||||
import com.xiaowang.messagehub.model.QqDispatchRequest;
|
||||
import com.xiaowang.messagehub.model.QqSendResult;
|
||||
import com.xiaowang.messagehub.service.channel.MessageChannelService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class QqSendService {
|
||||
|
||||
private final MessageChannelService messageChannelService;
|
||||
|
||||
public QqSendService(MessageChannelService messageChannelService) {
|
||||
this.messageChannelService = messageChannelService;
|
||||
}
|
||||
|
||||
public QqDispatchResult sendQq(QqDispatchRequest request) {
|
||||
log.info("Preparing QQ dispatch, receiver: {}, targetType: {}, channelId: {}, sourceSystem: {}",
|
||||
request.getReceiver(),
|
||||
request.getTargetType(),
|
||||
request.getChannelId(),
|
||||
request.getSourceSystem());
|
||||
return messageChannelService.sendQq(request);
|
||||
}
|
||||
|
||||
public record QqDispatchResult(ManagedChannelConfig channelConfig, QqSendResult sendResult, String finalContent) {
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
package com.xiaowang.messagehub.service.admin;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.xiaowang.messagehub.dto.admin.PushLogView;
|
||||
import com.xiaowang.messagehub.entity.PushLogDO;
|
||||
import com.xiaowang.messagehub.mapper.PushLogMapper;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class PushLogAdminService {
|
||||
|
||||
private final PushLogMapper pushLogMapper;
|
||||
|
||||
public PushLogAdminService(PushLogMapper pushLogMapper) {
|
||||
this.pushLogMapper = pushLogMapper;
|
||||
}
|
||||
|
||||
public List<PushLogView> listLogs(String sourceSystem,
|
||||
String channelType,
|
||||
Integer status,
|
||||
String keyword,
|
||||
Boolean deadLetter,
|
||||
int limit) {
|
||||
LambdaQueryWrapper<PushLogDO> wrapper = new LambdaQueryWrapper<>();
|
||||
if (StringUtils.hasText(sourceSystem)) {
|
||||
wrapper.eq(PushLogDO::getSourceSystem, sourceSystem.trim());
|
||||
}
|
||||
if (StringUtils.hasText(channelType)) {
|
||||
wrapper.eq(PushLogDO::getChannelType, channelType.trim().toUpperCase());
|
||||
}
|
||||
if (status != null) {
|
||||
wrapper.eq(PushLogDO::getStatus, status);
|
||||
}
|
||||
if (Boolean.TRUE.equals(deadLetter)) {
|
||||
wrapper.isNotNull(PushLogDO::getDeadLetterReason);
|
||||
}
|
||||
if (StringUtils.hasText(keyword)) {
|
||||
String value = keyword.trim();
|
||||
wrapper.and(item -> item.like(PushLogDO::getReceiver, value)
|
||||
.or()
|
||||
.like(PushLogDO::getUniqueId, value)
|
||||
.or()
|
||||
.like(PushLogDO::getTemplateCode, value)
|
||||
.or()
|
||||
.like(PushLogDO::getFailReason, value)
|
||||
.or()
|
||||
.like(PushLogDO::getDeadLetterReason, value));
|
||||
}
|
||||
wrapper.orderByDesc(PushLogDO::getCreateTime).last("LIMIT " + Math.max(1, Math.min(limit, 200)));
|
||||
return pushLogMapper.selectList(wrapper).stream().map(this::toView).toList();
|
||||
}
|
||||
|
||||
private PushLogView toView(PushLogDO entity) {
|
||||
PushLogView view = new PushLogView();
|
||||
view.setId(entity.getId());
|
||||
view.setSourceSystem(entity.getSourceSystem());
|
||||
view.setUniqueId(entity.getUniqueId());
|
||||
view.setReceiver(entity.getReceiver());
|
||||
view.setChannelType(entity.getChannelType());
|
||||
view.setChannelId(entity.getChannelId());
|
||||
view.setProviderCode(entity.getProviderCode());
|
||||
view.setMsgType(entity.getMsgType());
|
||||
view.setTemplateCode(entity.getTemplateCode());
|
||||
view.setFinalContent(entity.getFinalContent());
|
||||
view.setStatus(entity.getStatus());
|
||||
view.setRetryCount(entity.getRetryCount());
|
||||
view.setNextRetryTime(entity.getNextRetryTime());
|
||||
view.setFailReason(entity.getFailReason());
|
||||
view.setDeadLetterReason(entity.getDeadLetterReason());
|
||||
view.setSendTime(entity.getSendTime());
|
||||
view.setCreateTime(entity.getCreateTime());
|
||||
view.setUpdateTime(entity.getUpdateTime());
|
||||
return view;
|
||||
}
|
||||
}
|
||||
+267
-6
@@ -19,11 +19,19 @@ import com.xiaowang.messagehub.enums.ChannelTypeEnum;
|
||||
import com.xiaowang.messagehub.mapper.MessageChannelConfigMapper;
|
||||
import com.xiaowang.messagehub.mapper.PushTemplateMapper;
|
||||
import com.xiaowang.messagehub.model.ChannelHealthCheckResult;
|
||||
import com.xiaowang.messagehub.model.EmailDispatchRequest;
|
||||
import com.xiaowang.messagehub.model.EmailRenderResult;
|
||||
import com.xiaowang.messagehub.model.ManagedChannelConfig;
|
||||
import com.xiaowang.messagehub.model.QqDispatchRequest;
|
||||
import com.xiaowang.messagehub.model.QqSendResult;
|
||||
import com.xiaowang.messagehub.model.SmsDispatchRequest;
|
||||
import com.xiaowang.messagehub.model.SmsSendResult;
|
||||
import com.xiaowang.messagehub.service.QqSendService;
|
||||
import com.xiaowang.messagehub.service.channel.email.EmailChannelProvider;
|
||||
import com.xiaowang.messagehub.service.channel.qq.QqChannelProvider;
|
||||
import com.xiaowang.messagehub.service.channel.sms.SmsChannelProvider;
|
||||
import com.xiaowang.messagehub.service.email.AttachmentStorageService;
|
||||
import com.xiaowang.messagehub.service.email.EmailTemplateService;
|
||||
import com.xiaowang.messagehub.service.source.MessageSourceSystemService;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
@@ -60,7 +68,10 @@ public class MessageChannelService {
|
||||
private final MessageChannelProperties properties;
|
||||
private final List<EmailChannelProvider> emailProviders;
|
||||
private final List<SmsChannelProvider> smsProviders;
|
||||
private final List<QqChannelProvider> qqProviders;
|
||||
private final MessageSourceSystemService sourceSystemService;
|
||||
private final EmailTemplateService emailTemplateService;
|
||||
private final AttachmentStorageService attachmentStorageService;
|
||||
|
||||
public MessageChannelService(MessageChannelConfigMapper channelConfigMapper,
|
||||
PushTemplateMapper pushTemplateMapper,
|
||||
@@ -70,7 +81,10 @@ public class MessageChannelService {
|
||||
MessageChannelProperties properties,
|
||||
List<EmailChannelProvider> emailProviders,
|
||||
List<SmsChannelProvider> smsProviders,
|
||||
MessageSourceSystemService sourceSystemService) {
|
||||
List<QqChannelProvider> qqProviders,
|
||||
MessageSourceSystemService sourceSystemService,
|
||||
EmailTemplateService emailTemplateService,
|
||||
AttachmentStorageService attachmentStorageService) {
|
||||
this.channelConfigMapper = channelConfigMapper;
|
||||
this.pushTemplateMapper = pushTemplateMapper;
|
||||
this.objectMapper = objectMapper;
|
||||
@@ -79,7 +93,10 @@ public class MessageChannelService {
|
||||
this.properties = properties;
|
||||
this.emailProviders = emailProviders;
|
||||
this.smsProviders = smsProviders;
|
||||
this.qqProviders = qqProviders;
|
||||
this.sourceSystemService = sourceSystemService;
|
||||
this.emailTemplateService = emailTemplateService;
|
||||
this.attachmentStorageService = attachmentStorageService;
|
||||
}
|
||||
|
||||
public List<ChannelConfigView> listChannels() {
|
||||
@@ -116,6 +133,21 @@ public class MessageChannelService {
|
||||
.toList();
|
||||
}
|
||||
|
||||
public List<ChannelSmsTemplateView> listQqTemplates() {
|
||||
List<PushTemplateDO> templates = pushTemplateMapper.selectByChannelType(ChannelTypeEnum.QQ.getCode());
|
||||
Set<Long> channelIds = new LinkedHashSet<>();
|
||||
for (PushTemplateDO template : templates) {
|
||||
if (template.getChannelId() != null) {
|
||||
channelIds.add(template.getChannelId());
|
||||
}
|
||||
}
|
||||
Map<Long, MessageChannelConfigDO> channelMap = fetchChannelMap(channelIds);
|
||||
return templates.stream()
|
||||
.sorted(Comparator.comparing(PushTemplateDO::getId, Comparator.nullsLast(Long::compareTo)))
|
||||
.map(template -> toSmsTemplateView(template, channelMap.get(template.getChannelId())))
|
||||
.toList();
|
||||
}
|
||||
|
||||
public ChannelConfigView getChannel(Long id) {
|
||||
return toView(requireChannel(id));
|
||||
}
|
||||
@@ -144,6 +176,30 @@ public class MessageChannelService {
|
||||
return buildSmsTemplateView(requireSmsTemplate(id));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ChannelSmsTemplateView createQqTemplate(ChannelSmsTemplateSaveRequest request) {
|
||||
PushTemplateDO entity = new PushTemplateDO();
|
||||
applyQqTemplateRequest(entity, request, null);
|
||||
pushTemplateMapper.insert(entity);
|
||||
return buildSmsTemplateView(requireQqTemplate(entity.getId()));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ChannelSmsTemplateView updateQqTemplate(Long id, ChannelSmsTemplateSaveRequest request) {
|
||||
PushTemplateDO entity = requireQqTemplate(id);
|
||||
applyQqTemplateRequest(entity, request, id);
|
||||
pushTemplateMapper.updateById(entity);
|
||||
return buildSmsTemplateView(requireQqTemplate(id));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ChannelSmsTemplateView updateQqTemplateStatus(Long id, boolean enabled) {
|
||||
PushTemplateDO entity = requireQqTemplate(id);
|
||||
entity.setIsEnable(enabled ? 1 : 0);
|
||||
pushTemplateMapper.updateById(entity);
|
||||
return buildSmsTemplateView(requireQqTemplate(id));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ChannelConfigView createChannel(ChannelConfigSaveRequest request) {
|
||||
validateProvider(request.getChannelType(), request.getProviderCode());
|
||||
@@ -208,18 +264,46 @@ public class MessageChannelService {
|
||||
}
|
||||
ensureMockChannel(ChannelTypeEnum.SMS, ChannelProviderCodeEnum.MOCK_SMS, "开发环境 Mock 短信通道");
|
||||
ensureMockChannel(ChannelTypeEnum.EMAIL, ChannelProviderCodeEnum.MOCK_EMAIL, "开发环境 Mock 邮件通道");
|
||||
ensureMockChannel(ChannelTypeEnum.QQ, ChannelProviderCodeEnum.MOCK_QQ, "开发环境 Mock QQ 通道");
|
||||
}
|
||||
|
||||
public String sendTest(ChannelConfigTestRequest request) {
|
||||
ManagedChannelConfig channelConfig = buildManagedChannel(requireChannel(request.getChannelId()));
|
||||
ChannelTypeEnum channelType = ChannelTypeEnum.fromCode(channelConfig.entity().getChannelType());
|
||||
if (channelType == ChannelTypeEnum.EMAIL) {
|
||||
String subject = StringUtils.hasText(request.getSubject()) ? request.getSubject() : "MessageHub 测试邮件";
|
||||
String content = StringUtils.hasText(request.getContent()) ? request.getContent() : "这是一封来自 MessageHub 的测试邮件。";
|
||||
resolveEmailProvider(channelConfig.entity().getProviderCode()).send(channelConfig, request.getReceiver(), subject, content);
|
||||
EmailDispatchRequest emailRequest = new EmailDispatchRequest();
|
||||
emailRequest.setReceiver(request.getReceiver());
|
||||
emailRequest.setSubject(request.getSubject());
|
||||
emailRequest.setContent(request.getContent());
|
||||
emailRequest.setBodyType(request.getBodyType());
|
||||
emailRequest.setEmailTemplateCode(request.getTemplateCode());
|
||||
emailRequest.setTemplateParams(request.getTemplateParams() == null ? new LinkedHashMap<>() : new LinkedHashMap<>(request.getTemplateParams()));
|
||||
emailRequest.setAttachmentIds(request.getAttachmentIds());
|
||||
prepareEmailRequest(channelConfig, emailRequest);
|
||||
resolveEmailProvider(channelConfig.entity().getProviderCode()).send(channelConfig, emailRequest);
|
||||
return "邮件测试发送成功";
|
||||
}
|
||||
|
||||
if (channelType == ChannelTypeEnum.QQ) {
|
||||
QqDispatchRequest qqRequest = new QqDispatchRequest();
|
||||
qqRequest.setReceiver(request.getReceiver());
|
||||
qqRequest.setTargetType(request.getTargetType());
|
||||
qqRequest.setContent(request.getContent());
|
||||
qqRequest.setContentMode(request.getContentMode());
|
||||
qqRequest.setTemplateCode(request.getTemplateCode());
|
||||
qqRequest.setTemplateParams(request.getTemplateParams() == null ? new LinkedHashMap<>() : new LinkedHashMap<>(request.getTemplateParams()));
|
||||
qqRequest.setChannelId(request.getChannelId());
|
||||
QqSendService.QqDispatchResult dispatchResult = sendQq(qqRequest);
|
||||
QqSendResult sendResult = dispatchResult.sendResult();
|
||||
if (sendResult != null && StringUtils.hasText(sendResult.getMessageId())) {
|
||||
return "QQ 测试发送成功,消息ID: " + sendResult.getMessageId();
|
||||
}
|
||||
if (sendResult != null && StringUtils.hasText(sendResult.getRequestId())) {
|
||||
return "QQ 测试发送成功,请求ID: " + sendResult.getRequestId();
|
||||
}
|
||||
return "QQ 测试发送成功";
|
||||
}
|
||||
|
||||
SmsDispatchRequest smsDispatchRequest = new SmsDispatchRequest();
|
||||
smsDispatchRequest.setReceiver(request.getReceiver());
|
||||
PushTemplateDO template = requireEnabledTemplate(request.getTemplateCode());
|
||||
@@ -257,8 +341,20 @@ public class MessageChannelService {
|
||||
}
|
||||
|
||||
public void sendEmail(String to, String subject, String content, Long channelId, String sourceSystem) {
|
||||
ManagedChannelConfig channelConfig = resolveDispatchChannel(ChannelTypeEnum.EMAIL, channelId, sourceSystem);
|
||||
resolveEmailProvider(channelConfig.entity().getProviderCode()).send(channelConfig, to, subject, content);
|
||||
EmailDispatchRequest request = new EmailDispatchRequest();
|
||||
request.setReceiver(to);
|
||||
request.setSubject(subject);
|
||||
request.setContent(content);
|
||||
request.setChannelId(channelId);
|
||||
request.setSourceSystem(sourceSystem);
|
||||
sendEmail(request);
|
||||
}
|
||||
|
||||
public ManagedChannelConfig sendEmail(EmailDispatchRequest request) {
|
||||
ManagedChannelConfig channelConfig = resolveDispatchChannel(ChannelTypeEnum.EMAIL, request.getChannelId(), request.getSourceSystem());
|
||||
prepareEmailRequest(channelConfig, request);
|
||||
resolveEmailProvider(channelConfig.entity().getProviderCode()).send(channelConfig, request);
|
||||
return channelConfig;
|
||||
}
|
||||
|
||||
public void sendSms(SmsDispatchRequest request) {
|
||||
@@ -283,11 +379,67 @@ public class MessageChannelService {
|
||||
resolveSmsProvider(channelConfig.entity().getProviderCode()).send(channelConfig, request);
|
||||
}
|
||||
|
||||
public QqSendService.QqDispatchResult sendQq(QqDispatchRequest request) {
|
||||
ManagedChannelConfig channelConfig = resolveDispatchChannel(ChannelTypeEnum.QQ, request.getChannelId(), request.getSourceSystem());
|
||||
prepareQqRequest(channelConfig, request);
|
||||
QqSendResult sendResult = resolveQqProvider(channelConfig.entity().getProviderCode()).send(channelConfig, request);
|
||||
return new QqSendService.QqDispatchResult(channelConfig, sendResult, request.getContent());
|
||||
}
|
||||
|
||||
private void prepareQqRequest(ManagedChannelConfig channelConfig, QqDispatchRequest request) {
|
||||
if (request.getTemplateParams() == null) {
|
||||
request.setTemplateParams(new LinkedHashMap<>());
|
||||
}
|
||||
resolveQqTarget(channelConfig, request);
|
||||
request.setContentMode(resolveQqContentMode(channelConfig, request.getContentMode()));
|
||||
|
||||
Map<String, Object> templateParams = new LinkedHashMap<>(request.getTemplateParams());
|
||||
if (StringUtils.hasText(request.getContent())) {
|
||||
validateInlineTemplateParams(request.getContent(), templateParams);
|
||||
request.setContent(renderTemplateContent(request.getContent(), templateParams));
|
||||
return;
|
||||
}
|
||||
|
||||
PushTemplateDO template = requireEnabledTemplate(request.getTemplateCode());
|
||||
if (!ChannelTypeEnum.QQ.getCode().equalsIgnoreCase(template.getChannelType())) {
|
||||
throw new IllegalArgumentException("QQ template expected: " + request.getTemplateCode());
|
||||
}
|
||||
validateTemplateChannelBinding(template, channelConfig.entity().getId());
|
||||
validateTemplateParams(template, templateParams);
|
||||
request.setTemplateCode(template.getTemplateCode());
|
||||
request.setTemplateParams(templateParams);
|
||||
request.setContent(renderTemplateContent(template.getContentPattern(), templateParams));
|
||||
}
|
||||
|
||||
private void prepareEmailRequest(ManagedChannelConfig channelConfig, EmailDispatchRequest request) {
|
||||
if (request.getTemplateParams() == null) {
|
||||
request.setTemplateParams(new LinkedHashMap<>());
|
||||
}
|
||||
if (!StringUtils.hasText(request.getEmailTemplateCode()) && StringUtils.hasText(request.getLegacyTemplateCode())) {
|
||||
request.setEmailTemplateCode(request.getLegacyTemplateCode());
|
||||
}
|
||||
emailTemplateService.validateTemplateChannelBinding(request.getEmailTemplateCode(), channelConfig.entity().getId());
|
||||
EmailRenderResult renderResult = emailTemplateService.render(
|
||||
request.getSubject(),
|
||||
request.getContent(),
|
||||
request.getBodyType(),
|
||||
request.getEmailTemplateCode(),
|
||||
request.getTemplateParams()
|
||||
);
|
||||
request.setSubject(renderResult.getSubject());
|
||||
request.setContent(renderResult.getContent());
|
||||
request.setBodyType(renderResult.getBodyType());
|
||||
request.setAttachments(attachmentStorageService.resolveResources(request.getAttachmentIds()));
|
||||
}
|
||||
|
||||
private ChannelHealthCheckResult checkHealth(ManagedChannelConfig channelConfig) {
|
||||
ChannelTypeEnum channelType = ChannelTypeEnum.fromCode(channelConfig.entity().getChannelType());
|
||||
if (channelType == ChannelTypeEnum.EMAIL) {
|
||||
return resolveEmailProvider(channelConfig.entity().getProviderCode()).checkHealth(channelConfig);
|
||||
}
|
||||
if (channelType == ChannelTypeEnum.QQ) {
|
||||
return resolveQqProvider(channelConfig.entity().getProviderCode()).checkHealth(channelConfig);
|
||||
}
|
||||
return resolveSmsProvider(channelConfig.entity().getProviderCode()).checkHealth(channelConfig);
|
||||
}
|
||||
|
||||
@@ -307,6 +459,8 @@ public class MessageChannelService {
|
||||
ManagedChannelConfig managedChannelConfig = new ManagedChannelConfig(target, mergedConfig, mergedSecretConfig);
|
||||
if (channelType == ChannelTypeEnum.EMAIL) {
|
||||
resolveEmailProvider(provider.getCode()).validate(managedChannelConfig);
|
||||
} else if (channelType == ChannelTypeEnum.QQ) {
|
||||
resolveQqProvider(provider.getCode()).validate(managedChannelConfig);
|
||||
} else {
|
||||
resolveSmsProvider(provider.getCode()).validate(managedChannelConfig);
|
||||
}
|
||||
@@ -369,6 +523,14 @@ public class MessageChannelService {
|
||||
return entity;
|
||||
}
|
||||
|
||||
private PushTemplateDO requireQqTemplate(Long id) {
|
||||
PushTemplateDO entity = pushTemplateMapper.selectById(id);
|
||||
if (entity == null || !ChannelTypeEnum.QQ.getCode().equalsIgnoreCase(entity.getChannelType())) {
|
||||
throw new IllegalArgumentException("QQ template not found: " + id);
|
||||
}
|
||||
return entity;
|
||||
}
|
||||
|
||||
private void applySmsTemplateRequest(PushTemplateDO target,
|
||||
ChannelSmsTemplateSaveRequest request,
|
||||
Long currentId) {
|
||||
@@ -390,6 +552,27 @@ public class MessageChannelService {
|
||||
target.setDescription(trimToNull(request.getDescription()));
|
||||
}
|
||||
|
||||
private void applyQqTemplateRequest(PushTemplateDO target,
|
||||
ChannelSmsTemplateSaveRequest request,
|
||||
Long currentId) {
|
||||
String templateCode = resolveQqTemplateCode(request.getTemplateCode(), target.getTemplateCode());
|
||||
PushTemplateDO existing = pushTemplateMapper.selectByTemplateCode(templateCode);
|
||||
if (existing != null && !Objects.equals(existing.getId(), currentId)) {
|
||||
throw new IllegalArgumentException("Template code already exists: " + templateCode);
|
||||
}
|
||||
|
||||
target.setTemplateCode(templateCode);
|
||||
target.setTemplateName(requireTrimmedText(request.getTemplateName(), "Template name is required"));
|
||||
target.setChannelType(ChannelTypeEnum.QQ.getCode());
|
||||
target.setMsgType(request.getMsgType() == null ? 1 : request.getMsgType());
|
||||
target.setMsgCategory(request.getMsgCategory() == null ? 1 : request.getMsgCategory());
|
||||
target.setChannelId(requireQqTemplateBoundChannel(request.getChannelId()));
|
||||
target.setExternalId(trimToNull(request.getExternalId()));
|
||||
target.setContentPattern(requireTrimmedText(request.getContentPattern(), "Template content is required"));
|
||||
target.setIsEnable(Boolean.TRUE.equals(request.getEnabled()) ? 1 : 0);
|
||||
target.setDescription(trimToNull(request.getDescription()));
|
||||
}
|
||||
|
||||
private String resolveSmsTemplateCode(String requestedTemplateCode, String existingTemplateCode) {
|
||||
if (StringUtils.hasText(existingTemplateCode)) {
|
||||
return existingTemplateCode;
|
||||
@@ -397,6 +580,16 @@ public class MessageChannelService {
|
||||
return generateUniqueSmsTemplateCode();
|
||||
}
|
||||
|
||||
private String resolveQqTemplateCode(String requestedTemplateCode, String existingTemplateCode) {
|
||||
if (StringUtils.hasText(existingTemplateCode)) {
|
||||
return existingTemplateCode;
|
||||
}
|
||||
if (StringUtils.hasText(requestedTemplateCode)) {
|
||||
return requestedTemplateCode.trim();
|
||||
}
|
||||
return "QQ" + generateUniqueSmsTemplateCode().substring(0, 14);
|
||||
}
|
||||
|
||||
private String generateUniqueSmsTemplateCode() {
|
||||
for (int attempt = 0; attempt < 20; attempt++) {
|
||||
String candidate = buildRandomSmsTemplateCode();
|
||||
@@ -503,6 +696,13 @@ public class MessageChannelService {
|
||||
.orElseThrow(() -> new IllegalArgumentException("短信提供商不存在: " + providerCode));
|
||||
}
|
||||
|
||||
private QqChannelProvider resolveQqProvider(String providerCode) {
|
||||
return qqProviders.stream()
|
||||
.filter(provider -> provider.supports(providerCode))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new IllegalArgumentException("QQ provider not found: " + providerCode));
|
||||
}
|
||||
|
||||
private void validateProvider(String channelType, String providerCode) {
|
||||
ChannelTypeEnum typeEnum = ChannelTypeEnum.fromCode(channelType);
|
||||
ChannelProviderCodeEnum providerCodeEnum = ChannelProviderCodeEnum.fromCode(providerCode);
|
||||
@@ -593,6 +793,46 @@ public class MessageChannelService {
|
||||
return requireTemplateExternalId(requireEnabledTemplate(templateCode));
|
||||
}
|
||||
|
||||
private void resolveQqTarget(ManagedChannelConfig channelConfig, QqDispatchRequest request) {
|
||||
String receiver = requireTrimmedText(request.getReceiver(), "QQ receiver is required");
|
||||
String targetType = trimToNull(request.getTargetType());
|
||||
String lowerReceiver = receiver.toLowerCase(Locale.ROOT);
|
||||
if (lowerReceiver.startsWith("group:")) {
|
||||
targetType = "GROUP";
|
||||
receiver = receiver.substring("group:".length()).trim();
|
||||
} else if (lowerReceiver.startsWith("friend:")) {
|
||||
targetType = "FRIEND";
|
||||
receiver = receiver.substring("friend:".length()).trim();
|
||||
}
|
||||
if (!StringUtils.hasText(targetType)) {
|
||||
targetType = channelConfig.getStringConfig("defaultTargetType");
|
||||
}
|
||||
if (!StringUtils.hasText(targetType)) {
|
||||
targetType = "GROUP";
|
||||
}
|
||||
String normalizedTargetType = targetType.trim().toUpperCase(Locale.ROOT);
|
||||
if (!"GROUP".equals(normalizedTargetType) && !"FRIEND".equals(normalizedTargetType)) {
|
||||
throw new IllegalArgumentException("QQ targetType must be GROUP or FRIEND");
|
||||
}
|
||||
request.setTargetType(normalizedTargetType);
|
||||
request.setReceiver(requireTrimmedText(receiver, "QQ target id is required"));
|
||||
}
|
||||
|
||||
private String resolveQqContentMode(ManagedChannelConfig channelConfig, String requestedContentMode) {
|
||||
String contentMode = trimToNull(requestedContentMode);
|
||||
if (!StringUtils.hasText(contentMode)) {
|
||||
contentMode = channelConfig.getStringConfig("contentMode");
|
||||
}
|
||||
if (!StringUtils.hasText(contentMode)) {
|
||||
contentMode = "TEXT";
|
||||
}
|
||||
String normalizedContentMode = contentMode.trim().toUpperCase(Locale.ROOT);
|
||||
if (!"TEXT".equals(normalizedContentMode) && !"ONEBOT_JSON".equals(normalizedContentMode)) {
|
||||
throw new IllegalArgumentException("QQ contentMode must be TEXT or ONEBOT_JSON");
|
||||
}
|
||||
return normalizedContentMode;
|
||||
}
|
||||
|
||||
private PushTemplateDO requireEnabledTemplate(String templateCode) {
|
||||
if (!StringUtils.hasText(templateCode)) {
|
||||
throw new IllegalArgumentException("短信测试必须选择模板编码");
|
||||
@@ -617,6 +857,18 @@ public class MessageChannelService {
|
||||
return boundChannel.getId();
|
||||
}
|
||||
|
||||
private Long requireQqTemplateBoundChannel(Long channelId) {
|
||||
if (channelId == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
MessageChannelConfigDO boundChannel = requireChannel(channelId);
|
||||
if (!ChannelTypeEnum.QQ.getCode().equalsIgnoreCase(boundChannel.getChannelType())) {
|
||||
throw new IllegalArgumentException("Bound channel must be a QQ channel: " + channelId);
|
||||
}
|
||||
return boundChannel.getId();
|
||||
}
|
||||
|
||||
private boolean templateMatchesChannel(PushTemplateDO template, Long channelId) {
|
||||
return template != null
|
||||
&& (template.getChannelId() == null || Objects.equals(template.getChannelId(), channelId));
|
||||
@@ -651,6 +903,15 @@ public class MessageChannelService {
|
||||
}
|
||||
}
|
||||
|
||||
private void validateInlineTemplateParams(String contentPattern, Map<String, Object> templateParams) {
|
||||
List<String> missingKeys = extractTemplatePlaceholders(contentPattern).stream()
|
||||
.filter(key -> !templateParams.containsKey(key) || !StringUtils.hasText(String.valueOf(templateParams.get(key))))
|
||||
.toList();
|
||||
if (!missingKeys.isEmpty()) {
|
||||
throw new IllegalArgumentException("Message content missing template params: " + String.join(", ", missingKeys));
|
||||
}
|
||||
}
|
||||
|
||||
private String buildSmsTestSendMessage(SmsSendResult sendResult) {
|
||||
if (sendResult != null && StringUtils.hasText(sendResult.getRequestId())) {
|
||||
return "短信测试发送成功,请求ID: " + sendResult.getRequestId();
|
||||
|
||||
+5
@@ -1,6 +1,7 @@
|
||||
package com.xiaowang.messagehub.service.channel.email;
|
||||
|
||||
import com.xiaowang.messagehub.model.ChannelHealthCheckResult;
|
||||
import com.xiaowang.messagehub.model.EmailDispatchRequest;
|
||||
import com.xiaowang.messagehub.model.ManagedChannelConfig;
|
||||
|
||||
public interface EmailChannelProvider {
|
||||
@@ -11,5 +12,9 @@ public interface EmailChannelProvider {
|
||||
|
||||
void send(ManagedChannelConfig channelConfig, String to, String subject, String content);
|
||||
|
||||
default void send(ManagedChannelConfig channelConfig, EmailDispatchRequest request) {
|
||||
send(channelConfig, request.getReceiver(), request.getSubject(), request.getContent());
|
||||
}
|
||||
|
||||
ChannelHealthCheckResult checkHealth(ManagedChannelConfig channelConfig);
|
||||
}
|
||||
|
||||
+12
@@ -2,6 +2,7 @@ package com.xiaowang.messagehub.service.channel.email;
|
||||
|
||||
import com.xiaowang.messagehub.enums.ChannelProviderCodeEnum;
|
||||
import com.xiaowang.messagehub.model.ChannelHealthCheckResult;
|
||||
import com.xiaowang.messagehub.model.EmailDispatchRequest;
|
||||
import com.xiaowang.messagehub.model.ManagedChannelConfig;
|
||||
import com.xiaowang.messagehub.service.channel.ChannelEnvironmentService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -35,6 +36,17 @@ public class MockEmailChannelProvider implements EmailChannelProvider {
|
||||
log.info("[MockEmail] to={}, subject={}, content={}", to, subject, content);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void send(ManagedChannelConfig channelConfig, EmailDispatchRequest request) {
|
||||
validate(channelConfig);
|
||||
log.info("[MockEmail] to={}, subject={}, bodyType={}, content={}, attachments={}",
|
||||
request.getReceiver(),
|
||||
request.getSubject(),
|
||||
request.getBodyType(),
|
||||
request.getContent(),
|
||||
request.getAttachments());
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChannelHealthCheckResult checkHealth(ManagedChannelConfig channelConfig) {
|
||||
if (!environmentService.isDevelopmentEnvironment()) {
|
||||
|
||||
+51
-10
@@ -1,8 +1,13 @@
|
||||
package com.xiaowang.messagehub.service.channel.email;
|
||||
|
||||
import com.xiaowang.messagehub.enums.ChannelProviderCodeEnum;
|
||||
import com.xiaowang.messagehub.enums.ChannelTypeEnum;
|
||||
import com.xiaowang.messagehub.enums.EmailBodyTypeEnum;
|
||||
import com.xiaowang.messagehub.model.ChannelHealthCheckResult;
|
||||
import com.xiaowang.messagehub.model.EmailAttachmentResource;
|
||||
import com.xiaowang.messagehub.model.EmailDispatchRequest;
|
||||
import com.xiaowang.messagehub.model.ManagedChannelConfig;
|
||||
import org.springframework.mail.javamail.MimeMessageHelper;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
@@ -19,8 +24,9 @@ public class SmtpEmailChannelProvider implements EmailChannelProvider {
|
||||
|
||||
@Override
|
||||
public boolean supports(String providerCode) {
|
||||
return ChannelProviderCodeEnum.GMAIL.getCode().equalsIgnoreCase(providerCode)
|
||||
|| ChannelProviderCodeEnum.QQMAIL.getCode().equalsIgnoreCase(providerCode);
|
||||
ChannelProviderCodeEnum provider = ChannelProviderCodeEnum.fromCode(providerCode);
|
||||
return ChannelProviderCodeEnum.MOCK_EMAIL != provider
|
||||
&& ChannelTypeEnum.EMAIL.getCode().equalsIgnoreCase(provider.getChannelType());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -30,9 +36,11 @@ public class SmtpEmailChannelProvider implements EmailChannelProvider {
|
||||
if (port <= 0) {
|
||||
throw new IllegalArgumentException("SMTP 端口不能为空");
|
||||
}
|
||||
requireText(channelConfig.getStringConfig("username"), "SMTP 用户名不能为空");
|
||||
requireText(channelConfig.getStringConfig("fromAddress"), "发件人地址不能为空");
|
||||
requireText(channelConfig.getStringSecret("password"), "SMTP 密码不能为空");
|
||||
if (channelConfig.getBooleanConfig("auth", true)) {
|
||||
requireText(channelConfig.getStringConfig("username"), "SMTP 用户名不能为空");
|
||||
requireText(channelConfig.getStringSecret("password"), "SMTP 密码不能为空");
|
||||
}
|
||||
validateSecurityMode(channelConfig, port);
|
||||
}
|
||||
|
||||
@@ -56,6 +64,32 @@ public class SmtpEmailChannelProvider implements EmailChannelProvider {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void send(ManagedChannelConfig channelConfig, EmailDispatchRequest request) {
|
||||
validate(channelConfig);
|
||||
validateResolvedHost(channelConfig);
|
||||
requireText(request.getReceiver(), "收件人不能为空");
|
||||
requireText(request.getSubject(), "邮件主题不能为空");
|
||||
requireText(request.getContent(), "邮件内容不能为空");
|
||||
|
||||
try {
|
||||
MimeMessage message = new MimeMessage(buildSession(channelConfig));
|
||||
MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
|
||||
helper.setFrom(new InternetAddress(channelConfig.getStringConfig("fromAddress")));
|
||||
helper.setTo(InternetAddress.parse(request.getReceiver()));
|
||||
helper.setSubject(request.getSubject());
|
||||
boolean html = EmailBodyTypeEnum.HTML.name().equalsIgnoreCase(request.getBodyType());
|
||||
helper.setText(request.getContent(), html);
|
||||
|
||||
for (EmailAttachmentResource attachment : request.getAttachments()) {
|
||||
helper.addAttachment(attachment.originalFileName(), attachment.storagePath().toFile());
|
||||
}
|
||||
Transport.send(message);
|
||||
} catch (Exception exception) {
|
||||
throw new IllegalStateException("邮件发送失败: " + exception.getMessage(), exception);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChannelHealthCheckResult checkHealth(ManagedChannelConfig channelConfig) {
|
||||
try {
|
||||
@@ -63,12 +97,16 @@ public class SmtpEmailChannelProvider implements EmailChannelProvider {
|
||||
validateResolvedHost(channelConfig);
|
||||
Session session = buildSession(channelConfig);
|
||||
Transport transport = session.getTransport("smtp");
|
||||
transport.connect(
|
||||
channelConfig.getStringConfig("host"),
|
||||
channelConfig.getIntConfig("port", 25),
|
||||
channelConfig.getStringConfig("username"),
|
||||
channelConfig.getStringSecret("password")
|
||||
);
|
||||
if (channelConfig.getBooleanConfig("auth", true)) {
|
||||
transport.connect(
|
||||
channelConfig.getStringConfig("host"),
|
||||
channelConfig.getIntConfig("port", 25),
|
||||
channelConfig.getStringConfig("username"),
|
||||
channelConfig.getStringSecret("password")
|
||||
);
|
||||
} else {
|
||||
transport.connect(channelConfig.getStringConfig("host"), channelConfig.getIntConfig("port", 25), null, null);
|
||||
}
|
||||
transport.close();
|
||||
return ChannelHealthCheckResult.healthy("SMTP 连接成功");
|
||||
} catch (Exception exception) {
|
||||
@@ -89,6 +127,9 @@ public class SmtpEmailChannelProvider implements EmailChannelProvider {
|
||||
props.put("mail.smtp.connectiontimeout", "5000");
|
||||
props.put("mail.smtp.timeout", "5000");
|
||||
props.put("mail.smtp.writetimeout", "5000");
|
||||
if (!channelConfig.getBooleanConfig("auth", true)) {
|
||||
return Session.getInstance(props);
|
||||
}
|
||||
return Session.getInstance(props, new javax.mail.Authenticator() {
|
||||
@Override
|
||||
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
|
||||
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package com.xiaowang.messagehub.service.channel.qq;
|
||||
|
||||
import com.xiaowang.messagehub.enums.ChannelProviderCodeEnum;
|
||||
import com.xiaowang.messagehub.model.ChannelHealthCheckResult;
|
||||
import com.xiaowang.messagehub.model.ManagedChannelConfig;
|
||||
import com.xiaowang.messagehub.model.QqDispatchRequest;
|
||||
import com.xiaowang.messagehub.model.QqSendResult;
|
||||
import com.xiaowang.messagehub.service.channel.ChannelEnvironmentService;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
public class MockQqChannelProvider implements QqChannelProvider {
|
||||
|
||||
private final ChannelEnvironmentService environmentService;
|
||||
public MockQqChannelProvider(ChannelEnvironmentService environmentService) {
|
||||
this.environmentService = environmentService;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supports(String providerCode) {
|
||||
return ChannelProviderCodeEnum.MOCK_QQ.getCode().equalsIgnoreCase(providerCode);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void validate(ManagedChannelConfig channelConfig) {
|
||||
if (!environmentService.isDevelopmentEnvironment()) {
|
||||
throw new IllegalArgumentException("Mock QQ channel can only be used in development-like profiles");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public QqSendResult send(ManagedChannelConfig channelConfig, QqDispatchRequest request) {
|
||||
validate(channelConfig);
|
||||
QqSendResult result = new QqSendResult();
|
||||
result.setRequestId("mock-qq-" + UUID.randomUUID());
|
||||
result.setMessageId(result.getRequestId());
|
||||
result.setMessage("Mock QQ message accepted");
|
||||
result.setRawResponse("{\"success\":true,\"provider\":\"MOCK_QQ\"}");
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChannelHealthCheckResult checkHealth(ManagedChannelConfig channelConfig) {
|
||||
return ChannelHealthCheckResult.healthy("Mock QQ channel is ready");
|
||||
}
|
||||
}
|
||||
+322
@@ -0,0 +1,322 @@
|
||||
package com.xiaowang.messagehub.service.channel.qq;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xiaowang.messagehub.enums.ChannelProviderCodeEnum;
|
||||
import com.xiaowang.messagehub.model.ChannelHealthCheckResult;
|
||||
import com.xiaowang.messagehub.model.ManagedChannelConfig;
|
||||
import com.xiaowang.messagehub.model.QqDispatchRequest;
|
||||
import com.xiaowang.messagehub.model.QqSendResult;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Service
|
||||
public class QqAutoChannelProvider implements QqChannelProvider {
|
||||
|
||||
private static final String SERVICE_TOKEN_HEADER = "X-MessageHub-Service-Token";
|
||||
private static final String TARGET_GROUP = "GROUP";
|
||||
private static final String TARGET_FRIEND = "FRIEND";
|
||||
private static final String CONTENT_MODE_TEXT = "TEXT";
|
||||
private static final String CONTENT_MODE_ONEBOT_JSON = "ONEBOT_JSON";
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public QqAutoChannelProvider(ObjectMapper objectMapper) {
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supports(String providerCode) {
|
||||
return ChannelProviderCodeEnum.QQAUTO.getCode().equalsIgnoreCase(providerCode);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void validate(ManagedChannelConfig channelConfig) {
|
||||
requireText(channelConfig.getStringConfig("baseUrl"), "QQAuto baseUrl is required");
|
||||
requireText(channelConfig.getStringSecret("serviceToken"), "QQAuto serviceToken is required");
|
||||
int timeoutMs = channelConfig.getIntConfig("timeoutMs", 10000);
|
||||
if (timeoutMs <= 0) {
|
||||
throw new IllegalArgumentException("QQAuto timeoutMs must be greater than 0");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public QqSendResult send(ManagedChannelConfig channelConfig, QqDispatchRequest request) {
|
||||
validate(channelConfig);
|
||||
requireText(request.getReceiver(), "QQ target id is required");
|
||||
requireText(request.getTargetType(), "QQ targetType is required");
|
||||
requireText(request.getContent(), "QQ content is required");
|
||||
|
||||
try {
|
||||
String actionKey = resolveActionKey(request.getTargetType());
|
||||
Map<String, Object> payload = buildPayload(channelConfig, request);
|
||||
Map<String, Object> body = buildActionRequest(channelConfig, payload);
|
||||
HttpResponse response = postJson(buildActionUrl(channelConfig.getStringConfig("baseUrl"), actionKey),
|
||||
channelConfig.getStringSecret("serviceToken"),
|
||||
channelConfig.getIntConfig("timeoutMs", 10000),
|
||||
body);
|
||||
if (response.code < 200 || response.code >= 300) {
|
||||
throw new IllegalStateException("QQAuto request failed, HTTP " + response.code + ": " + response.body);
|
||||
}
|
||||
return validateSendResponse(response.body);
|
||||
} catch (Exception exception) {
|
||||
throw new IllegalStateException("QQAuto send failed: " + exception.getMessage(), exception);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChannelHealthCheckResult checkHealth(ManagedChannelConfig channelConfig) {
|
||||
try {
|
||||
validate(channelConfig);
|
||||
HttpResponse response = getJson(buildRuntimeStatusUrl(channelConfig.getStringConfig("baseUrl")),
|
||||
channelConfig.getStringSecret("serviceToken"),
|
||||
Math.min(channelConfig.getIntConfig("timeoutMs", 10000), 5000));
|
||||
if (response.code >= 200 && response.code < 300) {
|
||||
return ChannelHealthCheckResult.healthy("QQAuto gateway reachable");
|
||||
}
|
||||
return ChannelHealthCheckResult.unhealthy("QQAuto health check HTTP " + response.code + ": " + response.body);
|
||||
} catch (Exception exception) {
|
||||
return ChannelHealthCheckResult.unhealthy("QQAuto health check failed: " + exception.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, Object> buildPayload(ManagedChannelConfig channelConfig, QqDispatchRequest request) throws Exception {
|
||||
Map<String, Object> payload = new LinkedHashMap<>();
|
||||
if (TARGET_GROUP.equalsIgnoreCase(request.getTargetType())) {
|
||||
payload.put("group_id", request.getReceiver());
|
||||
} else {
|
||||
payload.put("user_id", request.getReceiver());
|
||||
}
|
||||
payload.put("message", resolveMessageContent(request));
|
||||
payload.put("auto_escape", resolveAutoEscape(channelConfig, request));
|
||||
payload.put("timeout", channelConfig.getIntConfig("timeoutMs", 10000));
|
||||
return payload;
|
||||
}
|
||||
|
||||
private Object resolveMessageContent(QqDispatchRequest request) throws Exception {
|
||||
String contentMode = normalizeContentMode(request.getContentMode());
|
||||
if (CONTENT_MODE_TEXT.equals(contentMode)) {
|
||||
return request.getContent();
|
||||
}
|
||||
if (CONTENT_MODE_ONEBOT_JSON.equals(contentMode)) {
|
||||
try {
|
||||
return objectMapper.readValue(request.getContent(), Object.class);
|
||||
} catch (Exception exception) {
|
||||
throw new IllegalArgumentException("ONEBOT_JSON content must be valid JSON", exception);
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("Unsupported QQ contentMode: " + request.getContentMode());
|
||||
}
|
||||
|
||||
private boolean resolveAutoEscape(ManagedChannelConfig channelConfig, QqDispatchRequest request) {
|
||||
if (CONTENT_MODE_ONEBOT_JSON.equals(normalizeContentMode(request.getContentMode()))) {
|
||||
return false;
|
||||
}
|
||||
return channelConfig.getBooleanConfig("autoEscape", true);
|
||||
}
|
||||
|
||||
private Map<String, Object> buildActionRequest(ManagedChannelConfig channelConfig, Map<String, Object> payload) {
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
String transportOverride = channelConfig.getStringConfig("transportOverride");
|
||||
if (StringUtils.hasText(transportOverride)) {
|
||||
body.put("transportOverride", transportOverride);
|
||||
}
|
||||
body.put("payload", payload);
|
||||
Long accountId = parseLong(channelConfig.getStringConfig("accountId"));
|
||||
if (accountId != null) {
|
||||
body.put("accountId", accountId);
|
||||
}
|
||||
String configCode = channelConfig.getStringConfig("configCode");
|
||||
if (StringUtils.hasText(configCode)) {
|
||||
body.put("configCode", configCode);
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
private QqSendResult validateSendResponse(String responseBody) throws Exception {
|
||||
QqSendResult result = new QqSendResult();
|
||||
result.setRawResponse(responseBody);
|
||||
Map<String, Object> root = objectMapper.readValue(responseBody, new TypeReference<>() {
|
||||
});
|
||||
Object success = root.get("success");
|
||||
if (success instanceof Boolean && !((Boolean) success)) {
|
||||
throw new IllegalStateException("QQAuto returned failure: " + firstText(root, "message", "error"));
|
||||
}
|
||||
result.setRequestId(firstText(root, "requestId"));
|
||||
result.setMessage(firstText(root, "message"));
|
||||
Object response = root.get("response");
|
||||
if (response instanceof Map<?, ?> responseMap) {
|
||||
Map<String, Object> responseBodyMap = castMap(responseMap);
|
||||
validateNapCatResponse(responseBodyMap);
|
||||
Object data = responseBodyMap.get("data");
|
||||
if (data instanceof Map<?, ?> dataMap) {
|
||||
result.setMessageId(firstText(castMap(dataMap), "message_id", "messageId"));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private void validateNapCatResponse(Map<String, Object> root) {
|
||||
String status = firstText(root, "status");
|
||||
Integer retcode = parseInt(root.get("retcode"));
|
||||
boolean failedStatus = StringUtils.hasText(status)
|
||||
&& !"ok".equalsIgnoreCase(status)
|
||||
&& !"success".equalsIgnoreCase(status);
|
||||
boolean failedRetcode = retcode != null && retcode != 0;
|
||||
if (!failedStatus && !failedRetcode) {
|
||||
return;
|
||||
}
|
||||
throw new IllegalStateException("NapCat business failure: " + firstText(root, "wording", "message", "msg", "error"));
|
||||
}
|
||||
|
||||
private HttpResponse postJson(String url, String serviceToken, int timeoutMs, Map<String, Object> body) throws Exception {
|
||||
HttpURLConnection connection = openConnection(url, serviceToken, timeoutMs);
|
||||
connection.setRequestMethod("POST");
|
||||
connection.setDoOutput(true);
|
||||
try (OutputStream outputStream = connection.getOutputStream()) {
|
||||
outputStream.write(objectMapper.writeValueAsBytes(body));
|
||||
}
|
||||
return readResponse(connection);
|
||||
}
|
||||
|
||||
private HttpResponse getJson(String url, String serviceToken, int timeoutMs) throws Exception {
|
||||
HttpURLConnection connection = openConnection(url, serviceToken, timeoutMs);
|
||||
connection.setRequestMethod("GET");
|
||||
return readResponse(connection);
|
||||
}
|
||||
|
||||
private HttpURLConnection openConnection(String url, String serviceToken, int timeoutMs) throws Exception {
|
||||
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
|
||||
connection.setRequestProperty("Content-Type", "application/json");
|
||||
connection.setRequestProperty("Accept", "application/json");
|
||||
connection.setRequestProperty(SERVICE_TOKEN_HEADER, serviceToken);
|
||||
connection.setConnectTimeout(timeoutMs);
|
||||
connection.setReadTimeout(timeoutMs);
|
||||
return connection;
|
||||
}
|
||||
|
||||
private HttpResponse readResponse(HttpURLConnection connection) throws Exception {
|
||||
int responseCode = connection.getResponseCode();
|
||||
String responseBody = readResponseBody(connection, responseCode);
|
||||
connection.disconnect();
|
||||
return new HttpResponse(responseCode, responseBody);
|
||||
}
|
||||
|
||||
private String readResponseBody(HttpURLConnection connection, int responseCode) throws Exception {
|
||||
if (responseCode >= 200 && responseCode < 400) {
|
||||
try (BufferedReader reader = new BufferedReader(
|
||||
new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
|
||||
return readAll(reader);
|
||||
}
|
||||
}
|
||||
if (connection.getErrorStream() == null) {
|
||||
return "";
|
||||
}
|
||||
try (BufferedReader reader = new BufferedReader(
|
||||
new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8))) {
|
||||
return readAll(reader);
|
||||
}
|
||||
}
|
||||
|
||||
private String readAll(BufferedReader reader) throws Exception {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
if (builder.length() > 0) {
|
||||
builder.append('\n');
|
||||
}
|
||||
builder.append(line);
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
private String resolveActionKey(String targetType) {
|
||||
if (TARGET_GROUP.equalsIgnoreCase(targetType)) {
|
||||
return "send_group_msg";
|
||||
}
|
||||
if (TARGET_FRIEND.equalsIgnoreCase(targetType)) {
|
||||
return "send_private_msg";
|
||||
}
|
||||
throw new IllegalArgumentException("Unsupported QQ targetType: " + targetType);
|
||||
}
|
||||
|
||||
private String normalizeContentMode(String contentMode) {
|
||||
return StringUtils.hasText(contentMode) ? contentMode.trim().toUpperCase() : CONTENT_MODE_TEXT;
|
||||
}
|
||||
|
||||
private String buildActionUrl(String baseUrl, String actionKey) {
|
||||
return trimTrailingSlash(baseUrl) + "/api/platforms/qq/actions/" + actionKey;
|
||||
}
|
||||
|
||||
private String buildRuntimeStatusUrl(String baseUrl) {
|
||||
return trimTrailingSlash(baseUrl) + "/api/platforms/qq/runtime/status";
|
||||
}
|
||||
|
||||
private String trimTrailingSlash(String value) {
|
||||
String result = value == null ? "" : value.trim();
|
||||
while (result.endsWith("/")) {
|
||||
result = result.substring(0, result.length() - 1);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private void requireText(String value, String message) {
|
||||
if (!StringUtils.hasText(value)) {
|
||||
throw new IllegalArgumentException(message);
|
||||
}
|
||||
}
|
||||
|
||||
private Long parseLong(String value) {
|
||||
if (!StringUtils.hasText(value)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return Long.parseLong(value.trim());
|
||||
} catch (NumberFormatException exception) {
|
||||
throw new IllegalArgumentException("accountId must be a number");
|
||||
}
|
||||
}
|
||||
|
||||
private Integer parseInt(Object value) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return Integer.parseInt(String.valueOf(value).trim());
|
||||
} catch (NumberFormatException ignored) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, Object> castMap(Map<?, ?> map) {
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
map.forEach((key, value) -> {
|
||||
if (key != null) {
|
||||
result.put(String.valueOf(key), value);
|
||||
}
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
private String firstText(Map<String, Object> map, String... keys) {
|
||||
for (String key : keys) {
|
||||
Object value = map.get(key);
|
||||
if (value != null && StringUtils.hasText(String.valueOf(value))) {
|
||||
return String.valueOf(value).trim();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private record HttpResponse(int code, String body) {
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.xiaowang.messagehub.service.channel.qq;
|
||||
|
||||
import com.xiaowang.messagehub.model.ChannelHealthCheckResult;
|
||||
import com.xiaowang.messagehub.model.ManagedChannelConfig;
|
||||
import com.xiaowang.messagehub.model.QqDispatchRequest;
|
||||
import com.xiaowang.messagehub.model.QqSendResult;
|
||||
|
||||
public interface QqChannelProvider {
|
||||
|
||||
boolean supports(String providerCode);
|
||||
|
||||
void validate(ManagedChannelConfig channelConfig);
|
||||
|
||||
QqSendResult send(ManagedChannelConfig channelConfig, QqDispatchRequest request);
|
||||
|
||||
ChannelHealthCheckResult checkHealth(ManagedChannelConfig channelConfig);
|
||||
}
|
||||
+211
@@ -0,0 +1,211 @@
|
||||
package com.xiaowang.messagehub.service.email;
|
||||
|
||||
import com.xiaowang.messagehub.dto.admin.EmailAttachmentView;
|
||||
import com.xiaowang.messagehub.entity.EmailAttachmentDO;
|
||||
import com.xiaowang.messagehub.entity.EmailAttachmentPolicyDO;
|
||||
import com.xiaowang.messagehub.mapper.EmailAttachmentMapper;
|
||||
import com.xiaowang.messagehub.model.EmailAttachmentResource;
|
||||
import com.xiaowang.messagehub.support.id.TimeOrderedSnowflakeIdGenerator;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
|
||||
@Service
|
||||
public class AttachmentStorageService {
|
||||
|
||||
private final EmailAttachmentMapper attachmentMapper;
|
||||
private final EmailAttachmentPolicyService policyService;
|
||||
private final TimeOrderedSnowflakeIdGenerator idGenerator;
|
||||
private final Path storageRoot;
|
||||
|
||||
public AttachmentStorageService(EmailAttachmentMapper attachmentMapper,
|
||||
EmailAttachmentPolicyService policyService,
|
||||
TimeOrderedSnowflakeIdGenerator idGenerator) {
|
||||
this.attachmentMapper = attachmentMapper;
|
||||
this.policyService = policyService;
|
||||
this.idGenerator = idGenerator;
|
||||
this.storageRoot = resolveStorageRoot();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public EmailAttachmentView upload(MultipartFile file) {
|
||||
if (file == null || file.isEmpty()) {
|
||||
throw new IllegalArgumentException("附件不能为空");
|
||||
}
|
||||
EmailAttachmentPolicyDO policy = policyService.getPolicyEntity();
|
||||
validateSingleFile(file, policy);
|
||||
|
||||
Long id = idGenerator.nextId();
|
||||
String originalFileName = sanitizeFileName(file.getOriginalFilename());
|
||||
String extension = extractExtension(originalFileName);
|
||||
String storedFileName = id + (StringUtils.hasText(extension) ? "." + extension : "");
|
||||
Path target = storageRoot.resolve(storedFileName).normalize();
|
||||
ensureWithinRoot(target);
|
||||
|
||||
try {
|
||||
Files.createDirectories(storageRoot);
|
||||
try (InputStream inputStream = file.getInputStream()) {
|
||||
Files.copy(inputStream, target);
|
||||
}
|
||||
} catch (Exception exception) {
|
||||
throw new IllegalStateException("附件保存失败: " + exception.getMessage(), exception);
|
||||
}
|
||||
|
||||
EmailAttachmentDO entity = new EmailAttachmentDO();
|
||||
entity.setId(id);
|
||||
entity.setOriginalFileName(originalFileName);
|
||||
entity.setStoredFileName(storedFileName);
|
||||
entity.setStoragePath(target.toAbsolutePath().toString());
|
||||
entity.setContentType(normalizeContentType(file.getContentType()));
|
||||
entity.setFileExtension(extension);
|
||||
entity.setFileSize(file.getSize());
|
||||
entity.setStatus("ACTIVE");
|
||||
entity.setExpireTime(LocalDateTime.now().plusDays(policy.getRetentionDays()));
|
||||
attachmentMapper.insert(entity);
|
||||
return toView(entity);
|
||||
}
|
||||
|
||||
public List<EmailAttachmentResource> resolveResources(List<Long> attachmentIds) {
|
||||
if (attachmentIds == null || attachmentIds.isEmpty()) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
EmailAttachmentPolicyDO policy = policyService.getPolicyEntity();
|
||||
if (attachmentIds.size() > policy.getMaxFileCount()) {
|
||||
throw new IllegalArgumentException("附件数量超过限制: " + policy.getMaxFileCount());
|
||||
}
|
||||
|
||||
long totalSize = 0L;
|
||||
Set<Long> uniqueIds = new LinkedHashSet<>(attachmentIds);
|
||||
List<EmailAttachmentResource> resources = uniqueIds.stream()
|
||||
.map(this::requireResource)
|
||||
.toList();
|
||||
for (EmailAttachmentResource resource : resources) {
|
||||
totalSize += resource.fileSize();
|
||||
}
|
||||
if (totalSize > policy.getMaxTotalFileSize()) {
|
||||
throw new IllegalArgumentException("附件总大小超过限制: " + policy.getMaxTotalFileSize());
|
||||
}
|
||||
return resources;
|
||||
}
|
||||
|
||||
private EmailAttachmentResource requireResource(Long attachmentId) {
|
||||
EmailAttachmentDO entity = attachmentMapper.selectById(attachmentId);
|
||||
if (entity == null) {
|
||||
throw new IllegalArgumentException("附件不存在: " + attachmentId);
|
||||
}
|
||||
if (!"ACTIVE".equalsIgnoreCase(entity.getStatus())) {
|
||||
throw new IllegalArgumentException("附件不可用: " + entity.getOriginalFileName());
|
||||
}
|
||||
if (entity.getExpireTime() != null && entity.getExpireTime().isBefore(LocalDateTime.now())) {
|
||||
throw new IllegalArgumentException("附件已过期: " + entity.getOriginalFileName());
|
||||
}
|
||||
Path path = Paths.get(entity.getStoragePath()).normalize();
|
||||
if (!Files.isRegularFile(path)) {
|
||||
throw new IllegalArgumentException("附件文件不存在: " + entity.getOriginalFileName());
|
||||
}
|
||||
return new EmailAttachmentResource(
|
||||
entity.getId(),
|
||||
entity.getOriginalFileName(),
|
||||
entity.getContentType(),
|
||||
entity.getFileSize() == null ? 0L : entity.getFileSize(),
|
||||
path
|
||||
);
|
||||
}
|
||||
|
||||
private void validateSingleFile(MultipartFile file, EmailAttachmentPolicyDO policy) {
|
||||
if (file.getSize() > policy.getMaxSingleFileSize()) {
|
||||
throw new IllegalArgumentException("附件大小超过单文件限制: " + policy.getMaxSingleFileSize());
|
||||
}
|
||||
|
||||
String fileName = sanitizeFileName(file.getOriginalFilename());
|
||||
String extension = extractExtension(fileName);
|
||||
Set<String> allowedExtensions = parseCsv(policy.getAllowedExtensions());
|
||||
if (!allowedExtensions.isEmpty() && !allowedExtensions.contains(extension.toLowerCase(Locale.ROOT))) {
|
||||
throw new IllegalArgumentException("附件扩展名不允许: " + extension);
|
||||
}
|
||||
|
||||
String contentType = normalizeContentType(file.getContentType());
|
||||
Set<String> allowedMimeTypes = parseCsv(policy.getAllowedMimeTypes());
|
||||
if (!allowedMimeTypes.isEmpty() && !allowedMimeTypes.contains(contentType.toLowerCase(Locale.ROOT))) {
|
||||
throw new IllegalArgumentException("附件 MIME 类型不允许: " + contentType);
|
||||
}
|
||||
}
|
||||
|
||||
private Set<String> parseCsv(String value) {
|
||||
if (!StringUtils.hasText(value)) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
Set<String> result = new LinkedHashSet<>();
|
||||
Arrays.stream(value.split(","))
|
||||
.map(String::trim)
|
||||
.filter(StringUtils::hasText)
|
||||
.map(item -> item.toLowerCase(Locale.ROOT))
|
||||
.forEach(result::add);
|
||||
return result;
|
||||
}
|
||||
|
||||
private String sanitizeFileName(String fileName) {
|
||||
String normalized = StringUtils.hasText(fileName) ? fileName.trim() : "attachment";
|
||||
normalized = normalized.replace("\\", "/");
|
||||
int slashIndex = normalized.lastIndexOf('/');
|
||||
if (slashIndex >= 0) {
|
||||
normalized = normalized.substring(slashIndex + 1);
|
||||
}
|
||||
return normalized.replaceAll("[\\r\\n]", "_");
|
||||
}
|
||||
|
||||
private String extractExtension(String fileName) {
|
||||
if (!StringUtils.hasText(fileName)) {
|
||||
return "";
|
||||
}
|
||||
int dotIndex = fileName.lastIndexOf('.');
|
||||
if (dotIndex < 0 || dotIndex == fileName.length() - 1) {
|
||||
return "";
|
||||
}
|
||||
return fileName.substring(dotIndex + 1).toLowerCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
private String normalizeContentType(String contentType) {
|
||||
return StringUtils.hasText(contentType) ? contentType.trim().toLowerCase(Locale.ROOT) : "application/octet-stream";
|
||||
}
|
||||
|
||||
private Path resolveStorageRoot() {
|
||||
String localAppData = System.getenv("LOCALAPPDATA");
|
||||
Path base = StringUtils.hasText(localAppData)
|
||||
? Paths.get(localAppData, "YumiNail", "MessageHub")
|
||||
: Paths.get(System.getProperty("user.home"), ".yuminail", "messagehub");
|
||||
return base.resolve("uploads").resolve("email-attachments").toAbsolutePath().normalize();
|
||||
}
|
||||
|
||||
private void ensureWithinRoot(Path target) {
|
||||
if (!target.toAbsolutePath().normalize().startsWith(storageRoot)) {
|
||||
throw new IllegalArgumentException("附件存储路径非法");
|
||||
}
|
||||
}
|
||||
|
||||
private EmailAttachmentView toView(EmailAttachmentDO entity) {
|
||||
EmailAttachmentView view = new EmailAttachmentView();
|
||||
view.setId(entity.getId());
|
||||
view.setOriginalFileName(entity.getOriginalFileName());
|
||||
view.setContentType(entity.getContentType());
|
||||
view.setFileExtension(entity.getFileExtension());
|
||||
view.setFileSize(entity.getFileSize());
|
||||
view.setStatus(entity.getStatus());
|
||||
view.setExpireTime(entity.getExpireTime());
|
||||
view.setCreateTime(entity.getCreateTime());
|
||||
return view;
|
||||
}
|
||||
}
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
package com.xiaowang.messagehub.service.email;
|
||||
|
||||
import com.xiaowang.messagehub.dto.admin.EmailAttachmentPolicyRequest;
|
||||
import com.xiaowang.messagehub.dto.admin.EmailAttachmentPolicyView;
|
||||
import com.xiaowang.messagehub.entity.EmailAttachmentPolicyDO;
|
||||
import com.xiaowang.messagehub.mapper.EmailAttachmentPolicyMapper;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
@Service
|
||||
public class EmailAttachmentPolicyService {
|
||||
|
||||
private static final long POLICY_ID = 1L;
|
||||
|
||||
private final EmailAttachmentPolicyMapper policyMapper;
|
||||
|
||||
public EmailAttachmentPolicyService(EmailAttachmentPolicyMapper policyMapper) {
|
||||
this.policyMapper = policyMapper;
|
||||
}
|
||||
|
||||
public EmailAttachmentPolicyDO getPolicyEntity() {
|
||||
EmailAttachmentPolicyDO policy = policyMapper.selectById(POLICY_ID);
|
||||
if (policy != null) {
|
||||
return policy;
|
||||
}
|
||||
|
||||
EmailAttachmentPolicyDO defaults = defaultPolicy();
|
||||
policyMapper.insert(defaults);
|
||||
return defaults;
|
||||
}
|
||||
|
||||
public EmailAttachmentPolicyView getPolicy() {
|
||||
return toView(getPolicyEntity());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public EmailAttachmentPolicyView updatePolicy(EmailAttachmentPolicyRequest request) {
|
||||
EmailAttachmentPolicyDO entity = getPolicyEntity();
|
||||
entity.setMaxSingleFileSize(request.getMaxSingleFileSize());
|
||||
entity.setMaxTotalFileSize(request.getMaxTotalFileSize());
|
||||
entity.setMaxFileCount(request.getMaxFileCount());
|
||||
entity.setAllowedExtensions(normalizeCsv(request.getAllowedExtensions()));
|
||||
entity.setAllowedMimeTypes(normalizeCsv(request.getAllowedMimeTypes()));
|
||||
entity.setRetentionDays(request.getRetentionDays());
|
||||
entity.setReadTimeoutMillis(request.getReadTimeoutMillis());
|
||||
policyMapper.updateById(entity);
|
||||
return toView(policyMapper.selectById(POLICY_ID));
|
||||
}
|
||||
|
||||
private EmailAttachmentPolicyDO defaultPolicy() {
|
||||
EmailAttachmentPolicyDO policy = new EmailAttachmentPolicyDO();
|
||||
policy.setId(POLICY_ID);
|
||||
policy.setMaxSingleFileSize(10L * 1024 * 1024);
|
||||
policy.setMaxTotalFileSize(20L * 1024 * 1024);
|
||||
policy.setMaxFileCount(5);
|
||||
policy.setAllowedExtensions("pdf,doc,docx,xls,xlsx,png,jpg,jpeg,txt");
|
||||
policy.setAllowedMimeTypes("application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,image/png,image/jpeg,text/plain");
|
||||
policy.setRetentionDays(7);
|
||||
policy.setReadTimeoutMillis(5000);
|
||||
return policy;
|
||||
}
|
||||
|
||||
private String normalizeCsv(String value) {
|
||||
if (!StringUtils.hasText(value)) {
|
||||
return "";
|
||||
}
|
||||
return value.trim().replace(",", ",");
|
||||
}
|
||||
|
||||
private EmailAttachmentPolicyView toView(EmailAttachmentPolicyDO entity) {
|
||||
EmailAttachmentPolicyView view = new EmailAttachmentPolicyView();
|
||||
view.setMaxSingleFileSize(entity.getMaxSingleFileSize());
|
||||
view.setMaxTotalFileSize(entity.getMaxTotalFileSize());
|
||||
view.setMaxFileCount(entity.getMaxFileCount());
|
||||
view.setAllowedExtensions(entity.getAllowedExtensions());
|
||||
view.setAllowedMimeTypes(entity.getAllowedMimeTypes());
|
||||
view.setRetentionDays(entity.getRetentionDays());
|
||||
view.setReadTimeoutMillis(entity.getReadTimeoutMillis());
|
||||
view.setUpdateTime(entity.getUpdateTime());
|
||||
return view;
|
||||
}
|
||||
}
|
||||
+278
@@ -0,0 +1,278 @@
|
||||
package com.xiaowang.messagehub.service.email;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.xiaowang.messagehub.dto.admin.EmailTemplateSaveRequest;
|
||||
import com.xiaowang.messagehub.dto.admin.EmailTemplateView;
|
||||
import com.xiaowang.messagehub.entity.EmailTemplateDO;
|
||||
import com.xiaowang.messagehub.entity.MessageChannelConfigDO;
|
||||
import com.xiaowang.messagehub.enums.ChannelTypeEnum;
|
||||
import com.xiaowang.messagehub.enums.EmailBodyTypeEnum;
|
||||
import com.xiaowang.messagehub.mapper.EmailTemplateMapper;
|
||||
import com.xiaowang.messagehub.mapper.MessageChannelConfigMapper;
|
||||
import com.xiaowang.messagehub.model.EmailRenderResult;
|
||||
import com.xiaowang.messagehub.support.id.TimeOrderedSnowflakeIdGenerator;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@Service
|
||||
public class EmailTemplateService {
|
||||
|
||||
private static final Pattern TEMPLATE_PLACEHOLDER_PATTERN = Pattern.compile("\\$\\{([^{}]+)}");
|
||||
private static final char[] TEMPLATE_CODE_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".toCharArray();
|
||||
private static final SecureRandom RANDOM = new SecureRandom();
|
||||
|
||||
private final EmailTemplateMapper emailTemplateMapper;
|
||||
private final MessageChannelConfigMapper channelConfigMapper;
|
||||
private final TimeOrderedSnowflakeIdGenerator idGenerator;
|
||||
|
||||
public EmailTemplateService(EmailTemplateMapper emailTemplateMapper,
|
||||
MessageChannelConfigMapper channelConfigMapper,
|
||||
TimeOrderedSnowflakeIdGenerator idGenerator) {
|
||||
this.emailTemplateMapper = emailTemplateMapper;
|
||||
this.channelConfigMapper = channelConfigMapper;
|
||||
this.idGenerator = idGenerator;
|
||||
}
|
||||
|
||||
public List<EmailTemplateView> listTemplates() {
|
||||
return emailTemplateMapper.selectAllTemplates().stream()
|
||||
.sorted(Comparator.comparing(EmailTemplateDO::getId, Comparator.nullsLast(Long::compareTo)))
|
||||
.map(this::toView)
|
||||
.toList();
|
||||
}
|
||||
|
||||
public List<EmailTemplateView> listEnabledTemplates() {
|
||||
return emailTemplateMapper.selectEnabledTemplates().stream()
|
||||
.sorted(Comparator.comparing(EmailTemplateDO::getId, Comparator.nullsLast(Long::compareTo)))
|
||||
.map(this::toView)
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public EmailTemplateView createTemplate(EmailTemplateSaveRequest request) {
|
||||
EmailTemplateDO entity = new EmailTemplateDO();
|
||||
applyRequest(entity, request, null);
|
||||
emailTemplateMapper.insert(entity);
|
||||
return toView(requireTemplate(entity.getId()));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public EmailTemplateView updateTemplate(Long id, EmailTemplateSaveRequest request) {
|
||||
EmailTemplateDO entity = requireTemplate(id);
|
||||
applyRequest(entity, request, id);
|
||||
emailTemplateMapper.updateById(entity);
|
||||
return toView(requireTemplate(id));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public EmailTemplateView updateTemplateStatus(Long id, boolean enabled) {
|
||||
EmailTemplateDO entity = requireTemplate(id);
|
||||
entity.setIsEnable(enabled ? 1 : 0);
|
||||
emailTemplateMapper.updateById(entity);
|
||||
return toView(requireTemplate(id));
|
||||
}
|
||||
|
||||
public EmailTemplateDO requireEnabledTemplate(String templateCode) {
|
||||
if (!StringUtils.hasText(templateCode)) {
|
||||
throw new IllegalArgumentException("邮件模板编码不能为空");
|
||||
}
|
||||
EmailTemplateDO template = emailTemplateMapper.selectByTemplateCode(templateCode.trim());
|
||||
if (template == null || template.getIsEnable() == null || template.getIsEnable() != 1) {
|
||||
throw new IllegalArgumentException("邮件模板不存在或已停用: " + templateCode);
|
||||
}
|
||||
return template;
|
||||
}
|
||||
|
||||
public EmailRenderResult render(String explicitSubject,
|
||||
String explicitContent,
|
||||
String explicitBodyType,
|
||||
String templateCode,
|
||||
Map<String, Object> templateParams) {
|
||||
String subject = trimToNull(explicitSubject);
|
||||
String content = trimToNull(explicitContent);
|
||||
String bodyType = normalizeBodyType(explicitBodyType);
|
||||
|
||||
if (StringUtils.hasText(subject) && StringUtils.hasText(content)) {
|
||||
return new EmailRenderResult(subject, content, bodyType);
|
||||
}
|
||||
|
||||
if (StringUtils.hasText(templateCode)) {
|
||||
EmailTemplateDO template = requireEnabledTemplate(templateCode);
|
||||
if (!StringUtils.hasText(subject)) {
|
||||
subject = replacePlaceholders(template.getSubjectPattern(), templateParams);
|
||||
}
|
||||
if (!StringUtils.hasText(content)) {
|
||||
content = replacePlaceholders(template.getBodyPattern(), templateParams);
|
||||
}
|
||||
if (!StringUtils.hasText(explicitBodyType)) {
|
||||
bodyType = normalizeBodyType(template.getBodyType());
|
||||
}
|
||||
}
|
||||
|
||||
if (!StringUtils.hasText(subject)) {
|
||||
subject = "MessageHub 邮件通知";
|
||||
}
|
||||
if (!StringUtils.hasText(content)) {
|
||||
Object message = templateParams == null ? null : templateParams.get("message");
|
||||
content = message == null ? "这是一封来自 MessageHub 的邮件。" : String.valueOf(message);
|
||||
}
|
||||
return new EmailRenderResult(subject, content, bodyType);
|
||||
}
|
||||
|
||||
public void validateTemplateChannelBinding(String templateCode, Long channelId) {
|
||||
if (!StringUtils.hasText(templateCode)) {
|
||||
return;
|
||||
}
|
||||
EmailTemplateDO template = requireEnabledTemplate(templateCode);
|
||||
if (template.getChannelId() == null || Objects.equals(template.getChannelId(), channelId)) {
|
||||
return;
|
||||
}
|
||||
MessageChannelConfigDO channel = channelConfigMapper.selectById(template.getChannelId());
|
||||
String bound = channel == null ? String.valueOf(template.getChannelId()) : channel.getChannelName() + " / ID:" + channel.getId();
|
||||
throw new IllegalArgumentException("邮件模板已绑定到其他通道: " + templateCode + " -> " + bound);
|
||||
}
|
||||
|
||||
public String replacePlaceholders(String pattern, Map<String, Object> templateParams) {
|
||||
if (!StringUtils.hasText(pattern)) {
|
||||
return pattern;
|
||||
}
|
||||
String rendered = pattern;
|
||||
if (templateParams != null) {
|
||||
for (Map.Entry<String, Object> entry : templateParams.entrySet()) {
|
||||
rendered = rendered.replace("${" + entry.getKey() + "}", entry.getValue() == null ? "" : String.valueOf(entry.getValue()));
|
||||
}
|
||||
}
|
||||
return rendered;
|
||||
}
|
||||
|
||||
public Set<String> extractPlaceholders(String... patterns) {
|
||||
if (patterns == null || patterns.length == 0) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
Set<String> placeholders = new LinkedHashSet<>();
|
||||
for (String pattern : patterns) {
|
||||
if (!StringUtils.hasText(pattern)) {
|
||||
continue;
|
||||
}
|
||||
Matcher matcher = TEMPLATE_PLACEHOLDER_PATTERN.matcher(pattern);
|
||||
while (matcher.find()) {
|
||||
String key = matcher.group(1);
|
||||
if (StringUtils.hasText(key)) {
|
||||
placeholders.add(key.trim());
|
||||
}
|
||||
}
|
||||
}
|
||||
return placeholders;
|
||||
}
|
||||
|
||||
private void applyRequest(EmailTemplateDO target, EmailTemplateSaveRequest request, Long currentId) {
|
||||
String templateCode = resolveTemplateCode(request.getTemplateCode(), target.getTemplateCode());
|
||||
EmailTemplateDO existing = emailTemplateMapper.selectByTemplateCode(templateCode);
|
||||
if (existing != null && !Objects.equals(existing.getId(), currentId)) {
|
||||
throw new IllegalArgumentException("邮件模板编码已存在: " + templateCode);
|
||||
}
|
||||
|
||||
target.setTemplateCode(templateCode);
|
||||
target.setTemplateName(requireText(request.getTemplateName(), "邮件模板名称不能为空"));
|
||||
target.setSubjectPattern(requireText(request.getSubjectPattern(), "邮件主题模板不能为空"));
|
||||
target.setBodyType(normalizeBodyType(request.getBodyType()));
|
||||
target.setBodyPattern(requireText(request.getBodyPattern(), "邮件正文模板不能为空"));
|
||||
target.setChannelId(requireEmailChannel(request.getChannelId()));
|
||||
target.setIsEnable(Boolean.TRUE.equals(request.getEnabled()) ? 1 : 0);
|
||||
target.setDescription(trimToNull(request.getDescription()));
|
||||
}
|
||||
|
||||
private Long requireEmailChannel(Long channelId) {
|
||||
if (channelId == null) {
|
||||
return null;
|
||||
}
|
||||
MessageChannelConfigDO channel = channelConfigMapper.selectById(channelId);
|
||||
if (channel == null || !ChannelTypeEnum.EMAIL.getCode().equalsIgnoreCase(channel.getChannelType())) {
|
||||
throw new IllegalArgumentException("绑定通道必须是邮件通道: " + channelId);
|
||||
}
|
||||
return channel.getId();
|
||||
}
|
||||
|
||||
private EmailTemplateDO requireTemplate(Long id) {
|
||||
EmailTemplateDO template = emailTemplateMapper.selectById(id);
|
||||
if (template == null) {
|
||||
throw new IllegalArgumentException("邮件模板不存在: " + id);
|
||||
}
|
||||
return template;
|
||||
}
|
||||
|
||||
private String resolveTemplateCode(String requestedCode, String existingCode) {
|
||||
if (StringUtils.hasText(existingCode)) {
|
||||
return existingCode;
|
||||
}
|
||||
if (StringUtils.hasText(requestedCode)) {
|
||||
return requestedCode.trim();
|
||||
}
|
||||
for (int attempt = 0; attempt < 20; attempt++) {
|
||||
String candidate = "EM" + buildRandomSuffix(14);
|
||||
if (emailTemplateMapper.selectByTemplateCode(candidate) == null) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
return "EM" + idGenerator.nextBase36String(14);
|
||||
}
|
||||
|
||||
private String buildRandomSuffix(int length) {
|
||||
StringBuilder builder = new StringBuilder(length);
|
||||
for (int index = 0; index < length; index++) {
|
||||
builder.append(TEMPLATE_CODE_ALPHABET[RANDOM.nextInt(TEMPLATE_CODE_ALPHABET.length)]);
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
private String normalizeBodyType(String bodyType) {
|
||||
return EmailBodyTypeEnum.fromCode(bodyType).name();
|
||||
}
|
||||
|
||||
private String requireText(String value, String message) {
|
||||
String trimmed = trimToNull(value);
|
||||
if (!StringUtils.hasText(trimmed)) {
|
||||
throw new IllegalArgumentException(message);
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
private String trimToNull(String value) {
|
||||
if (!StringUtils.hasText(value)) {
|
||||
return null;
|
||||
}
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
private EmailTemplateView toView(EmailTemplateDO entity) {
|
||||
MessageChannelConfigDO channel = entity.getChannelId() == null ? null : channelConfigMapper.selectById(entity.getChannelId());
|
||||
EmailTemplateView view = new EmailTemplateView();
|
||||
view.setId(entity.getId());
|
||||
view.setTemplateCode(entity.getTemplateCode());
|
||||
view.setTemplateName(entity.getTemplateName());
|
||||
view.setSubjectPattern(entity.getSubjectPattern());
|
||||
view.setBodyType(entity.getBodyType());
|
||||
view.setBodyPattern(entity.getBodyPattern());
|
||||
view.setChannelId(entity.getChannelId());
|
||||
view.setChannelName(channel == null ? null : channel.getChannelName());
|
||||
view.setEnabled(entity.getIsEnable() != null && entity.getIsEnable() == 1);
|
||||
view.setDescription(entity.getDescription());
|
||||
view.setPlaceholders(new ArrayList<>(extractPlaceholders(entity.getSubjectPattern(), entity.getBodyPattern())));
|
||||
view.setCreateTime(entity.getCreateTime());
|
||||
view.setUpdateTime(entity.getUpdateTime());
|
||||
return view;
|
||||
}
|
||||
}
|
||||
+81
-13
@@ -1,6 +1,8 @@
|
||||
package com.xiaowang.messagehub.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xiaowang.messagehub.config.MessageChannelProperties;
|
||||
import com.xiaowang.messagehub.dto.MessageDTO;
|
||||
import com.xiaowang.messagehub.entity.PushLogDO;
|
||||
import com.xiaowang.messagehub.entity.PushTemplateDO;
|
||||
@@ -27,28 +29,38 @@ import java.util.stream.Collectors;
|
||||
public class MessageHandleService {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MessageHandleService.class);
|
||||
private static final int MAX_RETRY_COUNT = 3;
|
||||
|
||||
private final Validator validator;
|
||||
private final PushLogMapper pushLogMapper;
|
||||
private final PushTemplateMapper pushTemplateMapper;
|
||||
private final MessageSourceSystemService sourceSystemService;
|
||||
private final MessageChannelProperties channelProperties;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public MessageHandleService(Validator validator,
|
||||
PushLogMapper pushLogMapper,
|
||||
PushTemplateMapper pushTemplateMapper,
|
||||
MessageSourceSystemService sourceSystemService) {
|
||||
MessageSourceSystemService sourceSystemService,
|
||||
MessageChannelProperties channelProperties,
|
||||
ObjectMapper objectMapper) {
|
||||
this.validator = validator;
|
||||
this.pushLogMapper = pushLogMapper;
|
||||
this.pushTemplateMapper = pushTemplateMapper;
|
||||
this.sourceSystemService = sourceSystemService;
|
||||
this.channelProperties = channelProperties;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
public MessageLogDecision validateAndPrepareLog(MessageDTO messageDTO, String messageId, LocalDateTime sendTime) {
|
||||
return validateAndPrepareLog(messageDTO, messageId, sendTime, null);
|
||||
}
|
||||
|
||||
public MessageLogDecision validateAndPrepareLog(MessageDTO messageDTO, String messageId, LocalDateTime sendTime, String requestPayload) {
|
||||
String failReason = validateMessage(messageDTO);
|
||||
|
||||
if (failReason != null) {
|
||||
saveOrUpdateRejectedLog(buildPushLog(messageDTO, messageId, sendTime), failReason);
|
||||
PushLogDO rejectedLog = buildPushLog(messageDTO, messageId, sendTime);
|
||||
rejectedLog.setRequestPayload(requestPayload);
|
||||
saveOrUpdateRejectedLog(rejectedLog, failReason);
|
||||
logger.warn("消息校验失败,messageId: {}, reason: {}", messageId, failReason);
|
||||
return MessageLogDecision.reject(failReason);
|
||||
}
|
||||
@@ -71,13 +83,14 @@ public class MessageHandleService {
|
||||
messageId, normalizeRetryCount(existingLog.getRetryCount()));
|
||||
return MessageLogDecision.reject("消息已达到最大重试次数");
|
||||
}
|
||||
refreshPendingLog(existingLog, messageDTO, sendTime);
|
||||
refreshPendingLog(existingLog, messageDTO, sendTime, requestPayload);
|
||||
logger.info("检测到重复投递消息,继续按重试流程处理,messageId: {}, retryCount: {}",
|
||||
messageId, normalizeRetryCount(existingLog.getRetryCount()));
|
||||
return MessageLogDecision.process();
|
||||
}
|
||||
|
||||
PushLogDO pushLog = buildPushLog(messageDTO, messageId, sendTime);
|
||||
pushLog.setRequestPayload(requestPayload);
|
||||
pushLog.setStatus(0);
|
||||
pushLog.setFailReason(null);
|
||||
insertPendingLog(pushLog);
|
||||
@@ -117,10 +130,33 @@ public class MessageHandleService {
|
||||
pushLog.setId(messageId);
|
||||
pushLog.setStatus(1);
|
||||
pushLog.setFailReason(null);
|
||||
pushLog.setDeadLetterReason(null);
|
||||
pushLog.setNextRetryTime(null);
|
||||
pushLog.setFinalContent(finalContent);
|
||||
pushLogMapper.updateById(pushLog);
|
||||
}
|
||||
|
||||
public void markDispatchChannel(String messageId, Long channelId, String providerCode) {
|
||||
if (!StringUtils.hasText(messageId)) {
|
||||
return;
|
||||
}
|
||||
PushLogDO pushLog = new PushLogDO();
|
||||
pushLog.setId(messageId);
|
||||
pushLog.setChannelId(channelId);
|
||||
pushLog.setProviderCode(providerCode);
|
||||
pushLogMapper.updateById(pushLog);
|
||||
}
|
||||
|
||||
public void markProviderResponse(String messageId, String providerResponse) {
|
||||
if (!StringUtils.hasText(messageId)) {
|
||||
return;
|
||||
}
|
||||
PushLogDO pushLog = new PushLogDO();
|
||||
pushLog.setId(messageId);
|
||||
pushLog.setProviderResponse(providerResponse);
|
||||
pushLogMapper.updateById(pushLog);
|
||||
}
|
||||
|
||||
public void updatePushLogStatus(String messageId, Integer status, String failReason) {
|
||||
if (!StringUtils.hasText(messageId)) {
|
||||
return;
|
||||
@@ -139,7 +175,7 @@ public class MessageHandleService {
|
||||
String failReason = buildFailReason(exception);
|
||||
if (!StringUtils.hasText(messageId)) {
|
||||
logger.warn("消息缺少 messageId,无法记录重试状态,reason: {}", failReason);
|
||||
return MessageRetryDecision.reject(failReason, MAX_RETRY_COUNT);
|
||||
return MessageRetryDecision.reject(failReason, Math.max(1, channelProperties.getRetry().getMaxAttempts()));
|
||||
}
|
||||
|
||||
PushLogDO existingLog = pushLogMapper.selectById(messageId);
|
||||
@@ -156,8 +192,10 @@ public class MessageHandleService {
|
||||
}
|
||||
|
||||
int nextRetryCount = normalizeRetryCount(existingLog == null ? null : existingLog.getRetryCount()) + 1;
|
||||
boolean shouldRetry = nextRetryCount < MAX_RETRY_COUNT;
|
||||
pushLogMapper.updateRetryStatus(messageId, shouldRetry ? 0 : 2, failReason);
|
||||
int maxAttempts = Math.max(1, channelProperties.getRetry().getMaxAttempts());
|
||||
boolean shouldRetry = nextRetryCount < maxAttempts;
|
||||
LocalDateTime nextRetryTime = shouldRetry ? LocalDateTime.now().plusNanos(resolveRetryDelayMillis(nextRetryCount) * 1_000_000L) : null;
|
||||
pushLogMapper.updateRetryStatus(messageId, shouldRetry ? 0 : 2, failReason, nextRetryTime, shouldRetry ? null : failReason);
|
||||
return shouldRetry
|
||||
? MessageRetryDecision.retry(failReason, nextRetryCount)
|
||||
: MessageRetryDecision.reject(failReason, nextRetryCount);
|
||||
@@ -174,6 +212,7 @@ public class MessageHandleService {
|
||||
pushLog.setStatus(2);
|
||||
pushLog.setRetryCount(0);
|
||||
pushLog.setFailReason(failReason);
|
||||
pushLog.setDeadLetterReason(failReason);
|
||||
saveOrUpdateRejectedLog(pushLog, failReason);
|
||||
}
|
||||
|
||||
@@ -203,7 +242,8 @@ public class MessageHandleService {
|
||||
pushLog.setChannelType(messageDTO.getChannelType());
|
||||
pushLog.setMsgType(messageDTO.getMsgType());
|
||||
pushLog.setTemplateCode(messageDTO.getTemplateCode());
|
||||
pushLog.setTemplateParams(messageDTO.getTemplateParams() != null ? messageDTO.getTemplateParams().toString() : null);
|
||||
pushLog.setChannelId(messageDTO.getChannelId());
|
||||
pushLog.setTemplateParams(toJson(messageDTO.getTemplateParams()));
|
||||
pushLog.setSendTime(sendTime);
|
||||
pushLog.setRetryCount(0);
|
||||
return pushLog;
|
||||
@@ -214,7 +254,10 @@ public class MessageHandleService {
|
||||
return null;
|
||||
}
|
||||
|
||||
PushLogDO existingLog = pushLogMapper.selectByUniqueId(messageDTO.getUniqueId());
|
||||
PushLogDO existingLog = pushLogMapper.selectBySourceSystemAndUniqueId(
|
||||
messageDTO.getSourceSystem(),
|
||||
messageDTO.getUniqueId()
|
||||
);
|
||||
if (existingLog == null) {
|
||||
return null;
|
||||
}
|
||||
@@ -242,6 +285,7 @@ public class MessageHandleService {
|
||||
|
||||
pushLog.setStatus(2);
|
||||
pushLog.setFailReason(failReason);
|
||||
pushLog.setDeadLetterReason(failReason);
|
||||
PushLogDO existingLog = pushLogMapper.selectById(pushLog.getId());
|
||||
if (existingLog == null) {
|
||||
insertPendingLog(pushLog);
|
||||
@@ -255,6 +299,7 @@ public class MessageHandleService {
|
||||
|
||||
existingLog.setStatus(2);
|
||||
existingLog.setFailReason(failReason);
|
||||
existingLog.setDeadLetterReason(failReason);
|
||||
existingLog.setSendTime(pushLog.getSendTime());
|
||||
if (StringUtils.hasText(pushLog.getSourceSystem())) {
|
||||
existingLog.setSourceSystem(pushLog.getSourceSystem());
|
||||
@@ -277,25 +322,31 @@ public class MessageHandleService {
|
||||
if (StringUtils.hasText(pushLog.getTemplateParams())) {
|
||||
existingLog.setTemplateParams(pushLog.getTemplateParams());
|
||||
}
|
||||
if (StringUtils.hasText(pushLog.getRequestPayload())) {
|
||||
existingLog.setRequestPayload(pushLog.getRequestPayload());
|
||||
}
|
||||
pushLogMapper.updateById(existingLog);
|
||||
}
|
||||
|
||||
private void refreshPendingLog(PushLogDO existingLog, MessageDTO messageDTO, LocalDateTime sendTime) {
|
||||
private void refreshPendingLog(PushLogDO existingLog, MessageDTO messageDTO, LocalDateTime sendTime, String requestPayload) {
|
||||
existingLog.setSourceSystem(messageDTO.getSourceSystem());
|
||||
existingLog.setUniqueId(messageDTO.getUniqueId());
|
||||
existingLog.setReceiver(messageDTO.getReceiver());
|
||||
existingLog.setChannelType(messageDTO.getChannelType());
|
||||
existingLog.setChannelId(messageDTO.getChannelId());
|
||||
existingLog.setMsgType(messageDTO.getMsgType());
|
||||
existingLog.setTemplateCode(messageDTO.getTemplateCode());
|
||||
existingLog.setTemplateParams(messageDTO.getTemplateParams() != null ? messageDTO.getTemplateParams().toString() : null);
|
||||
existingLog.setTemplateParams(toJson(messageDTO.getTemplateParams()));
|
||||
existingLog.setSendTime(sendTime);
|
||||
existingLog.setStatus(0);
|
||||
existingLog.setFailReason(null);
|
||||
existingLog.setDeadLetterReason(null);
|
||||
existingLog.setRequestPayload(requestPayload);
|
||||
pushLogMapper.updateById(existingLog);
|
||||
}
|
||||
|
||||
private boolean hasReachedMaxRetry(PushLogDO pushLogDO) {
|
||||
return normalizeRetryCount(pushLogDO == null ? null : pushLogDO.getRetryCount()) >= MAX_RETRY_COUNT;
|
||||
return normalizeRetryCount(pushLogDO == null ? null : pushLogDO.getRetryCount()) >= Math.max(1, channelProperties.getRetry().getMaxAttempts());
|
||||
}
|
||||
|
||||
private int normalizeRetryCount(Integer retryCount) {
|
||||
@@ -312,6 +363,23 @@ public class MessageHandleService {
|
||||
return exception.getClass().getSimpleName();
|
||||
}
|
||||
|
||||
private long resolveRetryDelayMillis(int retryCount) {
|
||||
MessageChannelProperties.Retry retry = channelProperties.getRetry();
|
||||
double delay = retry.getInitialDelayMillis() * Math.pow(Math.max(1.0D, retry.getMultiplier()), Math.max(0, retryCount - 1));
|
||||
return Math.min((long) delay, retry.getMaxDelayMillis());
|
||||
}
|
||||
|
||||
private String toJson(Object value) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return objectMapper.writeValueAsString(value);
|
||||
} catch (Exception exception) {
|
||||
return String.valueOf(value);
|
||||
}
|
||||
}
|
||||
|
||||
private String validateMessage(MessageDTO messageDTO) {
|
||||
Set<ConstraintViolation<MessageDTO>> violations = validator.validate(messageDTO);
|
||||
if (!violations.isEmpty()) {
|
||||
|
||||
+13
-2
@@ -58,6 +58,7 @@ public class MessageSourceSystemService {
|
||||
sourceSystemMapper.insert(entity);
|
||||
persistDefaultChannel(entity.getId(), ChannelTypeEnum.SMS.getCode(), request.getDefaultSmsChannelId());
|
||||
persistDefaultChannel(entity.getId(), ChannelTypeEnum.EMAIL.getCode(), request.getDefaultEmailChannelId());
|
||||
persistDefaultChannel(entity.getId(), ChannelTypeEnum.QQ.getCode(), request.getDefaultQqChannelId());
|
||||
return getSourceSystem(entity.getId());
|
||||
}
|
||||
|
||||
@@ -69,6 +70,7 @@ public class MessageSourceSystemService {
|
||||
sourceSystemMapper.updateById(entity);
|
||||
persistDefaultChannel(id, ChannelTypeEnum.SMS.getCode(), request.getDefaultSmsChannelId());
|
||||
persistDefaultChannel(id, ChannelTypeEnum.EMAIL.getCode(), request.getDefaultEmailChannelId());
|
||||
persistDefaultChannel(id, ChannelTypeEnum.QQ.getCode(), request.getDefaultQqChannelId());
|
||||
return getSourceSystem(id);
|
||||
}
|
||||
|
||||
@@ -140,6 +142,7 @@ public class MessageSourceSystemService {
|
||||
if (mappingByType != null) {
|
||||
fillDefaultChannel(view, ChannelTypeEnum.SMS.getCode(), mappingByType.get(ChannelTypeEnum.SMS.getCode()), channelMap);
|
||||
fillDefaultChannel(view, ChannelTypeEnum.EMAIL.getCode(), mappingByType.get(ChannelTypeEnum.EMAIL.getCode()), channelMap);
|
||||
fillDefaultChannel(view, ChannelTypeEnum.QQ.getCode(), mappingByType.get(ChannelTypeEnum.QQ.getCode()), channelMap);
|
||||
}
|
||||
return view;
|
||||
}
|
||||
@@ -159,8 +162,16 @@ public class MessageSourceSystemService {
|
||||
return;
|
||||
}
|
||||
|
||||
view.setDefaultEmailChannelId(mapping.getChannelId());
|
||||
view.setDefaultEmailChannelName(channel == null ? null : channel.getChannelName());
|
||||
if (ChannelTypeEnum.EMAIL.getCode().equals(channelType)) {
|
||||
view.setDefaultEmailChannelId(mapping.getChannelId());
|
||||
view.setDefaultEmailChannelName(channel == null ? null : channel.getChannelName());
|
||||
return;
|
||||
}
|
||||
|
||||
if (ChannelTypeEnum.QQ.getCode().equals(channelType)) {
|
||||
view.setDefaultQqChannelId(mapping.getChannelId());
|
||||
view.setDefaultQqChannelName(channel == null ? null : channel.getChannelName());
|
||||
}
|
||||
}
|
||||
|
||||
private Map<Long, MessageChannelConfigDO> fetchChannelMap(Set<Long> channelIds) {
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
spring:
|
||||
application:
|
||||
name: MessageHub
|
||||
servlet:
|
||||
multipart:
|
||||
max-file-size: 20MB
|
||||
max-request-size: 30MB
|
||||
|
||||
messagehub:
|
||||
channel:
|
||||
@@ -8,3 +12,8 @@ messagehub:
|
||||
encryption-key: ${MESSAGE_HUB_MASTER_KEY:MessageHub-Change-Me-2026}
|
||||
mock:
|
||||
auto-bootstrap: true
|
||||
retry:
|
||||
max-attempts: 3
|
||||
initial-delay-millis: 1000
|
||||
multiplier: 2.0
|
||||
max-delay-millis: 30000
|
||||
|
||||
@@ -4,24 +4,39 @@ spring:
|
||||
|
||||
cloud:
|
||||
nacos:
|
||||
discovery:
|
||||
server-addr: ${MESSAGE_HUB_NACOS_SERVER_ADDR}
|
||||
namespace: ${MESSAGE_HUB_NACOS_NAMESPACE:MessageHub-Dev}
|
||||
group: DEFAULT_GROUP
|
||||
service: ${spring.application.name}
|
||||
enabled: true
|
||||
register-enabled: true
|
||||
username: ${MESSAGE_HUB_NACOS_USERNAME}
|
||||
password: ${MESSAGE_HUB_NACOS_PASSWORD}
|
||||
# Nacos集群地址
|
||||
server-addr: home-nacos01:8848,home-nacos02:8848,home-nacos03:8848
|
||||
# 命名空间ID
|
||||
namespace: MessageHub-Dev
|
||||
# 分组名称
|
||||
group: DEFAULT_GROUP
|
||||
# 服务名称
|
||||
service: ${spring.application.name}
|
||||
# 是否启用服务发现
|
||||
enabled: true
|
||||
# 是否启用服务注册
|
||||
register-enabled: true
|
||||
# Nacos认证用户名
|
||||
username: xiaowang
|
||||
# Nacos认证密码
|
||||
password: 122503wcy....
|
||||
config:
|
||||
server-addr: ${MESSAGE_HUB_NACOS_SERVER_ADDR}
|
||||
namespace: ${MESSAGE_HUB_NACOS_NAMESPACE:MessageHub-Dev}
|
||||
# Nacos配置中心集群地址
|
||||
server-addr: home-nacos01:8848,home-nacos02:8848,home-nacos03:8848
|
||||
# 配置中心命名空间
|
||||
namespace: MessageHub-Dev
|
||||
# 配置分组
|
||||
group: DEFAULT_GROUP
|
||||
# 配置文件名称
|
||||
name: message-hub.yaml
|
||||
# 配置文件扩展名
|
||||
file-extension: yaml
|
||||
# 是否启用配置中心
|
||||
enabled: true
|
||||
username: ${MESSAGE_HUB_NACOS_USERNAME}
|
||||
password: ${MESSAGE_HUB_NACOS_PASSWORD}
|
||||
# Nacos认证用户名
|
||||
username: xiaowang
|
||||
# Nacos认证密码
|
||||
password: 122503wcy....
|
||||
shared-configs:
|
||||
- data-id: rabbitmq.yaml
|
||||
group: DEFAULT_GROUP
|
||||
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
-- MessageHub 邮件模板、附件与可靠投递补丁
|
||||
-- 适用日期:2026-05-12
|
||||
|
||||
USE `messagehub`;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `email_template` (
|
||||
`id` BIGINT NOT NULL COMMENT '主键',
|
||||
`template_code` VARCHAR(64) NOT NULL COMMENT '邮件模板编码',
|
||||
`template_name` VARCHAR(100) NOT NULL COMMENT '邮件模板名称',
|
||||
`subject_pattern` VARCHAR(255) NOT NULL COMMENT '主题模板',
|
||||
`body_type` VARCHAR(20) NOT NULL DEFAULT 'TEXT' COMMENT 'TEXT / HTML',
|
||||
`body_pattern` MEDIUMTEXT NOT NULL COMMENT '正文模板',
|
||||
`channel_id` BIGINT NULL COMMENT '绑定邮件通道ID,空表示全局通用',
|
||||
`is_enable` TINYINT NOT NULL DEFAULT 1 COMMENT '1 启用,0 停用',
|
||||
`description` VARCHAR(255) NULL COMMENT '描述',
|
||||
`create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_email_template_code` (`template_code`),
|
||||
KEY `idx_email_template_channel_id` (`channel_id`),
|
||||
KEY `idx_email_template_enable` (`is_enable`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='邮件模板表';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `email_attachment` (
|
||||
`id` BIGINT NOT NULL COMMENT '主键',
|
||||
`original_file_name` VARCHAR(255) NOT NULL COMMENT '原始文件名',
|
||||
`stored_file_name` VARCHAR(255) NOT NULL COMMENT '存储文件名',
|
||||
`storage_path` VARCHAR(1024) NOT NULL COMMENT '本地存储路径',
|
||||
`content_type` VARCHAR(128) NULL COMMENT 'MIME 类型',
|
||||
`file_extension` VARCHAR(32) NULL COMMENT '扩展名',
|
||||
`file_size` BIGINT NOT NULL COMMENT '文件大小,单位字节',
|
||||
`status` VARCHAR(20) NOT NULL DEFAULT 'ACTIVE' COMMENT 'ACTIVE / DELETED',
|
||||
`expire_time` DATETIME NULL COMMENT '过期时间',
|
||||
`create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_email_attachment_status` (`status`),
|
||||
KEY `idx_email_attachment_expire_time` (`expire_time`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='邮件附件表';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `email_attachment_policy` (
|
||||
`id` BIGINT NOT NULL COMMENT '固定主键',
|
||||
`max_single_file_size` BIGINT NOT NULL COMMENT '单文件最大字节数',
|
||||
`max_total_file_size` BIGINT NOT NULL COMMENT '单封邮件附件总字节数',
|
||||
`max_file_count` INT NOT NULL COMMENT '单封邮件最大附件数量',
|
||||
`allowed_extensions` TEXT NULL COMMENT '允许扩展名,逗号分隔',
|
||||
`allowed_mime_types` TEXT NULL COMMENT '允许 MIME,逗号分隔',
|
||||
`retention_days` INT NOT NULL COMMENT '附件保留天数',
|
||||
`read_timeout_millis` INT NOT NULL COMMENT '读取超时毫秒',
|
||||
`create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (`id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='邮件附件策略表';
|
||||
|
||||
INSERT INTO `email_attachment_policy` (
|
||||
`id`, `max_single_file_size`, `max_total_file_size`, `max_file_count`,
|
||||
`allowed_extensions`, `allowed_mime_types`, `retention_days`, `read_timeout_millis`
|
||||
)
|
||||
SELECT 1, 10485760, 20971520, 5,
|
||||
'pdf,doc,docx,xls,xlsx,png,jpg,jpeg,txt',
|
||||
'application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,image/png,image/jpeg,text/plain',
|
||||
7, 5000
|
||||
WHERE NOT EXISTS (SELECT 1 FROM `email_attachment_policy` WHERE `id` = 1);
|
||||
|
||||
DROP PROCEDURE IF EXISTS sp_add_column_if_missing;
|
||||
DROP PROCEDURE IF EXISTS sp_add_index_if_missing;
|
||||
|
||||
DELIMITER $$
|
||||
|
||||
CREATE PROCEDURE sp_add_column_if_missing(
|
||||
IN p_table_name VARCHAR(64),
|
||||
IN p_column_name VARCHAR(64),
|
||||
IN p_column_definition TEXT
|
||||
)
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = p_table_name
|
||||
AND COLUMN_NAME = p_column_name
|
||||
) THEN
|
||||
SET @alter_sql = CONCAT('ALTER TABLE `', p_table_name, '` ADD COLUMN `', p_column_name, '` ', p_column_definition);
|
||||
PREPARE stmt FROM @alter_sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
END IF;
|
||||
END$$
|
||||
|
||||
CREATE PROCEDURE sp_add_index_if_missing(
|
||||
IN p_table_name VARCHAR(64),
|
||||
IN p_index_name VARCHAR(64),
|
||||
IN p_index_definition TEXT
|
||||
)
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM information_schema.STATISTICS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = p_table_name
|
||||
AND INDEX_NAME = p_index_name
|
||||
) THEN
|
||||
SET @index_sql = CONCAT('ALTER TABLE `', p_table_name, '` ADD INDEX `', p_index_name, '` ', p_index_definition);
|
||||
PREPARE stmt FROM @index_sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
END IF;
|
||||
END$$
|
||||
|
||||
DELIMITER ;
|
||||
|
||||
CALL sp_add_column_if_missing('push_log', 'channel_id', 'BIGINT NULL COMMENT ''实际投递通道ID'' AFTER `channel_type`');
|
||||
CALL sp_add_column_if_missing('push_log', 'provider_code', 'VARCHAR(50) NULL COMMENT ''实际投递提供商'' AFTER `channel_id`');
|
||||
CALL sp_add_column_if_missing('push_log', 'next_retry_time', 'DATETIME NULL COMMENT ''下一次重试时间'' AFTER `retry_count`');
|
||||
CALL sp_add_column_if_missing('push_log', 'dead_letter_reason', 'VARCHAR(255) NULL COMMENT ''死信原因'' AFTER `fail_reason`');
|
||||
CALL sp_add_column_if_missing('push_log', 'request_payload', 'MEDIUMTEXT NULL COMMENT ''原始请求体'' AFTER `dead_letter_reason`');
|
||||
CALL sp_add_column_if_missing('push_log', 'provider_response', 'TEXT NULL COMMENT ''提供商响应摘要'' AFTER `request_payload`');
|
||||
CALL sp_add_column_if_missing('push_log', 'update_time', 'DATETIME NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT ''更新时间'' AFTER `create_time`');
|
||||
|
||||
DROP PROCEDURE IF EXISTS sp_add_column_if_missing;
|
||||
CALL sp_add_index_if_missing('push_log', 'idx_push_log_channel_id', '(`channel_id`)');
|
||||
CALL sp_add_index_if_missing('push_log', 'idx_push_log_next_retry_time', '(`next_retry_time`)');
|
||||
CALL sp_add_index_if_missing('push_log', 'idx_push_log_dead_letter_reason', '(`dead_letter_reason`)');
|
||||
CALL sp_add_index_if_missing('push_log', 'idx_push_log_source_unique_id', '(`source_system`, `unique_id`)');
|
||||
|
||||
DROP PROCEDURE IF EXISTS sp_add_index_if_missing;
|
||||
@@ -48,6 +48,104 @@ const PROVIDERS = {
|
||||
{ key: "password", label: "SMTP 密码/授权码", required: true }
|
||||
]
|
||||
},
|
||||
NETEASE_163: {
|
||||
label: "网易 163 邮箱 SMTP",
|
||||
helpText: "网易 163 邮箱常用 smtp.163.com,推荐 465+SSL 或 994/587 按账号策略配置,密码填写授权码。",
|
||||
configFields: [
|
||||
{ key: "host", label: "SMTP 主机", placeholder: "smtp.163.com", required: true, defaultValue: "smtp.163.com" },
|
||||
{ key: "port", label: "SMTP 端口", placeholder: "465", required: true, defaultValue: "465" },
|
||||
{ key: "username", label: "SMTP 用户名", placeholder: "your-account@163.com", required: true },
|
||||
{ key: "fromAddress", label: "发件地址", placeholder: "your-account@163.com", required: true },
|
||||
{ key: "auth", label: "启用认证", type: "checkbox", defaultValue: true },
|
||||
{ key: "starttls", label: "启用 STARTTLS", type: "checkbox", defaultValue: false },
|
||||
{ key: "ssl", label: "启用 SSL", type: "checkbox", defaultValue: true }
|
||||
],
|
||||
secretFields: [{ key: "password", label: "SMTP 密码/授权码", required: true }]
|
||||
},
|
||||
NETEASE_126: {
|
||||
label: "网易 126 邮箱 SMTP",
|
||||
helpText: "网易 126 邮箱常用 smtp.126.com,推荐 465+SSL,密码填写授权码。",
|
||||
configFields: [
|
||||
{ key: "host", label: "SMTP 主机", placeholder: "smtp.126.com", required: true, defaultValue: "smtp.126.com" },
|
||||
{ key: "port", label: "SMTP 端口", placeholder: "465", required: true, defaultValue: "465" },
|
||||
{ key: "username", label: "SMTP 用户名", placeholder: "your-account@126.com", required: true },
|
||||
{ key: "fromAddress", label: "发件地址", placeholder: "your-account@126.com", required: true },
|
||||
{ key: "auth", label: "启用认证", type: "checkbox", defaultValue: true },
|
||||
{ key: "starttls", label: "启用 STARTTLS", type: "checkbox", defaultValue: false },
|
||||
{ key: "ssl", label: "启用 SSL", type: "checkbox", defaultValue: true }
|
||||
],
|
||||
secretFields: [{ key: "password", label: "SMTP 密码/授权码", required: true }]
|
||||
},
|
||||
OUTLOOK: {
|
||||
label: "Outlook SMTP",
|
||||
helpText: "Outlook 推荐 smtp.office365.com:587,开启 STARTTLS,密码使用应用密码或账号授权方式。",
|
||||
configFields: [
|
||||
{ key: "host", label: "SMTP 主机", placeholder: "smtp.office365.com", required: true, defaultValue: "smtp.office365.com" },
|
||||
{ key: "port", label: "SMTP 端口", placeholder: "587", required: true, defaultValue: "587" },
|
||||
{ key: "username", label: "SMTP 用户名", placeholder: "your-account@outlook.com", required: true },
|
||||
{ key: "fromAddress", label: "发件地址", placeholder: "your-account@outlook.com", required: true },
|
||||
{ key: "auth", label: "启用认证", type: "checkbox", defaultValue: true },
|
||||
{ key: "starttls", label: "启用 STARTTLS", type: "checkbox", defaultValue: true },
|
||||
{ key: "ssl", label: "启用 SSL", type: "checkbox", defaultValue: false }
|
||||
],
|
||||
secretFields: [{ key: "password", label: "SMTP 密码/应用密码", required: true }]
|
||||
},
|
||||
HOTMAIL: {
|
||||
label: "Hotmail SMTP",
|
||||
helpText: "Hotmail 使用 Outlook SMTP,推荐 smtp.office365.com:587 + STARTTLS。",
|
||||
configFields: [
|
||||
{ key: "host", label: "SMTP 主机", placeholder: "smtp.office365.com", required: true, defaultValue: "smtp.office365.com" },
|
||||
{ key: "port", label: "SMTP 端口", placeholder: "587", required: true, defaultValue: "587" },
|
||||
{ key: "username", label: "SMTP 用户名", placeholder: "your-account@hotmail.com", required: true },
|
||||
{ key: "fromAddress", label: "发件地址", placeholder: "your-account@hotmail.com", required: true },
|
||||
{ key: "auth", label: "启用认证", type: "checkbox", defaultValue: true },
|
||||
{ key: "starttls", label: "启用 STARTTLS", type: "checkbox", defaultValue: true },
|
||||
{ key: "ssl", label: "启用 SSL", type: "checkbox", defaultValue: false }
|
||||
],
|
||||
secretFields: [{ key: "password", label: "SMTP 密码/应用密码", required: true }]
|
||||
},
|
||||
ALIYUN_ENTERPRISE: {
|
||||
label: "阿里企业邮箱 SMTP",
|
||||
helpText: "阿里企业邮箱常用 smtp.qiye.aliyun.com,推荐 465+SSL 或 587+STARTTLS。",
|
||||
configFields: [
|
||||
{ key: "host", label: "SMTP 主机", placeholder: "smtp.qiye.aliyun.com", required: true, defaultValue: "smtp.qiye.aliyun.com" },
|
||||
{ key: "port", label: "SMTP 端口", placeholder: "465", required: true, defaultValue: "465" },
|
||||
{ key: "username", label: "SMTP 用户名", placeholder: "name@company.com", required: true },
|
||||
{ key: "fromAddress", label: "发件地址", placeholder: "name@company.com", required: true },
|
||||
{ key: "auth", label: "启用认证", type: "checkbox", defaultValue: true },
|
||||
{ key: "starttls", label: "启用 STARTTLS", type: "checkbox", defaultValue: false },
|
||||
{ key: "ssl", label: "启用 SSL", type: "checkbox", defaultValue: true }
|
||||
],
|
||||
secretFields: [{ key: "password", label: "SMTP 密码/授权码", required: true }]
|
||||
},
|
||||
TENCENT_ENTERPRISE: {
|
||||
label: "腾讯企业邮箱 SMTP",
|
||||
helpText: "腾讯企业邮箱常用 smtp.exmail.qq.com,推荐 465+SSL 或 587+STARTTLS。",
|
||||
configFields: [
|
||||
{ key: "host", label: "SMTP 主机", placeholder: "smtp.exmail.qq.com", required: true, defaultValue: "smtp.exmail.qq.com" },
|
||||
{ key: "port", label: "SMTP 端口", placeholder: "465", required: true, defaultValue: "465" },
|
||||
{ key: "username", label: "SMTP 用户名", placeholder: "name@company.com", required: true },
|
||||
{ key: "fromAddress", label: "发件地址", placeholder: "name@company.com", required: true },
|
||||
{ key: "auth", label: "启用认证", type: "checkbox", defaultValue: true },
|
||||
{ key: "starttls", label: "启用 STARTTLS", type: "checkbox", defaultValue: false },
|
||||
{ key: "ssl", label: "启用 SSL", type: "checkbox", defaultValue: true }
|
||||
],
|
||||
secretFields: [{ key: "password", label: "SMTP 密码/授权码", required: true }]
|
||||
},
|
||||
SMTP_GENERIC: {
|
||||
label: "通用 SMTP",
|
||||
helpText: "用于自建或其他 SMTP 服务。若服务无需认证,可关闭“启用认证”并留空用户名/密码。",
|
||||
configFields: [
|
||||
{ key: "host", label: "SMTP 主机", placeholder: "smtp.example.com", required: true },
|
||||
{ key: "port", label: "SMTP 端口", placeholder: "587", required: true, defaultValue: "587" },
|
||||
{ key: "username", label: "SMTP 用户名", placeholder: "可选" },
|
||||
{ key: "fromAddress", label: "发件地址", placeholder: "notice@example.com", required: true },
|
||||
{ key: "auth", label: "启用认证", type: "checkbox", defaultValue: true },
|
||||
{ key: "starttls", label: "启用 STARTTLS", type: "checkbox", defaultValue: true },
|
||||
{ key: "ssl", label: "启用 SSL", type: "checkbox", defaultValue: false }
|
||||
],
|
||||
secretFields: [{ key: "password", label: "SMTP 密码/授权码", required: false }]
|
||||
},
|
||||
MOCK_EMAIL: {
|
||||
label: "开发 Mock 邮件",
|
||||
configFields: [
|
||||
@@ -55,6 +153,31 @@ const PROVIDERS = {
|
||||
],
|
||||
secretFields: []
|
||||
}
|
||||
},
|
||||
QQ: {
|
||||
QQAUTO: {
|
||||
label: "QQAuto QQ",
|
||||
helpText: "通过 qqauto gateway 调用 NapCat/QQ 机器人。MessageHub 使用服务令牌访问白名单发送接口,不依赖后台登录态。",
|
||||
configFields: [
|
||||
{ key: "baseUrl", label: "QQAuto 网关地址", placeholder: "http://localhost:8080", required: true, defaultValue: "http://localhost:8080" },
|
||||
{ key: "configCode", label: "机器人配置编码", placeholder: "main-bot" },
|
||||
{ key: "accountId", label: "账号ID", placeholder: "可选,留空按 configCode 路由" },
|
||||
{ key: "botSelfId", label: "机器人QQ号", placeholder: "可选,用于备注识别" },
|
||||
{ key: "transportOverride", label: "传输覆盖", placeholder: "AUTO / HTTP / WEBSOCKET", defaultValue: "AUTO" },
|
||||
{ key: "defaultTargetType", label: "默认目标类型", placeholder: "GROUP 或 FRIEND", defaultValue: "GROUP" },
|
||||
{ key: "timeoutMs", label: "超时时间毫秒", placeholder: "10000", required: true, defaultValue: "10000" },
|
||||
{ key: "contentMode", label: "默认内容模式", placeholder: "TEXT 或 ONEBOT_JSON", defaultValue: "TEXT" },
|
||||
{ key: "autoEscape", label: "文本自动转义", type: "checkbox", defaultValue: true }
|
||||
],
|
||||
secretFields: [
|
||||
{ key: "serviceToken", label: "MessageHub 服务令牌", required: true }
|
||||
]
|
||||
},
|
||||
MOCK_QQ: {
|
||||
label: "开发 Mock QQ",
|
||||
configFields: [],
|
||||
secretFields: []
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -62,10 +185,19 @@ const state = {
|
||||
channels: [],
|
||||
smsTemplates: [],
|
||||
smsTemplateConfigs: [],
|
||||
emailTemplates: [],
|
||||
emailTemplateConfigs: [],
|
||||
qqTemplates: [],
|
||||
qqTemplateConfigs: [],
|
||||
uploadedEmailAttachments: [],
|
||||
pushLogs: [],
|
||||
attachmentPolicy: null,
|
||||
sourceSystems: [],
|
||||
editingChannel: null,
|
||||
editingSourceSystem: null,
|
||||
editingSmsTemplate: null
|
||||
editingSmsTemplate: null,
|
||||
editingEmailTemplate: null,
|
||||
editingQqTemplate: null
|
||||
};
|
||||
|
||||
const elements = {
|
||||
@@ -84,6 +216,7 @@ const elements = {
|
||||
sourceSystemEnabled: document.getElementById("sourceSystemEnabled"),
|
||||
defaultSmsChannelId: document.getElementById("defaultSmsChannelId"),
|
||||
defaultEmailChannelId: document.getElementById("defaultEmailChannelId"),
|
||||
defaultQqChannelId: document.getElementById("defaultQqChannelId"),
|
||||
sourceFormTitle: document.getElementById("sourceFormTitle"),
|
||||
sourceFormSubtitle: document.getElementById("sourceFormSubtitle"),
|
||||
sourceResetButton: document.getElementById("sourceResetButton"),
|
||||
@@ -107,11 +240,23 @@ const elements = {
|
||||
testChannelId: document.getElementById("testChannelId"),
|
||||
testReceiver: document.getElementById("testReceiver"),
|
||||
testSubject: document.getElementById("testSubject"),
|
||||
testEmailTemplateCode: document.getElementById("testEmailTemplateCode"),
|
||||
testEmailBodyType: document.getElementById("testEmailBodyType"),
|
||||
testTemplateCode: document.getElementById("testTemplateCode"),
|
||||
testQqTargetType: document.getElementById("testQqTargetType"),
|
||||
testQqTemplateCode: document.getElementById("testQqTemplateCode"),
|
||||
testQqContentMode: document.getElementById("testQqContentMode"),
|
||||
testContent: document.getElementById("testContent"),
|
||||
testEmailTemplatePreview: document.getElementById("testEmailTemplatePreview"),
|
||||
testEmailTemplatePlaceholderFields: document.getElementById("testEmailTemplatePlaceholderFields"),
|
||||
testAttachmentFile: document.getElementById("testAttachmentFile"),
|
||||
testAttachmentUploadButton: document.getElementById("testAttachmentUploadButton"),
|
||||
testAttachmentList: document.getElementById("testAttachmentList"),
|
||||
testTemplatePreview: document.getElementById("testTemplatePreview"),
|
||||
testTemplatePlaceholderFields: document.getElementById("testTemplatePlaceholderFields"),
|
||||
testSmsPreview: document.getElementById("testSmsPreview"),
|
||||
testQqPreview: document.getElementById("testQqPreview"),
|
||||
testQqTemplatePlaceholderFields: document.getElementById("testQqTemplatePlaceholderFields"),
|
||||
|
||||
templateTableBody: document.getElementById("templateTableBody"),
|
||||
templateEmptyState: document.getElementById("templateEmptyState"),
|
||||
@@ -129,6 +274,59 @@ const elements = {
|
||||
templateFormSubtitle: document.getElementById("templateFormSubtitle"),
|
||||
templateResetButton: document.getElementById("templateResetButton"),
|
||||
|
||||
createEmailTemplateButton: document.getElementById("createEmailTemplateButton"),
|
||||
emailTemplateTableBody: document.getElementById("emailTemplateTableBody"),
|
||||
emailTemplateEmptyState: document.getElementById("emailTemplateEmptyState"),
|
||||
emailTemplateForm: document.getElementById("emailTemplateForm"),
|
||||
emailTemplateId: document.getElementById("emailTemplateId"),
|
||||
emailTemplateCode: document.getElementById("emailTemplateCode"),
|
||||
emailTemplateName: document.getElementById("emailTemplateName"),
|
||||
emailTemplateChannelId: document.getElementById("emailTemplateChannelId"),
|
||||
emailTemplateBodyType: document.getElementById("emailTemplateBodyType"),
|
||||
emailTemplateDescription: document.getElementById("emailTemplateDescription"),
|
||||
emailTemplateEnabled: document.getElementById("emailTemplateEnabled"),
|
||||
emailTemplateSubjectPattern: document.getElementById("emailTemplateSubjectPattern"),
|
||||
emailTemplateBodyPattern: document.getElementById("emailTemplateBodyPattern"),
|
||||
emailTemplatePlaceholderPreview: document.getElementById("emailTemplatePlaceholderPreview"),
|
||||
emailTemplateFormTitle: document.getElementById("emailTemplateFormTitle"),
|
||||
emailTemplateFormSubtitle: document.getElementById("emailTemplateFormSubtitle"),
|
||||
emailTemplateResetButton: document.getElementById("emailTemplateResetButton"),
|
||||
|
||||
createQqTemplateButton: document.getElementById("createQqTemplateButton"),
|
||||
qqTemplateTableBody: document.getElementById("qqTemplateTableBody"),
|
||||
qqTemplateEmptyState: document.getElementById("qqTemplateEmptyState"),
|
||||
qqTemplateForm: document.getElementById("qqTemplateForm"),
|
||||
qqTemplateId: document.getElementById("qqTemplateId"),
|
||||
qqTemplateCode: document.getElementById("qqTemplateCode"),
|
||||
qqTemplateName: document.getElementById("qqTemplateName"),
|
||||
qqTemplateChannelId: document.getElementById("qqTemplateChannelId"),
|
||||
qqTemplateDescription: document.getElementById("qqTemplateDescription"),
|
||||
qqTemplateEnabled: document.getElementById("qqTemplateEnabled"),
|
||||
qqTemplateContentPattern: document.getElementById("qqTemplateContentPattern"),
|
||||
qqTemplatePlaceholderPreview: document.getElementById("qqTemplatePlaceholderPreview"),
|
||||
qqTemplateFormTitle: document.getElementById("qqTemplateFormTitle"),
|
||||
qqTemplateFormSubtitle: document.getElementById("qqTemplateFormSubtitle"),
|
||||
qqTemplateResetButton: document.getElementById("qqTemplateResetButton"),
|
||||
|
||||
attachmentPolicyForm: document.getElementById("attachmentPolicyForm"),
|
||||
maxSingleFileSize: document.getElementById("maxSingleFileSize"),
|
||||
maxTotalFileSize: document.getElementById("maxTotalFileSize"),
|
||||
maxFileCount: document.getElementById("maxFileCount"),
|
||||
allowedExtensions: document.getElementById("allowedExtensions"),
|
||||
allowedMimeTypes: document.getElementById("allowedMimeTypes"),
|
||||
retentionDays: document.getElementById("retentionDays"),
|
||||
readTimeoutMillis: document.getElementById("readTimeoutMillis"),
|
||||
|
||||
loadPushLogsButton: document.getElementById("loadPushLogsButton"),
|
||||
pushLogFilterForm: document.getElementById("pushLogFilterForm"),
|
||||
pushLogSourceSystem: document.getElementById("pushLogSourceSystem"),
|
||||
pushLogChannelType: document.getElementById("pushLogChannelType"),
|
||||
pushLogStatus: document.getElementById("pushLogStatus"),
|
||||
pushLogKeyword: document.getElementById("pushLogKeyword"),
|
||||
pushLogDeadLetter: document.getElementById("pushLogDeadLetter"),
|
||||
pushLogEmptyState: document.getElementById("pushLogEmptyState"),
|
||||
pushLogTableBody: document.getElementById("pushLogTableBody"),
|
||||
|
||||
toast: document.getElementById("toast")
|
||||
};
|
||||
|
||||
@@ -209,6 +407,28 @@ function findSmsChannelById(channelId) {
|
||||
return state.channels.find((item) => String(item.id) === String(channelId)) || null;
|
||||
}
|
||||
|
||||
function listEmailChannels() {
|
||||
return state.channels
|
||||
.filter((item) => item.channelType === "EMAIL")
|
||||
.slice()
|
||||
.sort((left, right) => Number(left.id) - Number(right.id));
|
||||
}
|
||||
|
||||
function findEmailChannelById(channelId) {
|
||||
return state.channels.find((item) => String(item.id) === String(channelId)) || null;
|
||||
}
|
||||
|
||||
function listQqChannels() {
|
||||
return state.channels
|
||||
.filter((item) => item.channelType === "QQ")
|
||||
.slice()
|
||||
.sort((left, right) => Number(left.id) - Number(right.id));
|
||||
}
|
||||
|
||||
function findQqChannelById(channelId) {
|
||||
return state.channels.find((item) => String(item.id) === String(channelId)) || null;
|
||||
}
|
||||
|
||||
function getAvailableSmsTemplatesForTest() {
|
||||
const channel = findSelectedTestChannel();
|
||||
if (!channel || channel.channelType !== "SMS") {
|
||||
@@ -223,6 +443,34 @@ function findSelectedSmsTemplate() {
|
||||
return getAvailableSmsTemplatesForTest().find((item) => item.templateCode === elements.testTemplateCode.value) || null;
|
||||
}
|
||||
|
||||
function getAvailableEmailTemplatesForTest() {
|
||||
const channel = findSelectedTestChannel();
|
||||
if (!channel || channel.channelType !== "EMAIL") {
|
||||
return [];
|
||||
}
|
||||
return state.emailTemplates.filter((template) => {
|
||||
return template.channelId == null || String(template.channelId) === String(channel.id);
|
||||
});
|
||||
}
|
||||
|
||||
function findSelectedEmailTemplate() {
|
||||
return getAvailableEmailTemplatesForTest().find((item) => item.templateCode === elements.testEmailTemplateCode.value) || null;
|
||||
}
|
||||
|
||||
function getAvailableQqTemplatesForTest() {
|
||||
const channel = findSelectedTestChannel();
|
||||
if (!channel || channel.channelType !== "QQ") {
|
||||
return [];
|
||||
}
|
||||
return state.qqTemplates.filter((template) => {
|
||||
return template.channelId == null || String(template.channelId) === String(channel.id);
|
||||
});
|
||||
}
|
||||
|
||||
function findSelectedQqTemplate() {
|
||||
return getAvailableQqTemplatesForTest().find((item) => item.templateCode === elements.testQqTemplateCode.value) || null;
|
||||
}
|
||||
|
||||
function extractPlaceholdersFromContent(contentPattern) {
|
||||
const placeholders = [];
|
||||
const regex = /\$\{([^{}]+)\}/g;
|
||||
@@ -259,6 +507,14 @@ function generateSmsTemplateCode() {
|
||||
return chars.join("");
|
||||
}
|
||||
|
||||
function generateEmailTemplateCode() {
|
||||
return `EM${generateSmsTemplateCode().slice(0, 14)}`;
|
||||
}
|
||||
|
||||
function generateQqTemplateCode() {
|
||||
return `QQ${generateSmsTemplateCode().slice(0, 14)}`;
|
||||
}
|
||||
|
||||
function renderPlaceholderChips(placeholders) {
|
||||
if (!placeholders || placeholders.length === 0) {
|
||||
return '<span class="table-note">未识别到占位符</span>';
|
||||
@@ -277,7 +533,12 @@ function buildChannelOptions(channelType, selectedId = "") {
|
||||
items.unshift(selectedChannel);
|
||||
}
|
||||
|
||||
const defaultLabel = channelType === "SMS" ? "跟随全局默认短信通道" : "跟随全局默认邮件通道";
|
||||
const defaultLabels = {
|
||||
SMS: "跟随全局默认短信通道",
|
||||
EMAIL: "跟随全局默认邮件通道",
|
||||
QQ: "跟随全局默认 QQ 通道"
|
||||
};
|
||||
const defaultLabel = defaultLabels[channelType] || "跟随全局默认通道";
|
||||
const options = [`<option value="">${defaultLabel}</option>`];
|
||||
|
||||
items.forEach((channel) => {
|
||||
@@ -294,6 +555,7 @@ function buildChannelOptions(channelType, selectedId = "") {
|
||||
function fillSourceChannelOptions(sourceSystem = state.editingSourceSystem) {
|
||||
elements.defaultSmsChannelId.innerHTML = buildChannelOptions("SMS", sourceSystem?.defaultSmsChannelId || "");
|
||||
elements.defaultEmailChannelId.innerHTML = buildChannelOptions("EMAIL", sourceSystem?.defaultEmailChannelId || "");
|
||||
elements.defaultQqChannelId.innerHTML = buildChannelOptions("QQ", sourceSystem?.defaultQqChannelId || "");
|
||||
}
|
||||
|
||||
function fillSmsTemplateChannelOptions(selectedId = "") {
|
||||
@@ -308,6 +570,30 @@ function fillSmsTemplateChannelOptions(selectedId = "") {
|
||||
elements.smsTemplateChannelId.innerHTML = options.join("");
|
||||
}
|
||||
|
||||
function fillEmailTemplateChannelOptions(selectedId = "") {
|
||||
const options = ['<option value="">全局通用(不绑定)</option>'];
|
||||
listEmailChannels().forEach((channel) => {
|
||||
const selected = String(channel.id) === String(selectedId) ? "selected" : "";
|
||||
const statusText = channel.enabled ? "" : "(当前已停用)";
|
||||
options.push(
|
||||
`<option value="${channel.id}" ${selected}>${escapeHtml(channel.channelName)} / ID:${channel.id}${statusText}</option>`
|
||||
);
|
||||
});
|
||||
elements.emailTemplateChannelId.innerHTML = options.join("");
|
||||
}
|
||||
|
||||
function fillQqTemplateChannelOptions(selectedId = "") {
|
||||
const options = ['<option value="">全局通用(不绑定)</option>'];
|
||||
listQqChannels().forEach((channel) => {
|
||||
const selected = String(channel.id) === String(selectedId) ? "selected" : "";
|
||||
const statusText = channel.enabled ? "" : "(当前已停用)";
|
||||
options.push(
|
||||
`<option value="${channel.id}" ${selected}>${escapeHtml(channel.channelName)} / ID:${channel.id}${statusText}</option>`
|
||||
);
|
||||
});
|
||||
elements.qqTemplateChannelId.innerHTML = options.join("");
|
||||
}
|
||||
|
||||
function templateBindingText(template) {
|
||||
if (!template.channelId) {
|
||||
return '<span class="badge warn">全局通用</span>';
|
||||
@@ -316,6 +602,14 @@ function templateBindingText(template) {
|
||||
return `<strong>${channelName}</strong><div class="table-note">ID:${template.channelId}</div>`;
|
||||
}
|
||||
|
||||
function emailTemplateBindingText(template) {
|
||||
if (!template.channelId) {
|
||||
return '<span class="badge warn">全局通用</span>';
|
||||
}
|
||||
const channelName = template.channelName ? escapeHtml(template.channelName) : "未知通道";
|
||||
return `<strong>${channelName}</strong><div class="table-note">ID:${template.channelId}</div>`;
|
||||
}
|
||||
|
||||
function resetSourceSystemForm(sourceSystem = null) {
|
||||
state.editingSourceSystem = sourceSystem;
|
||||
elements.sourceSystemId.value = sourceSystem?.id || "";
|
||||
@@ -358,6 +652,7 @@ function renderSourceSystemTable() {
|
||||
<td>${sourceStatusBadge(sourceSystem)}</td>
|
||||
<td>${defaultChannelText(sourceSystem.defaultSmsChannelId, sourceSystem.defaultSmsChannelName)}</td>
|
||||
<td>${defaultChannelText(sourceSystem.defaultEmailChannelId, sourceSystem.defaultEmailChannelName)}</td>
|
||||
<td>${defaultChannelText(sourceSystem.defaultQqChannelId, sourceSystem.defaultQqChannelName)}</td>
|
||||
<td>${formatDateTime(sourceSystem.updateTime)}</td>
|
||||
<td>
|
||||
<div class="actions">
|
||||
@@ -391,7 +686,8 @@ async function onSourceSystemSubmit(event) {
|
||||
remark: elements.sourceSystemRemark.value.trim(),
|
||||
enabled: elements.sourceSystemEnabled.checked,
|
||||
defaultSmsChannelId: elements.defaultSmsChannelId.value ? Number(elements.defaultSmsChannelId.value) : null,
|
||||
defaultEmailChannelId: elements.defaultEmailChannelId.value ? Number(elements.defaultEmailChannelId.value) : null
|
||||
defaultEmailChannelId: elements.defaultEmailChannelId.value ? Number(elements.defaultEmailChannelId.value) : null,
|
||||
defaultQqChannelId: elements.defaultQqChannelId.value ? Number(elements.defaultQqChannelId.value) : null
|
||||
};
|
||||
|
||||
const sourceSystemId = elements.sourceSystemId.value;
|
||||
@@ -608,6 +904,92 @@ function renderSmsTemplateTable() {
|
||||
});
|
||||
}
|
||||
|
||||
function updateEmailTemplatePlaceholderPreview() {
|
||||
const subjectPattern = elements.emailTemplateSubjectPattern.value.trim();
|
||||
const bodyPattern = elements.emailTemplateBodyPattern.value.trim();
|
||||
const placeholders = [
|
||||
...new Set([
|
||||
...extractPlaceholdersFromContent(subjectPattern),
|
||||
...extractPlaceholdersFromContent(bodyPattern)
|
||||
])
|
||||
];
|
||||
|
||||
if (!subjectPattern && !bodyPattern) {
|
||||
setPreviewText(elements.emailTemplatePlaceholderPreview, "", "输入主题或正文后,这里会自动识别占位符并展示预览。");
|
||||
return;
|
||||
}
|
||||
|
||||
elements.emailTemplatePlaceholderPreview.innerHTML = `
|
||||
<div><strong>主题预览</strong></div>
|
||||
<div class="template-content-snippet">${escapeHtml(subjectPattern || "未填写主题")}</div>
|
||||
<div class="table-note">识别到 ${placeholders.length} 个占位符</div>
|
||||
${renderPlaceholderChips(placeholders)}
|
||||
<div class="template-content-snippet">${escapeHtml(bodyPattern || "未填写正文")}</div>
|
||||
`;
|
||||
elements.emailTemplatePlaceholderPreview.classList.remove("empty-state");
|
||||
}
|
||||
|
||||
function resetEmailTemplateForm(template = null) {
|
||||
state.editingEmailTemplate = template;
|
||||
elements.emailTemplateId.value = template?.id || "";
|
||||
elements.emailTemplateCode.value = template?.templateCode || generateEmailTemplateCode();
|
||||
elements.emailTemplateName.value = template?.templateName || "";
|
||||
fillEmailTemplateChannelOptions(template?.channelId ?? "");
|
||||
elements.emailTemplateBodyType.value = template?.bodyType || "TEXT";
|
||||
elements.emailTemplateDescription.value = template?.description || "";
|
||||
elements.emailTemplateEnabled.checked = template?.enabled ?? true;
|
||||
elements.emailTemplateSubjectPattern.value = template?.subjectPattern || "";
|
||||
elements.emailTemplateBodyPattern.value = template?.bodyPattern || "";
|
||||
elements.emailTemplateFormTitle.textContent = template ? "编辑邮件模板" : "新增邮件模板";
|
||||
elements.emailTemplateFormSubtitle.textContent = template
|
||||
? `当前模板 ID:${template.id}。已绑定通道的模板只能在对应邮件通道中测试和发送。`
|
||||
: "保存后可在测试发送和 MQ 邮件消息中使用。";
|
||||
updateEmailTemplatePlaceholderPreview();
|
||||
}
|
||||
|
||||
function emailTemplateStatusBadge(template) {
|
||||
return template.enabled
|
||||
? '<span class="badge good">已启用</span>'
|
||||
: '<span class="badge bad">已停用</span>';
|
||||
}
|
||||
|
||||
function renderEmailTemplateTable() {
|
||||
elements.emailTemplateTableBody.innerHTML = "";
|
||||
elements.emailTemplateEmptyState.hidden = state.emailTemplateConfigs.length > 0;
|
||||
|
||||
state.emailTemplateConfigs.forEach((template) => {
|
||||
const row = document.createElement("tr");
|
||||
row.innerHTML = `
|
||||
<td>
|
||||
<strong>${escapeHtml(template.templateName)}</strong>
|
||||
<div class="table-note">模板ID:<code>${escapeHtml(template.templateCode)}</code></div>
|
||||
${template.description ? `<div class="table-note">${escapeHtml(template.description)}</div>` : ""}
|
||||
</td>
|
||||
<td>${emailTemplateBindingText(template)}</td>
|
||||
<td><span class="badge warn">${escapeHtml(template.bodyType || "TEXT")}</span></td>
|
||||
<td>${emailTemplateStatusBadge(template)}</td>
|
||||
<td>
|
||||
<div class="template-content-snippet"><strong>${escapeHtml(template.subjectPattern || "")}</strong></div>
|
||||
<div class="template-content-snippet">${escapeHtml(template.bodyPattern || "")}</div>
|
||||
${renderPlaceholderChips(template.placeholders || [])}
|
||||
</td>
|
||||
<td>${formatDateTime(template.updateTime)}</td>
|
||||
<td>
|
||||
<div class="actions">
|
||||
<button class="ghost-button small" data-email-template-action="edit" data-id="${template.id}">编辑</button>
|
||||
<button class="ghost-button small" data-email-template-action="status" data-id="${template.id}">
|
||||
${template.enabled ? "停用" : "启用"}
|
||||
</button>
|
||||
<button class="ghost-button small" data-email-template-action="test" data-id="${template.id}" ${template.enabled ? "" : "disabled"}>
|
||||
带入测试
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
`;
|
||||
elements.emailTemplateTableBody.appendChild(row);
|
||||
});
|
||||
}
|
||||
|
||||
function statusBadge(channel) {
|
||||
if (!channel.enabled) {
|
||||
return `<span class="badge warn">已停用</span>`;
|
||||
@@ -664,6 +1046,52 @@ function renderChannelTable() {
|
||||
fillTestChannelOptions();
|
||||
}
|
||||
|
||||
function pushLogStatusText(status) {
|
||||
if (status === 1) {
|
||||
return '<span class="badge good">成功</span>';
|
||||
}
|
||||
if (status === 2) {
|
||||
return '<span class="badge bad">失败</span>';
|
||||
}
|
||||
return '<span class="badge warn">待发送/重试</span>';
|
||||
}
|
||||
|
||||
function renderPushLogTable() {
|
||||
elements.pushLogTableBody.innerHTML = "";
|
||||
elements.pushLogEmptyState.hidden = state.pushLogs.length > 0;
|
||||
|
||||
state.pushLogs.forEach((log) => {
|
||||
const row = document.createElement("tr");
|
||||
const reason = log.deadLetterReason || log.failReason || "-";
|
||||
row.innerHTML = `
|
||||
<td>
|
||||
<strong>${escapeHtml(log.receiver || "-")}</strong>
|
||||
<div class="table-note">消息ID:<code>${escapeHtml(log.id || "-")}</code></div>
|
||||
<div class="table-note">来源:${escapeHtml(log.sourceSystem || "-")} / 业务ID:${escapeHtml(log.uniqueId || "-")}</div>
|
||||
</td>
|
||||
<td>
|
||||
<strong>${escapeHtml(log.channelType || "-")}</strong>
|
||||
<div class="table-note">通道ID:${log.channelId || "-"}</div>
|
||||
<div class="table-note">Provider:${escapeHtml(log.providerCode || "-")}</div>
|
||||
</td>
|
||||
<td>${pushLogStatusText(log.status)}</td>
|
||||
<td>
|
||||
<strong>${log.retryCount ?? 0}</strong>
|
||||
<div class="table-note">下次:${formatDateTime(log.nextRetryTime)}</div>
|
||||
</td>
|
||||
<td>
|
||||
<div class="template-content-snippet">${escapeHtml(reason)}</div>
|
||||
${log.deadLetterReason ? '<span class="badge bad">死信</span>' : ""}
|
||||
</td>
|
||||
<td>
|
||||
<div>${formatDateTime(log.createTime)}</div>
|
||||
<div class="table-note">发送:${formatDateTime(log.sendTime)}</div>
|
||||
</td>
|
||||
`;
|
||||
elements.pushLogTableBody.appendChild(row);
|
||||
});
|
||||
}
|
||||
|
||||
function fillTestChannelOptions(selectedId = "") {
|
||||
const options = state.channels.map((channel) => {
|
||||
const selected = String(channel.id) === String(selectedId) ? "selected" : "";
|
||||
@@ -708,6 +1136,23 @@ function fillSmsTemplateOptions(selectedCode = "") {
|
||||
elements.testTemplateCode.value = "";
|
||||
}
|
||||
|
||||
function fillEmailTemplateOptions(selectedCode = "") {
|
||||
const templates = getAvailableEmailTemplatesForTest();
|
||||
const options = ['<option value="">不使用邮件模板</option>'];
|
||||
templates.forEach((template) => {
|
||||
const selected = template.templateCode === selectedCode ? "selected" : "";
|
||||
const templateName = template.templateName ? ` / ${escapeHtml(template.templateName)}` : "";
|
||||
const bindingTag = template.channelId ? ` / 通道ID:${template.channelId}` : " / 全局";
|
||||
options.push(
|
||||
`<option value="${escapeHtml(template.templateCode)}" ${selected}>${escapeHtml(template.templateCode)}${templateName}${bindingTag}</option>`
|
||||
);
|
||||
});
|
||||
elements.testEmailTemplateCode.innerHTML = options.join("");
|
||||
if (selectedCode && templates.some((item) => item.templateCode === selectedCode)) {
|
||||
elements.testEmailTemplateCode.value = selectedCode;
|
||||
}
|
||||
}
|
||||
|
||||
function collectTemplateParamsFromInputs() {
|
||||
const params = {};
|
||||
elements.testTemplatePlaceholderFields
|
||||
@@ -718,6 +1163,52 @@ function collectTemplateParamsFromInputs() {
|
||||
return params;
|
||||
}
|
||||
|
||||
function collectEmailTemplateParamsFromInputs() {
|
||||
const params = {};
|
||||
elements.testEmailTemplatePlaceholderFields
|
||||
.querySelectorAll("[data-email-template-key]")
|
||||
.forEach((input) => {
|
||||
params[input.dataset.emailTemplateKey] = input.value.trim();
|
||||
});
|
||||
return params;
|
||||
}
|
||||
|
||||
function renderEmailTemplateFields() {
|
||||
const template = findSelectedEmailTemplate();
|
||||
if (!template) {
|
||||
elements.testEmailTemplatePlaceholderFields.innerHTML = "";
|
||||
setPreviewText(elements.testEmailTemplatePreview, "", "选择邮件模板后查看主题与正文。");
|
||||
return;
|
||||
}
|
||||
|
||||
const previousValues = collectEmailTemplateParamsFromInputs();
|
||||
const placeholders = template.placeholders || [];
|
||||
elements.testEmailBodyType.value = template.bodyType || "TEXT";
|
||||
elements.testEmailTemplatePreview.innerHTML = `
|
||||
<div><strong>${escapeHtml(template.subjectPattern || "")}</strong></div>
|
||||
<div class="template-content-snippet">${escapeHtml(template.bodyPattern || "")}</div>
|
||||
${renderPlaceholderChips(placeholders)}
|
||||
`;
|
||||
elements.testEmailTemplatePreview.classList.remove("empty-state");
|
||||
|
||||
if (placeholders.length === 0) {
|
||||
elements.testEmailTemplatePlaceholderFields.innerHTML = '<p class="template-placeholder-note">该邮件模板没有占位符,可直接发送。</p>';
|
||||
return;
|
||||
}
|
||||
|
||||
elements.testEmailTemplatePlaceholderFields.innerHTML = placeholders.map((key) => `
|
||||
<label>
|
||||
<span>占位符 ${escapeHtml(key)}</span>
|
||||
<input
|
||||
type="text"
|
||||
data-email-template-key="${escapeHtml(key)}"
|
||||
placeholder="请输入 ${escapeHtml(key)} 的替换值"
|
||||
value="${escapeHtml(previousValues[key] || "")}"
|
||||
>
|
||||
</label>
|
||||
`).join("");
|
||||
}
|
||||
|
||||
function renderSmsTemplateFields() {
|
||||
const availableTemplates = getAvailableSmsTemplatesForTest();
|
||||
if (availableTemplates.length === 0) {
|
||||
@@ -817,10 +1308,61 @@ async function loadSmsTemplateConfigs() {
|
||||
renderSmsTemplateFields();
|
||||
}
|
||||
|
||||
async function loadEmailTemplateConfigs() {
|
||||
state.emailTemplateConfigs = (await request("/admin/api/email-templates"))
|
||||
.slice()
|
||||
.sort((left, right) => Number(left.id) - Number(right.id));
|
||||
const editingId = state.editingEmailTemplate?.id;
|
||||
if (editingId) {
|
||||
state.editingEmailTemplate = state.emailTemplateConfigs.find((item) => item.id === editingId) || null;
|
||||
}
|
||||
state.emailTemplates = state.emailTemplateConfigs.filter((item) => item.enabled);
|
||||
renderEmailTemplateTable();
|
||||
resetEmailTemplateForm(state.editingEmailTemplate);
|
||||
fillEmailTemplateOptions(elements.testEmailTemplateCode.value);
|
||||
renderEmailTemplateFields();
|
||||
}
|
||||
|
||||
async function loadAttachmentPolicy() {
|
||||
state.attachmentPolicy = await request("/admin/api/email-attachment-policies");
|
||||
elements.maxSingleFileSize.value = state.attachmentPolicy.maxSingleFileSize || "";
|
||||
elements.maxTotalFileSize.value = state.attachmentPolicy.maxTotalFileSize || "";
|
||||
elements.maxFileCount.value = state.attachmentPolicy.maxFileCount || "";
|
||||
elements.allowedExtensions.value = state.attachmentPolicy.allowedExtensions || "";
|
||||
elements.allowedMimeTypes.value = state.attachmentPolicy.allowedMimeTypes || "";
|
||||
elements.retentionDays.value = state.attachmentPolicy.retentionDays || "";
|
||||
elements.readTimeoutMillis.value = state.attachmentPolicy.readTimeoutMillis || "";
|
||||
}
|
||||
|
||||
async function loadPushLogs() {
|
||||
const params = new URLSearchParams();
|
||||
if (elements.pushLogSourceSystem.value.trim()) {
|
||||
params.set("sourceSystem", elements.pushLogSourceSystem.value.trim());
|
||||
}
|
||||
if (elements.pushLogChannelType.value) {
|
||||
params.set("channelType", elements.pushLogChannelType.value);
|
||||
}
|
||||
if (elements.pushLogStatus.value) {
|
||||
params.set("status", elements.pushLogStatus.value);
|
||||
}
|
||||
if (elements.pushLogKeyword.value.trim()) {
|
||||
params.set("keyword", elements.pushLogKeyword.value.trim());
|
||||
}
|
||||
if (elements.pushLogDeadLetter.checked) {
|
||||
params.set("deadLetter", "true");
|
||||
}
|
||||
params.set("limit", "50");
|
||||
state.pushLogs = await request(`/admin/api/push-logs?${params.toString()}`);
|
||||
renderPushLogTable();
|
||||
}
|
||||
|
||||
async function reloadAll() {
|
||||
await loadChannels();
|
||||
await loadSourceSystems();
|
||||
await loadSmsTemplateConfigs();
|
||||
await loadEmailTemplateConfigs();
|
||||
await loadAttachmentPolicy();
|
||||
await loadPushLogs();
|
||||
}
|
||||
|
||||
async function onChannelTableClick(event) {
|
||||
@@ -922,6 +1464,36 @@ async function onSubmitSmsTemplateForm(event) {
|
||||
await loadSmsTemplateConfigs();
|
||||
}
|
||||
|
||||
async function onSubmitEmailTemplateForm(event) {
|
||||
event.preventDefault();
|
||||
|
||||
const payload = {
|
||||
templateCode: elements.emailTemplateCode.value.trim() || generateEmailTemplateCode(),
|
||||
templateName: elements.emailTemplateName.value.trim(),
|
||||
channelId: elements.emailTemplateChannelId.value ? Number(elements.emailTemplateChannelId.value) : null,
|
||||
bodyType: elements.emailTemplateBodyType.value,
|
||||
subjectPattern: elements.emailTemplateSubjectPattern.value.trim(),
|
||||
bodyPattern: elements.emailTemplateBodyPattern.value.trim(),
|
||||
description: elements.emailTemplateDescription.value.trim(),
|
||||
enabled: elements.emailTemplateEnabled.checked
|
||||
};
|
||||
|
||||
const templateId = elements.emailTemplateId.value;
|
||||
const savedTemplate = templateId
|
||||
? await request(`/admin/api/email-templates/${templateId}`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify(payload)
|
||||
})
|
||||
: await request("/admin/api/email-templates", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
|
||||
showToast(`邮件模板已保存:${savedTemplate.templateCode}`);
|
||||
state.editingEmailTemplate = savedTemplate;
|
||||
await loadEmailTemplateConfigs();
|
||||
}
|
||||
|
||||
async function onSmsTemplateTableClick(event) {
|
||||
const target = event.target.closest("button[data-template-action]");
|
||||
if (!target) {
|
||||
@@ -965,6 +1537,115 @@ async function onSmsTemplateTableClick(event) {
|
||||
}
|
||||
}
|
||||
|
||||
async function onEmailTemplateTableClick(event) {
|
||||
const target = event.target.closest("button[data-email-template-action]");
|
||||
if (!target) {
|
||||
return;
|
||||
}
|
||||
|
||||
const id = target.dataset.id;
|
||||
const action = target.dataset.emailTemplateAction;
|
||||
const template = state.emailTemplateConfigs.find((item) => String(item.id) === String(id));
|
||||
if (!template) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "edit") {
|
||||
resetEmailTemplateForm(template);
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "status") {
|
||||
await request(`/admin/api/email-templates/${id}/status`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ enabled: !template.enabled })
|
||||
});
|
||||
showToast(template.enabled ? `邮件模板已停用:${template.templateCode}` : `邮件模板已启用:${template.templateCode}`);
|
||||
await loadEmailTemplateConfigs();
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "test") {
|
||||
if (!template.enabled) {
|
||||
showToast("请先启用邮件模板后再带入测试", true);
|
||||
return;
|
||||
}
|
||||
if (template.channelId && findEmailChannelById(template.channelId)) {
|
||||
elements.testChannelId.value = String(template.channelId);
|
||||
syncTestFormVisibility();
|
||||
}
|
||||
elements.testEmailTemplateCode.value = template.templateCode;
|
||||
renderEmailTemplateFields();
|
||||
elements.testReceiver.focus();
|
||||
}
|
||||
}
|
||||
|
||||
async function onSubmitAttachmentPolicy(event) {
|
||||
event.preventDefault();
|
||||
const payload = {
|
||||
maxSingleFileSize: Number(elements.maxSingleFileSize.value),
|
||||
maxTotalFileSize: Number(elements.maxTotalFileSize.value),
|
||||
maxFileCount: Number(elements.maxFileCount.value),
|
||||
allowedExtensions: elements.allowedExtensions.value.trim(),
|
||||
allowedMimeTypes: elements.allowedMimeTypes.value.trim(),
|
||||
retentionDays: Number(elements.retentionDays.value),
|
||||
readTimeoutMillis: Number(elements.readTimeoutMillis.value)
|
||||
};
|
||||
state.attachmentPolicy = await request("/admin/api/email-attachment-policies", {
|
||||
method: "PUT",
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
showToast("邮件附件策略已保存");
|
||||
await loadAttachmentPolicy();
|
||||
}
|
||||
|
||||
async function uploadTestAttachment() {
|
||||
const file = elements.testAttachmentFile.files[0];
|
||||
if (!file) {
|
||||
showToast("请先选择附件文件", true);
|
||||
return;
|
||||
}
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
const response = await fetch("/admin/api/email-attachments", {
|
||||
method: "POST",
|
||||
body: formData
|
||||
});
|
||||
const payload = await response.json().catch(() => ({ code: 1, message: "附件上传响应解析失败" }));
|
||||
if (!response.ok || payload.code !== 0) {
|
||||
throw new Error(payload.message || "附件上传失败");
|
||||
}
|
||||
state.uploadedEmailAttachments.push(payload.data);
|
||||
elements.testAttachmentFile.value = "";
|
||||
renderTestAttachmentList();
|
||||
showToast(`附件已上传:${payload.data.originalFileName}`);
|
||||
}
|
||||
|
||||
function renderTestAttachmentList() {
|
||||
if (state.uploadedEmailAttachments.length === 0) {
|
||||
elements.testAttachmentList.textContent = "暂无附件。";
|
||||
elements.testAttachmentList.classList.add("empty-state");
|
||||
return;
|
||||
}
|
||||
elements.testAttachmentList.classList.remove("empty-state");
|
||||
elements.testAttachmentList.innerHTML = state.uploadedEmailAttachments.map((attachment) => `
|
||||
<span class="template-chip">
|
||||
${escapeHtml(attachment.originalFileName)} / ${Math.ceil((attachment.fileSize || 0) / 1024)}KB
|
||||
<button type="button" class="chip-remove" data-remove-attachment-id="${attachment.id}">移除</button>
|
||||
</span>
|
||||
`).join("");
|
||||
}
|
||||
|
||||
function onTestAttachmentListClick(event) {
|
||||
const target = event.target.closest("button[data-remove-attachment-id]");
|
||||
if (!target) {
|
||||
return;
|
||||
}
|
||||
state.uploadedEmailAttachments = state.uploadedEmailAttachments.filter((item) => String(item.id) !== String(target.dataset.removeAttachmentId));
|
||||
renderTestAttachmentList();
|
||||
}
|
||||
|
||||
function syncTestFormVisibility() {
|
||||
const channel = findSelectedTestChannel();
|
||||
const emailOnly = document.querySelectorAll(".test-only-email");
|
||||
@@ -975,7 +1656,9 @@ function syncTestFormVisibility() {
|
||||
smsOnly.forEach((node) => { node.hidden = true; });
|
||||
setPreviewText(elements.testTemplatePreview, "", "请选择短信模板后查看内容");
|
||||
setPreviewText(elements.testSmsPreview, "", "填写占位符后将自动生成预览内容");
|
||||
setPreviewText(elements.testEmailTemplatePreview, "", "选择邮件模板后查看主题与正文。");
|
||||
elements.testTemplatePlaceholderFields.innerHTML = "";
|
||||
elements.testEmailTemplatePlaceholderFields.innerHTML = "";
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -984,6 +1667,8 @@ function syncTestFormVisibility() {
|
||||
smsOnly.forEach((node) => { node.hidden = isEmail; });
|
||||
|
||||
if (isEmail) {
|
||||
fillEmailTemplateOptions(elements.testEmailTemplateCode.value);
|
||||
renderEmailTemplateFields();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1007,6 +1692,10 @@ async function onSubmitTest(event) {
|
||||
if (channel.channelType === "EMAIL") {
|
||||
payload.subject = elements.testSubject.value.trim();
|
||||
payload.content = elements.testContent.value.trim();
|
||||
payload.bodyType = elements.testEmailBodyType.value;
|
||||
payload.templateCode = elements.testEmailTemplateCode.value;
|
||||
payload.templateParams = collectEmailTemplateParamsFromInputs();
|
||||
payload.attachmentIds = state.uploadedEmailAttachments.map((item) => Number(item.id));
|
||||
} else {
|
||||
if (!elements.testTemplateCode.value) {
|
||||
showToast("请选择短信模板", true);
|
||||
@@ -1028,9 +1717,11 @@ function bindEvents() {
|
||||
elements.createButton.addEventListener("click", () => resetChannelForm());
|
||||
elements.createSourceButton.addEventListener("click", () => resetSourceSystemForm());
|
||||
elements.createTemplateButton.addEventListener("click", () => resetSmsTemplateForm());
|
||||
elements.createEmailTemplateButton.addEventListener("click", () => resetEmailTemplateForm());
|
||||
elements.resetButton.addEventListener("click", () => resetChannelForm());
|
||||
elements.sourceResetButton.addEventListener("click", () => resetSourceSystemForm());
|
||||
elements.templateResetButton.addEventListener("click", () => resetSmsTemplateForm());
|
||||
elements.emailTemplateResetButton.addEventListener("click", () => resetEmailTemplateForm());
|
||||
|
||||
elements.sourceSystemForm.addEventListener("submit", (event) => onSourceSystemSubmit(event).catch(handleError));
|
||||
elements.sourceSystemTableBody.addEventListener("click", (event) => onSourceSystemTableClick(event).catch(handleError));
|
||||
@@ -1042,8 +1733,21 @@ function bindEvents() {
|
||||
elements.smsTemplateForm.addEventListener("submit", (event) => onSubmitSmsTemplateForm(event).catch(handleError));
|
||||
elements.templateTableBody.addEventListener("click", (event) => onSmsTemplateTableClick(event).catch(handleError));
|
||||
elements.smsTemplateContentPattern.addEventListener("input", updateSmsTemplatePlaceholderPreview);
|
||||
elements.emailTemplateForm.addEventListener("submit", (event) => onSubmitEmailTemplateForm(event).catch(handleError));
|
||||
elements.emailTemplateTableBody.addEventListener("click", (event) => onEmailTemplateTableClick(event).catch(handleError));
|
||||
elements.emailTemplateSubjectPattern.addEventListener("input", updateEmailTemplatePlaceholderPreview);
|
||||
elements.emailTemplateBodyPattern.addEventListener("input", updateEmailTemplatePlaceholderPreview);
|
||||
elements.attachmentPolicyForm.addEventListener("submit", (event) => onSubmitAttachmentPolicy(event).catch(handleError));
|
||||
elements.testAttachmentUploadButton.addEventListener("click", () => uploadTestAttachment().catch(handleError));
|
||||
elements.testAttachmentList.addEventListener("click", onTestAttachmentListClick);
|
||||
elements.loadPushLogsButton.addEventListener("click", () => loadPushLogs().catch(handleError));
|
||||
elements.pushLogFilterForm.addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
loadPushLogs().catch(handleError);
|
||||
});
|
||||
elements.testChannelId.addEventListener("change", syncTestFormVisibility);
|
||||
elements.testTemplateCode.addEventListener("change", renderSmsTemplateFields);
|
||||
elements.testEmailTemplateCode.addEventListener("change", renderEmailTemplateFields);
|
||||
elements.testTemplatePlaceholderFields.addEventListener("input", updateSmsPreview);
|
||||
elements.testForm.addEventListener("submit", (event) => onSubmitTest(event).catch(handleError));
|
||||
}
|
||||
@@ -1058,6 +1762,8 @@ async function bootstrap() {
|
||||
resetChannelForm();
|
||||
resetSourceSystemForm();
|
||||
resetSmsTemplateForm();
|
||||
resetEmailTemplateForm();
|
||||
renderTestAttachmentList();
|
||||
await reloadAll();
|
||||
}
|
||||
|
||||
|
||||
@@ -36,6 +36,9 @@
|
||||
<a href="#test-send">测试发送</a>
|
||||
<a href="#template-list">模板列表</a>
|
||||
<a href="#template-form">模板表单</a>
|
||||
<a href="#email-template-list">邮件模板</a>
|
||||
<a href="#attachment-policy">附件策略</a>
|
||||
<a href="#delivery-log">投递日志</a>
|
||||
</nav>
|
||||
</div>
|
||||
</aside>
|
||||
@@ -207,6 +210,19 @@
|
||||
<span>邮件主题</span>
|
||||
<input id="testSubject" type="text" placeholder="留空则使用默认主题">
|
||||
</label>
|
||||
<label class="test-only-email">
|
||||
<span>邮件模板</span>
|
||||
<select id="testEmailTemplateCode">
|
||||
<option value="">不使用邮件模板</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="test-only-email">
|
||||
<span>正文类型</span>
|
||||
<select id="testEmailBodyType">
|
||||
<option value="TEXT">TEXT</option>
|
||||
<option value="HTML">HTML</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="test-only-sms">
|
||||
<span>模板ID</span>
|
||||
<select id="testTemplateCode">
|
||||
@@ -217,6 +233,19 @@
|
||||
<span>邮件正文</span>
|
||||
<textarea id="testContent" rows="4" placeholder="邮件测试时会作为正文内容发送"></textarea>
|
||||
</label>
|
||||
<label class="full-width test-only-email">
|
||||
<span>邮件模板预览</span>
|
||||
<div id="testEmailTemplatePreview" class="template-preview empty-state">选择邮件模板后查看主题与正文。</div>
|
||||
</label>
|
||||
<div id="testEmailTemplatePlaceholderFields" class="dynamic-fields full-width test-only-email"></div>
|
||||
<div class="full-width test-only-email attachment-upload-row">
|
||||
<label>
|
||||
<span>邮件附件</span>
|
||||
<input id="testAttachmentFile" type="file">
|
||||
</label>
|
||||
<button id="testAttachmentUploadButton" type="button" class="ghost-button small">上传附件</button>
|
||||
<div id="testAttachmentList" class="attachment-list empty-state">暂无附件。</div>
|
||||
</div>
|
||||
<label class="full-width test-only-sms">
|
||||
<span>模板内容</span>
|
||||
<div id="testTemplatePreview" class="template-preview empty-state">请选择短信模板后查看内容</div>
|
||||
@@ -318,6 +347,195 @@
|
||||
</form>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
<section class="section-grid">
|
||||
<section id="email-template-list" class="panel anchor-panel">
|
||||
<div class="panel-header">
|
||||
<div>
|
||||
<h2>邮件模板配置</h2>
|
||||
<p>这里维护邮件主题、正文和占位符。模板可绑定邮件通道,不绑定时对所有邮件通道通用。</p>
|
||||
</div>
|
||||
<button id="createEmailTemplateButton" class="ghost-button small">新增邮件模板</button>
|
||||
</div>
|
||||
<div id="emailTemplateEmptyState" class="empty-state" hidden>暂无邮件模板,请先新增。</div>
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>模板</th>
|
||||
<th>绑定通道</th>
|
||||
<th>正文类型</th>
|
||||
<th>状态</th>
|
||||
<th>主题与正文</th>
|
||||
<th>最后更新</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="emailTemplateTableBody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section id="email-template-form" class="panel anchor-panel">
|
||||
<div class="panel-header">
|
||||
<div>
|
||||
<h2 id="emailTemplateFormTitle">新增邮件模板</h2>
|
||||
<p id="emailTemplateFormSubtitle">保存后可在测试发送和 MQ 邮件消息中使用。</p>
|
||||
</div>
|
||||
<button id="emailTemplateResetButton" class="ghost-button small">重置</button>
|
||||
</div>
|
||||
<form id="emailTemplateForm" class="form-grid">
|
||||
<input type="hidden" id="emailTemplateId">
|
||||
<label>
|
||||
<span>模板ID(自动生成)</span>
|
||||
<input id="emailTemplateCode" type="text" maxlength="64" readonly placeholder="保存前自动生成">
|
||||
</label>
|
||||
<label>
|
||||
<span>模板名称</span>
|
||||
<input id="emailTemplateName" type="text" maxlength="100" required placeholder="例如:订单通知邮件">
|
||||
</label>
|
||||
<label>
|
||||
<span>绑定邮件通道</span>
|
||||
<select id="emailTemplateChannelId">
|
||||
<option value="">全局通用(不绑定)</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
<span>正文类型</span>
|
||||
<select id="emailTemplateBodyType">
|
||||
<option value="TEXT">TEXT</option>
|
||||
<option value="HTML">HTML</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
<span>描述</span>
|
||||
<input id="emailTemplateDescription" type="text" maxlength="255" placeholder="可选,用于说明适用场景">
|
||||
</label>
|
||||
<div class="inline-checks">
|
||||
<label class="checkbox">
|
||||
<input id="emailTemplateEnabled" type="checkbox" checked>
|
||||
<span>启用</span>
|
||||
</label>
|
||||
</div>
|
||||
<label class="full-width">
|
||||
<span>主题模板</span>
|
||||
<input id="emailTemplateSubjectPattern" type="text" required placeholder="例如:您的订单${orderNo}已更新">
|
||||
</label>
|
||||
<label class="full-width">
|
||||
<span>正文模板</span>
|
||||
<textarea id="emailTemplateBodyPattern" rows="7" required placeholder="例如:您好,${name},您的订单状态是${status}。"></textarea>
|
||||
</label>
|
||||
<label class="full-width">
|
||||
<span>占位符识别</span>
|
||||
<div id="emailTemplatePlaceholderPreview" class="template-preview empty-state">输入主题或正文后,这里会自动识别占位符并展示预览。</div>
|
||||
</label>
|
||||
<div class="form-actions">
|
||||
<button type="submit" class="primary-button">保存邮件模板</button>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
<section class="section-grid">
|
||||
<section id="attachment-policy" class="panel anchor-panel">
|
||||
<div class="panel-header">
|
||||
<div>
|
||||
<h2>邮件附件策略</h2>
|
||||
<p>这里配置测试发送和 MQ 邮件附件的大小、数量、类型和保留时间限制。</p>
|
||||
</div>
|
||||
</div>
|
||||
<form id="attachmentPolicyForm" class="form-grid">
|
||||
<label>
|
||||
<span>单文件最大字节数</span>
|
||||
<input id="maxSingleFileSize" type="number" min="1" required>
|
||||
</label>
|
||||
<label>
|
||||
<span>总附件最大字节数</span>
|
||||
<input id="maxTotalFileSize" type="number" min="1" required>
|
||||
</label>
|
||||
<label>
|
||||
<span>最大附件数量</span>
|
||||
<input id="maxFileCount" type="number" min="1" required>
|
||||
</label>
|
||||
<label>
|
||||
<span>保留天数</span>
|
||||
<input id="retentionDays" type="number" min="1" required>
|
||||
</label>
|
||||
<label class="full-width">
|
||||
<span>允许扩展名(逗号分隔)</span>
|
||||
<input id="allowedExtensions" type="text" placeholder="pdf,docx,png,jpg">
|
||||
</label>
|
||||
<label class="full-width">
|
||||
<span>允许 MIME(逗号分隔)</span>
|
||||
<textarea id="allowedMimeTypes" rows="3" placeholder="application/pdf,image/png"></textarea>
|
||||
</label>
|
||||
<label>
|
||||
<span>读取超时毫秒</span>
|
||||
<input id="readTimeoutMillis" type="number" min="1000" required>
|
||||
</label>
|
||||
<div class="form-actions">
|
||||
<button type="submit" class="primary-button">保存附件策略</button>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section id="delivery-log" class="panel anchor-panel">
|
||||
<div class="panel-header">
|
||||
<div>
|
||||
<h2>投递日志</h2>
|
||||
<p>按来源系统、通道、状态、关键字和死信状态筛选最近投递记录。</p>
|
||||
</div>
|
||||
<button id="loadPushLogsButton" class="ghost-button small">查询日志</button>
|
||||
</div>
|
||||
<form id="pushLogFilterForm" class="form-grid compact-filter">
|
||||
<label>
|
||||
<span>来源系统</span>
|
||||
<input id="pushLogSourceSystem" type="text" placeholder="例如:user-service">
|
||||
</label>
|
||||
<label>
|
||||
<span>通道类型</span>
|
||||
<select id="pushLogChannelType">
|
||||
<option value="">全部</option>
|
||||
<option value="SMS">SMS</option>
|
||||
<option value="EMAIL">EMAIL</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
<span>状态</span>
|
||||
<select id="pushLogStatus">
|
||||
<option value="">全部</option>
|
||||
<option value="0">待发送/重试</option>
|
||||
<option value="1">成功</option>
|
||||
<option value="2">失败</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
<span>关键字</span>
|
||||
<input id="pushLogKeyword" type="text" placeholder="接收目标、业务ID、模板或失败原因">
|
||||
</label>
|
||||
<label class="checkbox">
|
||||
<input id="pushLogDeadLetter" type="checkbox">
|
||||
<span>仅死信</span>
|
||||
</label>
|
||||
</form>
|
||||
<div id="pushLogEmptyState" class="empty-state" hidden>暂无投递日志。</div>
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>消息</th>
|
||||
<th>通道</th>
|
||||
<th>状态</th>
|
||||
<th>重试</th>
|
||||
<th>失败/死信原因</th>
|
||||
<th>时间</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="pushLogTableBody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
</section>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -370,6 +370,7 @@ textarea {
|
||||
.template-chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 5px 10px;
|
||||
border-radius: 999px;
|
||||
background: rgba(184, 91, 47, 0.12);
|
||||
@@ -378,6 +379,36 @@ textarea {
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.chip-remove {
|
||||
padding: 2px 6px;
|
||||
border-radius: 999px;
|
||||
font-size: 11px;
|
||||
background: rgba(183, 66, 48, 0.12);
|
||||
color: var(--bad);
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.attachment-upload-row {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(220px, 1fr) auto;
|
||||
gap: 12px;
|
||||
align-items: end;
|
||||
}
|
||||
|
||||
.attachment-list {
|
||||
grid-column: 1 / -1;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
min-height: 48px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.compact-filter {
|
||||
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.template-content-snippet {
|
||||
max-width: 440px;
|
||||
white-space: pre-wrap;
|
||||
@@ -494,6 +525,10 @@ textarea {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.attachment-upload-row {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
th,
|
||||
td {
|
||||
padding: 12px 8px;
|
||||
|
||||
@@ -0,0 +1,684 @@
|
||||
# MessageHub 大模型切换交接全量索引
|
||||
|
||||
编写基线:2026-05-12 当前本地工作区
|
||||
适用范围:仅 `MessageHub` 项目
|
||||
适用对象:
|
||||
- 后续新的大模型 / AI 编程代理接手 `MessageHub` 仓库开发、排障、继续迭代
|
||||
- 未来若要在 `MessageHub` 业务里接入或替换 AI / LLM 能力的设计与落点索引
|
||||
|
||||
注意:
|
||||
- 本文以当前工作区代码为准,不以旧文档或远端历史提交为准。
|
||||
- 当前工作区中 `MessageHub` 存在较多未提交修改与新增文件,本文已经把这些“当前真实存在的代码”一并纳入索引。
|
||||
- 文中只记录配置名、用途、路径,不记录账号、密码、密钥明文。
|
||||
- 当前仓库并不存在现成的 LLM / Prompt / AI Provider 业务实现,所谓“大模型切换”主要是“后续代理接手索引”和“将来若引入 AI 时的改造落点索引”。
|
||||
|
||||
## 1. 5 分钟接手路径
|
||||
|
||||
### 1.1 先看哪些文件
|
||||
1. `pom.xml`
|
||||
2. `src/main/java/com/xiaowang/messagehub/MessageHubApplication.java`
|
||||
3. `src/main/java/com/xiaowang/messagehub/config/RabbitMQConfig.java`
|
||||
4. `src/main/java/com/xiaowang/messagehub/service/channel/MessageChannelService.java`
|
||||
5. `src/main/java/com/xiaowang/messagehub/service/impl/MessageHandleService.java`
|
||||
6. `src/main/resources/application.yml`
|
||||
7. `src/main/resources/bootstrap.yaml`
|
||||
8. `src/main/resources/static/messagehub-admin/index.html`
|
||||
9. `src/main/resources/static/messagehub-admin/app.js`
|
||||
10. `src/main/resources/sql/2026-05-12_messagehub_email_templates_attachments_reliability_patch.sql`
|
||||
|
||||
### 1.2 先理解哪几条链路
|
||||
- 启动链路:`MessageHubApplication` -> Spring Boot -> `ApplicationStartupListener` -> `ConnectionHealthChecker` / `MessageChannelService.runStartupHealthChecks`
|
||||
- MQ 生产链路:`MessageProducerService`
|
||||
- SMS 消费链路:`SmsQueueListener` -> `MessageHandleService` -> `SmsSendServiceImpl` -> `MessageChannelService` -> `SpugSmsChannelProvider` / `MockSmsChannelProvider`
|
||||
- Email 消费链路:`EmailQueueListener` -> `MessageHandleService` -> `EmailSendService` -> `MessageChannelService` -> `EmailTemplateService` / `AttachmentStorageService` -> `SmtpEmailChannelProvider` / `MockEmailChannelProvider`
|
||||
- QQ 消费链路:`QqQueueListener` -> `MessageHandleService` -> `QqSendService` -> `MessageChannelService` -> `QqAutoChannelProvider` / `MockQqChannelProvider`
|
||||
- 后台管理链路:`static/messagehub-admin/*` -> `controller/*AdminController` -> `service/*` -> `mapper/*` -> MySQL
|
||||
|
||||
### 1.3 常见误判
|
||||
- 这不是 AI/LLM 项目,当前真实职责是消息中心。
|
||||
- 旧文档很多仍停留在“SMS / EMAIL 双通道”阶段,但当前代码已经扩到 QQ、邮件模板、附件、死信、投递日志查询。
|
||||
- `bootstrap.yaml` 当前仍有硬编码 Nacos 地址/账号/密码,属于高风险项。
|
||||
- `application.yml` 与 `MessageChannelProperties` 对 `MESSAGE_HUB_MASTER_KEY` 仍提供默认值,生产环境不安全。
|
||||
- `src/test` 只有一个手工短信测试,不是可靠回归基线。
|
||||
- `log4j2.xml` 的日志目录和 `MessageHubApplication` 的运行时目录约定并不一致。
|
||||
|
||||
## 2. 当前项目真实状态
|
||||
|
||||
### 2.1 项目定位
|
||||
- 当前 `MessageHub` 是消息中心服务,不是 AI 服务。
|
||||
- 主要职责是统一承接异步消息、做模板渲染、选通道、发消息、落推送日志、提供后台管理。
|
||||
|
||||
### 2.2 当前真实能力
|
||||
- 短信发送
|
||||
- 邮件发送
|
||||
- QQ 消息发送
|
||||
- 来源系统白名单与默认通道管理
|
||||
- 通道配置、启停、默认通道、健康检查、测试发送
|
||||
- 短信模板管理
|
||||
- QQ 模板管理
|
||||
- 邮件模板管理
|
||||
- 邮件附件上传与附件策略管理
|
||||
- 推送日志查询
|
||||
- 死信记录与 provider 响应摘要记录
|
||||
- 开发环境 Mock SMS / Mock Email / Mock QQ 通道
|
||||
|
||||
### 2.3 当前技术栈
|
||||
- Java 17
|
||||
- Spring Boot 2.7.18
|
||||
- Spring Cloud 2021.0.8
|
||||
- Spring Cloud Alibaba 2021.0.5.0
|
||||
- RabbitMQ
|
||||
- MySQL
|
||||
- Nacos
|
||||
- MyBatis-Plus 3.5.3.1
|
||||
- Druid
|
||||
- Log4j2
|
||||
- JavaMail
|
||||
|
||||
### 2.4 当前工作区覆盖范围
|
||||
- `src/main/java`:99 个 Java 文件
|
||||
- `src/main/resources`:16 个资源文件
|
||||
- `src/test`:1 个测试文件
|
||||
- 根目录已有多份历史文档,但存在明显漂移,必须以代码为准
|
||||
|
||||
## 3. 全量代码地图
|
||||
|
||||
索引字段说明:
|
||||
- 职责:这个文件在系统中的角色
|
||||
- 关键输入:主要入参、触发点或上游
|
||||
- 关键输出 / 副作用:返回值、数据库写入、外部网络调用、日志、文件落盘等
|
||||
- 直接依赖:最直接的上下游类、框架或外部资源
|
||||
- 接手建议:后续代理首次改这个领域时应从哪里切
|
||||
|
||||
### 3.1 根目录与顶层文件
|
||||
|
||||
| 文件 | 职责 | 关键输入 | 关键输出 / 副作用 | 直接依赖 | 接手建议 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| `pom.xml` | Maven 依赖与构建入口 | Maven 构建命令 | 决定技术栈、打包物名称 | Spring Boot / Cloud / Alibaba / AMQP / MyBatis | 升级框架、加依赖、看版本冲突先看这里 |
|
||||
| `.gitattributes` | Git 文本属性 | Git | 行尾策略 | Git | 只需仓库治理时关注 |
|
||||
| `.gitignore` | Git 忽略规则 | Git | 控制未跟踪文件 | Git | 新增本地产物目录时同步更新 |
|
||||
| `MessageHub_文档.md` | 早期系统综述 | 人工阅读 | 历史设计说明 | 旧版实现 | 明显偏旧,只可参考宏观背景 |
|
||||
| `MESSAGE_EXAMPLES.md` | MQ 示例消息 | 人工阅读 | 示例 JSON | 旧版对外契约 | 样例需按当前 DTO 校验一遍再用 |
|
||||
| `外部系统对接接口文档.md` | 外部系统接入文档 | 人工阅读 | RabbitMQ / 管理接口说明 | 旧版对外能力 | 部分过期,不能直接当真值 |
|
||||
| `项目详细总结.md` | 历史总结 | 人工阅读 | 旧版结构说明 | 旧版实现 | 仅作历史背景,不作现状基线 |
|
||||
| `消息队列处理流程.md` | 旧版短信流程说明 | 人工阅读 | 旧版 SMS 处理链路 | 旧类名 / 旧方法名 | 明显过期,仅供理解早期演进 |
|
||||
|
||||
### 3.2 资源文件全量索引
|
||||
|
||||
| 文件 | 职责 | 关键输入 | 关键输出 / 副作用 | 直接依赖 | 接手建议 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| `src/main/resources/application.yml` | 应用本地配置 | 环境变量、Spring 配置 | 定义主密钥默认值、Mock 开关、重试参数、上传大小 | Spring Boot 配置绑定 | 改本地默认行为、通道安全参数先看这里 |
|
||||
| `src/main/resources/bootstrap.yaml` | Nacos 接入配置 | Nacos 地址、账号、密码、namespace | 决定启动期配置中心 / 服务发现接入 | Spring Cloud Alibaba Nacos | 当前存在明文敏感配置,必须重点关注 |
|
||||
| `src/main/resources/CHANGELOG_2026-03-23.md` | 2026-03-23 变更记录 | 人工阅读 | 历史迭代说明 | 当时代码版本 | 只作时间线参考 |
|
||||
| `src/main/resources/files/消息推送系统需求设计文档.docx` | 历史需求文档 | 人工阅读 | 非代码需求背景 | 需求设计 | 有需求追溯需求时再读 |
|
||||
| `src/main/resources/log4j2.xml` | 日志配置 | Log4j2 | 控制台日志、滚动日志、错误日志输出 | Log4j2 | 当前 `LOG_HOME` 固定到工作区,和运行时目录逻辑不一致 |
|
||||
| `src/main/resources/PROJECT_OVERVIEW.md` | 内部运行说明 | 人工阅读 | 启动与联调说明 | 当前 / 近期代码 | 先读,但要和真实 `bootstrap.yaml` 交叉核对 |
|
||||
| `src/main/resources/sql/2026-03-23_message_channel_management_patch.sql` | 通道管理表补丁 | MySQL | 创建 `message_channel_config` | MySQL | 增量环境补通道表时使用 |
|
||||
| `src/main/resources/sql/2026-03-23_message_source_system_patch.sql` | 来源系统补丁 | MySQL | 创建 `message_source_system` / `message_source_system_channel` | MySQL | 增量环境补来源系统表时使用 |
|
||||
| `src/main/resources/sql/2026-03-23_messagehub_complete_manual_init.sql` | 推荐的完整初始化 SQL | MySQL | 一次性创建核心表并写入初始数据 | MySQL | 新环境优先看这个,不要直接从 `init.sql` 起步 |
|
||||
| `src/main/resources/sql/2026-03-23_messagehub_sms_template_channel_binding_patch.sql` | 短信模板绑定通道补丁 | MySQL | 给 `push_template` 增加 `channel_id` 并回填 | MySQL | 改短信模板绑定规则先看这里 |
|
||||
| `src/main/resources/sql/2026-03-30_messagehub_snowflake_id_alignment_patch.sql` | 雪花 ID 对齐补丁 | MySQL | 去掉若干表 `id` 的 `AUTO_INCREMENT` | MySQL / Snowflake ID 生成器 | 处理老库主键策略时要用 |
|
||||
| `src/main/resources/sql/2026-05-12_messagehub_email_templates_attachments_reliability_patch.sql` | 邮件模板、附件、可靠性补丁 | MySQL | 新建 `email_template` / `email_attachment` / `email_attachment_policy`,并扩 `push_log` | MySQL | 当前邮件模板、附件、死信相关能力都基于此 |
|
||||
| `src/main/resources/sql/init.sql` | 早期初始化脚本 | MySQL | 仅创建 `messageDO` | MySQL | 已明显偏旧,不应作为当前主初始化脚本 |
|
||||
| `src/main/resources/static/messagehub-admin/app.js` | 后台单页逻辑 | 浏览器事件、REST 接口 | 调接口、渲染表格、上传附件、查看日志 | 浏览器 Fetch + 所有 admin API | 改后台交互先看这里 |
|
||||
| `src/main/resources/static/messagehub-admin/index.html` | 后台单页结构 | 浏览器 | 提供来源系统、通道、测试发送、短信模板、邮件模板、附件策略、投递日志页面骨架 | 静态资源 | 改页面结构和挂载点先看这里 |
|
||||
| `src/main/resources/static/messagehub-admin/styles.css` | 后台样式 | HTML 类名 | 页面视觉表现 | index.html | 改 UI 样式只看这里即可 |
|
||||
|
||||
### 3.3 SQL 补丁执行建议
|
||||
|
||||
- 新库优先:`src/main/resources/sql/2026-03-23_messagehub_complete_manual_init.sql`
|
||||
- 老库增量:
|
||||
1. `src/main/resources/sql/2026-03-23_message_channel_management_patch.sql`
|
||||
2. `src/main/resources/sql/2026-03-23_message_source_system_patch.sql`
|
||||
3. `src/main/resources/sql/2026-03-23_messagehub_sms_template_channel_binding_patch.sql`
|
||||
4. `src/main/resources/sql/2026-03-30_messagehub_snowflake_id_alignment_patch.sql`
|
||||
5. `src/main/resources/sql/2026-05-12_messagehub_email_templates_attachments_reliability_patch.sql`
|
||||
- `src/main/resources/sql/init.sql` 视为早期遗留脚本,不应单独作为当前环境初始化入口。
|
||||
|
||||
### 3.4 Java 文件全量索引
|
||||
|
||||
#### 3.4.1 入口、健康、异常、支持层
|
||||
|
||||
| 文件 | 职责 | 关键输入 | 关键输出 / 副作用 | 直接依赖 | 接手建议 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| `src/main/java/com/xiaowang/messagehub/MessageHubApplication.java` | 应用入口与运行目录准备 | JVM 启动、`LOCALAPPDATA` | 设置 `JM.LOG.PATH` / `JM.SNAPSHOT.PATH`,启动 Spring | Spring Boot、文件系统 | 启动异常、运行目录冲突先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/health/ConnectionHealthChecker.java` | 启动后基础设施连通性检查 | Spring `Environment` | 检查 MySQL / RabbitMQ / Nacos 并记日志 | JDBC / RabbitMQ / Nacos 配置 | 启动联调失败先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/exception/SmsException.java` | 旧短信异常封装 | `MessageExceptionEnum` | 抛运行时异常 | 枚举 | 多数新逻辑已偏向 `IllegalArgumentException` / `RuntimeException`,这里只算遗留异常层 |
|
||||
| `src/main/java/com/xiaowang/messagehub/support/id/TimeOrderedSnowflakeIdGenerator.java` | 雪花 ID 生成器 | 系统时钟、网卡 / 主机信息 | 生成主键、模板码后备值、附件 ID | 时间、主机信息 | 涉及 ID 规则、排序、主键冲突先看这里 |
|
||||
|
||||
#### 3.4.2 config 包
|
||||
|
||||
| 文件 | 职责 | 关键输入 | 关键输出 / 副作用 | 直接依赖 | 接手建议 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| `src/main/java/com/xiaowang/messagehub/config/JacksonConfig.java` | Long 转字符串 JSON 配置 | Spring Jackson 初始化 | 影响所有 long 输出格式 | Jackson | 前端 ID 精度问题先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/config/MessageChannelProperties.java` | `messagehub.channel.*` 配置绑定 | `application.yml` / 环境变量 | 暴露加密、Mock、重试参数 | Spring `@ConfigurationProperties` | 改通道安全或重试参数先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/config/MyBatisPlusConfig.java` | MyBatis-Plus 插件与主键生成配置 | Spring 初始化 | 分页 / 拦截器 / 雪花 ID 对接 | MyBatis-Plus、Snowflake | 改 ORM 行为、主键策略先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/config/MyMetaObjectHandler.java` | 自动填充创建/更新时间 | MyBatis 插入更新 | 填充实体时间字段 | MyBatis-Plus | 时间字段异常先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/config/RabbitMQConfig.java` | RabbitMQ 队列、交换机、绑定配置 | Spring 初始化 | 声明 SMS / Email / QQ 主队列与死信队列 | Spring AMQP | 改队列、路由键、死信交换机先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/config/ValidationConfig.java` | Bean Validation 配置 | Spring 初始化 | 开启参数校验 | Jakarta Validation | Controller/Service 参数校验不生效先看这里 |
|
||||
|
||||
#### 3.4.3 controller 包
|
||||
|
||||
| 文件 | 职责 | 关键输入 | 关键输出 / 副作用 | 直接依赖 | 接手建议 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| `src/main/java/com/xiaowang/messagehub/controller/EmailAttachmentAdminController.java` | 邮件附件上传与策略管理接口 | `MultipartFile`、策略请求体 | 写附件文件、写 `email_attachment`、更新策略 | `AttachmentStorageService`、`EmailAttachmentPolicyService` | 改附件接口或策略先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/controller/EmailTemplateAdminController.java` | 邮件模板管理接口 | 模板保存 / 状态请求体 | 读写 `email_template` | `EmailTemplateService` | 改邮件模板后台接口先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/controller/GlobalExceptionHandler.java` | 统一异常转 `ApiResponse` | Controller 异常 | 把校验 / SQL / 运行时异常转统一错误体 | Spring MVC | 接口报错格式统一先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/controller/MessageChannelAdminController.java` | 通道、短信模板、QQ 模板、测试发送接口 | REST 请求体与路径参数 | 通道 CRUD、模板 CRUD、体检、测试发送 | `MessageChannelService` | 后台通道相关需求都从这里切 |
|
||||
| `src/main/java/com/xiaowang/messagehub/controller/MessageHubAdminPageController.java` | 后台静态页入口 | 浏览器访问 `/messagehub-admin` | 跳转到 `index.html` | Spring MVC | 改后台入口路由先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/controller/MessageSourceSystemAdminController.java` | 来源系统管理接口 | 来源系统保存 / 状态请求体 | 读写来源系统及默认通道映射 | `MessageSourceSystemService` | 改来源系统后台接口先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/controller/PushLogAdminController.java` | 投递日志查询接口 | 查询参数 | 返回 `push_log` 列表 | `PushLogAdminService` | 增日志检索字段或重放入口先从这里扩 |
|
||||
|
||||
#### 3.4.4 dto/common 与 dto 包
|
||||
|
||||
| 文件 | 职责 | 关键输入 | 关键输出 / 副作用 | 直接依赖 | 接手建议 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| `src/main/java/com/xiaowang/messagehub/dto/common/ApiResponse.java` | 统一接口返回体 | `data` / `message` | 所有后台接口返回 JSON | Controller | 改接口返回格式先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/dto/MessageDTO.java` | 通用 MQ 消息体基类 | `receiver/channelType/msgType/templateCode/templateParams/channelId/sourceSystem/uniqueId` | 被三类消息 DTO 继承 | Bean Validation | 改 MQ 基础契约必须从这里开始 |
|
||||
| `src/main/java/com/xiaowang/messagehub/dto/SmsMessageDTO.java` | 短信 MQ 消息体 | 继承 `MessageDTO` + `sendMethod` | 供 SMS 生产 / 消费使用 | `SmsQueueListener` | 改短信消息字段同步监听器与示例文档 |
|
||||
| `src/main/java/com/xiaowang/messagehub/dto/EmailMessageDTO.java` | 邮件 MQ 消息体 | 继承 `MessageDTO` + 主题、正文、模板、附件 | 供邮件消费链路使用 | `EmailQueueListener` | 改邮件消息字段同步模板渲染与附件解析 |
|
||||
| `src/main/java/com/xiaowang/messagehub/dto/QqMessageDTO.java` | QQ MQ 消息体 | 继承 `MessageDTO` + `targetType/content/contentMode` | 供 QQ 消费链路使用 | `QqQueueListener` | 改 QQ 消息协议同步 provider |
|
||||
|
||||
#### 3.4.5 dto/admin 包
|
||||
|
||||
| 文件 | 职责 | 关键输入 | 关键输出 / 副作用 | 直接依赖 | 接手建议 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| `src/main/java/com/xiaowang/messagehub/dto/admin/ChannelConfigSaveRequest.java` | 后台通道保存请求 | 通道基础信息、`config`、`secretConfig` | 创建 / 更新通道 | `MessageChannelAdminController` | 加通道字段先改这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/dto/admin/ChannelConfigTestRequest.java` | 测试发送请求 | 渠道、接收方、模板、附件、参数 | 驱动 `sendTest` | `MessageChannelService` | 扩测试发送能力先改这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/dto/admin/ChannelConfigView.java` | 通道后台展示返回体 | Service 填充 | 给前端显示通道详情、健康状态 | `MessageChannelService` | 前端通道展示缺字段先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/dto/admin/ChannelSmsTemplateSaveRequest.java` | 短信 / QQ 模板保存请求 | 模板码、名称、内容、绑定通道 | 保存 `push_template` | `MessageChannelService` | 短信和 QQ 模板共用此请求体 |
|
||||
| `src/main/java/com/xiaowang/messagehub/dto/admin/ChannelSmsTemplateStatusUpdateRequest.java` | 短信 / QQ 模板启停请求 | `enabled` | 更新模板状态 | Controller | 模板启停先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/dto/admin/ChannelSmsTemplateView.java` | 短信 / QQ 模板展示体 | Service 填充 | 提供模板列表与占位符预览 | `MessageChannelService` | 改模板列表字段先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/dto/admin/ChannelStatusUpdateRequest.java` | 通道启停请求 | `enabled` | 更新通道状态 | Controller | 通道启停扩展时同步前端 |
|
||||
| `src/main/java/com/xiaowang/messagehub/dto/admin/ChannelTemplateOptionView.java` | 测试发送模板下拉项 | Service 填充 | 返回模板选项与占位符 | `MessageChannelService` | 改模板下拉展示先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/dto/admin/EmailAttachmentPolicyRequest.java` | 附件策略保存请求 | 大小、数量、类型、保留天数 | 更新策略 | `EmailAttachmentPolicyService` | 附件约束扩展先改这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/dto/admin/EmailAttachmentPolicyView.java` | 附件策略展示体 | Service 填充 | 前端展示策略 | `EmailAttachmentPolicyService` | 前端策略展示异常先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/dto/admin/EmailAttachmentView.java` | 附件上传返回体 | Service 填充 | 返回附件元数据 | `AttachmentStorageService` | 改上传返回字段先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/dto/admin/EmailTemplateSaveRequest.java` | 邮件模板保存请求 | 名称、主题、正文、bodyType、绑定通道 | 保存 `email_template` | `EmailTemplateService` | 扩邮件模板字段先改这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/dto/admin/EmailTemplateStatusUpdateRequest.java` | 邮件模板启停请求 | `enabled` | 更新邮件模板状态 | Controller | 启停逻辑扩展先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/dto/admin/EmailTemplateView.java` | 邮件模板展示体 | Service 填充 | 前端邮件模板列表与预览 | `EmailTemplateService` | 模板预览字段不符先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/dto/admin/PushLogView.java` | 投递日志展示体 | Service 填充 | 前端展示状态、死信、重试信息 | `PushLogAdminService` | 日志列表加字段先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/dto/admin/SourceSystemSaveRequest.java` | 来源系统保存请求 | 系统码、名称、默认通道 | 保存系统及默认通道绑定 | `MessageSourceSystemService` | 改来源系统字段先改这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/dto/admin/SourceSystemStatusUpdateRequest.java` | 来源系统启停请求 | `enabled` | 更新系统状态 | Controller | 状态管理扩展先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/dto/admin/SourceSystemView.java` | 来源系统展示体 | Service 填充 | 返回系统信息和默认通道 | `MessageSourceSystemService` | 改来源系统列表字段先看这里 |
|
||||
|
||||
#### 3.4.6 entity 包
|
||||
|
||||
| 文件 | 职责 | 关键输入 | 关键输出 / 副作用 | 直接依赖 | 接手建议 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| `src/main/java/com/xiaowang/messagehub/entity/EmailAttachmentDO.java` | `email_attachment` ORM 实体 | Mapper / Service 写入 | 存附件元数据 | MyBatis-Plus | 改附件表结构先同步 SQL |
|
||||
| `src/main/java/com/xiaowang/messagehub/entity/EmailAttachmentPolicyDO.java` | `email_attachment_policy` ORM 实体 | Policy Service | 存附件策略 | MyBatis-Plus | 改策略字段先同步前端 |
|
||||
| `src/main/java/com/xiaowang/messagehub/entity/EmailTemplateDO.java` | `email_template` ORM 实体 | Email Template Service | 存邮件模板 | MyBatis-Plus | 改邮件模板表结构先同步 render |
|
||||
| `src/main/java/com/xiaowang/messagehub/entity/MessageChannelConfigDO.java` | `message_channel_config` ORM 实体 | 通道服务 | 存通道配置 / 加密秘钥 / 健康状态 | MyBatis-Plus | 所有 provider 配置改动都要经过它 |
|
||||
| `src/main/java/com/xiaowang/messagehub/entity/MessageDO.java` | 早期 `messageDO` ORM 实体 | 旧 mapper | 早期消息表记录 | MyBatis-Plus | 偏遗留,不是当前主链路核心 |
|
||||
| `src/main/java/com/xiaowang/messagehub/entity/MessageSourceSystemChannelDO.java` | 来源系统默认通道映射实体 | SourceSystem Service | 存系统与默认通道关系 | MyBatis-Plus | 改默认通道策略先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/entity/MessageSourceSystemDO.java` | 来源系统实体 | SourceSystem Service | 存系统白名单 | MyBatis-Plus | 改来源系统核心表先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/entity/PushLogDO.java` | `push_log` ORM 实体 | Listener / HandleService / AdminService | 记录状态、重试、死信、payload、provider 响应 | MyBatis-Plus | 投递日志字段扩展的核心实体 |
|
||||
| `src/main/java/com/xiaowang/messagehub/entity/PushTemplateDO.java` | `push_template` ORM 实体 | MessageChannelService / MessageHandleService | 存短信 / QQ 模板 | MyBatis-Plus | 短信和 QQ 模板能力都基于它 |
|
||||
|
||||
#### 3.4.7 enums 包
|
||||
|
||||
| 文件 | 职责 | 关键输入 | 关键输出 / 副作用 | 直接依赖 | 接手建议 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| `src/main/java/com/xiaowang/messagehub/enums/ChannelHealthStatusEnum.java` | 通道健康状态枚举 | 状态码 | 约束 `UNKNOWN/HEALTHY/UNHEALTHY` | 通道服务 | 新健康状态先同步前端徽标 |
|
||||
| `src/main/java/com/xiaowang/messagehub/enums/ChannelProviderCodeEnum.java` | Provider 代码枚举 | providerCode | 约束 SPUG / SMTP / MOCK / QQAUTO 等 | 通道服务 / providers | 加新 provider 必改这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/enums/ChannelTypeEnum.java` | 通道类型枚举 | channelType | 约束 SMS / EMAIL / QQ / PUSH / WECHAT | DTO / 服务层 | MQ 与后台同时要认它 |
|
||||
| `src/main/java/com/xiaowang/messagehub/enums/EmailBodyTypeEnum.java` | 邮件正文类型枚举 | bodyType | 约束 TEXT / HTML | 邮件模板 / SMTP Provider | 扩邮件正文渲染方式先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/enums/MessageExceptionEnum.java` | 旧异常码枚举 | code | 生成旧短信异常 | `SmsException` | 主要是遗留兼容 |
|
||||
|
||||
#### 3.4.8 listener 包
|
||||
|
||||
| 文件 | 职责 | 关键输入 | 关键输出 / 副作用 | 直接依赖 | 接手建议 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| `src/main/java/com/xiaowang/messagehub/listener/ApplicationStartupListener.java` | 应用启动后执行检查 | `ApplicationReadyEvent` | 打基础设施检查日志、跑通道健康检查 | `ConnectionHealthChecker`、`MessageChannelService` | 启动后自动动作全在这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/listener/EmailQueueListener.java` | 消费 `emailQueue` | RabbitMQ Message | 校验、渲染、发邮件、落日志、失败可入死信 | `EmailSendService`、`MessageHandleService`、`RabbitTemplate` | 邮件 MQ 消费异常先从这里顺链排 |
|
||||
| `src/main/java/com/xiaowang/messagehub/listener/QqQueueListener.java` | 消费 `qqQueue` | RabbitMQ Message | 校验、发 QQ、记 provider 响应、失败可入死信 | `QqSendService`、`MessageHandleService`、`RabbitTemplate` | QQ 能力入口,排障优先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/listener/SmsQueueListener.java` | 消费 `smsQueue` | RabbitMQ Message | 校验、发短信、落日志、失败重试 / 拒绝 | `SmsSendServiceImpl`、`MessageHandleService` | 短信问题从这里顺到 provider |
|
||||
|
||||
#### 3.4.9 mapper 包
|
||||
|
||||
| 文件 | 职责 | 关键输入 | 关键输出 / 副作用 | 直接依赖 | 接手建议 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| `src/main/java/com/xiaowang/messagehub/mapper/EmailAttachmentMapper.java` | 附件表 Mapper | 附件 ID / 实体 | 读写 `email_attachment` | `EmailAttachmentDO` | 改附件查询先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/mapper/EmailAttachmentPolicyMapper.java` | 附件策略 Mapper | 固定 ID 1 / 策略实体 | 读写 `email_attachment_policy` | `EmailAttachmentPolicyDO` | 改策略存取先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/mapper/EmailTemplateMapper.java` | 邮件模板 Mapper | 模板码 / 启用状态 | 读写 `email_template` | `EmailTemplateDO` | 改邮件模板查询先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/mapper/MessageChannelConfigMapper.java` | 通道配置 Mapper | 通道实体 / 查询条件 | 读写 `message_channel_config` | `MessageChannelConfigDO` | 改通道数据库访问先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/mapper/MessageMapper.java` | 旧消息表 Mapper | 旧消息实体 | 读写 `messageDO` | `MessageDO` | 遗留层,当前主链路用得少 |
|
||||
| `src/main/java/com/xiaowang/messagehub/mapper/MessageSourceSystemChannelMapper.java` | 来源系统默认通道 Mapper | systemId / channelType | 读写映射表 | `MessageSourceSystemChannelDO` | 改默认通道绑定先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/mapper/MessageSourceSystemMapper.java` | 来源系统 Mapper | systemCode / 实体 | 读写 `message_source_system` | `MessageSourceSystemDO` | 改来源系统查询先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/mapper/PushLogMapper.java` | 投递日志 Mapper | messageId / uniqueId / 条件查询 | 读写 `push_log`,含重试计数与搜索 | `PushLogDO` | 日志检索、重试、幂等都要看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/mapper/PushTemplateMapper.java` | 短信 / QQ 模板 Mapper | templateCode / channelType | 读写 `push_template` | `PushTemplateDO` | 改短信 / QQ 模板查询先看这里 |
|
||||
|
||||
#### 3.4.10 model 包
|
||||
|
||||
| 文件 | 职责 | 关键输入 | 关键输出 / 副作用 | 直接依赖 | 接手建议 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| `src/main/java/com/xiaowang/messagehub/model/ChannelHealthCheckResult.java` | 通道体检结果对象 | provider 体检结果 | 封装健康状态与消息 | Provider / 通道服务 | 统一体检输出先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/model/EmailAttachmentResource.java` | 已解析附件资源 | 附件 ID 与路径 | 提供文件路径、大小、类型给 SMTP Provider | `AttachmentStorageService` | 改附件发送逻辑先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/model/EmailDispatchRequest.java` | 邮件运行时投递请求 | DTO / 测试发送请求 | 聚合主题、正文、模板、附件 | `EmailSendService` / `MessageChannelService` | 邮件渲染前后的中间态都在这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/model/EmailRenderResult.java` | 邮件渲染结果 | 明文主题 / 正文 / bodyType | 给发送层最终内容 | `EmailTemplateService` | 改模板渲染输出先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/model/ManagedChannelConfig.java` | 通道运行时视图 | `MessageChannelConfigDO` + 反序列化配置 | 对 provider 提供 config / secret 读取 API | `MessageChannelService` | 所有 provider 配置读取都基于它 |
|
||||
| `src/main/java/com/xiaowang/messagehub/model/QqDispatchRequest.java` | QQ 运行时投递请求 | DTO / 测试发送请求 | 聚合接收方、内容模式、模板参数 | `QqSendService` / `MessageChannelService` | 改 QQ 投递协议先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/model/QqSendResult.java` | QQ provider 返回对象 | Provider 原始响应 | 记录 requestId、messageId、rawResponse | `QqAutoChannelProvider` | 改 QQ 响应解析先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/model/SmsDispatchRequest.java` | 短信运行时投递请求 | DTO / 测试发送请求 | 聚合接收方、模板与参数 | `SmsSendServiceImpl` / `MessageChannelService` | 改短信 provider 入参先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/model/SmsSendResult.java` | 短信 provider 返回对象 | Provider 响应 | 记录短信发送结果 | `SpugSmsChannelProvider` / `MockSmsChannelProvider` | 改短信响应解析先看这里 |
|
||||
|
||||
#### 3.4.11 service 根包与 admin / impl / source
|
||||
|
||||
| 文件 | 职责 | 关键输入 | 关键输出 / 副作用 | 直接依赖 | 接手建议 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| `src/main/java/com/xiaowang/messagehub/service/EmailSendService.java` | 邮件发送门面 | 收件人或 `EmailDispatchRequest` | 调用通道服务发送邮件 | `MessageChannelService` | 邮件服务层入口 |
|
||||
| `src/main/java/com/xiaowang/messagehub/service/MessageProducerService.java` | MQ 生产者门面 | 各类 DTO | 序列化消息并投递到交换机 | `RabbitTemplate`、`ObjectMapper`、`RabbitMQConfig` | 改生产端路由键或消息头先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/service/QqSendService.java` | QQ 发送门面 | `QqDispatchRequest` | 调用通道服务发 QQ 并返回发送结果 | `MessageChannelService` | QQ 服务层入口 |
|
||||
| `src/main/java/com/xiaowang/messagehub/service/SmsSendService.java` | 短信发送接口 | `SmsMessageDTO` | 规范短信服务调用 | `SmsSendServiceImpl` | 若要替换短信服务实现先从接口收口 |
|
||||
| `src/main/java/com/xiaowang/messagehub/service/admin/PushLogAdminService.java` | 投递日志查询服务 | 过滤条件 | 返回 `PushLogView` 列表 | `PushLogMapper` | 扩日志后台能力从这里扩 |
|
||||
| `src/main/java/com/xiaowang/messagehub/service/impl/MessageHandleService.java` | 消费链路核心编排 | DTO、messageId、时间、payload | 校验、幂等、日志落库、状态更新、模板渲染、重试决策 | `Validator`、`PushLogMapper`、`PushTemplateMapper`、`MessageSourceSystemService` | 这是整个消息处理核心,任何投递规则变化都要先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/service/impl/SmsSendServiceImpl.java` | 短信发送实现 | `SmsMessageDTO` | 构造 `SmsDispatchRequest` 并发短信 | `MessageChannelService` | 短信门面到通道层的适配点 |
|
||||
| `src/main/java/com/xiaowang/messagehub/service/source/MessageSourceSystemService.java` | 来源系统与默认通道服务 | 保存请求、systemCode | 管来源系统白名单、默认通道映射、启停校验 | `MessageSourceSystemMapper`、`MessageSourceSystemChannelMapper` | 接入系统治理都在这里 |
|
||||
|
||||
#### 3.4.12 service/channel 核心包
|
||||
|
||||
| 文件 | 职责 | 关键输入 | 关键输出 / 副作用 | 直接依赖 | 接手建议 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| `src/main/java/com/xiaowang/messagehub/service/channel/ChannelCryptoService.java` | 通道敏感配置加解密 | 主密钥、明文 / 密文 | 加密 / 解密 / 脱敏 | `MessageChannelProperties` | 改密钥策略先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/service/channel/ChannelEnvironmentService.java` | 环境识别服务 | Spring `Environment` | 判断是否开发环境 | `MessageChannelProperties` | Mock 通道是否可用先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/service/channel/MessageChannelService.java` | 通道域核心服务 | 通道配置请求、测试发送请求、运行时 dispatch request | 管通道 CRUD、默认通道、体检、测试发送、短信模板、QQ 模板、邮件发送、QQ 发送 | Mapper、Crypto、Provider 列表、Template Service、Attachment Service、SourceSystem Service | 这是“所有通道能力”的总中枢,改功能首看这里 |
|
||||
|
||||
#### 3.4.13 service/channel/email 包
|
||||
|
||||
| 文件 | 职责 | 关键输入 | 关键输出 / 副作用 | 直接依赖 | 接手建议 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| `src/main/java/com/xiaowang/messagehub/service/channel/email/EmailChannelProvider.java` | 邮件 provider 抽象 | `ManagedChannelConfig`、邮件内容 | 规范发送与体检接口 | `MessageChannelService` | 加新邮件 provider 先实现它 |
|
||||
| `src/main/java/com/xiaowang/messagehub/service/channel/email/MockEmailChannelProvider.java` | 开发环境 Mock 邮件 provider | 运行时邮件请求 | 打日志,不真实外发 | `ChannelEnvironmentService` | 本地联调邮件问题先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/service/channel/email/SmtpEmailChannelProvider.java` | SMTP 邮件 provider | 通道配置、正文、附件 | 建 SMTP Session、发送 MIME 邮件、体检 | JavaMail、附件资源 | 真实邮件发送异常首看这里 |
|
||||
|
||||
#### 3.4.14 service/channel/qq 包
|
||||
|
||||
| 文件 | 职责 | 关键输入 | 关键输出 / 副作用 | 直接依赖 | 接手建议 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| `src/main/java/com/xiaowang/messagehub/service/channel/qq/QqChannelProvider.java` | QQ provider 抽象 | `ManagedChannelConfig`、QQ 请求 | 规范发送与体检接口 | `MessageChannelService` | 加新 QQ provider 先实现它 |
|
||||
| `src/main/java/com/xiaowang/messagehub/service/channel/qq/MockQqChannelProvider.java` | 开发环境 Mock QQ provider | QQ 请求 | 打日志,不真实外发 | `ChannelEnvironmentService` | 本地 QQ 联调先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/service/channel/qq/QqAutoChannelProvider.java` | QQAuto / NapCat 真实 provider | baseUrl、serviceToken、QQ 请求 | 发 HTTP 请求、解析业务响应、体检运行状态 | `ObjectMapper`、HTTP、QQ 网关 | QQ 供应商切换或协议变更从这里改 |
|
||||
|
||||
#### 3.4.15 service/channel/sms 包
|
||||
|
||||
| 文件 | 职责 | 关键输入 | 关键输出 / 副作用 | 直接依赖 | 接手建议 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| `src/main/java/com/xiaowang/messagehub/service/channel/sms/SmsChannelProvider.java` | 短信 provider 抽象 | `ManagedChannelConfig`、短信请求 | 规范发送与体检接口 | `MessageChannelService` | 加新短信 provider 先实现它 |
|
||||
| `src/main/java/com/xiaowang/messagehub/service/channel/sms/MockSmsChannelProvider.java` | 开发环境 Mock 短信 provider | 短信请求 | 打日志,不真实外发 | `ChannelEnvironmentService` | 本地短信联调先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/service/channel/sms/SpugSmsChannelProvider.java` | Spug 短信 provider | baseUrl、apiKey、模板外部 ID、短信请求 | 发 HTTP 请求、解析响应、体检 | `ObjectMapper`、HTTP | 真实短信发送异常首看这里 |
|
||||
|
||||
#### 3.4.16 service/email 包
|
||||
|
||||
| 文件 | 职责 | 关键输入 | 关键输出 / 副作用 | 直接依赖 | 接手建议 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| `src/main/java/com/xiaowang/messagehub/service/email/AttachmentStorageService.java` | 附件落盘与解析 | `MultipartFile`、附件 ID | 写本地文件、写 `email_attachment`、解析附件资源 | 文件系统、Mapper、Policy | 上传路径、白名单、保留期从这里改 |
|
||||
| `src/main/java/com/xiaowang/messagehub/service/email/EmailAttachmentPolicyService.java` | 附件策略服务 | 策略请求体 | 读写 `email_attachment_policy` | Policy Mapper | 调整附件上限或 MIME 白名单先看这里 |
|
||||
| `src/main/java/com/xiaowang/messagehub/service/email/EmailTemplateService.java` | 邮件模板服务 | 模板请求体、显式主题正文、模板参数 | 模板 CRUD、占位符提取、渲染主题和正文 | Template Mapper、Channel Mapper、Snowflake ID | 邮件模板是独立子域,改邮件内容生成先看这里 |
|
||||
|
||||
### 3.5 测试文件全量索引
|
||||
|
||||
| 文件 | 职责 | 关键输入 | 关键输出 / 副作用 | 直接依赖 | 接手建议 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| `src/test/java/com/xiaowang/messagehub/SmsMessageTest.java` | 手工短信联调用例 | RabbitTemplate、真实 / 半真实环境 | 直接往 `smsQueue` 投短信消息 | SpringBootTest、RabbitMQ | 这不是安全回归测试,只能手工联调时使用 |
|
||||
|
||||
## 4. 关键链路索引
|
||||
|
||||
### 4.1 启动链路
|
||||
- 入口:`src/main/java/com/xiaowang/messagehub/MessageHubApplication.java`
|
||||
- 做的事:
|
||||
- 计算运行时目录
|
||||
- 设置 `JM.LOG.PATH`
|
||||
- 设置 `JM.SNAPSHOT.PATH`
|
||||
- 启动 Spring Boot
|
||||
- 启动后:
|
||||
- `src/main/java/com/xiaowang/messagehub/listener/ApplicationStartupListener.java`
|
||||
- 调 `src/main/java/com/xiaowang/messagehub/health/ConnectionHealthChecker.java`
|
||||
- 调 `src/main/java/com/xiaowang/messagehub/service/channel/MessageChannelService.java` 的启动期健康检查
|
||||
|
||||
### 4.2 MQ 生产链路
|
||||
- 入口:`src/main/java/com/xiaowang/messagehub/service/MessageProducerService.java`
|
||||
- 典型流程:
|
||||
1. 生成 `messageId`
|
||||
2. 如无 `uniqueId` 则补默认值
|
||||
3. 把 DTO 序列化为 JSON
|
||||
4. 根据 `channelType` 拼接路由键
|
||||
5. 发送到 `messageExchange`
|
||||
- 当前注意:
|
||||
- `SMS` / `EMAIL` / `QQ` 有消费链路
|
||||
- `PUSH` / `WECHAT` 有生产方法,但当前 `RabbitMQConfig` 并没有对应消费队列和监听器
|
||||
|
||||
### 4.3 SMS 消费链路
|
||||
- 入口:`src/main/java/com/xiaowang/messagehub/listener/SmsQueueListener.java`
|
||||
- 主链:
|
||||
- `SmsQueueListener.handleSmsMessage`
|
||||
- `MessageHandleService.validateAndPrepareLog`
|
||||
- `SmsSendServiceImpl.sendSms`
|
||||
- `MessageChannelService.sendSms`
|
||||
- `SpugSmsChannelProvider` 或 `MockSmsChannelProvider`
|
||||
- `MessageHandleService.markSendSuccess / recordSendFailure`
|
||||
- 关键表:
|
||||
- `push_log`
|
||||
- `push_template`
|
||||
- `message_channel_config`
|
||||
- `message_source_system`
|
||||
|
||||
### 4.4 Email 消费链路
|
||||
- 入口:`src/main/java/com/xiaowang/messagehub/listener/EmailQueueListener.java`
|
||||
- 主链:
|
||||
- `EmailQueueListener.handleEmailMessage`
|
||||
- `MessageHandleService.validateAndPrepareLog(..., requestPayload)`
|
||||
- `EmailSendService.sendEmail(EmailDispatchRequest)`
|
||||
- `MessageChannelService.sendEmail`
|
||||
- `EmailTemplateService.render`
|
||||
- `AttachmentStorageService.resolveResources`
|
||||
- `SmtpEmailChannelProvider` 或 `MockEmailChannelProvider`
|
||||
- `MessageHandleService.markDispatchChannel / markSendSuccess`
|
||||
- 关键表:
|
||||
- `email_template`
|
||||
- `email_attachment`
|
||||
- `email_attachment_policy`
|
||||
- `push_log`
|
||||
- `message_channel_config`
|
||||
|
||||
### 4.5 QQ 消费链路
|
||||
- 入口:`src/main/java/com/xiaowang/messagehub/listener/QqQueueListener.java`
|
||||
- 主链:
|
||||
- `QqQueueListener.handleQqMessage`
|
||||
- `MessageHandleService.validateAndPrepareLog(..., requestPayload)`
|
||||
- `QqSendService.sendQq`
|
||||
- `MessageChannelService.sendQq`
|
||||
- `QqAutoChannelProvider` 或 `MockQqChannelProvider`
|
||||
- `MessageHandleService.markDispatchChannel / markProviderResponse / markSendSuccess`
|
||||
- 失败处理:
|
||||
- 达到失败阈值后发布到 `messageDeadLetterExchange`
|
||||
- 路由键 `dead.qq`
|
||||
- 记录 `dead_letter_reason`
|
||||
|
||||
### 4.6 后台管理链路
|
||||
- 静态页:
|
||||
- `src/main/resources/static/messagehub-admin/index.html`
|
||||
- `src/main/resources/static/messagehub-admin/app.js`
|
||||
- `src/main/resources/static/messagehub-admin/styles.css`
|
||||
- 已覆盖页面模块:
|
||||
- 来源系统列表 / 表单
|
||||
- 通道列表 / 表单
|
||||
- 测试发送
|
||||
- 短信模板列表 / 表单
|
||||
- 邮件模板列表 / 表单
|
||||
- 附件策略
|
||||
- 投递日志
|
||||
- 后台接口:
|
||||
- `/admin/api/source-systems`
|
||||
- `/admin/api/channels`
|
||||
- `/admin/api/channels/sms-templates`
|
||||
- `/admin/api/channels/qq-templates`
|
||||
- `/admin/api/email-templates`
|
||||
- `/admin/api/email-attachments`
|
||||
- `/admin/api/email-attachment-policies`
|
||||
- `/admin/api/push-logs`
|
||||
|
||||
### 4.7 附件上传链路
|
||||
- 入口:`src/main/java/com/xiaowang/messagehub/controller/EmailAttachmentAdminController.java`
|
||||
- 主链:
|
||||
- 前端文件上传
|
||||
- `AttachmentStorageService.upload`
|
||||
- 文件落到本机目录
|
||||
- 元数据写 `email_attachment`
|
||||
- 后续邮件发送通过 `resolveResources` 取回
|
||||
|
||||
### 4.8 投递日志链路
|
||||
- 写入入口:
|
||||
- `MessageHandleService.validateAndPrepareLog`
|
||||
- `MessageHandleService.markSendSuccess`
|
||||
- `MessageHandleService.recordSendFailure`
|
||||
- `MessageHandleService.markMessageRejected`
|
||||
- 查询入口:
|
||||
- `PushLogAdminService`
|
||||
- `PushLogAdminController`
|
||||
- `app.js` 的 `delivery-log` 模块
|
||||
|
||||
## 5. 配置与运行时索引
|
||||
|
||||
### 5.1 配置文件
|
||||
- `src/main/resources/application.yml`
|
||||
- `messagehub.channel.security.encryption-key`
|
||||
- `messagehub.channel.mock.auto-bootstrap`
|
||||
- `messagehub.channel.retry.max-attempts`
|
||||
- `messagehub.channel.retry.initial-delay-millis`
|
||||
- `messagehub.channel.retry.multiplier`
|
||||
- `messagehub.channel.retry.max-delay-millis`
|
||||
- `src/main/resources/bootstrap.yaml`
|
||||
- Nacos server-addr / namespace / username / password
|
||||
- shared configs:`rabbitmq.yaml`、`datasource.yaml`、`mybatis-plus.yaml`、`logging.yaml`
|
||||
- `src/main/resources/log4j2.xml`
|
||||
- 控制台 INFO 阈值
|
||||
- `messagehub.log`
|
||||
- `messagehub-error.log`
|
||||
|
||||
### 5.2 环境变量与敏感配置
|
||||
|
||||
文档里可以记录名字,但不要记录真实值:
|
||||
- `MESSAGE_HUB_MASTER_KEY`
|
||||
- Nacos 地址 / 用户名 / 密码
|
||||
- RabbitMQ 地址 / 用户名 / 密码
|
||||
- MySQL 地址 / 用户名 / 密码
|
||||
|
||||
当前真实风险:
|
||||
- `bootstrap.yaml` 中仍有 Nacos 明文地址、用户名、密码
|
||||
- `application.yml` / `MessageChannelProperties` 对主密钥存在默认值兜底
|
||||
|
||||
### 5.3 本地运行目录约定
|
||||
- `MessageHubApplication`
|
||||
- 日志 / Nacos snapshot 基础目录:`LOCALAPPDATA/YumiNail/MessageHub` 或 `~/.yuminail/messagehub`
|
||||
- `JM.LOG.PATH`
|
||||
- `JM.SNAPSHOT.PATH`
|
||||
- `AttachmentStorageService`
|
||||
- 邮件附件:`LOCALAPPDATA/YumiNail/MessageHub/uploads/email-attachments`
|
||||
- `log4j2.xml`
|
||||
- 当前文件日志直接写到 `E:/code/xiaowang/MessageHub/logs`
|
||||
|
||||
结论:
|
||||
- Nacos snapshot 与附件目录偏向“用户本地运行目录”
|
||||
- Log4j2 文件日志偏向“工作区固定目录”
|
||||
- 这两个约定目前不统一,是后续接手时需要注意的运行时差异
|
||||
|
||||
## 6. 数据与接口索引
|
||||
|
||||
### 6.1 DTO 契约
|
||||
- `MessageDTO`
|
||||
- 基础字段:`receiver`、`channelType`、`msgType`、`templateCode`、`templateParams`、`channelId`、`sourceSystem`、`uniqueId`
|
||||
- `SmsMessageDTO`
|
||||
- 在基础字段上增加 `sendMethod`
|
||||
- `EmailMessageDTO`
|
||||
- 在基础字段上增加 `subject`、`content`、`bodyType`、`emailTemplateCode`、`attachmentIds`
|
||||
- `QqMessageDTO`
|
||||
- 在基础字段上增加 `targetType`、`content`、`contentMode`
|
||||
|
||||
### 6.2 管理接口索引
|
||||
- `/admin/api/channels`
|
||||
- 通道 CRUD、健康检查、测试发送
|
||||
- `/admin/api/channels/sms-templates`
|
||||
- 短信模板管理
|
||||
- `/admin/api/channels/qq-templates`
|
||||
- QQ 模板管理
|
||||
- `/admin/api/source-systems`
|
||||
- 来源系统与默认通道管理
|
||||
- `/admin/api/email-templates`
|
||||
- 邮件模板管理
|
||||
- `/admin/api/email-attachments`
|
||||
- 邮件附件上传
|
||||
- `/admin/api/email-attachment-policies`
|
||||
- 附件策略管理
|
||||
- `/admin/api/push-logs`
|
||||
- 投递日志查询
|
||||
|
||||
### 6.3 MQ 契约索引
|
||||
- 交换机:
|
||||
- `messageExchange`
|
||||
- `messageDeadLetterExchange`
|
||||
- 主队列:
|
||||
- `smsQueue`
|
||||
- `emailQueue`
|
||||
- `qqQueue`
|
||||
- 死信队列:
|
||||
- `smsDeadLetterQueue`
|
||||
- `emailDeadLetterQueue`
|
||||
- `qqDeadLetterQueue`
|
||||
- 主路由键:
|
||||
- `sms.#`
|
||||
- `email.#`
|
||||
- `qq.#`
|
||||
- 死信路由键:
|
||||
- `dead.sms`
|
||||
- `dead.email`
|
||||
- `dead.qq`
|
||||
|
||||
### 6.4 数据表索引
|
||||
- `message_channel_config`
|
||||
- `push_template`
|
||||
- `email_template`
|
||||
- `email_attachment`
|
||||
- `email_attachment_policy`
|
||||
- `message_source_system`
|
||||
- `message_source_system_channel`
|
||||
- `push_log`
|
||||
- `messageDO`(遗留)
|
||||
|
||||
## 7. 后续模型 / 代理接手索引
|
||||
|
||||
### 7.1 当前没有的东西
|
||||
- 当前仓库没有:
|
||||
- `service/ai`
|
||||
- `prompt` 模板管理
|
||||
- AI provider 抽象
|
||||
- OpenAI / Qwen / DeepSeek / Claude / Gemini 等供应商接入代码
|
||||
- 向量检索、RAG、Agent、对话上下文管理
|
||||
|
||||
### 7.2 新代理接手仓库时的最短定位路径
|
||||
- 改通道配置 / 增新 provider
|
||||
- 先看 `MessageChannelService`
|
||||
- 再看对应 provider interface 与实现
|
||||
- 再看 `ChannelProviderCodeEnum`
|
||||
- 再看 `static/messagehub-admin/app.js`
|
||||
- 改 MQ 消费逻辑
|
||||
- 先看 `RabbitMQConfig`
|
||||
- 再看 `SmsQueueListener` / `EmailQueueListener` / `QqQueueListener`
|
||||
- 再看 `MessageHandleService`
|
||||
- 改模板
|
||||
- 短信 / QQ:`PushTemplateDO`、`PushTemplateMapper`、`MessageChannelService`
|
||||
- 邮件:`EmailTemplateDO`、`EmailTemplateMapper`、`EmailTemplateService`
|
||||
- 改日志 / 死信 / 重试
|
||||
- `PushLogDO`
|
||||
- `PushLogMapper`
|
||||
- `MessageHandleService`
|
||||
- `PushLogAdminService`
|
||||
- 改后台
|
||||
- `index.html` 定结构
|
||||
- `app.js` 定交互
|
||||
- 对应 `*AdminController`
|
||||
- 对应 Service / Mapper
|
||||
|
||||
### 7.3 如果未来要在 MessageHub 里接 AI / LLM
|
||||
|
||||
推荐落点:
|
||||
- 新建 `src/main/java/com/xiaowang/messagehub/service/ai/`
|
||||
- 作为 AI 业务门面
|
||||
- 新建 `src/main/java/com/xiaowang/messagehub/service/ai/provider/`
|
||||
- 复用当前 `service/channel/*Provider` 的抽象方式
|
||||
- 新建独立配置绑定
|
||||
- 例如 `messagehub.ai.*`
|
||||
- 如果做“模型切换”
|
||||
- 用 provider registry + `supports(modelCode)` 的方式
|
||||
- 不要把供应商判断散落到 controller / listener
|
||||
|
||||
推荐插入点:
|
||||
- 短信 / QQ 文本生成增强
|
||||
- `MessageHandleService.buildFinalContent` 前后
|
||||
- 邮件主题 / 正文生成增强
|
||||
- `EmailTemplateService.render` 前后
|
||||
- 发送前审计 / 安全检查
|
||||
- `MessageChannelService` 里进入 provider 之前
|
||||
- 生成结果落库
|
||||
- 可扩 `push_log`,但更建议单独设计 AI 审计表,避免污染消息主表
|
||||
|
||||
不推荐的做法:
|
||||
- 不要直接在 `controller` 里发模型请求
|
||||
- 不要直接在 `listener` 里拼 prompt
|
||||
- 不要让 MQ 基础消息体立刻依赖 AI 供应商字段
|
||||
|
||||
### 7.4 如果未来要做“模型切换”索引
|
||||
|
||||
建议新增的稳定接口层:
|
||||
- `AiGenerationService`
|
||||
- `AiProvider`
|
||||
- `PromptTemplateService`
|
||||
- `AiAuditService`
|
||||
|
||||
建议保留的现有稳定层:
|
||||
- `MessageHandleService`
|
||||
- `MessageChannelService`
|
||||
- `EmailTemplateService`
|
||||
- `AttachmentStorageService`
|
||||
|
||||
思路:
|
||||
- 先生成内容,再交给现有通道体系发送
|
||||
- 通道发送和 AI 生成两层解耦
|
||||
- AI 失败不应直接破坏既有 MQ 契约
|
||||
|
||||
## 8. 现有文档关系与漂移清单
|
||||
|
||||
### 8.1 文档状态判断
|
||||
|
||||
| 文档 | 状态 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `MessageHub_文档.md` | 部分过期 | 仍有系统概览价值,但写法停留在更早期能力边界 |
|
||||
| `项目详细总结.md` | 部分过期 | 仍可帮助理解项目定位,但未覆盖 QQ、邮件模板、附件、死信 |
|
||||
| `消息队列处理流程.md` | 明显过期 | 只讲 SMS,且引用旧类名 / 旧方法名 |
|
||||
| `MESSAGE_EXAMPLES.md` | 部分过期 | 仍可作消息体样例参考,但缺少邮件新字段与 QQ 样例 |
|
||||
| `外部系统对接接口文档.md` | 部分过期 | 对外口径仍以 SMS/EMAIL 为主,未完整反映当前代码 |
|
||||
| `src/main/resources/PROJECT_OVERVIEW.md` | 近期文档但需交叉验证 | 运行思路较新,但要和真实 `bootstrap.yaml`、工作区代码对照 |
|
||||
|
||||
### 8.2 已确认的显著不一致项
|
||||
|
||||
1. `外部系统对接接口文档.md` 仍按仅 `SMS/EMAIL` 描述当前对外主能力,但代码里已经存在 `QQ` DTO、监听器、provider、后台模板和死信逻辑。
|
||||
2. `外部系统对接接口文档.md` 中对 `PUSH/WECHAT` 的描述仍偏旧;当前代码里 `MessageProducerService` 还能生成这两类路由键,但 `RabbitMQConfig` 并没有对应消费绑定。
|
||||
3. `消息队列处理流程.md` 仍按旧版短信链路描述,里面提到的旧类名和旧方法名已经和当前实现不完全一致。
|
||||
4. `MessageHub_文档.md` 仍出现更早期的多渠道口径与旧实现名词,不能直接映射到当前 provider 结构。
|
||||
5. `PROJECT_OVERVIEW.md` 倾向把 Nacos 说成运行时环境变量注入,但当前真实 `bootstrap.yaml` 仍存在硬编码敏感配置。
|
||||
6. 当前代码已支持邮件模板、邮件附件、附件策略、投递日志死信字段,但旧文档基本没有覆盖。
|
||||
|
||||
## 9. 风险与待确认事项
|
||||
|
||||
### 9.1 高风险
|
||||
- `src/main/resources/bootstrap.yaml` 当前含 Nacos 明文地址、账号、密码。
|
||||
- `src/main/resources/application.yml` 和 `MessageChannelProperties` 对主密钥存在默认值,生产环境风险高。
|
||||
- 当前后台接口未看到内建鉴权层;`pom.xml` 里也没有 Spring Security 依赖,意味着 `/admin/api/*` 默认暴露风险较高。
|
||||
|
||||
### 9.2 中风险
|
||||
- `src/test` 只有 `SmsMessageTest`,而且是手工式、可能触达真实环境的联调用例,几乎不能作为自动回归基线。
|
||||
- `log4j2.xml` 使用固定工作区日志目录,而 `MessageHubApplication` 和 `AttachmentStorageService` 使用本地运行目录,部署 / 本机运行时容易混淆。
|
||||
- 当前工作区新增了大量未提交的 MessageHub 文件,和旧文档、远端主干很可能不一致;后续代理接手时必须先确认“当前工作树”是否就是目标基线。
|
||||
|
||||
### 9.3 低风险但需留意
|
||||
- 终端查看中文注释和文档时可能出现乱码,判断时要以逻辑和字段名为准。
|
||||
- `messageDO` / `MessageMapper` / `MessageDO` 这条旧层仍在仓库里,但不是当前短信 / 邮件 / QQ 主链路核心。
|
||||
|
||||
## 10. 接手时建议的工作顺序
|
||||
|
||||
1. 先确认本地工作区是否就是目标基线,而不是默认以远端历史提交为准。
|
||||
2. 先读本索引的“5 分钟接手路径”和“关键链路索引”。
|
||||
3. 再读 `pom.xml`、`MessageHubApplication.java`、`RabbitMQConfig.java`、`MessageChannelService.java`、`MessageHandleService.java`。
|
||||
4. 然后按你的目标领域切到对应表与对应前端:
|
||||
- 通道 -> `message_channel_config` + `MessageChannelService` + `app.js`
|
||||
- 短信 / QQ 模板 -> `push_template` + `MessageChannelService`
|
||||
- 邮件模板 / 附件 -> `email_template` / `email_attachment*` + `EmailTemplateService` / `AttachmentStorageService`
|
||||
- 日志 -> `push_log` + `MessageHandleService` / `PushLogAdminService`
|
||||
5. 最后再回看旧文档,只把它们当背景,不当真值。
|
||||
|
||||
## 11. 结论
|
||||
|
||||
- 当前 `MessageHub` 的真实核心是“多通道消息中心”,不是“大模型项目”。
|
||||
- 如果后续是“新的大模型代理来接手这个仓库”,最重要的是先掌握消息链路、通道抽象、日志落库和后台单页。
|
||||
- 如果后续是“在这个项目里接入 AI / LLM”,最合适的方式不是改动现有 MQ 契约,而是在 `service` 层新增独立 AI 子域,复用当前 provider 抽象思路。
|
||||
- 本文已经把当前工作区里的 Java、资源、SQL、测试、根目录文档全量纳入索引;后续任何接手动作,都建议先以本文为导航,再下钻到具体源码。
|
||||
@@ -1,110 +1,130 @@
|
||||
const navigation = require('../../utils/navigation')
|
||||
|
||||
Component({
|
||||
options: {
|
||||
multipleSlots: true // 在组件定义时的选项中启用多slot支持
|
||||
multipleSlots: true,
|
||||
},
|
||||
/**
|
||||
* 组件的属性列表
|
||||
*/
|
||||
properties: {
|
||||
extClass: {
|
||||
type: String,
|
||||
value: ''
|
||||
value: '',
|
||||
},
|
||||
title: {
|
||||
type: String,
|
||||
value: ''
|
||||
value: '',
|
||||
},
|
||||
background: {
|
||||
type: String,
|
||||
value: ''
|
||||
value: '',
|
||||
},
|
||||
color: {
|
||||
type: String,
|
||||
value: ''
|
||||
value: '',
|
||||
},
|
||||
back: {
|
||||
type: Boolean,
|
||||
value: true
|
||||
value: true,
|
||||
},
|
||||
showBack: {
|
||||
type: Boolean,
|
||||
value: true,
|
||||
},
|
||||
isTabPage: {
|
||||
type: Boolean,
|
||||
value: false,
|
||||
},
|
||||
fallbackPath: {
|
||||
type: String,
|
||||
value: '/pages/home/index',
|
||||
},
|
||||
loading: {
|
||||
type: Boolean,
|
||||
value: false
|
||||
value: false,
|
||||
},
|
||||
homeButton: {
|
||||
type: Boolean,
|
||||
value: false,
|
||||
},
|
||||
animated: {
|
||||
// 显示隐藏的时候opacity动画效果
|
||||
type: Boolean,
|
||||
value: true
|
||||
},
|
||||
show: {
|
||||
// 显示隐藏导航,隐藏的时候navigation-bar的高度占位还在
|
||||
type: Boolean,
|
||||
value: true,
|
||||
observer: '_showChange'
|
||||
},
|
||||
// back为true的时候,返回的页面深度
|
||||
show: {
|
||||
type: Boolean,
|
||||
value: true,
|
||||
observer: '_showChange',
|
||||
},
|
||||
delta: {
|
||||
type: Number,
|
||||
value: 1
|
||||
value: 1,
|
||||
},
|
||||
safeAreaMode: {
|
||||
type: String,
|
||||
value: 'solid',
|
||||
},
|
||||
},
|
||||
/**
|
||||
* 组件的初始数据
|
||||
*/
|
||||
observers: {
|
||||
'back, showBack, isTabPage': 'updateResolvedBack',
|
||||
},
|
||||
data: {
|
||||
displayStyle: ''
|
||||
displayStyle: '',
|
||||
resolvedShowBack: false,
|
||||
},
|
||||
lifetimes: {
|
||||
attached() {
|
||||
const rect = wx.getMenuButtonBoundingClientRect()
|
||||
const platform = (wx.getDeviceInfo() || wx.getSystemInfoSync()).platform
|
||||
const deviceInfo = (typeof wx.getDeviceInfo === 'function' ? wx.getDeviceInfo() : wx.getSystemInfoSync()) || {}
|
||||
const windowInfo = (typeof wx.getWindowInfo === 'function' ? wx.getWindowInfo() : wx.getSystemInfoSync()) || {}
|
||||
const platform = deviceInfo.platform
|
||||
const isAndroid = platform === 'android'
|
||||
const isDevtools = platform === 'devtools'
|
||||
const { windowWidth, safeArea: { top = 0, bottom = 0 } = {} } = wx.getWindowInfo() || wx.getSystemInfoSync()
|
||||
const safeArea = windowInfo.safeArea || {}
|
||||
const top = safeArea.top || 0
|
||||
const windowWidth = windowInfo.windowWidth || deviceInfo.windowWidth || 375
|
||||
|
||||
this.setData({
|
||||
ios: !isAndroid,
|
||||
innerPaddingRight: `padding-right: ${windowWidth - rect.left}px`,
|
||||
leftWidth: `width: ${windowWidth - rect.left}px`,
|
||||
safeAreaTop: isDevtools || isAndroid ? `height: calc(var(--height) + ${top}px); padding-top: ${top}px` : ``
|
||||
safeAreaTop: isDevtools || isAndroid ? `height: calc(var(--height) + ${top}px); padding-top: ${top}px` : '',
|
||||
})
|
||||
this.updateResolvedBack()
|
||||
},
|
||||
},
|
||||
/**
|
||||
* 组件的方法列表
|
||||
*/
|
||||
methods: {
|
||||
updateResolvedBack() {
|
||||
const resolvedShowBack = !this.data.isTabPage && Boolean(this.data.showBack && this.data.back)
|
||||
this.setData({
|
||||
resolvedShowBack,
|
||||
})
|
||||
},
|
||||
_showChange(show) {
|
||||
const animated = this.data.animated
|
||||
let displayStyle = ''
|
||||
if (animated) {
|
||||
displayStyle = `opacity: ${show ? '1' : '0'
|
||||
};transition:opacity 0.5s;`
|
||||
displayStyle = `opacity: ${show ? '1' : '0'};transition:opacity 0.3s;`
|
||||
} else {
|
||||
displayStyle = `display: ${show ? '' : 'none'}`
|
||||
}
|
||||
this.setData({
|
||||
displayStyle
|
||||
displayStyle,
|
||||
})
|
||||
},
|
||||
back() {
|
||||
const data = this.data
|
||||
const pages = getCurrentPages()
|
||||
if (data.delta && pages.length > data.delta) {
|
||||
if (this.data.delta && pages.length > this.data.delta) {
|
||||
wx.navigateBack({
|
||||
delta: data.delta
|
||||
delta: this.data.delta,
|
||||
})
|
||||
return
|
||||
}
|
||||
this.triggerEvent('back', { delta: data.delta }, {})
|
||||
|
||||
navigation.goBack(this.data.fallbackPath || '/pages/home/index')
|
||||
},
|
||||
home() {
|
||||
wx.switchTab({
|
||||
url: '/pages/home/index'
|
||||
url: '/pages/home/index',
|
||||
})
|
||||
this.triggerEvent('home', {}, {})
|
||||
}
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
@@ -1,52 +1,45 @@
|
||||
<view class="weui-navigation-bar {{extClass}}">
|
||||
<view class="weui-navigation-bar__inner {{ios ? 'ios' : 'android'}}" style="color: {{color}}; background: {{background}}; {{displayStyle}}; {{innerPaddingRight}}; {{safeAreaTop}};">
|
||||
|
||||
<!-- 左侧按钮 -->
|
||||
<view class='weui-navigation-bar__left' style="{{leftWidth}};">
|
||||
<block wx:if="{{back || homeButton}}">
|
||||
<!-- 返回上一页 -->
|
||||
<block wx:if="{{back}}">
|
||||
<view class="weui-navigation-bar__buttons weui-navigation-bar__buttons_goback">
|
||||
<view
|
||||
bindtap="back"
|
||||
class="weui-navigation-bar__btn_goback_wrapper"
|
||||
hover-class="weui-active"
|
||||
hover-stay-time="100"
|
||||
aria-role="button"
|
||||
aria-label="返回"
|
||||
>
|
||||
<view class="weui-navigation-bar__button weui-navigation-bar__btn_goback"></view>
|
||||
</view>
|
||||
<view class="weui-navigation-bar {{extClass}} {{safeAreaMode === 'overlay' ? 'weui-navigation-bar--overlay' : ''}}">
|
||||
<view
|
||||
class="weui-navigation-bar__inner {{ios ? 'ios' : 'android'}}"
|
||||
style="color: {{color}}; background: {{background}}; {{displayStyle}}; {{innerPaddingRight}}; {{safeAreaTop}};"
|
||||
>
|
||||
<view class="weui-navigation-bar__left" style="{{leftWidth}};">
|
||||
<block wx:if="{{resolvedShowBack || homeButton}}">
|
||||
<view wx:if="{{resolvedShowBack}}" class="weui-navigation-bar__buttons">
|
||||
<view
|
||||
bindtap="back"
|
||||
class="weui-navigation-bar__action"
|
||||
hover-class="weui-navigation-bar__action--active"
|
||||
hover-stay-time="80"
|
||||
aria-role="button"
|
||||
aria-label="返回"
|
||||
>
|
||||
<text class="weui-navigation-bar__arrow">‹</text>
|
||||
<text class="weui-navigation-bar__label">返回</text>
|
||||
</view>
|
||||
</block>
|
||||
<!-- 返回首页 -->
|
||||
<block wx:if="{{homeButton}}">
|
||||
<view class="weui-navigation-bar__buttons weui-navigation-bar__buttons_home">
|
||||
<view
|
||||
bindtap="home"
|
||||
class="weui-navigation-bar__btn_home_wrapper"
|
||||
hover-class="weui-active"
|
||||
aria-role="button"
|
||||
aria-label="首页"
|
||||
>
|
||||
<view class="weui-navigation-bar__button weui-navigation-bar__btn_home"></view>
|
||||
</view>
|
||||
</view>
|
||||
<view wx:if="{{homeButton}}" class="weui-navigation-bar__buttons">
|
||||
<view
|
||||
bindtap="home"
|
||||
class="weui-navigation-bar__action"
|
||||
hover-class="weui-navigation-bar__action--active"
|
||||
hover-stay-time="80"
|
||||
aria-role="button"
|
||||
aria-label="首页"
|
||||
>
|
||||
<text class="weui-navigation-bar__home-dot"></text>
|
||||
<text class="weui-navigation-bar__label">首页</text>
|
||||
</view>
|
||||
</block>
|
||||
</view>
|
||||
</block>
|
||||
<block wx:else>
|
||||
<slot name="left"></slot>
|
||||
</block>
|
||||
</view>
|
||||
|
||||
<!-- 标题 -->
|
||||
<view class='weui-navigation-bar__center'>
|
||||
<view class="weui-navigation-bar__center">
|
||||
<view wx:if="{{loading}}" class="weui-navigation-bar__loading" aria-role="alert">
|
||||
<view
|
||||
class="weui-loading"
|
||||
aria-role="img"
|
||||
aria-label="加载中"
|
||||
></view>
|
||||
<view class="weui-loading" aria-role="img" aria-label="加载中"></view>
|
||||
</view>
|
||||
<block wx:if="{{title}}">
|
||||
<text>{{title}}</text>
|
||||
@@ -55,9 +48,8 @@
|
||||
<slot name="center"></slot>
|
||||
</block>
|
||||
</view>
|
||||
|
||||
<!-- 右侧留空 -->
|
||||
<view class='weui-navigation-bar__right'>
|
||||
|
||||
<view class="weui-navigation-bar__right">
|
||||
<slot name="right"></slot>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
@@ -1,24 +1,23 @@
|
||||
.weui-navigation-bar {
|
||||
--weui-FG-0:rgba(0,0,0,.9);
|
||||
--weui-FG-0: rgba(0, 0, 0, 0.92);
|
||||
--height: 44px;
|
||||
--left: 16px;
|
||||
--left: 20rpx;
|
||||
color: var(--weui-FG-0);
|
||||
position: relative;
|
||||
z-index: 30;
|
||||
}
|
||||
|
||||
.weui-navigation-bar .android {
|
||||
--height: 48px;
|
||||
}
|
||||
|
||||
.weui-navigation-bar {
|
||||
overflow: hidden;
|
||||
color: var(--weui-FG-0);
|
||||
flex: none;
|
||||
position: relative;
|
||||
z-index: 20;
|
||||
.weui-navigation-bar--overlay {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
}
|
||||
|
||||
.weui-navigation-bar__inner {
|
||||
position: relative;
|
||||
top: 0;
|
||||
left: 0;
|
||||
z-index: 1;
|
||||
height: calc(var(--height) + env(safe-area-inset-top));
|
||||
display: flex;
|
||||
@@ -30,34 +29,65 @@
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.weui-navigation-bar__left {
|
||||
.weui-navigation-bar__left,
|
||||
.weui-navigation-bar__right {
|
||||
position: relative;
|
||||
padding-left: var(--left);
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: flex-start;
|
||||
align-items: center;
|
||||
height: 100%;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.weui-navigation-bar__btn_goback_wrapper {
|
||||
padding: 11px 18px 11px 16px;
|
||||
margin: -11px -18px -11px -16px;
|
||||
.weui-navigation-bar__left {
|
||||
padding-left: var(--left);
|
||||
}
|
||||
|
||||
.weui-navigation-bar__btn_goback_wrapper.weui-active {
|
||||
opacity: 0.5;
|
||||
.weui-navigation-bar__right {
|
||||
justify-content: flex-end;
|
||||
min-width: 120rpx;
|
||||
padding-right: 24rpx;
|
||||
}
|
||||
|
||||
.weui-navigation-bar__btn_goback {
|
||||
font-size: 12px;
|
||||
width: 12px;
|
||||
height: 24px;
|
||||
-webkit-mask: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='24' viewBox='0 0 12 24'%3E %3Cpath fill-opacity='.9' fill-rule='evenodd' d='M10 19.438L8.955 20.5l-7.666-7.79a1.02 1.02 0 0 1 0-1.42L8.955 3.5 10 4.563 2.682 12 10 19.438z'/%3E%3C/svg%3E") no-repeat 50% 50%;
|
||||
mask: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='24' viewBox='0 0 12 24'%3E %3Cpath fill-opacity='.9' fill-rule='evenodd' d='M10 19.438L8.955 20.5l-7.666-7.79a1.02 1.02 0 0 1 0-1.42L8.955 3.5 10 4.563 2.682 12 10 19.438z'/%3E%3C/svg%3E") no-repeat 50% 50%;
|
||||
-webkit-mask-size: cover;
|
||||
mask-size: cover;
|
||||
background-color: currentColor;
|
||||
.weui-navigation-bar__buttons {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.weui-navigation-bar__action {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 10rpx;
|
||||
min-height: 64rpx;
|
||||
padding: 0 18rpx 0 8rpx;
|
||||
border-radius: 999rpx;
|
||||
background: rgba(255, 255, 255, 0.86);
|
||||
border: 1rpx solid rgba(255, 255, 255, 0.94);
|
||||
box-shadow: 0 10rpx 28rpx rgba(45, 36, 48, 0.08);
|
||||
}
|
||||
|
||||
.weui-navigation-bar__action--active {
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.weui-navigation-bar__arrow {
|
||||
font-size: 40rpx;
|
||||
font-weight: 700;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.weui-navigation-bar__home-dot {
|
||||
width: 20rpx;
|
||||
height: 20rpx;
|
||||
border-radius: 999rpx;
|
||||
background: currentColor;
|
||||
}
|
||||
|
||||
.weui-navigation-bar__label {
|
||||
font-size: 24rpx;
|
||||
font-weight: 700;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.weui-navigation-bar__center {
|
||||
@@ -68,13 +98,22 @@
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-weight: bold;
|
||||
font-weight: 700;
|
||||
flex: 1;
|
||||
height: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.weui-navigation-bar__center text {
|
||||
max-width: 100%;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.weui-navigation-bar__loading {
|
||||
margin-right: 4px;
|
||||
margin-right: 8rpx;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
@@ -83,15 +122,14 @@
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
display: block;
|
||||
background: transparent url("data:image/svg+xml,%3C%3Fxml version='1.0' encoding='UTF-8'%3F%3E%3Csvg width='80px' height='80px' viewBox='0 0 80 80' version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'%3E%3Ctitle%3Eloading%3C/title%3E%3Cdefs%3E%3ClinearGradient x1='94.0869141%25' y1='0%25' x2='94.0869141%25' y2='90.559082%25' id='linearGradient-1'%3E%3Cstop stop-color='%23606060' stop-opacity='0' offset='0%25'%3E%3C/stop%3E%3Cstop stop-color='%23606060' stop-opacity='0.3' offset='100%25'%3E%3C/stop%3E%3C/linearGradient%3E%3ClinearGradient x1='100%25' y1='8.67370605%25' x2='100%25' y2='90.6286621%25' id='linearGradient-2'%3E%3Cstop stop-color='%23606060' offset='0%25'%3E%3C/stop%3E%3Cstop stop-color='%23606060' stop-opacity='0.3' offset='100%25'%3E%3C/stop%3E%3C/linearGradient%3E%3C/defs%3E%3Cg stroke='none' stroke-width='1' fill='none' fill-rule='evenodd' opacity='0.9'%3E%3Cg%3E%3Cpath d='M40,0 C62.09139,0 80,17.90861 80,40 C80,62.09139 62.09139,80 40,80 L40,73 C58.2253967,73 73,58.2253967 73,40 C73,21.7746033 58.2253967,7 40,7 L40,0 Z' fill='url(%23linearGradient-1)'%3E%3C/path%3E%3Cpath d='M40,0 L40,7 C21.7746033,7 7,21.7746033 7,40 C7,58.2253967 21.7746033,73 40,73 L40,80 C17.90861,80 0,62.09139 0,40 C0,17.90861 17.90861,0 40,0 Z' fill='url(%23linearGradient-2)'%3E%3C/path%3E%3Ccircle id='Oval' fill='%23606060' cx='40.5' cy='3.5' r='3.5'%3E%3C/circle%3E%3C/g%3E%3C/g%3E%3C/svg%3E%0A") no-repeat;
|
||||
background: transparent url("data:image/svg+xml,%3C%3Fxml version='1.0' encoding='UTF-8'%3F%3E%3Csvg width='80px' height='80px' viewBox='0 0 80 80' version='1.1' xmlns='http://www.w3.org/2000/svg'%3E%3Cg stroke='none' stroke-width='1' fill='none' fill-rule='evenodd' opacity='0.9'%3E%3Cg%3E%3Cpath d='M40,0 C62.09139,0 80,17.90861 80,40 C80,62.09139 62.09139,80 40,80 L40,73 C58.2253967,73 73,58.2253967 73,40 C73,21.7746033 58.2253967,7 40,7 L40,0 Z' fill='rgba(96,96,96,0.3)'/%3E%3Cpath d='M40,0 L40,7 C21.7746033,7 7,21.7746033 7,40 C7,58.2253967 21.7746033,73 40,73 L40,80 C17.90861,80 0,62.09139 0,40 C0,17.90861 17.90861,0 40,0 Z' fill='%23606060'/%3E%3Ccircle fill='%23606060' cx='40.5' cy='3.5' r='3.5'%3E%3C/circle%3E%3C/g%3E%3C/g%3E%3C/svg%3E") no-repeat;
|
||||
background-size: 100%;
|
||||
margin-left: 0;
|
||||
animation: loading linear infinite 1s;
|
||||
animation: loading 1s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes loading {
|
||||
from {
|
||||
transform: rotate(0);
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
|
||||
@@ -1,15 +1,7 @@
|
||||
<view class="auth-page-root">
|
||||
<navigation-bar title="账号中心" back="{{false}}" color="#2d2430" background="#fff7f8"></navigation-bar>
|
||||
<navigation-bar title="账号中心" showBack="{{true}}" fallbackPath="/pages/home/index" color="#2d2430" background="#fff7f8"></navigation-bar>
|
||||
|
||||
<scroll-view
|
||||
class="auth-scroll"
|
||||
scroll-y
|
||||
enable-flex
|
||||
enhanced
|
||||
show-scrollbar="false"
|
||||
scroll-with-animation="{{true}}"
|
||||
scroll-into-view="{{keyboardAnchorId}}"
|
||||
>
|
||||
<view class="auth-scroll">
|
||||
<view class="page-shell auth-page-shell auth-page">
|
||||
<view class="page-content auth-content {{keyboardVisible ? 'keyboard-active' : ''}}">
|
||||
<view class="page-card auth-panel">
|
||||
@@ -294,7 +286,7 @@
|
||||
|
||||
<view wx:if="{{keyboardVisible}}" class="keyboard-spacer" style="height: {{keyboardInsetRpx}}rpx;"></view>
|
||||
</view>
|
||||
</scroll-view>
|
||||
</view>
|
||||
|
||||
<view wx:if="{{showMiniShopSelector}}" class="mini-shop-mask" catchtouchmove="noop">
|
||||
<view class="page-card mini-shop-modal">
|
||||
|
||||
@@ -1,13 +1,9 @@
|
||||
.auth-page-root {
|
||||
height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.auth-scroll {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
min-height: 100%;
|
||||
}
|
||||
|
||||
.auth-page-shell {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<navigation-bar title="购物车" back="{{false}}" color="#2d2430" background="#fff7f8"></navigation-bar>
|
||||
<navigation-bar title="购物车" showBack="{{false}}" isTabPage="{{true}}" color="#2d2430" background="#fff7f8"></navigation-bar>
|
||||
|
||||
<view class="page-shell cart-page">
|
||||
<view class="page-content cart-content">
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<navigation-bar title="我的优惠券" color="#2d2430" background="#fff7f8" bindback="handleBack"></navigation-bar>
|
||||
<navigation-bar title="我的优惠券" showBack="{{true}}" fallbackPath="/pages/profile/index" color="#2d2430" background="#fff7f8"></navigation-bar>
|
||||
|
||||
<view class="page-shell coupons-page">
|
||||
<view class="page-content">
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<view class="home-page-root">
|
||||
<navigation-bar title="{{navTitle}}" back="{{false}}" color="#2d2430" background="#fff7f8"></navigation-bar>
|
||||
<navigation-bar title="{{navTitle}}" showBack="{{false}}" isTabPage="{{true}}" color="#2d2430" background="#fff7f8"></navigation-bar>
|
||||
|
||||
<scroll-view class="home-scroll" scroll-y enable-flex enhanced show-scrollbar="false" scroll-with-animation="{{true}}" scroll-into-view="{{keyboardAnchorId}}">
|
||||
<view class="home-scroll">
|
||||
<view class="page-shell home-page {{keyboardVisible ? 'keyboard-active' : ''}}">
|
||||
<view class="page-content">
|
||||
<view class="page-hero home-hero">
|
||||
@@ -142,5 +142,5 @@
|
||||
</view>
|
||||
<view wx:if="{{keyboardVisible}}" class="keyboard-light-spacer" style="height: {{keyboardInsetRpx}}rpx;"></view>
|
||||
</view>
|
||||
</scroll-view>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
@@ -1,13 +1,9 @@
|
||||
.home-page-root {
|
||||
height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.home-scroll {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
min-height: 100%;
|
||||
}
|
||||
|
||||
.home-page {
|
||||
|
||||
@@ -1,7 +1,28 @@
|
||||
const auth = require('../../utils/auth')
|
||||
|
||||
Page({
|
||||
data: {
|
||||
navTitle: '游客模式'
|
||||
},
|
||||
|
||||
onLoad() {
|
||||
this.syncNavTitle()
|
||||
wx.switchTab({
|
||||
url: '/pages/home/index'
|
||||
})
|
||||
},
|
||||
|
||||
onShow() {
|
||||
this.syncNavTitle()
|
||||
},
|
||||
|
||||
syncNavTitle() {
|
||||
const userInfo = auth.getStoredUserInfo()
|
||||
const navTitle = userInfo && String(userInfo.shopName || '').trim()
|
||||
? String(userInfo.shopName).trim()
|
||||
: '游客模式'
|
||||
this.setData({
|
||||
navTitle
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<navigation-bar title="Yumi Nail" back="{{false}}" color="#2d2430" background="#fff7f8"></navigation-bar>
|
||||
<navigation-bar title="{{navTitle}}" showBack="{{false}}" color="#2d2430" background="#fff7f8"></navigation-bar>
|
||||
<view class="redirect-page">
|
||||
<view class="redirect-card">
|
||||
<view class="redirect-title">正在进入首页</view>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
page {
|
||||
height: 100vh;
|
||||
min-height: 100vh;
|
||||
background: #fff7f8;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<navigation-bar title="我的订单" color="#2d2430" background="#fff7f8" bindback="handleBack"></navigation-bar>
|
||||
<navigation-bar title="我的订单" showBack="{{true}}" fallbackPath="/pages/profile/index" color="#2d2430" background="#fff7f8"></navigation-bar>
|
||||
|
||||
<view class="page-shell orders-page">
|
||||
<view class="page-content">
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<navigation-bar title="{{product ? product.displayTitle : '作品详情'}}" color="#2d2430" background="#fff7f8" bindback="handleBack"></navigation-bar>
|
||||
<navigation-bar title="{{product ? product.displayTitle : '作品详情'}}" showBack="{{true}}" fallbackPath="/pages/products/index" color="#2d2430" background="#fff7f8"></navigation-bar>
|
||||
|
||||
<view class="page-shell detail-page">
|
||||
<view wx:if="{{loadError}}" class="page-content">
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<navigation-bar title="作品库" back="{{false}}" color="#2d2430" background="#fff7f8"></navigation-bar>
|
||||
<navigation-bar title="作品库" showBack="{{false}}" isTabPage="{{true}}" color="#2d2430" background="#fff7f8"></navigation-bar>
|
||||
|
||||
<view class="page-shell product-page {{keyboardVisible ? 'keyboard-active' : ''}}">
|
||||
<view class="page-content product-page-content" style="{{keyboardVisible ? 'padding-bottom: ' + keyboardInsetRpx + 'rpx;' : ''}}">
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
<view class="profile-page-root">
|
||||
<navigation-bar title="个人中心" back="{{false}}" color="#ffffff" background="transparent"></navigation-bar>
|
||||
<navigation-bar title="个人中心" showBack="{{false}}" isTabPage="{{true}}" color="#ffffff" background="transparent" safeAreaMode="overlay"></navigation-bar>
|
||||
<view class="profile-bg"></view>
|
||||
|
||||
<scroll-view class="profile-scroll" scroll-y enable-flex enhanced show-scrollbar="false">
|
||||
<view class="profile-scroll">
|
||||
<view class="page-shell profile-page">
|
||||
<view class="page-content profile-content">
|
||||
<view wx:if="{{!isLoggedIn}}" class="page-card guest-card">
|
||||
@@ -41,7 +41,7 @@
|
||||
<view class="shop-box" bindtap="handleSwitchShop">
|
||||
<view>
|
||||
<view class="shop-label">当前登录门店</view>
|
||||
<view class="shop-name">{{userInfo.shopName || '暂未选择门店'}}</view>
|
||||
<view class="shop-name">{{userInfo.shopName || '当前暂无可用门店'}}</view>
|
||||
</view>
|
||||
<view class="shop-link">{{(userInfo.shopIds && userInfo.shopIds.length > 1) ? '切换' : '查看'}}</view>
|
||||
</view>
|
||||
@@ -79,5 +79,5 @@
|
||||
</block>
|
||||
</view>
|
||||
</view>
|
||||
</scroll-view>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
@@ -1,13 +1,9 @@
|
||||
.profile-page-root {
|
||||
height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.profile-scroll {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
min-height: 100%;
|
||||
}
|
||||
|
||||
.profile-page {
|
||||
|
||||
@@ -1,15 +1,7 @@
|
||||
<view class="settings-page-root">
|
||||
<navigation-bar title="设置中心" color="#2d2430" background="#fff7f8" bindback="handleBack"></navigation-bar>
|
||||
<navigation-bar title="设置中心" showBack="{{true}}" fallbackPath="/pages/profile/index" color="#2d2430" background="#fff7f8"></navigation-bar>
|
||||
|
||||
<scroll-view
|
||||
class="settings-scroll"
|
||||
scroll-y
|
||||
enable-flex
|
||||
enhanced
|
||||
show-scrollbar="false"
|
||||
scroll-with-animation="{{true}}"
|
||||
scroll-into-view="{{keyboardAnchorId}}"
|
||||
>
|
||||
<view class="settings-scroll">
|
||||
<view class="page-shell settings-page-shell {{keyboardVisible ? 'keyboard-active' : ''}}">
|
||||
<view class="page-content">
|
||||
<view wx:if="{{!isLoggedIn}}" class="page-card empty-card">
|
||||
@@ -302,5 +294,5 @@
|
||||
|
||||
<view wx:if="{{keyboardVisible}}" class="keyboard-spacer" style="height: {{keyboardInsetRpx}}rpx;"></view>
|
||||
</view>
|
||||
</scroll-view>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
@@ -1,13 +1,9 @@
|
||||
.settings-page-root {
|
||||
height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.settings-scroll {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
min-height: 100%;
|
||||
}
|
||||
|
||||
.settings-page-shell {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<navigation-bar title="{{shopInfo ? shopInfo.shopName : '门店详情'}}" color="#ffffff" background="transparent" bindback="handleBack"></navigation-bar>
|
||||
<navigation-bar title="{{shopInfo ? shopInfo.shopName : '门店详情'}}" showBack="{{true}}" fallbackPath="{{returnTo || '/pages/home/index'}}" color="#ffffff" background="transparent" safeAreaMode="overlay"></navigation-bar>
|
||||
|
||||
<view class="page-shell shop-page">
|
||||
<view class="shop-hero">
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<navigation-bar title="我的收藏" color="#2d2430" background="#fff7f8" bindback="handleBack"></navigation-bar>
|
||||
<navigation-bar title="我的收藏" showBack="{{true}}" fallbackPath="/pages/profile/index" color="#2d2430" background="#fff7f8"></navigation-bar>
|
||||
|
||||
<view class="page-shell wishlist-page">
|
||||
<view class="page-content">
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.7.18</version>
|
||||
<relativePath/>
|
||||
</parent>
|
||||
|
||||
<groupId>com.xiaowang</groupId>
|
||||
<artifactId>YumiNail-Calendar-Core</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<name>YumiNail-Calendar-Core</name>
|
||||
<description>Independent appointment calendar backend for nail artists.</description>
|
||||
|
||||
<properties>
|
||||
<java.version>17</java.version>
|
||||
<mybatis-plus.version>3.5.3.1</mybatis-plus.version>
|
||||
<druid.version>1.2.23</druid.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-logging</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-logging</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-log4j2</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.baomidou</groupId>
|
||||
<artifactId>mybatis-plus-boot-starter</artifactId>
|
||||
<version>${mybatis-plus.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-logging</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>druid-spring-boot-starter</artifactId>
|
||||
<version>${druid.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-logging</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.mysql</groupId>
|
||||
<artifactId>mysql-connector-j</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>1.18.32</version>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-logging</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>YumiNail-Calendar-Core</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.8.1</version>
|
||||
<configuration>
|
||||
<source>${java.version}</source>
|
||||
<target>${java.version}</target>
|
||||
<annotationProcessorPaths>
|
||||
<path>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>1.18.32</version>
|
||||
</path>
|
||||
</annotationProcessorPaths>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.xiaowang.yuminailcalendarcore;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class YumiNailCalendarCoreApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(YumiNailCalendarCoreApplication.class, args);
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.xiaowang.yuminailcalendarcore.common;
|
||||
|
||||
public class ConflictException extends RuntimeException {
|
||||
|
||||
public ConflictException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package com.xiaowang.yuminailcalendarcore.common;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.context.support.DefaultMessageSourceResolvable;
|
||||
import org.springframework.validation.BindException;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
|
||||
import javax.validation.ConstraintViolationException;
|
||||
|
||||
@Slf4j
|
||||
@RestControllerAdvice
|
||||
public class GlobalExceptionHandler {
|
||||
|
||||
@ExceptionHandler(ConflictException.class)
|
||||
public Result<Void> handleConflictException(ConflictException e) {
|
||||
return Result.error(409, e.getMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
public Result<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
|
||||
String message = e.getBindingResult().getAllErrors().stream()
|
||||
.map(DefaultMessageSourceResolvable::getDefaultMessage)
|
||||
.findFirst()
|
||||
.orElse("请求参数不合法");
|
||||
return Result.error(message);
|
||||
}
|
||||
|
||||
@ExceptionHandler(BindException.class)
|
||||
public Result<Void> handleBindException(BindException e) {
|
||||
String message = e.getBindingResult().getAllErrors().stream()
|
||||
.map(DefaultMessageSourceResolvable::getDefaultMessage)
|
||||
.findFirst()
|
||||
.orElse("请求参数不合法");
|
||||
return Result.error(message);
|
||||
}
|
||||
|
||||
@ExceptionHandler(ConstraintViolationException.class)
|
||||
public Result<Void> handleConstraintViolationException(ConstraintViolationException e) {
|
||||
String message = e.getConstraintViolations().stream()
|
||||
.map(violation -> violation.getMessage())
|
||||
.findFirst()
|
||||
.orElse("请求参数不合法");
|
||||
return Result.error(message);
|
||||
}
|
||||
|
||||
@ExceptionHandler(IllegalArgumentException.class)
|
||||
public Result<Void> handleIllegalArgumentException(IllegalArgumentException e) {
|
||||
return Result.error(e.getMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler(RuntimeException.class)
|
||||
public Result<Void> handleRuntimeException(RuntimeException e) {
|
||||
log.error("业务异常", e);
|
||||
return Result.error(e.getMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
public Result<Void> handleException(Exception e) {
|
||||
log.error("系统异常", e);
|
||||
return Result.error("系统繁忙,请稍后重试");
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package com.xiaowang.yuminailcalendarcore.common;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class Result<T> implements Serializable {
|
||||
|
||||
private Integer code;
|
||||
private String message;
|
||||
private T data;
|
||||
|
||||
public static <T> Result<T> success() {
|
||||
return new Result<>(200, "操作成功", null);
|
||||
}
|
||||
|
||||
public static <T> Result<T> success(T data) {
|
||||
return new Result<>(200, "操作成功", data);
|
||||
}
|
||||
|
||||
public static <T> Result<T> error(String message) {
|
||||
return new Result<>(500, message, null);
|
||||
}
|
||||
|
||||
public static <T> Result<T> error(Integer code, String message) {
|
||||
return new Result<>(code, message, null);
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.xiaowang.yuminailcalendarcore.config;
|
||||
|
||||
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
|
||||
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class JacksonConfig {
|
||||
|
||||
@Bean
|
||||
public Jackson2ObjectMapperBuilderCustomizer longToStringJacksonCustomizer() {
|
||||
return builder -> {
|
||||
builder.serializerByType(Long.class, ToStringSerializer.instance);
|
||||
builder.serializerByType(Long.TYPE, ToStringSerializer.instance);
|
||||
};
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.xiaowang.yuminailcalendarcore.config;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.DbType;
|
||||
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
|
||||
import org.mybatis.spring.annotation.MapperScan;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@MapperScan("com.xiaowang.yuminailcalendarcore.mapper")
|
||||
public class MyBatisPlusConfig {
|
||||
|
||||
@Bean
|
||||
public MybatisPlusInterceptor mybatisPlusInterceptor() {
|
||||
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
|
||||
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
|
||||
interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
|
||||
return interceptor;
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.xiaowang.yuminailcalendarcore.config;
|
||||
|
||||
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
|
||||
import org.apache.ibatis.reflection.MetaObject;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Component
|
||||
public class MyMetaObjectHandler implements MetaObjectHandler {
|
||||
|
||||
@Override
|
||||
public void insertFill(MetaObject metaObject) {
|
||||
this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
|
||||
this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateFill(MetaObject metaObject) {
|
||||
this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
package com.xiaowang.yuminailcalendarcore.controller;
|
||||
|
||||
import com.xiaowang.yuminailcalendarcore.common.Result;
|
||||
import com.xiaowang.yuminailcalendarcore.dto.AppointmentBatchDeleteRequest;
|
||||
import com.xiaowang.yuminailcalendarcore.dto.AppointmentImportRequest;
|
||||
import com.xiaowang.yuminailcalendarcore.dto.AppointmentSaveRequest;
|
||||
import com.xiaowang.yuminailcalendarcore.dto.AppointmentStatusUpdateRequest;
|
||||
import com.xiaowang.yuminailcalendarcore.service.AppointmentService;
|
||||
import com.xiaowang.yuminailcalendarcore.vo.AppointmentDashboardVO;
|
||||
import com.xiaowang.yuminailcalendarcore.vo.AppointmentExportVO;
|
||||
import com.xiaowang.yuminailcalendarcore.vo.AppointmentVO;
|
||||
import com.xiaowang.yuminailcalendarcore.vo.CalendarDaySummaryVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.format.annotation.DateTimeFormat;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PatchMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import java.time.LocalDate;
|
||||
import java.time.YearMonth;
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/appointment")
|
||||
public class AppointmentController {
|
||||
|
||||
private final AppointmentService appointmentService;
|
||||
|
||||
@GetMapping("/day")
|
||||
public Result<List<AppointmentVO>> getAppointmentsByDay(@RequestParam("date")
|
||||
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
|
||||
LocalDate date,
|
||||
@RequestParam(value = "keyword", required = false) String keyword,
|
||||
@RequestParam(value = "sortBy", required = false) String sortBy) {
|
||||
return Result.success(appointmentService.getAppointmentsByDay(date, keyword, sortBy));
|
||||
}
|
||||
|
||||
@GetMapping("/list")
|
||||
public Result<List<AppointmentVO>> searchAppointments(@RequestParam(value = "startDate", required = false)
|
||||
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
|
||||
LocalDate startDate,
|
||||
@RequestParam(value = "endDate", required = false)
|
||||
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
|
||||
LocalDate endDate,
|
||||
@RequestParam(value = "customerId", required = false) Long customerId,
|
||||
@RequestParam(value = "keyword", required = false) String keyword,
|
||||
@RequestParam(value = "serviceName", required = false) String serviceName,
|
||||
@RequestParam(value = "status", required = false) String status,
|
||||
@RequestParam(value = "sortBy", required = false) String sortBy) {
|
||||
return Result.success(appointmentService.searchAppointments(startDate, endDate, customerId, keyword, serviceName, status, sortBy));
|
||||
}
|
||||
|
||||
@GetMapping("/month-overview")
|
||||
public Result<List<CalendarDaySummaryVO>> getMonthOverview(@RequestParam("month") String month) {
|
||||
return Result.success(appointmentService.getMonthSummary(YearMonth.parse(month)));
|
||||
}
|
||||
|
||||
@GetMapping("/dashboard")
|
||||
public Result<AppointmentDashboardVO> getDashboard(@RequestParam(value = "date", required = false)
|
||||
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
|
||||
LocalDate date) {
|
||||
return Result.success(appointmentService.getDashboard(date));
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public Result<AppointmentVO> getAppointment(@PathVariable("id") Long id) {
|
||||
return Result.success(appointmentService.getAppointment(id));
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public Result<List<AppointmentVO>> createAppointment(@Valid @RequestBody AppointmentSaveRequest request) {
|
||||
return Result.success(appointmentService.createAppointment(request));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public Result<List<AppointmentVO>> updateAppointment(@PathVariable("id") Long id,
|
||||
@Valid @RequestBody AppointmentSaveRequest request) {
|
||||
return Result.success(appointmentService.updateAppointment(id, request));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public Result<Void> deleteAppointment(@PathVariable("id") Long id,
|
||||
@RequestParam(value = "deleteSeries", defaultValue = "false") boolean deleteSeries) {
|
||||
appointmentService.deleteAppointment(id, deleteSeries);
|
||||
return Result.success();
|
||||
}
|
||||
|
||||
@PostMapping("/batch-delete")
|
||||
public Result<Void> batchDelete(@Valid @RequestBody AppointmentBatchDeleteRequest request) {
|
||||
appointmentService.batchDelete(request);
|
||||
return Result.success();
|
||||
}
|
||||
|
||||
@PatchMapping("/{id}/status")
|
||||
public Result<AppointmentVO> updateStatus(@PathVariable("id") Long id,
|
||||
@Valid @RequestBody AppointmentStatusUpdateRequest request) {
|
||||
return Result.success(appointmentService.updateStatus(id, request));
|
||||
}
|
||||
|
||||
@GetMapping("/export")
|
||||
public Result<AppointmentExportVO> exportAppointments(@RequestParam(value = "startDate", required = false)
|
||||
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
|
||||
LocalDate startDate,
|
||||
@RequestParam(value = "endDate", required = false)
|
||||
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
|
||||
LocalDate endDate) {
|
||||
return Result.success(appointmentService.exportAppointments(startDate, endDate));
|
||||
}
|
||||
|
||||
@PostMapping("/import")
|
||||
public Result<List<AppointmentVO>> importAppointments(@Valid @RequestBody AppointmentImportRequest request) {
|
||||
return Result.success(appointmentService.importAppointments(request));
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user