feat: 支持管理员消息推送

This commit is contained in:
richarjiang
2026-04-12 22:18:34 +08:00
parent c60821c5ff
commit 6cee28bf66
26 changed files with 780 additions and 161 deletions

View File

@@ -47,6 +47,7 @@ interface MenuItem {
const props = defineProps<{
isAdmin: boolean
requireAuth?: boolean
activeMembershipCount?: number
}>()
const emit = defineEmits<{
@@ -56,12 +57,17 @@ const emit = defineEmits<{
}>()
const menuItems = computed<MenuItem[]>(() => {
const membershipBadge = props.activeMembershipCount && props.activeMembershipCount > 0
? `${props.activeMembershipCount}`
: undefined
const items: MenuItem[] = [
{
key: 'membership',
type: 'item',
title: '我的会员卡',
path: '/pages/profile/membership',
badge: membershipBadge,
requireAuth: true,
},
{
@@ -346,11 +352,17 @@ function handleTap(item: MenuItem) {
&__badge {
font-size: 22rpx;
color: #ffffff;
background: $error-color;
border-radius: 20rpx;
padding: 2rpx 12rpx;
line-height: 1;
font-weight: 600;
color: #496578;
background: linear-gradient(135deg, rgba(239, 247, 251, 0.98), rgba(218, 234, 243, 0.96));
border-radius: 999rpx;
padding: 9rpx 18rpx;
margin-right: $spacing-sm;
border: 1rpx solid rgba(123, 165, 190, 0.18);
box-shadow:
inset 0 1rpx 0 rgba(255, 255, 255, 0.92),
0 6rpx 16rpx rgba(123, 165, 190, 0.16);
}
&__arrow {

View File

@@ -68,7 +68,7 @@
<!-- OPEN + booked by me -->
<template v-else-if="timeSlot.status === TimeSlotStatus.OPEN && timeSlot.isBookedByMe">
<view class="action-badge badge-booked">
<text>已预约</text>
<text>{{ myBookingLabel }}</text>
</view>
<view class="cancel-link" @tap.stop="emit('cancel', timeSlot)">
<text>取消</text>
@@ -96,7 +96,7 @@
<script setup lang="ts">
import type { TimeSlotWithBookingStatus } from '@mp-pilates/shared'
import { TimeSlotStatus } from '@mp-pilates/shared'
import { BookingStatus, TimeSlotStatus } from '@mp-pilates/shared'
import { computed } from 'vue'
import { isSlotPast } from '../utils/format'
@@ -120,6 +120,12 @@ const durationMin = computed(() => {
return (eh * 60 + em) - (sh * 60 + sm)
})
const myBookingLabel = computed(() => (
props.timeSlot.myBookingStatus === BookingStatus.PENDING_CONFIRMATION
? '已预约待确认'
: '已预约'
))
const capacityLabel = computed(() => {
const { bookedCount, capacity, status } = props.timeSlot
if (status === TimeSlotStatus.CLOSED) return '已关闭'

View File

@@ -1,40 +1,64 @@
<template>
<view class="studio-info">
<!-- Horizontal photo strip -->
<scroll-view v-if="studioInfo?.photos?.length" scroll-x class="photo-strip" :show-scrollbar="false">
<view class="photo-strip-inner">
<image v-for="(photo, idx) in studioInfo.photos" :key="idx" class="strip-photo" :src="photo" mode="aspectFill"
@tap="previewPhoto(idx)" />
</view>
</scroll-view>
<!-- Address + Chat row -->
<view class="location-row">
<view class="location-left" @tap="handleAddressTap">
<view class="location-icon" />
<text class="location-text">
{{ studioInfo?.address || '深圳市宝安区西乡街道财富港 D 座 1203D' }}
</text>
<view class="location-content">
<text class="location-label">场馆地址</text>
<text class="location-text">
{{ studioInfo?.address || '深圳市宝安区西乡街道财富港 D 座 1203D' }}
</text>
</view>
</view>
<button class="chat-btn" open-type="contact">
<view class="chat-icon" />
</button>
</view>
<!-- Horizontal gallery -->
<view class="gallery-block">
<scroll-view scroll-x class="gallery-scroll" :show-scrollbar="false" enhanced>
<view class="gallery-track">
<view
v-for="(photo, idx) in galleryPhotos"
:key="photo"
class="gallery-item"
@tap="previewPhoto(idx)"
>
<image class="gallery-image" :src="photo" mode="aspectFill" />
<view class="gallery-overlay" />
</view>
</view>
</scroll-view>
</view>
</view>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import type { StudioConfig } from '@mp-pilates/shared'
const props = defineProps<{
studioInfo: StudioConfig | null
}>()
const defaultGalleryPhotos = [
'https://plates-1251306435.cos.ap-guangzhou.myqcloud.com/mp/images/place_1.jpg',
'https://plates-1251306435.cos.ap-guangzhou.myqcloud.com/mp/images/place_2.jpg',
'https://plates-1251306435.cos.ap-guangzhou.myqcloud.com/mp/images/place_3.jpg',
'https://plates-1251306435.cos.ap-guangzhou.myqcloud.com/mp/images/place_4.jpg',
]
const galleryPhotos = computed(() => {
const photos = props.studioInfo?.photos?.filter(Boolean) ?? []
return photos.length ? photos : defaultGalleryPhotos
})
function previewPhoto(index: number) {
if (!props.studioInfo?.photos?.length) return
uni.previewImage({
current: index,
urls: props.studioInfo.photos,
urls: galleryPhotos.value,
})
}
@@ -76,33 +100,12 @@ function copyAddress() {
box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}
/* ── Photo strip ── */
.photo-strip {
width: 100%;
padding: 24rpx 0;
}
.photo-strip-inner {
display: flex;
flex-direction: row;
gap: 16rpx;
padding: 0 24rpx;
width: max-content;
}
.strip-photo {
width: 240rpx;
height: 160rpx;
border-radius: 12rpx;
flex-shrink: 0;
}
/* ── Location row ── */
.location-row {
display: flex;
align-items: center;
justify-content: space-between;
padding: 24rpx 32rpx 28rpx;
padding: 28rpx 32rpx 24rpx;
gap: 24rpx;
}
@@ -114,11 +117,64 @@ function copyAddress() {
min-width: 0;
}
.location-content {
flex: 1;
min-width: 0;
}
.location-label {
display: block;
font-size: 22rpx;
color: #b39a92;
letter-spacing: 2rpx;
margin-bottom: 6rpx;
}
.location-text {
font-size: 26rpx;
color: #666;
line-height: 1.5;
word-break: break-all;
color: #5f5955;
line-height: 1.6;
word-break: break-word;
}
/* ── Gallery ── */
.gallery-block {
padding: 6rpx 0 28rpx;
}
.gallery-scroll {
width: 100%;
}
.gallery-track {
display: flex;
gap: 14rpx;
padding: 0 32rpx;
width: max-content;
}
.gallery-item {
position: relative;
width: 192rpx;
height: 108rpx;
border-radius: 14rpx;
overflow: hidden;
flex-shrink: 0;
background: linear-gradient(135deg, #eadfd8 0%, #d5c0b4 100%);
box-shadow: 0 8rpx 18rpx rgba(124, 95, 82, 0.1);
}
.gallery-image {
width: 100%;
height: 100%;
}
.gallery-overlay {
position: absolute;
inset: 0;
background:
linear-gradient(180deg, rgba(255, 255, 255, 0.1) 0%, rgba(38, 28, 24, 0.2) 100%),
linear-gradient(135deg, rgba(255, 255, 255, 0.08) 0%, transparent 48%);
}
/* ── Icons ── */

View File

@@ -25,14 +25,16 @@
mode="aspectFill"
@error="onAvatarError"
/>
<!-- VIP badge hidden for now -->
<!-- <view class="user-card__vip-badge" v-if="vipLevel">
<text class="user-card__vip-text">{{ vipLevel }}</text>
</view> -->
</view>
<view class="user-card__info">
<view class="user-card__name-row">
<text class="user-card__nickname">{{ user!.nickname }}</text>
<view v-if="hasMembership" class="user-card__member-badge">
<view class="user-card__member-icon">
<text class="user-card__member-letter">C</text>
</view>
<text class="user-card__member-label">CLUB</text>
</view>
</view>
<text v-if="maskedPhone" class="user-card__phone">{{ maskedPhone }}</text>
</view>
@@ -75,7 +77,7 @@
<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import type { UserProfileResponse, UserStatsResponse, MembershipWithCardType } from '@mp-pilates/shared'
import { MembershipStatus } from '@mp-pilates/shared'
import { CardTypeCategory, MembershipStatus } from '@mp-pilates/shared'
const props = defineProps<{
loggedIn: boolean
@@ -117,24 +119,25 @@ const maskedPhone = computed(() => {
return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
})
// Derive VIP level from active memberships count
const activeMemberships = computed(() =>
props.memberships?.filter((m) => m.status === MembershipStatus.ACTIVE) ?? [],
)
const vipLevel = computed(() => {
const count = activeMemberships.value.length
if (count >= 3) return 'VIP3'
if (count >= 2) return 'VIP2'
if (count >= 1) return 'VIP1'
return null
})
const activeMembershipCount = computed(
() => props.user?.activeMembershipCount ?? activeMemberships.value.length,
)
const hasMembership = computed(() => activeMembershipCount.value > 0)
function toSafeCount(value: number | null | undefined): number {
return typeof value === 'number' && Number.isFinite(value) ? value : 0
}
// Sum remaining sessions from all active time-based memberships
const remainingSessions = computed(() =>
activeMemberships.value
.filter((m) => m.cardType.type === 'TIMES')
.reduce((sum, m) => sum + m.remainingCount, 0),
.filter((m) => m.cardType.type === CardTypeCategory.TIMES)
.reduce((sum, m) => sum + toSafeCount(m.remainingTimes), 0),
)
function onAvatarError() {
@@ -220,24 +223,6 @@ function handleLogin() {
border: 4rpx solid rgba(255, 255, 255, 0.4);
}
&__vip-badge {
position: absolute;
bottom: -6rpx;
left: 50%;
transform: translateX(-50%);
background: linear-gradient(135deg, #fbbf24, #f59e0b);
border-radius: 20rpx;
padding: 2rpx 12rpx;
border: 2rpx solid #ffffff;
}
&__vip-text {
font-size: 18rpx;
font-weight: 700;
color: #7c2d12;
line-height: 1;
}
&__info {
flex: 1;
display: flex;
@@ -257,6 +242,59 @@ function handleLogin() {
color: #ffffff;
}
&__member-badge {
display: inline-flex;
align-items: center;
gap: 10rpx;
padding: 6rpx 14rpx 6rpx 8rpx;
border-radius: 999rpx;
background: linear-gradient(135deg, rgba(244, 250, 253, 0.98), rgba(219, 235, 243, 0.94));
border: 1rpx solid rgba(123, 165, 190, 0.22);
box-shadow:
inset 0 1rpx 0 rgba(255, 255, 255, 0.9),
0 8rpx 20rpx rgba(79, 123, 148, 0.16);
}
&__member-icon {
width: 34rpx;
height: 34rpx;
border-radius: 50%;
position: relative;
display: flex;
align-items: center;
justify-content: center;
background: radial-gradient(circle at 30% 30%, #ffffff 0%, #dfeef6 38%, #8fb6cb 100%);
box-shadow:
inset 0 2rpx 4rpx rgba(255, 255, 255, 0.76),
0 3rpx 8rpx rgba(77, 117, 140, 0.18);
&::after {
content: '';
position: absolute;
inset: 3rpx;
border-radius: 50%;
border: 1.5rpx solid rgba(92, 132, 156, 0.35);
}
}
&__member-letter {
position: relative;
z-index: 1;
font-size: 20rpx;
line-height: 1;
font-weight: 800;
color: #4f6f82;
letter-spacing: 1rpx;
}
&__member-label {
font-size: 20rpx;
line-height: 1;
font-weight: 700;
color: #537488;
letter-spacing: 2rpx;
}
&__phone {
font-size: 26rpx;
color: rgba(255, 255, 255, 0.75);

View File

@@ -169,6 +169,21 @@
<text class="arrow-text"></text>
</view>
</view>
<view class="list-item" @tap="handleIncreaseSubscriptionCount">
<view class="item-left">
<view class="item-icon-wrap icon--subscribe">
<text class="item-icon-text"></text>
</view>
<view class="item-text-group">
<text class="item-title">增加订阅次数</text>
<text class="item-desc">当前剩余 {{ user?.adminBookingSubscriptionCount ?? 0 }} </text>
</view>
</view>
<view class="item-arrow">
<text class="arrow-text">{{ adminSubscribeLoading ? '...' : '' }}</text>
</view>
</view>
</view>
<view style="height: 40rpx" />
@@ -177,17 +192,24 @@
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { storeToRefs } from 'pinia'
import CustomNavBar from '../../components/CustomNavBar.vue'
import { getSystemLayout } from '../../utils/system'
import { useAdminStore } from '../../stores/admin'
import { useUserStore } from '../../stores/user'
import type { AdminStats } from '../../stores/admin'
import { requestAdminBookingSubscriptionCount } from '../../utils/wechat-subscription'
import { getErrorMessage } from '../../utils/auth'
const navBarHeight = ref('64px')
const adminStore = useAdminStore()
const userStore = useUserStore()
const { user } = storeToRefs(userStore)
const statsLoading = ref(false)
const stats = ref<AdminStats>({ todayBookings: 0, totalOrders: 0, totalBookings: 0 })
const adminSubscribeLoading = ref(false)
function navigate(path: string) {
uni.navigateTo({ url: path })
@@ -204,9 +226,32 @@ async function loadStats() {
}
}
async function handleIncreaseSubscriptionCount() {
if (adminSubscribeLoading.value) {
return
}
adminSubscribeLoading.value = true
try {
const profile = await requestAdminBookingSubscriptionCount()
if (!profile) {
uni.showToast({ title: '已取消本次授权', icon: 'none' })
return
}
userStore.setProfile(profile)
uni.showToast({ title: `订阅次数 +1剩余 ${profile.adminBookingSubscriptionCount}`, icon: 'none' })
} catch (err: unknown) {
uni.showToast({ title: getErrorMessage(err, '订阅授权失败'), icon: 'none' })
} finally {
adminSubscribeLoading.value = false
}
}
onMounted(() => {
navBarHeight.value = `${getSystemLayout().navBarHeight}px`
loadStats()
userStore.fetchProfile()
})
</script>
@@ -347,6 +392,7 @@ onMounted(() => {
.icon--card { background: linear-gradient(135deg, #C48E7E, #B47E6E); }
.icon--flash-sale { background: linear-gradient(135deg, #D4A59A, #C08B7E); }
.icon--studio { background: linear-gradient(135deg, #9E9E7E, #8E8E6E); }
.icon--subscribe { background: linear-gradient(135deg, #5D8C8A, #476D72); }
.item-text-group {
display: flex;

View File

@@ -207,6 +207,11 @@
<text class="action-btn-text">立即预约</text>
</view>
</view>
<view v-else-if="slotData.isBookedByMe && slotData.myBookingId" class="action-bar">
<view class="action-btn action-btn--disabled" @tap="goToMyBookingDetail">
<text class="action-btn-text">{{ slotActionLabel }}</text>
</view>
</view>
<view v-else-if="slotData.status === TimeSlotStatus.FULL" class="action-bar">
<view class="action-btn action-btn--disabled">
<text class="action-btn-text">已约满</text>
@@ -293,6 +298,14 @@ const canBook = computed(() => {
return !isSlotPast(slotData.value.date, slotData.value.startTime)
})
const slotActionLabel = computed(() => {
if (slotData.value?.myBookingStatus === BookingStatus.PENDING_CONFIRMATION) {
return '已预约待确认'
}
return '已预约'
})
const slotCapacityClass = computed(() => {
if (!slotData.value) return ''
const { bookedCount, capacity } = slotData.value
@@ -346,6 +359,11 @@ async function loadSlotData() {
// ─── Slot mode: Booking flow ─────────────────────────────────────────────
async function handleSlotBook() {
if (slotData.value?.isBookedByMe) {
goToMyBookingDetail()
return
}
if (!userStore.loggedIn) {
uni.showModal({
title: '提示',
@@ -386,6 +404,11 @@ async function handleSlotBook() {
showConfirmPopup.value = true
}
function goToMyBookingDetail() {
if (!slotData.value?.myBookingId) return
uni.redirectTo({ url: `/pages/booking/detail?id=${slotData.value.myBookingId}` })
}
async function onConfirmBooking(payload: { timeSlotId: string; membershipId: string }) {
showConfirmPopup.value = false
uni.showLoading({ title: '预约中...' })

View File

@@ -84,7 +84,7 @@
import { ref, computed, onMounted } from 'vue'
import { onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'
import type { TimeSlotWithBookingStatus, MembershipWithCardType } from '@mp-pilates/shared'
import { TIME_PERIODS } from '@mp-pilates/shared'
import { BookingStatus, TIME_PERIODS } from '@mp-pilates/shared'
import { useBookingStore } from '../../stores/booking'
import { useUserStore } from '../../stores/user'
import { getErrorMessage } from '../../utils/auth'
@@ -196,6 +196,19 @@ function onSlotCardTap(slot: TimeSlotWithBookingStatus) {
// ─── Book flow ────────────────────────────────────────────
async function onBookTap(slot: TimeSlotWithBookingStatus) {
if (slot.isBookedByMe) {
if (slot.myBookingId) {
uni.navigateTo({ url: `/pages/booking/detail?id=${slot.myBookingId}` })
return
}
const title = slot.myBookingStatus === BookingStatus.PENDING_CONFIRMATION
? '该时段已预约,等待老师确认'
: '该时段已预约'
uni.showToast({ title, icon: 'none' })
return
}
// 1. Ensure logged in
if (!userStore.loggedIn) {
uni.showModal({

View File

@@ -123,6 +123,7 @@ async function refreshData() {
if (userStore.loggedIn) {
tasks.push(
userStore.fetchProfile(),
userStore.fetchMemberships(),
bookingStore.fetchUpcomingBookings(),
)

View File

@@ -8,8 +8,14 @@
:loading="loginLoading" :nav-bar-height="navBarHeight" @login="handleLogin" />
<!-- Menu section: always visible -->
<ProfileMenu :is-admin="isAdmin" :require-auth="loggedIn" @clear-cache="handleClearCache" @about="handleAbout"
@require-login="handleLogin" />
<ProfileMenu
:is-admin="isAdmin"
:require-auth="loggedIn"
:active-membership-count="activeMembershipCount"
@clear-cache="handleClearCache"
@about="handleAbout"
@require-login="handleLogin"
/>
<!-- Logout button: only when logged in -->
<view v-if="loggedIn" class="profile-page__logout-wrap">
@@ -19,7 +25,7 @@
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ref, computed, onMounted } from 'vue'
import { onShow, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'
import { storeToRefs } from 'pinia'
import { useUserStore } from '../../stores/user'
@@ -35,6 +41,10 @@ const { loggedIn, hasProfile, user, stats, memberships, isAdmin } = storeToRefs(
const loginLoading = ref(false)
const navBarHeight = ref(64)
const activeMembershipCount = computed(
() => user.value?.activeMembershipCount ?? userStore.activeMemberships.length,
)
// ─── 微信分享 ───────────────────────────────────────────────
onShareAppMessage(() => {
return {

View File

@@ -35,6 +35,7 @@ export const useUserStore = defineStore('user', () => {
const result = await wxLogin()
token.value = result.token
user.value = result.user
cacheSubscriptionMessageTemplateConfig(result.user.subscriptionMessageTemplates)
return { user: result.user, isNewUser: result.isNewUser }
} catch (err) {
console.error('Login failed:', err)
@@ -61,6 +62,7 @@ export const useUserStore = defineStore('user', () => {
try {
user.value = await get<UserProfileResponse>('/user/profile')
cacheSubscriptionMessageTemplateConfig(user.value.subscriptionMessageTemplates)
return user.value
} catch (err) {
console.error('Fetch profile failed:', err)
}
@@ -87,9 +89,15 @@ export const useUserStore = defineStore('user', () => {
async function updateProfile(data: { nickname?: string; avatarUrl?: string }) {
const updated = await put<UserProfileResponse>('/user/profile', data)
user.value = updated
cacheSubscriptionMessageTemplateConfig(updated.subscriptionMessageTemplates)
return updated
}
function setProfile(profile: UserProfileResponse) {
user.value = profile
cacheSubscriptionMessageTemplateConfig(profile.subscriptionMessageTemplates)
}
function checkAuth() {
if (isLoggedIn()) {
fetchProfile()
@@ -122,6 +130,7 @@ export const useUserStore = defineStore('user', () => {
fetchStats,
fetchMemberships,
updateProfile,
setProfile,
checkAuth,
logout,
}

View File

@@ -6,6 +6,7 @@ import type {
SubscriptionMessageRequestItem,
SubscriptionMessageTemplate,
SubscriptionMessageTemplateConfig,
UserProfileResponse,
} from '@mp-pilates/shared'
import { post } from './request'
@@ -30,16 +31,20 @@ function stringifyDebugPayload(payload: unknown): string {
function getSubscribeDebugContext() {
try {
const systemInfo = uni.getSystemInfoSync()
const host = systemInfo.host as { env?: string } | string | undefined
const windowInfo = typeof uni.getWindowInfo === 'function' ? uni.getWindowInfo() : null
const appBaseInfo = typeof uni.getAppBaseInfo === 'function' ? uni.getAppBaseInfo() : null
const deviceInfo = typeof uni.getDeviceInfo === 'function' ? uni.getDeviceInfo() : null
const host = appBaseInfo?.host as { env?: string } | string | undefined
return {
platform: systemInfo.platform,
platform: deviceInfo?.platform ?? 'unknown',
hostEnv: typeof host === 'object' && host ? host.env : undefined,
app: systemInfo.appName,
system: systemInfo.system,
language: systemInfo.language,
version: systemInfo.version,
SDKVersion: systemInfo.SDKVersion,
app: appBaseInfo?.appName,
system: deviceInfo?.system,
language: appBaseInfo?.language,
version: appBaseInfo?.version,
SDKVersion: appBaseInfo?.SDKVersion,
windowWidth: windowInfo?.windowWidth,
}
} catch {
return {
@@ -182,6 +187,61 @@ export async function requestBookingCreatedSubscriptionMessage(): Promise<Subscr
return requestSubscriptionMessage(SubscriptionMessageScene.BOOKING_CREATED)
}
export async function requestAdminBookingSubscriptionCount(): Promise<UserProfileResponse | null> {
if (!isMpWeixin()) {
return null
}
const config = await fetchTemplateConfig()
const templates = getTemplatesByScene(config, SubscriptionMessageScene.ADMIN_BOOKING_CREATED)
.filter((item) => item.usageTarget === 'counter')
if (templates.length === 0) {
console.error('[subscribe] no admin counter template configured', stringifyDebugPayload({
scene: SubscriptionMessageScene.ADMIN_BOOKING_CREATED,
config,
debugContext: getSubscribeDebugContext(),
}))
return null
}
const templateId = templates[0].templateId
const debugContext = getSubscribeDebugContext()
console.log('[subscribe] requestSubscribeMessage:adminCounter:start', stringifyDebugPayload({
templateId,
debugContext,
}))
const result = await new Promise<RequestSubscribeMessageSuccess>((resolve, reject) => {
uni.requestSubscribeMessage({
tmplIds: [templateId],
success: (res) => {
console.log('[subscribe] requestSubscribeMessage:adminCounter:success', stringifyDebugPayload({ response: res, templateId, debugContext }))
resolve(res as RequestSubscribeMessageSuccess)
},
fail: (err) => {
console.error('[subscribe] requestSubscribeMessage:adminCounter:fail', stringifyDebugPayload({ error: err, templateId, debugContext }))
reject(buildSubscribeError(err as RequestSubscribeMessageFail, SubscriptionMessageScene.ADMIN_BOOKING_CREATED, [templateId]))
},
})
})
const normalized = normalizeResult(result[templateId])
console.log('[subscribe] requestSubscribeMessage:adminCounter:normalized', stringifyDebugPayload({
templateId,
normalized,
rawResult: result,
debugContext,
}))
if (normalized !== 'accept') {
return null
}
return post<UserProfileResponse>('/user/subscription-messages/admin-booking-count')
}
export function resetSubscriptionMessageTemplateCache(): void {
cachedConfig = null
uni.removeStorageSync(TEMPLATE_CONFIG_STORAGE_KEY)

View File

@@ -66,15 +66,16 @@ enum FlashSaleOrderStatus {
// ===== Models =====
model User {
id String @id @default(uuid())
openid String @unique
unionid String?
phone String?
nickname String @default("")
avatarUrl String? @map("avatar_url")
role UserRole @default(MEMBER)
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
id String @id @default(uuid())
openid String @unique
unionid String?
phone String?
nickname String @default("")
avatarUrl String? @map("avatar_url")
role UserRole @default(MEMBER)
adminBookingSubscriptionCount Int @default(0) @map("admin_booking_subscription_count")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
memberships Membership[]
bookings Booking[]

View File

@@ -98,6 +98,7 @@ async function main() {
openid: 'admin_test_openid',
nickname: '教练',
role: UserRole.ADMIN,
adminBookingSubscriptionCount: 0,
},
})
console.log(' ✅ Admin user created')

View File

@@ -80,6 +80,7 @@ export class AuthService {
...(unionid !== undefined && { unionid }),
nickname: nickname || generateDefaultNickname(this.randomFn),
...(avatarUrl && { avatarUrl }),
adminBookingSubscriptionCount: 0,
},
}))

View File

@@ -5,7 +5,7 @@ import {
ForbiddenException,
NotFoundException,
} from '@nestjs/common'
import { BookingStatus, CardTypeCategory, MembershipStatus, TimeSlotStatus } from '@mp-pilates/shared'
import { BookingStatus, CardTypeCategory, MembershipStatus, TimeSlotStatus, UserRole } from '@mp-pilates/shared'
import { BookingService } from '../booking.service'
import { PrismaService } from '../../prisma/prisma.service'
import { MembershipService } from '../../membership/membership.service'
@@ -152,7 +152,7 @@ describe('BookingService', () => {
let service: BookingService
let prisma: jest.Mocked<PrismaService>
let studioService: jest.Mocked<StudioService>
let subscriptionMessageService: { sendBookingConfirmedMessage: jest.Mock }
let subscriptionMessageService: { sendBookingConfirmedMessage: jest.Mock; sendAdminBookingCreatedMessage: jest.Mock }
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
@@ -179,6 +179,7 @@ describe('BookingService', () => {
},
user: {
findUnique: jest.fn(),
findMany: jest.fn(),
},
},
},
@@ -200,6 +201,7 @@ describe('BookingService', () => {
provide: SubscriptionMessageService,
useValue: {
sendBookingConfirmedMessage: jest.fn(),
sendAdminBookingCreatedMessage: jest.fn(),
},
},
],
@@ -284,6 +286,7 @@ describe('BookingService', () => {
timeSlot: mockOpenSlot,
membership: mockActiveMembership,
})
;(prisma.user.findMany as jest.Mock).mockResolvedValue([])
const result = await service.createBooking(MOCK_USER_ID, dto)
@@ -323,6 +326,7 @@ describe('BookingService', () => {
timeSlot: nearFullSlot,
membership: mockActiveMembership,
})
;(prisma.user.findMany as jest.Mock).mockResolvedValue([])
await service.createBooking(MOCK_USER_ID, dto)
@@ -353,6 +357,7 @@ describe('BookingService', () => {
timeSlot: mockOpenSlot,
membership: mockDurationMembership,
})
;(prisma.user.findMany as jest.Mock).mockResolvedValue([])
await service.createBooking(MOCK_USER_ID, durationDto)
@@ -379,12 +384,61 @@ describe('BookingService', () => {
timeSlot: mockOpenSlot,
membership: mockMembershipNoTimes,
})
;(prisma.user.findMany as jest.Mock).mockResolvedValue([])
await service.createBooking(MOCK_USER_ID, dto)
expect(tx.membership.update).not.toHaveBeenCalled()
})
it('sends admin booking created subscription message to admins with remaining count', async () => {
const tx = buildTxMock()
tx.timeSlot.findUnique.mockResolvedValue(mockOpenSlot)
tx.booking.findFirst.mockResolvedValue(null)
tx.membership.findUnique.mockResolvedValue(mockActiveMembership)
tx.booking.create.mockResolvedValue({
...mockConfirmedBooking,
status: BookingStatus.PENDING_CONFIRMATION,
})
;(prisma.$transaction as jest.Mock).mockImplementation((fn) => fn(tx))
;(prisma.booking.findUnique as jest.Mock).mockResolvedValue({
...mockConfirmedBooking,
status: BookingStatus.PENDING_CONFIRMATION,
timeSlot: mockOpenSlot,
membership: mockActiveMembership,
})
;(prisma.user.findMany as jest.Mock).mockResolvedValue([
{ openid: 'admin-openid-1' },
])
;(prisma.user.findUnique as jest.Mock).mockResolvedValue({ nickname: 'Alice', phone: '13800000000' })
studioService.getInfo.mockResolvedValue({
...mockStudioConfig,
name: 'FocusCore Pilates',
})
subscriptionMessageService.sendAdminBookingCreatedMessage.mockResolvedValue(true)
await service.createBooking(MOCK_USER_ID, dto)
expect(prisma.user.findMany).toHaveBeenCalledWith({
where: {
role: UserRole.ADMIN,
adminBookingSubscriptionCount: { gt: 0 },
},
select: {
openid: true,
},
})
expect(subscriptionMessageService.sendAdminBookingCreatedMessage).toHaveBeenCalledWith({
openid: 'admin-openid-1',
bookingId: MOCK_BOOKING_ID,
bookingContent: 'Alice已预约',
bookingTime: '2099-12-31 09:00',
courseName: 'FocusCore Pilates',
bookingPeriod: '2099-12-31 09:00~10:00',
})
})
it('throws BadRequestException when slot is FULL', async () => {
const fullDto = { timeSlotId: mockFullSlot.id, membershipId: MOCK_MEMBERSHIP_ID }

View File

@@ -140,7 +140,9 @@ export class BookingService {
})
// Re-fetch with relations after transaction
return this.fetchBookingWithRelations(booking.id)
const bookingWithRelations = await this.fetchBookingWithRelations(booking.id)
await this.trySendAdminBookingCreatedSubscriptionMessages(bookingWithRelations)
return bookingWithRelations
}
// ─── Confirm Booking (Admin) ─────────────────────────────────────────────
@@ -600,4 +602,63 @@ export class BookingService {
console.error('Send booking confirmed subscription message failed:', error)
}
}
private async trySendAdminBookingCreatedSubscriptionMessages(
booking: BookingWithRelations,
): Promise<void> {
try {
const admins = await this.prisma.user.findMany({
where: {
role: 'ADMIN',
adminBookingSubscriptionCount: { gt: 0 },
},
select: {
openid: true,
},
})
if (admins.length === 0) {
return
}
const student = await this.prisma.user.findUnique({
where: { id: booking.userId },
select: { nickname: true, phone: true },
})
const studio = await this.studioService.getInfo()
const bookingDate = booking.timeSlot.date
const dateLabel = `${bookingDate.getFullYear()}-${String(bookingDate.getMonth() + 1).padStart(2, '0')}-${String(bookingDate.getDate()).padStart(2, '0')}`
const periodLabel = `${booking.timeSlot.startTime.slice(0, 5)}~${booking.timeSlot.endTime.slice(0, 5)}`
const studentLabel = this.buildAdminBookingStudentLabel(student)
await Promise.allSettled(
admins
.filter((admin) => admin.openid)
.map((admin) => this.subscriptionMessageService.sendAdminBookingCreatedMessage({
openid: admin.openid,
bookingId: booking.id,
bookingContent: `${studentLabel}已预约`.slice(0, 20),
bookingTime: `${dateLabel} ${booking.timeSlot.startTime.slice(0, 5)}`,
courseName: studio.name || '普拉提课程',
bookingPeriod: `${dateLabel} ${periodLabel}`,
})),
)
} catch (error) {
console.error('Send admin booking created subscription message failed:', error)
}
}
private buildAdminBookingStudentLabel(student: { nickname: string; phone: string | null } | null): string {
const nickname = (student?.nickname || '').trim()
if (nickname) {
return nickname.slice(0, 8)
}
const phone = student?.phone || ''
if (phone.length >= 4) {
return `尾号${phone.slice(-4)}`
}
return '学员'
}
}

View File

@@ -84,14 +84,26 @@ describe('TimeSlotService', () => {
expect(result[0].myBookingId).toBeNull()
})
it('marks isBookedByMe=true and sets myBookingId when user has a CONFIRMED booking', async () => {
const slot = makeSlot({ bookings: [{ id: 'booking-42' }] })
it('marks isBookedByMe=true and sets my booking info when user has a CONFIRMED booking', async () => {
const slot = makeSlot({ bookings: [{ id: 'booking-42', status: BookingStatus.CONFIRMED }] })
mockPrisma.timeSlot.findMany.mockResolvedValueOnce([slot])
const result = await service.getAvailableSlots('2026-04-07', 'user-1')
expect(result[0].isBookedByMe).toBe(true)
expect(result[0].myBookingId).toBe('booking-42')
expect(result[0].myBookingStatus).toBe(BookingStatus.CONFIRMED)
})
it('marks pending confirmation booking as already booked by current user', async () => {
const slot = makeSlot({ bookings: [{ id: 'booking-99', status: BookingStatus.PENDING_CONFIRMATION }] })
mockPrisma.timeSlot.findMany.mockResolvedValueOnce([slot])
const result = await service.getAvailableSlots('2026-04-07', 'user-1')
expect(result[0].isBookedByMe).toBe(true)
expect(result[0].myBookingId).toBe('booking-99')
expect(result[0].myBookingStatus).toBe(BookingStatus.PENDING_CONFIRMATION)
})
it('excludes CLOSED slots from query', async () => {
@@ -134,11 +146,12 @@ describe('TimeSlotService', () => {
expect(result[0].isBookedByMe).toBe(false)
expect(result[0].myBookingId).toBeNull()
expect(result[0].myBookingStatus).toBeNull()
})
it('maps multiple slots correctly', async () => {
const slots = [
makeSlot({ id: 'slot-1', startTime: '09:00', bookings: [{ id: 'bk-1' }] }),
makeSlot({ id: 'slot-1', startTime: '09:00', bookings: [{ id: 'bk-1', status: BookingStatus.CONFIRMED }] }),
makeSlot({ id: 'slot-2', startTime: '10:00', bookings: [] }),
]
mockPrisma.timeSlot.findMany.mockResolvedValueOnce(slots)
@@ -148,8 +161,10 @@ describe('TimeSlotService', () => {
expect(result).toHaveLength(2)
expect(result[0].isBookedByMe).toBe(true)
expect(result[0].myBookingId).toBe('bk-1')
expect(result[0].myBookingStatus).toBe(BookingStatus.CONFIRMED)
expect(result[1].isBookedByMe).toBe(false)
expect(result[1].myBookingId).toBeNull()
expect(result[1].myBookingStatus).toBeNull()
})
})
@@ -164,7 +179,20 @@ describe('TimeSlotService', () => {
const result = await service.getSlotById('slot-1')
expect(result).toEqual(slot)
expect(result).toMatchObject({
id: slot.id,
date: '2026-04-07',
startTime: slot.startTime,
endTime: slot.endTime,
capacity: slot.capacity,
bookedCount: slot.bookedCount,
status: slot.status,
source: slot.source,
templateId: slot.templateId,
isBookedByMe: false,
myBookingId: null,
myBookingStatus: null,
})
expect(mockPrisma.timeSlot.findUnique).toHaveBeenCalledWith(
expect.objectContaining({ where: { id: 'slot-1' } }),
)

View File

@@ -32,7 +32,7 @@ export class TimeSlotService {
createdAt: Date
updatedAt: Date
},
myBooking: { id: string } | null,
myBooking: { id: string; status: string } | null,
): TimeSlotWithBookingStatus {
return {
id: slot.id,
@@ -48,6 +48,7 @@ export class TimeSlotService {
updatedAt: slot.updatedAt.toISOString(),
isBookedByMe: myBooking !== null,
myBookingId: myBooking?.id ?? null,
myBookingStatus: (myBooking?.status as BookingStatus | undefined) ?? null,
}
}
@@ -71,9 +72,9 @@ export class TimeSlotService {
? {
where: {
userId,
status: BookingStatus.CONFIRMED,
status: { in: [BookingStatus.PENDING_CONFIRMATION, BookingStatus.CONFIRMED] },
},
select: { id: true },
select: { id: true, status: true },
}
: false,
},
@@ -97,9 +98,9 @@ export class TimeSlotService {
? {
where: {
userId,
status: BookingStatus.CONFIRMED,
status: { in: [BookingStatus.PENDING_CONFIRMATION, BookingStatus.CONFIRMED] },
},
select: { id: true },
select: { id: true, status: true },
}
: false,
},

View File

@@ -22,6 +22,7 @@ const makeUser = (overrides: Record<string, unknown> = {}) => ({
nickname: 'Alice',
avatarUrl: 'https://example.com/avatar.png',
role: UserRole.MEMBER,
adminBookingSubscriptionCount: 0,
createdAt: new Date('2024-01-01T00:00:00Z'),
updatedAt: new Date('2024-01-01T00:00:00Z'),
_count: { memberships: 2 },
@@ -119,12 +120,20 @@ describe('UserService', () => {
avatarUrl: 'https://example.com/avatar.png',
role: UserRole.MEMBER,
activeMembershipCount: 3,
adminBookingSubscriptionCount: 0,
subscriptionMessageTemplates: {
templates: [
{
templateId: 'tmpl-booking-confirmed',
scene: SubscriptionMessageScene.BOOKING_CREATED,
description: '购卡或预约时请求一次订阅,用于后续预约确认通知推送',
usageTarget: 'consent',
},
{
templateId: 'tmpl-booking-confirmed',
scene: SubscriptionMessageScene.ADMIN_BOOKING_CREATED,
description: '管理员主动增加预约提醒次数,用于接收学员新预约通知',
usageTarget: 'counter',
},
],
},
@@ -255,7 +264,38 @@ describe('UserService', () => {
expect(result.nickname).toBe('Bob')
expect(result.avatarUrl).toBe('https://example.com/new.png')
expect(result.activeMembershipCount).toBe(1)
expect(result.subscriptionMessageTemplates.templates).toHaveLength(1)
expect(result.adminBookingSubscriptionCount).toBe(0)
expect(result.subscriptionMessageTemplates.templates).toHaveLength(2)
})
it('increments admin booking subscription count for admin users', async () => {
mockPrisma.user.findUnique.mockResolvedValue(makeUser({
role: UserRole.ADMIN,
adminBookingSubscriptionCount: 2,
}))
mockPrisma.user.update.mockResolvedValue(makeUser({
role: UserRole.ADMIN,
adminBookingSubscriptionCount: 3,
}))
const result = await service.grantAdminBookingSubscriptionCount('user-1')
expect(mockPrisma.user.update).toHaveBeenCalledWith({
where: { id: 'user-1' },
data: {
adminBookingSubscriptionCount: {
increment: 1,
},
},
include: {
_count: {
select: {
memberships: { where: { status: MembershipStatus.ACTIVE } },
},
},
},
})
expect(result.adminBookingSubscriptionCount).toBe(3)
})
it('only includes provided fields in the update payload', async () => {

View File

@@ -4,6 +4,7 @@ import {
Logger,
} from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import { SubscriptionMessageScene } from '@mp-pilates/shared'
import { PrismaService } from '../prisma/prisma.service'
interface BookingConfirmedTemplatePayload {
@@ -15,6 +16,15 @@ interface BookingConfirmedTemplatePayload {
readonly bookingPeriod: string
}
interface AdminBookingCreatedTemplatePayload {
readonly openid: string
readonly bookingId: string
readonly bookingContent: string
readonly bookingTime: string
readonly courseName: string
readonly bookingPeriod: string
}
interface WechatAccessTokenResponse {
access_token?: string
expires_in?: number
@@ -50,6 +60,60 @@ export class SubscriptionMessageService {
}
async sendBookingConfirmedMessage(payload: BookingConfirmedTemplatePayload): Promise<boolean> {
return this.sendConsentBasedBookingMessage(payload)
}
async sendAdminBookingCreatedMessage(payload: AdminBookingCreatedTemplatePayload): Promise<boolean> {
const templateId = this.getBookingConfirmedTemplateId()
if (!templateId) {
this.logger.warn('WX_SUBSCRIBE_TEMPLATE_BOOKING_CONFIRMED is not configured, skip sending admin subscription message')
return false
}
const adminUser = await this.prisma.user.findUnique({
where: { openid: payload.openid },
select: { id: true, adminBookingSubscriptionCount: true },
})
if (!adminUser) {
this.logger.warn(`Admin user not found for subscription send: ${stringifyDebugPayload({ openid: payload.openid, bookingId: payload.bookingId, templateId })}`)
return false
}
if (adminUser.adminBookingSubscriptionCount <= 0) {
this.logger.warn(`Admin subscription quota exhausted: ${stringifyDebugPayload({ userId: adminUser.id, bookingId: payload.bookingId, remainingCount: adminUser.adminBookingSubscriptionCount, templateId })}`)
return false
}
const sent = await this.sendWechatSubscribeMessage({
openid: payload.openid,
bookingId: payload.bookingId,
templateId,
payload,
logContext: {
target: 'admin',
userId: adminUser.id,
scene: SubscriptionMessageScene.ADMIN_BOOKING_CREATED,
},
})
if (!sent) {
return false
}
await this.prisma.user.update({
where: { id: adminUser.id },
data: {
adminBookingSubscriptionCount: {
decrement: 1,
},
},
})
return true
}
private async sendConsentBasedBookingMessage(payload: BookingConfirmedTemplatePayload): Promise<boolean> {
const templateId = this.getBookingConfirmedTemplateId()
if (!templateId) {
this.logger.warn('WX_SUBSCRIBE_TEMPLATE_BOOKING_CONFIRMED is not configured, skip sending subscription message')
@@ -60,7 +124,7 @@ export class SubscriptionMessageService {
where: {
user: { openid: payload.openid },
templateId,
scene: 'BOOKING_CREATED',
scene: SubscriptionMessageScene.BOOKING_CREATED,
acceptCount: { gt: 0 },
totalRequestCount: { gt: 0 },
},
@@ -71,7 +135,7 @@ export class SubscriptionMessageService {
})
if (!consent) {
this.logger.warn(`No subscription quota found: ${stringifyDebugPayload({ openid: payload.openid, bookingId: payload.bookingId, templateId, scene: 'BOOKING_CREATED' })}`)
this.logger.warn(`No subscription quota found: ${stringifyDebugPayload({ openid: payload.openid, bookingId: payload.bookingId, templateId, scene: SubscriptionMessageScene.BOOKING_CREATED })}`)
return false
}
@@ -80,21 +144,55 @@ export class SubscriptionMessageService {
return false
}
const sent = await this.sendWechatSubscribeMessage({
openid: payload.openid,
bookingId: payload.bookingId,
templateId,
payload,
logContext: {
target: 'member',
consentId: consent.id,
scene: SubscriptionMessageScene.BOOKING_CREATED,
},
})
if (!sent) {
return false
}
await this.prisma.subscriptionMessageConsent.update({
where: { id: consent.id },
data: {
sentCount: { increment: 1 },
lastSentAt: new Date(),
},
})
return true
}
private async sendWechatSubscribeMessage(params: {
openid: string
bookingId: string
templateId: string
payload: BookingConfirmedTemplatePayload | AdminBookingCreatedTemplatePayload
logContext: Record<string, unknown>
}): Promise<boolean> {
const accessToken = await this.getAccessToken()
const page = `/pages/booking/detail?id=${payload.bookingId}`
const page = `/pages/booking/detail?id=${params.bookingId}`
const requestBody = {
touser: payload.openid,
template_id: templateId,
touser: params.openid,
template_id: params.templateId,
page,
data: {
thing1: { value: payload.bookingContent.slice(0, 20) },
time2: { value: payload.bookingTime.slice(0, 20) },
thing25: { value: payload.courseName.slice(0, 20) },
time35: { value: payload.bookingPeriod.slice(0, 20) },
thing1: { value: params.payload.bookingContent.slice(0, 20) },
time2: { value: params.payload.bookingTime.slice(0, 20) },
thing25: { value: params.payload.courseName.slice(0, 20) },
time35: { value: params.payload.bookingPeriod.slice(0, 20) },
},
}
this.logger.log(`WeChat subscribe send request: ${stringifyDebugPayload({ bookingId: payload.bookingId, templateId, requestBody, consentId: consent.id })}`)
this.logger.log(`WeChat subscribe send request: ${stringifyDebugPayload({ bookingId: params.bookingId, templateId: params.templateId, requestBody, ...params.logContext })}`)
const response = await fetch(
`https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=${accessToken}`,
@@ -109,26 +207,17 @@ export class SubscriptionMessageService {
if (!response.ok) {
const responseText = await response.text()
this.logger.error(`WeChat subscribe send http error: ${stringifyDebugPayload({ status: response.status, statusText: response.statusText, body: responseText, bookingId: payload.bookingId, templateId, requestBody })}`)
this.logger.error(`WeChat subscribe send http error: ${stringifyDebugPayload({ status: response.status, statusText: response.statusText, body: responseText, bookingId: params.bookingId, templateId: params.templateId, requestBody, ...params.logContext })}`)
throw new InternalServerErrorException('调用微信订阅消息接口失败')
}
const result = (await response.json()) as WechatSubscribeSendResponse
if (result.errcode && result.errcode !== 0) {
this.logger.warn(`WeChat subscribe send failed: ${stringifyDebugPayload({ bookingId: payload.bookingId, templateId, requestBody, response: result, consentId: consent.id })}`)
this.logger.warn(`WeChat subscribe send failed: ${stringifyDebugPayload({ bookingId: params.bookingId, templateId: params.templateId, requestBody, response: result, ...params.logContext })}`)
return false
}
this.logger.log(`WeChat subscribe send success: ${stringifyDebugPayload({ bookingId: payload.bookingId, templateId, response: result, consentId: consent.id })}`)
await this.prisma.subscriptionMessageConsent.update({
where: { id: consent.id },
data: {
sentCount: { increment: 1 },
lastSentAt: new Date(),
},
})
this.logger.log(`WeChat subscribe send success: ${stringifyDebugPayload({ bookingId: params.bookingId, templateId: params.templateId, response: result, ...params.logContext })}`)
return true
}

View File

@@ -57,6 +57,11 @@ export class UserController {
return this.userService.reportSubscriptionMessageRequests(userId, dto.requests)
}
@Post('user/subscription-messages/admin-booking-count')
increaseAdminBookingSubscriptionCount(@CurrentUser('sub') userId: string) {
return this.userService.grantAdminBookingSubscriptionCount(userId)
}
// ─── Admin: Member Management ─────────────────────────────────────────────
@Get('admin/members')

View File

@@ -13,6 +13,7 @@ import type {
SubscriptionMessageConsentSummary,
SubscriptionMessageRequestItem,
SubscriptionMessageRequestResult,
SubscriptionMessageTemplate,
SubscriptionMessageTemplateConfig,
} from '@mp-pilates/shared'
import { ConfigService } from '@nestjs/config'
@@ -20,6 +21,7 @@ import { PrismaService } from '../prisma/prisma.service'
import { UpdateUserMembershipDto } from './dto/update-user-membership.dto'
const VALID_CARD_TYPES = new Set<string>(Object.values(CardTypeCategory))
const ADMIN_BOOKING_SUBSCRIPTION_INCREMENT = 1
type SubscriptionMessageConsentDelegate = PrismaService['subscriptionMessageConsent']
type SubscriptionMessageConsentRecord = Awaited<ReturnType<SubscriptionMessageConsentDelegate['findMany']>>[number]
@@ -32,14 +34,46 @@ export class UserService {
) {}
private buildSubscriptionTemplateConfig(): SubscriptionMessageTemplateConfig {
const templates = [
{
templateId: this.configService.get<string>('WX_SUBSCRIBE_TEMPLATE_BOOKING_CONFIRMED', ''),
scene: SubscriptionMessageScene.BOOKING_CREATED,
description: '购卡或预约时请求一次订阅,用于后续预约确认通知推送',
usageTarget: 'consent' as const,
},
{
templateId: this.configService.get<string>('WX_SUBSCRIBE_TEMPLATE_BOOKING_CONFIRMED', ''),
scene: SubscriptionMessageScene.ADMIN_BOOKING_CREATED,
description: '管理员主动增加预约提醒次数,用于接收学员新预约通知',
usageTarget: 'counter' as const,
},
] satisfies SubscriptionMessageTemplate[]
return {
templates: [
{
templateId: this.configService.get<string>('WX_SUBSCRIBE_TEMPLATE_BOOKING_CONFIRMED', ''),
scene: SubscriptionMessageScene.BOOKING_CREATED,
description: '购卡或预约时请求一次订阅,用于后续预约确认通知推送',
},
].filter((item) => item.templateId),
templates: templates.filter((item) => item.templateId),
}
}
private mapProfile(user: {
id: string
phone: string | null
nickname: string
avatarUrl: string | null
role: string
adminBookingSubscriptionCount: number
createdAt: Date
_count: { memberships: number }
}): UserProfileResponse {
return {
id: user.id,
phone: user.phone,
nickname: user.nickname,
avatarUrl: user.avatarUrl,
role: user.role as UserRole,
activeMembershipCount: user._count.memberships,
adminBookingSubscriptionCount: user.adminBookingSubscriptionCount,
subscriptionMessageTemplates: this.buildSubscriptionTemplateConfig(),
createdAt: user.createdAt.toISOString(),
}
}
@@ -61,16 +95,7 @@ export class UserService {
throw new NotFoundException('User not found')
}
return {
id: user.id,
phone: user.phone,
nickname: user.nickname,
avatarUrl: user.avatarUrl,
role: user.role as UserRole,
activeMembershipCount: user._count.memberships,
subscriptionMessageTemplates: this.buildSubscriptionTemplateConfig(),
createdAt: user.createdAt.toISOString(),
}
return this.mapProfile(user)
}
async updateProfile(
@@ -94,16 +119,7 @@ export class UserService {
},
})
return {
id: updated.id,
phone: updated.phone,
nickname: updated.nickname,
avatarUrl: updated.avatarUrl,
role: updated.role as UserRole,
activeMembershipCount: updated._count.memberships,
subscriptionMessageTemplates: this.buildSubscriptionTemplateConfig(),
createdAt: updated.createdAt.toISOString(),
}
return this.mapProfile(updated)
}
getSubscriptionMessageTemplates(): SubscriptionMessageTemplateConfig {
@@ -181,6 +197,49 @@ export class UserService {
}))
}
async grantAdminBookingSubscriptionCount(userId: string): Promise<UserProfileResponse> {
const user = await this.prisma.user.findUnique({
where: { id: userId },
include: {
_count: {
select: {
memberships: {
where: { status: MembershipStatus.ACTIVE },
},
},
},
},
})
if (!user) {
throw new NotFoundException('User not found')
}
if (user.role !== UserRole.ADMIN) {
return this.mapProfile(user)
}
const updated = await this.prisma.user.update({
where: { id: userId },
data: {
adminBookingSubscriptionCount: {
increment: ADMIN_BOOKING_SUBSCRIPTION_INCREMENT,
},
},
include: {
_count: {
select: {
memberships: {
where: { status: MembershipStatus.ACTIVE },
},
},
},
},
})
return this.mapProfile(updated)
}
async getStats(userId: string): Promise<UserStatsResponse> {
const completedBookings = await this.prisma.booking.findMany({
where: {

View File

@@ -63,4 +63,5 @@ export enum FlashSaleOrderStatus {
export enum SubscriptionMessageScene {
ORDER_PAID = 'ORDER_PAID',
BOOKING_CREATED = 'BOOKING_CREATED',
ADMIN_BOOKING_CREATED = 'ADMIN_BOOKING_CREATED',
}

View File

@@ -13,6 +13,7 @@ export interface SubscriptionMessageTemplate {
readonly templateId: string
readonly scene: SubscriptionMessageScene
readonly description: string
readonly usageTarget?: 'consent' | 'counter'
}
export interface SubscriptionMessageTemplateConfig {

View File

@@ -1,4 +1,4 @@
import { TimeSlotStatus, TimeSlotSource } from '../enums'
import { BookingStatus, TimeSlotStatus, TimeSlotSource } from '../enums'
export interface TimeSlot {
readonly id: string
@@ -19,6 +19,8 @@ export interface TimeSlotWithBookingStatus extends TimeSlot {
readonly isBookedByMe: boolean
/** 当前用户在此时段的预约 ID用于取消 */
readonly myBookingId: string | null
/** 当前用户在此时段的预约状态,仅在 isBookedByMe=true 时有值 */
readonly myBookingStatus: BookingStatus | null
}
export interface CreateManualSlotDto {

View File

@@ -20,6 +20,7 @@ export interface UserProfileResponse {
readonly avatarUrl: string | null
readonly role: UserRole
readonly activeMembershipCount: number
readonly adminBookingSubscriptionCount: number
readonly subscriptionMessageTemplates: SubscriptionMessageTemplateConfig
readonly createdAt: string
}