feat: 人生事件和剧本收藏从 localStorage 切换为真实 API

- 后端:新增 t_event_favorite 表(UNIQUE KEY + MyBatis-Plus Entity)
- 后端:LifeEventController 新增 /favorite/toggle、/favorite/page、/favorite/check 三个真实端点
- 后端:EventFavoriteService 完整 CRUD,含 toggle/分页/批量查询/状态检查
- 后端:删除旧的 favorite-placeholder mock 端点
- 前端:life-event/detail.vue 从 localStorage 假收藏切换为真实 API + localStorage 缓存防闪烁
- 前端:ScriptLibraryView.vue 从 localFavorites 切换为 checkFavoriteScript 真实 API
- 前端:stores/app.js 新增 toggleEventFavorite / checkEventFavorite 方法
- 修复:审核发现的 UNIQUE 约束缺失、未使用 watch 导入、Controller 参数注解遗漏、Controller 委托 Service 构造 Response

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-07-19 23:23:40 +08:00
parent a3bfad099a
commit dd11cfae73
12 changed files with 451 additions and 41 deletions
+34 -8
View File
@@ -134,14 +134,41 @@ const isDescriptionCollapsed = ref(false)
const scrollTop = ref(0)
const currentScrollTop = ref(0)
// 从 localStorage 读取缓存的收藏状态
const getCachedFavoriteStatus = (id) => {
const cached = uni.getStorageSync(`favorite_event_${id}`)
return cached === 'true'
}
// 缓存收藏状态到 localStorage
const setCachedFavoriteStatus = (id, status) => {
uni.setStorageSync(`favorite_event_${id}`, status ? 'true' : 'false')
}
onMounted(async () => {
const info = uni.getWindowInfo()
safeAreaBottom.value = info.safeAreaInsets?.bottom || 0
const pages = getCurrentPages()
eventId.value = pages[pages.length - 1]?.options?.id || ''
// 先从缓存读取收藏状态,避免闪烁
if (eventId.value) {
isFavorite.value = getCachedFavoriteStatus(eventId.value)
}
cachedEvent.value = uni.getStorageSync('current_life_event') || null
if (!store.events?.length) await store.fetchEvents()
isFavorite.value = Boolean(uni.getStorageSync(`event_favorite_${eventId.value}`))
// 异步校验真实收藏状态并更新缓存
if (eventId.value) {
const result = await store.checkEventFavorite(eventId.value)
if (result.success) {
const realStatus = result.data
isFavorite.value = realStatus
setCachedFavoriteStatus(eventId.value, realStatus)
}
}
analytics.trackPageView(pagePath, {
life_event_id: eventId.value,
tag_count: Array.isArray(displayEvent.value.tags) ? displayEvent.value.tags.length : 0
@@ -305,20 +332,19 @@ const editEvent = () => {
const toggleFavorite = async () => {
if (!eventId.value) return
const next = !isFavorite.value
const result = await store.favoriteEvent({ id: eventId.value, favorite: next })
const result = await store.toggleEventFavorite(eventId.value)
if (!result.success) {
uni.showToast({ title: result.error || '收藏失败', icon: 'none' })
return
}
isFavorite.value = next
if (next) uni.setStorageSync(`event_favorite_${eventId.value}`, '1')
else uni.removeStorageSync(`event_favorite_${eventId.value}`)
const newStatus = result.data?.isFavorited ?? false
isFavorite.value = newStatus
setCachedFavoriteStatus(eventId.value, newStatus)
analytics.track('life_event_favorite', {
life_event_id: eventId.value,
favorite: next
favorite: newStatus
}, { eventType: 'life_event', pagePath })
uni.showToast({ title: next ? '已收藏' : '已取消收藏', icon: 'success' })
uni.showToast({ title: newStatus ? '已收藏' : '已取消收藏', icon: 'success' })
}
const chatEvent = async () => {
@@ -147,9 +147,9 @@
</template>
<script setup>
import { computed, ref } from 'vue'
import { computed, ref, watch } from 'vue'
import { useAppStore } from '../../stores/app.js'
import { toggleFavoriteScript } from '../../services/epicScript.js'
import { toggleFavoriteScript, checkFavoriteScript } from '../../services/epicScript.js'
const store = useAppStore()
const activeType = ref('long')
@@ -157,7 +157,7 @@ const activeStatus = ref('all')
const keyword = ref('')
const sortMode = ref('updated')
const viewMode = ref('list')
const localFavorites = ref(uni.getStorageSync('script_favorites') || {})
const favoriteStatus = ref({})
const activeMenuId = ref('')
const deleteTarget = ref(null)
const deletingScript = ref(false)
@@ -198,6 +198,26 @@ const visibleScripts = computed(() => {
})
})
// 列表加载后批量检查收藏状态
const loadFavoriteStatus = async () => {
const ids = scripts.value.map(s => String(s.id)).filter(id => !id.startsWith('demo-'))
if (!ids.length) return
const status = {}
await Promise.all(ids.map(async (id) => {
try {
status[id] = await checkFavoriteScript(id)
} catch {
status[id] = false
}
}))
favoriteStatus.value = status
}
// 监听 scripts 变化时重新加载收藏状态
watch(scripts, () => {
loadFavoriteStatus()
}, { immediate: true })
const sortLabel = computed(() => {
const map = { updated: '最近更新⌄', words: '字数最多⌄', progress: '进度最高⌄' }
return map[sortMode.value] || '最近更新⌄'
@@ -243,7 +263,7 @@ const getProgress = (script) => Math.max(0, Math.min(99, Number(script.progress
const getInitial = (script) => (script.title || '剧').slice(0, 1)
const isFavorite = (script) => {
return Boolean(script.isFavorite || script.favorite || localFavorites.value[String(script.id)])
return Boolean(favoriteStatus.value[String(script.id)])
}
const openScriptChat = (script) => {
@@ -319,15 +339,14 @@ const toggleScriptMenu = (script) => {
const toggleFavorite = async (script) => {
const wasFav = isFavorite(script)
// 乐观更新:先改本地缓存
const next = { ...localFavorites.value }
// 乐观更新:先改内存状态
const next = { ...favoriteStatus.value }
if (wasFav) {
delete next[String(script.id)]
} else {
next[String(script.id)] = true
}
localFavorites.value = next
uni.setStorageSync('script_favorites', next)
favoriteStatus.value = next
closeScriptMenu()
try {
@@ -335,14 +354,13 @@ const toggleFavorite = async (script) => {
uni.showToast({ title: result.isFavorited ? '已收藏' : '已取消收藏', icon: 'success' })
} catch (error) {
// 回滚乐观更新
const restored = { ...localFavorites.value }
const restored = { ...favoriteStatus.value }
if (wasFav) {
restored[String(script.id)] = true
} else {
delete restored[String(script.id)]
}
localFavorites.value = restored
uni.setStorageSync('script_favorites', restored)
favoriteStatus.value = restored
uni.showToast({ title: error?.message || '操作失败', icon: 'none' })
}
}
@@ -383,10 +401,9 @@ const confirmDeleteScript = async () => {
return
}
const next = { ...localFavorites.value }
const next = { ...favoriteStatus.value }
delete next[id]
localFavorites.value = next
uni.setStorageSync('script_favorites', next)
favoriteStatus.value = next
const conversationId = deleteTarget.value.conversationId || deleteTarget.value.plotJson?.conversationId
if (conversationId) uni.removeStorageSync(`script_conversation_history_${conversationId}`)
uni.removeStorageSync(`script_chat_history_${id}`)
+24 -3
View File
@@ -64,8 +64,28 @@ export const shareEvent = async (eventData = {}) => {
return post('/lifeEvent/share-placeholder', eventData)
}
export const favoriteEvent = async ({ id, favorite }) => {
return post('/lifeEvent/favorite-placeholder', { id, favorite })
/**
* 切换人生事件收藏状态(收藏/取消收藏)
* @param {string} eventId 事件ID
* @returns {Promise<{success: boolean, isFavorited: boolean}>}
*/
export const toggleFavoriteEvent = async (eventId) => {
const res = await post('/lifeEvent/favorite/toggle', { eventId })
return {
success: true,
isFavorited: res.data?.isFavorited ?? false,
favoriteTime: res.data?.favoriteTime ?? null
}
}
/**
* 检查人生事件是否已收藏
* @param {string} eventId 事件ID
* @returns {Promise<boolean>}
*/
export const checkFavoriteEvent = async (eventId) => {
const res = await get('/lifeEvent/favorite/check', { eventId })
return res.data?.isFavorited ?? false
}
const transformToBackendFormat = (frontendData) => {
@@ -153,7 +173,8 @@ export default {
assistEventWriting,
chatAboutEvent,
shareEvent,
favoriteEvent,
toggleFavoriteEvent,
checkFavoriteEvent,
transformToFrontendFormat,
transformListToFrontend
}
+14 -4
View File
@@ -232,10 +232,19 @@ const shareEvent = async (eventData) => {
}
}
const favoriteEvent = async ({ id, favorite }) => {
const toggleEventFavorite = async (eventId) => {
try {
const res = await lifeEventService.favoriteEvent({ id, favorite })
return { success: true, data: res.data }
const result = await lifeEventService.toggleFavoriteEvent(eventId)
return { success: true, data: result }
} catch (error) {
return { success: false, error: error.message }
}
}
const checkEventFavorite = async (eventId) => {
try {
const isFavorited = await lifeEventService.checkFavoriteEvent(eventId)
return { success: true, data: isFavorited }
} catch (error) {
return { success: false, error: error.message }
}
@@ -479,7 +488,8 @@ export const useAppStore = () => {
assistEventWriting,
chatAboutEvent,
shareEvent,
favoriteEvent,
toggleEventFavorite,
checkEventFavorite,
getEventById,
fetchScripts,
createScript,