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:
2026-05-28 03:59:14 +08:00
parent cc010b5c83
commit ab24f210a6
39 changed files with 2842 additions and 62 deletions
+9
View File
@@ -8,7 +8,16 @@ RUN npm install
COPY . .
ARG VITE_API_URL=http://localhost:8080
ARG VITE_REVERB_APP_KEY
ARG VITE_REVERB_HOST=localhost
ARG VITE_REVERB_PORT=8085
ARG VITE_REVERB_SCHEME=http
ENV VITE_API_URL=$VITE_API_URL
ENV VITE_REVERB_APP_KEY=$VITE_REVERB_APP_KEY
ENV VITE_REVERB_HOST=$VITE_REVERB_HOST
ENV VITE_REVERB_PORT=$VITE_REVERB_PORT
ENV VITE_REVERB_SCHEME=$VITE_REVERB_SCHEME
RUN npm run build
+230
View File
@@ -9,7 +9,9 @@
"version": "0.0.0",
"dependencies": {
"axios": "^1.16.0",
"laravel-echo": "^2.3.4",
"pinia": "^3.0.4",
"pusher-js": "^8.5.0",
"vue": "^3.5.32",
"vue-router": "^4.6.4"
},
@@ -450,6 +452,12 @@
"integrity": "sha512-3ngTAv6F/Py35BsYbeeLeecvhMKdsKm4AoOETVhAA+Qc8nrA2I0kF7oa93mE9qnIurngOSpMnQ0x2nQY2FPviA==",
"dev": true
},
"node_modules/@socket.io/component-emitter": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.2.tgz",
"integrity": "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==",
"peer": true
},
"node_modules/@tybys/wasm-util": {
"version": "0.10.2",
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.2.tgz",
@@ -890,6 +898,23 @@
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="
},
"node_modules/debug": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
"peer": true,
"dependencies": {
"ms": "^2.1.3"
},
"engines": {
"node": ">=6.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
}
},
"node_modules/delayed-stream": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
@@ -938,6 +963,28 @@
"integrity": "sha512-kOrWphBi8TOZyiJZqsgqIle0lw+tzmnQK83pV9dZUd01Nm2POECSyFQMAuarzZdYqQW7FH9RaYOuaRo3h+bQ3w==",
"dev": true
},
"node_modules/engine.io-client": {
"version": "6.6.5",
"resolved": "https://registry.npmjs.org/engine.io-client/-/engine.io-client-6.6.5.tgz",
"integrity": "sha512-QCwxUDULPlXv8F6tqMMKx5dNkTe6OaBYRMPYeXKBlyOoKvAmE0ac6pW7fFhSscJ/5SI7666/U/B+MElbsrJlIg==",
"peer": true,
"dependencies": {
"@socket.io/component-emitter": "~3.1.0",
"debug": "~4.4.1",
"engine.io-parser": "~5.2.1",
"ws": "~8.20.1",
"xmlhttprequest-ssl": "~2.1.1"
}
},
"node_modules/engine.io-parser": {
"version": "5.2.3",
"resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.2.3.tgz",
"integrity": "sha512-HqD3yTBfnBxIrbnM1DoD6Pcq8NECnh8d4As1Qgh0z5Gg3jRRIqijury0CL3ghu/edArpUYiYqQiDUQBIs4np3Q==",
"peer": true,
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/entities": {
"version": "7.0.1",
"resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz",
@@ -1315,6 +1362,18 @@
"jiti": "bin/jiti.js"
}
},
"node_modules/laravel-echo": {
"version": "2.3.4",
"resolved": "https://registry.npmjs.org/laravel-echo/-/laravel-echo-2.3.4.tgz",
"integrity": "sha512-rpALCIK1uw2SrttcK9P5JzItt5I85RcfXQKUNnkcorzhtKeXi5GS0PVFFBH8ppNo8wnbdBKuD1EtIHgTbXo9FQ==",
"engines": {
"node": ">=20"
},
"peerDependencies": {
"pusher-js": "*",
"socket.io-client": "*"
}
},
"node_modules/lightningcss": {
"version": "1.32.0",
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz",
@@ -1656,6 +1715,12 @@
"resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz",
"integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw=="
},
"node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"peer": true
},
"node_modules/mz": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz",
@@ -1946,6 +2011,14 @@
"node": ">=10"
}
},
"node_modules/pusher-js": {
"version": "8.5.0",
"resolved": "https://registry.npmjs.org/pusher-js/-/pusher-js-8.5.0.tgz",
"integrity": "sha512-V7uzGi9bqOOOyM/6IkJdpFyjGZj7llz1v0oWnYkZKcYLvbz6VcHVLmzKqkvegjuMumpfIEKGLmWHwFb39XFCpw==",
"dependencies": {
"tweetnacl": "^1.0.3"
}
},
"node_modules/queue-microtask": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz",
@@ -2097,6 +2170,34 @@
"queue-microtask": "^1.2.2"
}
},
"node_modules/socket.io-client": {
"version": "4.8.3",
"resolved": "https://registry.npmjs.org/socket.io-client/-/socket.io-client-4.8.3.tgz",
"integrity": "sha512-uP0bpjWrjQmUt5DTHq9RuoCBdFJF10cdX9X+a368j/Ft0wmaVgxlrjvK3kjvgCODOMMOz9lcaRzxmso0bTWZ/g==",
"peer": true,
"dependencies": {
"@socket.io/component-emitter": "~3.1.0",
"debug": "~4.4.1",
"engine.io-client": "~6.6.1",
"socket.io-parser": "~4.2.4"
},
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/socket.io-parser": {
"version": "4.2.6",
"resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.6.tgz",
"integrity": "sha512-asJqbVBDsBCJx0pTqw3WfesSY0iRX+2xzWEWzrpcH7L6fLzrhyF8WPI8UaeM4YCuDfpwA/cgsdugMsmtz8EJeg==",
"peer": true,
"dependencies": {
"@socket.io/component-emitter": "~3.1.0",
"debug": "~4.4.1"
},
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/source-map-js": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
@@ -2257,6 +2358,11 @@
"dev": true,
"optional": true
},
"node_modules/tweetnacl": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz",
"integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw=="
},
"node_modules/update-browserslist-db": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz",
@@ -2408,6 +2514,36 @@
"version": "6.6.4",
"resolved": "https://registry.npmjs.org/@vue/devtools-api/-/devtools-api-6.6.4.tgz",
"integrity": "sha512-sGhTPMuXqZ1rVOk32RylztWkfXTRhuS7vgAKv0zjqk8gbsHkJ7xfFf+jbySxt7tWObEJwyKaHMikV/WGDiQm8g=="
},
"node_modules/ws": {
"version": "8.20.1",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.20.1.tgz",
"integrity": "sha512-It4dO0K5v//JtTXuPkfEOaI3uUN87iYPnqo/ZzqCoG3g8uhA66QUMs/SrM0YK7/NAu+r4LMh/9dq2A7k+rHs+w==",
"peer": true,
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
},
"node_modules/xmlhttprequest-ssl": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/xmlhttprequest-ssl/-/xmlhttprequest-ssl-2.1.2.tgz",
"integrity": "sha512-TEU+nJVUUnA4CYJFLvK5X9AOeH4KvDvhIfm0vV1GaQRtchnG0hgK5p8hw/xjv8cunWYCsiPCSDzObPyhEwq3KQ==",
"peer": true,
"engines": {
"node": ">=0.4.0"
}
}
},
"dependencies": {
@@ -2664,6 +2800,12 @@
"integrity": "sha512-3ngTAv6F/Py35BsYbeeLeecvhMKdsKm4AoOETVhAA+Qc8nrA2I0kF7oa93mE9qnIurngOSpMnQ0x2nQY2FPviA==",
"dev": true
},
"@socket.io/component-emitter": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.2.tgz",
"integrity": "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==",
"peer": true
},
"@tybys/wasm-util": {
"version": "0.10.2",
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.2.tgz",
@@ -2979,6 +3121,15 @@
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="
},
"debug": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
"peer": true,
"requires": {
"ms": "^2.1.3"
}
},
"delayed-stream": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
@@ -3018,6 +3169,25 @@
"integrity": "sha512-kOrWphBi8TOZyiJZqsgqIle0lw+tzmnQK83pV9dZUd01Nm2POECSyFQMAuarzZdYqQW7FH9RaYOuaRo3h+bQ3w==",
"dev": true
},
"engine.io-client": {
"version": "6.6.5",
"resolved": "https://registry.npmjs.org/engine.io-client/-/engine.io-client-6.6.5.tgz",
"integrity": "sha512-QCwxUDULPlXv8F6tqMMKx5dNkTe6OaBYRMPYeXKBlyOoKvAmE0ac6pW7fFhSscJ/5SI7666/U/B+MElbsrJlIg==",
"peer": true,
"requires": {
"@socket.io/component-emitter": "~3.1.0",
"debug": "~4.4.1",
"engine.io-parser": "~5.2.1",
"ws": "~8.20.1",
"xmlhttprequest-ssl": "~2.1.1"
}
},
"engine.io-parser": {
"version": "5.2.3",
"resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.2.3.tgz",
"integrity": "sha512-HqD3yTBfnBxIrbnM1DoD6Pcq8NECnh8d4As1Qgh0z5Gg3jRRIqijury0CL3ghu/edArpUYiYqQiDUQBIs4np3Q==",
"peer": true
},
"entities": {
"version": "7.0.1",
"resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz",
@@ -3263,6 +3433,12 @@
"integrity": "sha512-/imKNG4EbWNrVjoNC/1H5/9GFy+tqjGBHCaSsN+P2RnPqjsLmv6UD3Ej+Kj8nBWaRAwyk7kK5ZUc+OEatnTR3A==",
"dev": true
},
"laravel-echo": {
"version": "2.3.4",
"resolved": "https://registry.npmjs.org/laravel-echo/-/laravel-echo-2.3.4.tgz",
"integrity": "sha512-rpALCIK1uw2SrttcK9P5JzItt5I85RcfXQKUNnkcorzhtKeXi5GS0PVFFBH8ppNo8wnbdBKuD1EtIHgTbXo9FQ==",
"requires": {}
},
"lightningcss": {
"version": "1.32.0",
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz",
@@ -3427,6 +3603,12 @@
"resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz",
"integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw=="
},
"ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"peer": true
},
"mz": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz",
@@ -3578,6 +3760,14 @@
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-2.1.0.tgz",
"integrity": "sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA=="
},
"pusher-js": {
"version": "8.5.0",
"resolved": "https://registry.npmjs.org/pusher-js/-/pusher-js-8.5.0.tgz",
"integrity": "sha512-V7uzGi9bqOOOyM/6IkJdpFyjGZj7llz1v0oWnYkZKcYLvbz6VcHVLmzKqkvegjuMumpfIEKGLmWHwFb39XFCpw==",
"requires": {
"tweetnacl": "^1.0.3"
}
},
"queue-microtask": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz",
@@ -3675,6 +3865,28 @@
"queue-microtask": "^1.2.2"
}
},
"socket.io-client": {
"version": "4.8.3",
"resolved": "https://registry.npmjs.org/socket.io-client/-/socket.io-client-4.8.3.tgz",
"integrity": "sha512-uP0bpjWrjQmUt5DTHq9RuoCBdFJF10cdX9X+a368j/Ft0wmaVgxlrjvK3kjvgCODOMMOz9lcaRzxmso0bTWZ/g==",
"peer": true,
"requires": {
"@socket.io/component-emitter": "~3.1.0",
"debug": "~4.4.1",
"engine.io-client": "~6.6.1",
"socket.io-parser": "~4.2.4"
}
},
"socket.io-parser": {
"version": "4.2.6",
"resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.6.tgz",
"integrity": "sha512-asJqbVBDsBCJx0pTqw3WfesSY0iRX+2xzWEWzrpcH7L6fLzrhyF8WPI8UaeM4YCuDfpwA/cgsdugMsmtz8EJeg==",
"peer": true,
"requires": {
"@socket.io/component-emitter": "~3.1.0",
"debug": "~4.4.1"
}
},
"source-map-js": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
@@ -3794,6 +4006,11 @@
"dev": true,
"optional": true
},
"tweetnacl": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz",
"integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw=="
},
"update-browserslist-db": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz",
@@ -3850,6 +4067,19 @@
"integrity": "sha512-sGhTPMuXqZ1rVOk32RylztWkfXTRhuS7vgAKv0zjqk8gbsHkJ7xfFf+jbySxt7tWObEJwyKaHMikV/WGDiQm8g=="
}
}
},
"ws": {
"version": "8.20.1",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.20.1.tgz",
"integrity": "sha512-It4dO0K5v//JtTXuPkfEOaI3uUN87iYPnqo/ZzqCoG3g8uhA66QUMs/SrM0YK7/NAu+r4LMh/9dq2A7k+rHs+w==",
"peer": true,
"requires": {}
},
"xmlhttprequest-ssl": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/xmlhttprequest-ssl/-/xmlhttprequest-ssl-2.1.2.tgz",
"integrity": "sha512-TEU+nJVUUnA4CYJFLvK5X9AOeH4KvDvhIfm0vV1GaQRtchnG0hgK5p8hw/xjv8cunWYCsiPCSDzObPyhEwq3KQ==",
"peer": true
}
}
}
+2
View File
@@ -10,7 +10,9 @@
},
"dependencies": {
"axios": "^1.16.0",
"laravel-echo": "^2.3.4",
"pinia": "^3.0.4",
"pusher-js": "^8.5.0",
"vue": "^3.5.32",
"vue-router": "^4.6.4"
},
+274
View File
@@ -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 }
}
+2
View File
@@ -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')
+36
View File
@@ -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
+11 -3
View File
@@ -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')
+11 -3
View File
@@ -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')
+28
View File
@@ -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,
}
})
+25
View File
@@ -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
+77 -34
View File
@@ -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>