feat: 即時預約聊天室(realtime booking chat)
## 新增功能 - 會員與教練在 confirmed 預約期間可互傳文字與圖片訊息 - Presence Channel 顯示對方在線狀態(即時加入/離線) - 已讀回執:對方讀取訊息後即時更新 - 預約完成(completed)後訊息封存唯讀 - 圖片上傳使用 intervention/image 處理(移除 EXIF、限制尺寸、強制重新編碼) ## 通知系統 - 收到新訊息時 Bell Icon 即時更新(NotificationCreated via private channel) - 預約列表卡片顯示未讀角標(GET /api/bookings/messages/unread-counts 批次查詢) - 瀏覽器分頁在背景時推送 Web Notification ## 基礎建設 - 引入 Laravel Reverb 作為自架 WebSocket 伺服器 - docker-compose 新增 reverb service(連接 proxy_net,供 NPM 代理) - 前端安裝 laravel-echo + pusher-js,初始化 Echo plugin - Dockerfile 補 GD JPEG/WebP/FreeType 支援 ## 清理 - 移除 test_broadcast.php 與 resources/js/echo.js(Blade 殘留) - 移除 /ping、/testpost 測試路由 - channels.php 改用 class-based 授權語法,移除 debug log - BookingChat.vue otherType 提取為 computed 消除重複 - docker-entrypoint.sh 健康檢查改用 env var 取代硬編碼密碼 Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,274 @@
|
||||
<script setup>
|
||||
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
|
||||
import api from '../api/axios'
|
||||
import coachApi from '../api/coachAxios'
|
||||
import echo from '../plugins/echo'
|
||||
import { useNotificationStore } from '../stores/notifications'
|
||||
|
||||
const props = defineProps({
|
||||
bookingId: { type: Number, required: true },
|
||||
bookingStatus: { type: String, required: true },
|
||||
currentUserType: { type: String, required: true }, // 'member' | 'provider'
|
||||
})
|
||||
|
||||
const emit = defineEmits(['read'])
|
||||
|
||||
const messages = ref([])
|
||||
const messageListRef = ref(null)
|
||||
const textInput = ref('')
|
||||
const isSending = ref(false)
|
||||
const otherUserOnline = ref(false)
|
||||
const channel = ref(null)
|
||||
|
||||
const notificationStore = useNotificationStore()
|
||||
|
||||
const isConfirmed = computed(() => props.bookingStatus === 'confirmed')
|
||||
const isCompleted = computed(() => props.bookingStatus === 'completed')
|
||||
const canSend = computed(() => isConfirmed.value && !isSending.value && textInput.value.trim())
|
||||
const otherType = computed(() => props.currentUserType === 'member' ? 'provider' : 'member')
|
||||
|
||||
const axiosInstance = computed(() => props.currentUserType === 'provider' ? coachApi : api)
|
||||
|
||||
// 請求瀏覽器通知權限(只問一次)
|
||||
async function requestBrowserNotificationPermission() {
|
||||
if ('Notification' in window && Notification.permission === 'default') {
|
||||
await Notification.requestPermission()
|
||||
}
|
||||
}
|
||||
|
||||
// 使用者不在頁面時才推瀏覽器通知
|
||||
function showBrowserNotification(msg) {
|
||||
if (!('Notification' in window) || Notification.permission !== 'granted') return
|
||||
if (!document.hidden) return // 使用者正在看這個 tab,不需要
|
||||
|
||||
const body = msg.type === 'image' ? '傳送了一張圖片' : msg.content
|
||||
new Notification('新訊息', {
|
||||
body,
|
||||
icon: '/favicon.ico',
|
||||
tag: `booking-chat-${props.bookingId}`, // 同一個預約只顯示一則,不疊加
|
||||
})
|
||||
}
|
||||
|
||||
function scrollToBottom() {
|
||||
nextTick(() => {
|
||||
if (messageListRef.value) {
|
||||
messageListRef.value.scrollTop = messageListRef.value.scrollHeight
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async function loadHistory() {
|
||||
try {
|
||||
const res = await axiosInstance.value.get(`/bookings/${props.bookingId}/messages`)
|
||||
messages.value = res.data.data
|
||||
scrollToBottom()
|
||||
await markLastRead()
|
||||
// 使用者打開聊天室後已讀,立刻刷新 bell badge
|
||||
notificationStore.fetchUnreadCount()
|
||||
} catch (e) {
|
||||
// 403 means no access, silently ignore
|
||||
}
|
||||
}
|
||||
|
||||
async function markLastRead() {
|
||||
if (!messages.value.length) return
|
||||
const lastId = messages.value[messages.value.length - 1].id
|
||||
try {
|
||||
await axiosInstance.value.post(`/bookings/${props.bookingId}/messages/read`, {
|
||||
last_read_message_id: lastId,
|
||||
})
|
||||
messages.value.forEach(m => {
|
||||
if (m.sender_type !== props.currentUserType && !m.read_at) {
|
||||
m.read_at = new Date().toISOString()
|
||||
}
|
||||
})
|
||||
emit('read') // 通知父層清除未讀角標
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
async function sendText() {
|
||||
if (!canSend.value) return
|
||||
const content = textInput.value.trim()
|
||||
textInput.value = ''
|
||||
isSending.value = true
|
||||
try {
|
||||
await axiosInstance.value.post(`/bookings/${props.bookingId}/messages`, {
|
||||
type: 'text',
|
||||
content,
|
||||
})
|
||||
} catch (e) {
|
||||
textInput.value = content
|
||||
} finally {
|
||||
isSending.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function sendImage(event) {
|
||||
if (!isConfirmed.value) return
|
||||
const file = event.target.files[0]
|
||||
if (!file) return
|
||||
event.target.value = ''
|
||||
|
||||
const formData = new FormData()
|
||||
formData.append('type', 'image')
|
||||
formData.append('file', file)
|
||||
|
||||
isSending.value = true
|
||||
try {
|
||||
await axiosInstance.value.post(`/bookings/${props.bookingId}/messages`, formData, {
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
})
|
||||
} catch (e) {
|
||||
console.error('圖片上傳失敗', e)
|
||||
} finally {
|
||||
isSending.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function subscribeChannel() {
|
||||
channel.value = echo.join(`booking.${props.bookingId}`)
|
||||
.here(users => {
|
||||
otherUserOnline.value = users.some(u => u.user_type === otherType.value)
|
||||
// Reverb 不會發 member_added,主動 whisper 告知對方自己已上線
|
||||
channel.value?.whisper('presence', { user_type: props.currentUserType, online: true })
|
||||
})
|
||||
.joining(user => {
|
||||
if (user.user_type === otherType.value) otherUserOnline.value = true
|
||||
})
|
||||
.leaving(user => {
|
||||
if (user.user_type === otherType.value) otherUserOnline.value = false
|
||||
})
|
||||
.listenForWhisper('presence', (e) => {
|
||||
if (e.user_type === otherType.value) otherUserOnline.value = e.online
|
||||
})
|
||||
.listen('.MessageSent', async (e) => {
|
||||
messages.value.push({
|
||||
id: e.id,
|
||||
sender_id: e.sender_id,
|
||||
sender_type: e.sender_type,
|
||||
type: e.type,
|
||||
content: e.content,
|
||||
read_at: null,
|
||||
created_at: e.created_at,
|
||||
})
|
||||
scrollToBottom()
|
||||
if (e.sender_type !== props.currentUserType) {
|
||||
// 對方傳來的訊息:推瀏覽器通知、刷新 bell badge
|
||||
showBrowserNotification(e)
|
||||
notificationStore.fetchUnreadCount()
|
||||
await markLastRead()
|
||||
}
|
||||
})
|
||||
.listen('.MessageRead', (e) => {
|
||||
if (e.reader_type !== props.currentUserType) {
|
||||
messages.value.forEach(m => {
|
||||
if (m.sender_type === props.currentUserType && m.id <= e.last_read_message_id) {
|
||||
m.read_at = m.read_at || new Date().toISOString()
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await requestBrowserNotificationPermission()
|
||||
await loadHistory()
|
||||
if (isConfirmed.value) {
|
||||
subscribeChannel()
|
||||
}
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
if (channel.value) {
|
||||
channel.value.whisper('presence', { user_type: props.currentUserType, online: false })
|
||||
echo.leave(`booking.${props.bookingId}`)
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="isConfirmed || isCompleted" class="flex flex-col h-full border rounded-lg overflow-hidden">
|
||||
<!-- 頂部狀態列 -->
|
||||
<div class="flex items-center justify-between px-4 py-2 bg-gray-50 border-b text-sm">
|
||||
<span class="font-medium text-gray-700">訊息</span>
|
||||
<div v-if="isConfirmed" class="flex items-center gap-1.5">
|
||||
<span
|
||||
:class="otherUserOnline ? 'bg-green-400' : 'bg-gray-300'"
|
||||
class="w-2 h-2 rounded-full"
|
||||
/>
|
||||
<span class="text-gray-500">{{ otherUserOnline ? '對方在線' : '對方離線' }}</span>
|
||||
</div>
|
||||
<span v-else class="text-gray-400">對話已封存</span>
|
||||
</div>
|
||||
|
||||
<!-- 訊息列表 -->
|
||||
<div ref="messageListRef" class="flex-1 overflow-y-auto p-4 space-y-3 bg-white" style="max-height: 400px">
|
||||
<div v-if="messages.length === 0" class="text-center text-gray-400 text-sm py-8">
|
||||
尚無訊息
|
||||
</div>
|
||||
<div
|
||||
v-for="msg in messages"
|
||||
:key="msg.id"
|
||||
:class="msg.sender_type === currentUserType ? 'items-end' : 'items-start'"
|
||||
class="flex flex-col"
|
||||
>
|
||||
<div
|
||||
:class="msg.sender_type === currentUserType
|
||||
? 'bg-blue-500 text-white rounded-br-none'
|
||||
: 'bg-gray-100 text-gray-800 rounded-bl-none'"
|
||||
class="max-w-[75%] px-3 py-2 rounded-2xl text-sm"
|
||||
>
|
||||
<img
|
||||
v-if="msg.type === 'image'"
|
||||
:src="msg.content"
|
||||
alt="圖片訊息"
|
||||
class="max-w-full rounded-lg"
|
||||
style="max-height: 200px; object-fit: contain"
|
||||
/>
|
||||
<span v-else>{{ msg.content }}</span>
|
||||
</div>
|
||||
<div class="flex items-center gap-1 mt-0.5 text-[10px] text-gray-400">
|
||||
<span>{{ new Date(msg.created_at).toLocaleTimeString('zh-TW', { hour: '2-digit', minute: '2-digit' }) }}</span>
|
||||
<span v-if="msg.sender_type === currentUserType">
|
||||
{{ msg.read_at ? '已讀' : '未讀' }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 輸入區(僅 confirmed) -->
|
||||
<div v-if="isConfirmed" class="border-t bg-white p-3">
|
||||
<div class="flex items-end gap-2">
|
||||
<label class="flex-shrink-0 cursor-pointer text-gray-400 hover:text-blue-500 transition">
|
||||
<svg class="w-5 h-5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round"
|
||||
d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"/>
|
||||
</svg>
|
||||
<input type="file" accept="image/*" class="hidden" @change="sendImage" :disabled="isSending" />
|
||||
</label>
|
||||
<textarea
|
||||
v-model="textInput"
|
||||
rows="1"
|
||||
placeholder="輸入訊息..."
|
||||
class="flex-1 resize-none rounded-lg border border-gray-200 px-3 py-2 text-sm focus:outline-none focus:border-blue-400"
|
||||
style="max-height: 80px"
|
||||
@keydown.enter.exact.prevent="sendText"
|
||||
/>
|
||||
<button
|
||||
@click="sendText"
|
||||
:disabled="!canSend"
|
||||
class="flex-shrink-0 w-8 h-8 flex items-center justify-center rounded-full bg-blue-500 text-white disabled:opacity-40 transition hover:bg-blue-600"
|
||||
>
|
||||
<svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path d="M10.894 2.553a1 1 0 00-1.788 0l-7 14a1 1 0 001.169 1.409l5-1.429A1 1 0 009 15.571V11a1 1 0 112 0v4.571a1 1 0 00.725.962l5 1.428a1 1 0 001.17-1.408l-7-14z"/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 封存提示(completed) -->
|
||||
<div v-if="isCompleted" class="border-t bg-gray-50 px-4 py-3 text-center text-sm text-gray-400">
|
||||
課程已結束,對話已封存
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,39 @@
|
||||
import { ref, onUnmounted } from 'vue'
|
||||
|
||||
/**
|
||||
* 追蹤多個 booking 的未讀訊息數。
|
||||
* @param {import('axios').AxiosInstance} axiosInstance - member 或 provider 的 axios
|
||||
*/
|
||||
export function useBookingUnreadCounts(axiosInstance) {
|
||||
const counts = ref({}) // { [bookingId]: number }
|
||||
let timer = null
|
||||
|
||||
async function fetchCounts() {
|
||||
try {
|
||||
const res = await axiosInstance.get('/bookings/messages/unread-counts')
|
||||
counts.value = res.data.data ?? {}
|
||||
} catch {
|
||||
// 靜默失敗,不影響主要頁面
|
||||
}
|
||||
}
|
||||
|
||||
/** 開啟聊天室後呼叫,清除該 booking 的角標 */
|
||||
function clearCount(bookingId) {
|
||||
counts.value = { ...counts.value, [bookingId]: 0 }
|
||||
}
|
||||
|
||||
/** 頁面 mount 時呼叫,立即拉取一次並啟動 60s 輪詢 */
|
||||
function startPolling() {
|
||||
fetchCounts()
|
||||
timer = setInterval(fetchCounts, 60_000)
|
||||
}
|
||||
|
||||
function stopPolling() {
|
||||
if (timer) clearInterval(timer)
|
||||
timer = null
|
||||
}
|
||||
|
||||
onUnmounted(stopPolling)
|
||||
|
||||
return { counts, fetchCounts, clearCount, startPolling, stopPolling }
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import router from './router'
|
||||
import { useAuthStore } from './stores/auth'
|
||||
import { useCoachAuthStore } from './stores/coachAuth'
|
||||
import { useAdminAuthStore } from './stores/adminAuth'
|
||||
import echo from './plugins/echo'
|
||||
|
||||
const app = createApp(App)
|
||||
const pinia = createPinia()
|
||||
@@ -19,4 +20,5 @@ useCoachAuthStore().init()
|
||||
useAdminAuthStore().init()
|
||||
|
||||
app.use(router)
|
||||
app.config.globalProperties.$echo = echo
|
||||
app.mount('#app')
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import Echo from 'laravel-echo'
|
||||
import Pusher from 'pusher-js'
|
||||
|
||||
window.Pusher = Pusher
|
||||
|
||||
function getAuthToken() {
|
||||
return localStorage.getItem('coach_token') || localStorage.getItem('token') || null
|
||||
}
|
||||
|
||||
const echo = new Echo({
|
||||
broadcaster: 'reverb',
|
||||
key: import.meta.env.VITE_REVERB_APP_KEY,
|
||||
wsHost: import.meta.env.VITE_REVERB_HOST,
|
||||
wsPort: import.meta.env.VITE_REVERB_PORT ?? 443,
|
||||
wssPort: import.meta.env.VITE_REVERB_PORT ?? 443,
|
||||
forceTLS: (import.meta.env.VITE_REVERB_SCHEME ?? 'https') === 'https',
|
||||
enabledTransports: ['ws', 'wss'],
|
||||
authEndpoint: `${import.meta.env.VITE_API_URL}/api/broadcasting/auth`,
|
||||
auth: {
|
||||
headers: {
|
||||
Authorization: `Bearer ${getAuthToken()}`,
|
||||
Accept: 'application/json',
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
// 登入後更新 auth header,讓 presence channel 授權帶正確 token
|
||||
export function updateEchoToken() {
|
||||
const token = getAuthToken()
|
||||
echo.options.auth.headers.Authorization = `Bearer ${token}`
|
||||
// 重新連線讓新 token 生效
|
||||
echo.disconnect()
|
||||
echo.connect()
|
||||
}
|
||||
|
||||
export default echo
|
||||
@@ -2,6 +2,7 @@ import { defineStore } from 'pinia'
|
||||
import { ref, computed } from 'vue'
|
||||
import api from '../api/axios'
|
||||
import { useNotificationStore } from './notifications'
|
||||
import { updateEchoToken } from '../plugins/echo'
|
||||
|
||||
export const useAuthStore = defineStore('auth', () => {
|
||||
const user = ref(null)
|
||||
@@ -15,7 +16,9 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
if (saved) {
|
||||
token.value = saved
|
||||
user.value = savedUser ? JSON.parse(savedUser) : null
|
||||
useNotificationStore().startPolling()
|
||||
const ns = useNotificationStore()
|
||||
ns.startPolling()
|
||||
ns.startRealtime(user.value?.id)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,14 +27,19 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
token.value = tokenValue
|
||||
localStorage.setItem('token', tokenValue)
|
||||
localStorage.setItem('user', JSON.stringify(userData))
|
||||
useNotificationStore().startPolling()
|
||||
const ns = useNotificationStore()
|
||||
ns.startPolling()
|
||||
ns.startRealtime(userData.id)
|
||||
updateEchoToken()
|
||||
}
|
||||
|
||||
async function logout() {
|
||||
try {
|
||||
await api.post('/member/logout')
|
||||
} catch {}
|
||||
useNotificationStore().stopPolling()
|
||||
const ns = useNotificationStore()
|
||||
ns.stopRealtime()
|
||||
ns.stopPolling()
|
||||
user.value = null
|
||||
token.value = null
|
||||
localStorage.removeItem('token')
|
||||
|
||||
@@ -2,6 +2,7 @@ import { defineStore } from 'pinia'
|
||||
import { ref, computed } from 'vue'
|
||||
import coachApi from '../api/coachAxios'
|
||||
import { useNotificationStore } from './notifications'
|
||||
import { updateEchoToken } from '../plugins/echo'
|
||||
|
||||
export const useCoachAuthStore = defineStore('coachAuth', () => {
|
||||
const user = ref(null)
|
||||
@@ -15,7 +16,9 @@ export const useCoachAuthStore = defineStore('coachAuth', () => {
|
||||
if (savedToken) {
|
||||
token.value = savedToken
|
||||
user.value = savedUser ? JSON.parse(savedUser) : null
|
||||
useNotificationStore().startPolling()
|
||||
const ns = useNotificationStore()
|
||||
ns.startPolling()
|
||||
ns.startRealtime(user.value?.id)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,14 +27,19 @@ export const useCoachAuthStore = defineStore('coachAuth', () => {
|
||||
token.value = tokenValue
|
||||
localStorage.setItem('coach_token', tokenValue)
|
||||
localStorage.setItem('coach_user', JSON.stringify(userData))
|
||||
useNotificationStore().startPolling()
|
||||
const ns = useNotificationStore()
|
||||
ns.startPolling()
|
||||
ns.startRealtime(userData.id)
|
||||
updateEchoToken()
|
||||
}
|
||||
|
||||
async function logout() {
|
||||
try {
|
||||
await coachApi.post('/provider/logout')
|
||||
} catch {}
|
||||
useNotificationStore().stopPolling()
|
||||
const ns = useNotificationStore()
|
||||
ns.stopRealtime()
|
||||
ns.stopPolling()
|
||||
user.value = null
|
||||
token.value = null
|
||||
localStorage.removeItem('coach_token')
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref } from 'vue'
|
||||
import api from '../api/notificationAxios'
|
||||
import echo from '../plugins/echo'
|
||||
|
||||
export const useNotificationStore = defineStore('notifications', () => {
|
||||
const unreadCount = ref(0)
|
||||
@@ -10,6 +11,7 @@ export const useNotificationStore = defineStore('notifications', () => {
|
||||
let intervalId = null
|
||||
let currentInterval = null
|
||||
let visibilityHandler = null
|
||||
let privateChannel = null // 訂閱 private user channel 用
|
||||
|
||||
async function fetchUnreadCount() {
|
||||
try {
|
||||
@@ -76,6 +78,31 @@ export const useNotificationStore = defineStore('notifications', () => {
|
||||
isOpen.value = false
|
||||
}
|
||||
|
||||
/**
|
||||
* 訂閱使用者的 private channel,收到 notification.created 立刻更新 bell。
|
||||
* 在 startPolling() 後呼叫,需要傳入 userId。
|
||||
*/
|
||||
let realtimeUserId = null
|
||||
|
||||
function startRealtime(userId) {
|
||||
if (!userId) return
|
||||
stopRealtime() // 防止重複訂閱
|
||||
realtimeUserId = userId
|
||||
privateChannel = echo
|
||||
.private(`App.Models.User.${userId}`)
|
||||
.listen('.notification.created', () => {
|
||||
fetchUnreadCount()
|
||||
})
|
||||
}
|
||||
|
||||
function stopRealtime() {
|
||||
if (realtimeUserId) {
|
||||
echo.leave(`App.Models.User.${realtimeUserId}`)
|
||||
realtimeUserId = null
|
||||
privateChannel = null
|
||||
}
|
||||
}
|
||||
|
||||
async function markRead(id) {
|
||||
const n = notifications.value.find(n => n.id === id)
|
||||
if (n && !n.read_at) {
|
||||
@@ -110,6 +137,7 @@ export const useNotificationStore = defineStore('notifications', () => {
|
||||
unreadCount, notifications, isOpen,
|
||||
fetchNotifications, fetchUnreadCount,
|
||||
startPolling, stopPolling,
|
||||
startRealtime, stopRealtime,
|
||||
markRead, markAllRead, remove,
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,12 +1,17 @@
|
||||
<script setup>
|
||||
import { ref, onMounted } from 'vue'
|
||||
import { getMyBookings, cancelBooking } from '../api/bookingApi'
|
||||
import BookingChat from '../components/BookingChat.vue'
|
||||
import { useBookingUnreadCounts } from '../composables/useBookingUnreadCounts'
|
||||
import api from '../api/axios'
|
||||
|
||||
const bookings = ref([])
|
||||
const loading = ref(true)
|
||||
const error = ref('')
|
||||
const expanded = ref(new Set())
|
||||
|
||||
const { counts: unreadCounts, clearCount, startPolling } = useBookingUnreadCounts(api)
|
||||
|
||||
const STATUS_LABEL = {
|
||||
pending: { text: '待教練確認', color: 'bg-yellow-100 text-yellow-700', hint: '等待教練確認中,確認後才完成預約' },
|
||||
confirmed: { text: '預約成功', color: 'bg-green-100 text-green-700', hint: '教練已確認,請準時出席' },
|
||||
@@ -26,6 +31,7 @@ onMounted(async () => {
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
startPolling()
|
||||
})
|
||||
|
||||
function toggle(id) {
|
||||
@@ -84,6 +90,16 @@ function formatDate(dateStr) {
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex items-center gap-3 shrink-0">
|
||||
<!-- 未讀訊息角標 -->
|
||||
<span
|
||||
v-if="(unreadCounts[b.id] ?? 0) > 0"
|
||||
class="flex items-center gap-1 bg-red-500 text-white text-[10px] font-bold px-2 py-0.5 rounded-full leading-none"
|
||||
>
|
||||
<svg class="w-3 h-3" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"/>
|
||||
</svg>
|
||||
{{ unreadCounts[b.id] }}
|
||||
</span>
|
||||
<span class="text-xs px-3 py-1 rounded-full font-medium" :class="STATUS_LABEL[b.status]?.color">
|
||||
{{ STATUS_LABEL[b.status]?.text || b.status }}
|
||||
</span>
|
||||
@@ -141,6 +157,15 @@ function formatDate(dateStr) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 即時訊息(confirmed / completed) -->
|
||||
<BookingChat
|
||||
v-if="b.status === 'confirmed' || b.status === 'completed'"
|
||||
:bookingId="b.id"
|
||||
:bookingStatus="b.status"
|
||||
currentUserType="member"
|
||||
@read="clearCount(b.id)"
|
||||
/>
|
||||
|
||||
<!-- 操作按鈕列 -->
|
||||
<div class="flex items-center justify-between pt-1">
|
||||
<RouterLink
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
<script setup>
|
||||
import { ref, onMounted, computed } from 'vue'
|
||||
import { getProviderBookings, confirmBooking, rejectBooking, cancelBooking, completeBooking } from '../../api/coachBookingApi'
|
||||
import BookingChat from '../../components/BookingChat.vue'
|
||||
import { useBookingUnreadCounts } from '../../composables/useBookingUnreadCounts'
|
||||
import coachApi from '../../api/coachAxios'
|
||||
|
||||
const bookings = ref([])
|
||||
const loading = ref(true)
|
||||
@@ -31,8 +34,23 @@ const groupedByOffer = computed(() => {
|
||||
})
|
||||
|
||||
const pendingCount = computed(() => bookings.value.filter(b => b.status === 'pending').length)
|
||||
const chatExpanded = ref(new Set())
|
||||
|
||||
onMounted(fetchBookings)
|
||||
const { counts: unreadCounts, clearCount, startPolling } = useBookingUnreadCounts(coachApi)
|
||||
|
||||
function toggleChat(id) {
|
||||
if (chatExpanded.value.has(id)) chatExpanded.value.delete(id)
|
||||
else chatExpanded.value.add(id)
|
||||
}
|
||||
|
||||
function canChat(status) {
|
||||
return status === 'confirmed' || status === 'completed'
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
fetchBookings()
|
||||
startPolling()
|
||||
})
|
||||
|
||||
async function fetchBookings() {
|
||||
loading.value = true
|
||||
@@ -88,43 +106,68 @@ async function doAction(booking, action) {
|
||||
<div
|
||||
v-for="b in group"
|
||||
:key="b.id"
|
||||
class="bg-white rounded-xl border px-5 py-4 flex items-start justify-between flex-wrap gap-3"
|
||||
class="bg-white rounded-xl border overflow-hidden"
|
||||
:class="b.status === 'pending' ? 'border-yellow-200 shadow-sm' : 'border-gray-100'"
|
||||
>
|
||||
<div class="min-w-0">
|
||||
<p class="text-sm font-medium text-gray-700">
|
||||
{{ b.scheduled_date }} {{ b.start_time }}
|
||||
</p>
|
||||
<p class="text-sm text-gray-500 mt-0.5">
|
||||
{{ b.member_name }}
|
||||
<span class="text-gray-400">({{ b.member_email }})</span>
|
||||
・{{ b.participants }} 人・NT$ {{ b.total_price?.toLocaleString() }}
|
||||
</p>
|
||||
<p v-if="b.notes" class="text-xs text-gray-400 mt-1">備注:{{ b.notes }}</p>
|
||||
<div class="px-5 py-4 flex items-start justify-between flex-wrap gap-3">
|
||||
<div class="min-w-0">
|
||||
<p class="text-sm font-medium text-gray-700">
|
||||
{{ b.scheduled_date }} {{ b.start_time }}
|
||||
</p>
|
||||
<p class="text-sm text-gray-500 mt-0.5">
|
||||
{{ b.member_name }}
|
||||
<span class="text-gray-400">({{ b.member_email }})</span>
|
||||
・{{ b.participants }} 人・NT$ {{ b.total_price?.toLocaleString() }}
|
||||
</p>
|
||||
<p v-if="b.notes" class="text-xs text-gray-400 mt-1">備注:{{ b.notes }}</p>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col items-end gap-2 shrink-0">
|
||||
<span class="text-xs px-3 py-1 rounded-full font-medium" :class="STATUS_LABEL[b.status]?.color">
|
||||
{{ STATUS_LABEL[b.status]?.text || b.status }}
|
||||
</span>
|
||||
<div class="flex gap-2 flex-wrap justify-end">
|
||||
<button v-if="b.status === 'pending'" @click="doAction(b, 'confirm')"
|
||||
class="text-xs bg-green-600 hover:bg-green-500 text-white px-3 py-1 rounded-full transition">
|
||||
確認
|
||||
</button>
|
||||
<button v-if="b.status === 'pending'" @click="doAction(b, 'reject')"
|
||||
class="text-xs bg-red-500 hover:bg-red-400 text-white px-3 py-1 rounded-full transition">
|
||||
拒絕
|
||||
</button>
|
||||
<button v-if="b.status === 'confirmed'" @click="doAction(b, 'complete')"
|
||||
class="text-xs bg-blue-600 hover:bg-blue-500 text-white px-3 py-1 rounded-full transition">
|
||||
完成
|
||||
</button>
|
||||
<button v-if="b.status === 'confirmed'" @click="doAction(b, 'cancel')"
|
||||
class="text-xs text-orange-500 hover:text-orange-700 underline">
|
||||
取消
|
||||
</button>
|
||||
<button v-if="canChat(b.status)" @click="toggleChat(b.id)"
|
||||
class="relative text-xs border px-3 py-1 rounded-full transition"
|
||||
:class="chatExpanded.has(b.id)
|
||||
? 'border-blue-400 text-blue-600'
|
||||
: 'border-gray-300 hover:border-blue-400 hover:text-blue-600 text-gray-600'"
|
||||
>
|
||||
{{ chatExpanded.has(b.id) ? '收起訊息' : '訊息' }}
|
||||
<!-- 未讀紅點 -->
|
||||
<span
|
||||
v-if="(unreadCounts[b.id] ?? 0) > 0 && !chatExpanded.has(b.id)"
|
||||
class="absolute -top-1 -right-1 min-w-[1rem] h-4 flex items-center justify-center bg-red-500 text-white text-[9px] font-bold rounded-full px-0.5"
|
||||
>{{ unreadCounts[b.id] }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col items-end gap-2 shrink-0">
|
||||
<span class="text-xs px-3 py-1 rounded-full font-medium" :class="STATUS_LABEL[b.status]?.color">
|
||||
{{ STATUS_LABEL[b.status]?.text || b.status }}
|
||||
</span>
|
||||
<div class="flex gap-2">
|
||||
<button v-if="b.status === 'pending'" @click="doAction(b, 'confirm')"
|
||||
class="text-xs bg-green-600 hover:bg-green-500 text-white px-3 py-1 rounded-full transition">
|
||||
確認
|
||||
</button>
|
||||
<button v-if="b.status === 'pending'" @click="doAction(b, 'reject')"
|
||||
class="text-xs bg-red-500 hover:bg-red-400 text-white px-3 py-1 rounded-full transition">
|
||||
拒絕
|
||||
</button>
|
||||
<button v-if="b.status === 'confirmed'" @click="doAction(b, 'complete')"
|
||||
class="text-xs bg-blue-600 hover:bg-blue-500 text-white px-3 py-1 rounded-full transition">
|
||||
完成
|
||||
</button>
|
||||
<button v-if="b.status === 'confirmed'" @click="doAction(b, 'cancel')"
|
||||
class="text-xs text-orange-500 hover:text-orange-700 underline">
|
||||
取消
|
||||
</button>
|
||||
</div>
|
||||
<!-- 即時訊息(confirmed / completed,點擊展開) -->
|
||||
<div v-if="canChat(b.status) && chatExpanded.has(b.id)" class="border-t border-gray-100 p-4">
|
||||
<BookingChat
|
||||
:bookingId="b.id"
|
||||
:bookingStatus="b.status"
|
||||
currentUserType="provider"
|
||||
@read="clearCount(b.id)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user