更新小程序配置,切换API基础地址至真实后端。实现@用户提及功能,允许在内容中插入用户信息并高亮显示,优化用户体验。调整后端逻辑以支持免费章节的判断,确保章节信息的准确性与一致性。

This commit is contained in:
Alex-larget
2026-03-08 11:56:27 +08:00
parent 73ecead336
commit 90d32a5121
3 changed files with 181 additions and 14 deletions

View File

@@ -8,9 +8,9 @@ const { parseScene } = require('./utils/scene.js')
App({ App({
globalData: { globalData: {
// API基础地址 - 连接真实后端 // API基础地址 - 连接真实后端
// baseUrl: 'https://soulapi.quwanzhi.com', baseUrl: 'https://soulapi.quwanzhi.com',
// baseUrl: 'https://souldev.quwanzhi.com', // baseUrl: 'https://souldev.quwanzhi.com',
baseUrl: 'http://localhost:8080', // baseUrl: 'http://localhost:8080',
// 小程序配置 - 真实AppID // 小程序配置 - 真实AppID

View File

@@ -36,6 +36,7 @@ import {
Plus, Plus,
Image as ImageIcon, Image as ImageIcon,
Search, Search,
AtSign,
} from 'lucide-react' } from 'lucide-react'
import { get, put, del } from '@/api/client' import { get, put, del } from '@/api/client'
import { ChapterTree } from './ChapterTree' import { ChapterTree } from './ChapterTree'
@@ -156,6 +157,12 @@ export function ContentPage() {
const [editingPart, setEditingPart] = useState<{ id: string; title: string } | null>(null) const [editingPart, setEditingPart] = useState<{ id: string; title: string } | null>(null)
const [isSavingPartTitle, setIsSavingPartTitle] = useState(false) const [isSavingPartTitle, setIsSavingPartTitle] = useState(false)
const [showMentionUserDialog, setShowMentionUserDialog] = useState(false)
const [mentionTarget, setMentionTarget] = useState<'new' | 'edit'>('new')
const [mentionUserList, setMentionUserList] = useState<{ id: string; nickname: string }[]>([])
const [mentionUserSearch, setMentionUserSearch] = useState('')
const [mentionUserLoading, setMentionUserLoading] = useState(false)
const tree = buildTree(sectionsList) const tree = buildTree(sectionsList)
const totalSections = sectionsList.length const totalSections = sectionsList.length
@@ -178,6 +185,43 @@ export function ContentPage() {
loadList() loadList()
}, []) }, [])
const loadMentionUsers = useCallback(async () => {
setMentionUserLoading(true)
try {
const params = new URLSearchParams({ pageSize: '200' })
if (mentionUserSearch.trim()) params.set('search', mentionUserSearch.trim())
const data = await get<{ success?: boolean; users?: { id: string; nickname?: string }[] }>(
`/api/db/users?${params}`,
)
const users = Array.isArray(data?.users) ? data.users : []
setMentionUserList(users.map((u) => ({ id: String(u.id), nickname: u.nickname || '用户' })))
} catch (e) {
console.error(e)
setMentionUserList([])
} finally {
setMentionUserLoading(false)
}
}, [mentionUserSearch])
useEffect(() => {
if (showMentionUserDialog) loadMentionUsers()
}, [showMentionUserDialog, loadMentionUsers])
const openMentionUserDialog = (target: 'new' | 'edit') => {
setMentionTarget(target)
setMentionUserSearch('')
setShowMentionUserDialog(true)
}
const insertMentionUser = (user: { id: string; nickname: string }) => {
const snippet = `{{@${user.id}:${user.nickname}}}`
if (mentionTarget === 'new') {
setNewSection((prev) => ({ ...prev, content: (prev.content || '') + snippet }))
} else if (editingSection) {
setEditingSection({ ...editingSection, content: (editingSection.content || '') + snippet })
}
setShowMentionUserDialog(false)
}
const togglePart = (partId: string) => { const togglePart = (partId: string) => {
setExpandedParts((prev) => setExpandedParts((prev) =>
@@ -563,10 +607,22 @@ export function ContentPage() {
</div> </div>
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
<Label className="text-gray-300"> (Markdown格式)</Label> <div className="flex items-center justify-between">
<Label className="text-gray-300"> (Markdown格式)</Label>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => openMentionUserDialog('new')}
className="border-gray-600 text-gray-300 hover:bg-gray-700/50 bg-transparent"
>
<AtSign className="w-4 h-4 mr-1" />
@用户
</Button>
</div>
<Textarea <Textarea
className="bg-[#0a1628] border-gray-700 text-white min-h-[300px] font-mono text-sm placeholder:text-gray-500" className="bg-[#0a1628] border-gray-700 text-white min-h-[300px] font-mono text-sm placeholder:text-gray-500"
placeholder="输入章节内容..." placeholder="输入章节内容... 可点击「插入 @用户」插入 {{@用户ID:昵称}},小程序内将高亮可点"
value={newSection.content} value={newSection.content}
onChange={(e) => setNewSection({ ...newSection, content: e.target.value })} onChange={(e) => setNewSection({ ...newSection, content: e.target.value })}
/> />
@@ -746,6 +802,16 @@ export function ContentPage() {
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<Label className="text-gray-300"> (Markdown格式)</Label> <Label className="text-gray-300"> (Markdown格式)</Label>
<div className="flex gap-2"> <div className="flex gap-2">
<Button
type="button"
variant="outline"
size="sm"
onClick={() => openMentionUserDialog('edit')}
className="border-gray-600 text-gray-300 hover:bg-gray-700/50 bg-transparent"
>
<AtSign className="w-4 h-4 mr-1" />
@用户
</Button>
<input <input
ref={imageInputRef} ref={imageInputRef}
type="file" type="file"
@@ -807,6 +873,55 @@ export function ContentPage() {
</DialogContent> </DialogContent>
</Dialog> </Dialog>
{/* 插入 @用户 - 选择用户弹窗 */}
<Dialog open={showMentionUserDialog} onOpenChange={setShowMentionUserDialog}>
<DialogContent className="bg-[#0f2137] border-gray-700 text-white max-w-md max-h-[80vh] overflow-hidden flex flex-col" showCloseButton>
<DialogHeader>
<DialogTitle className="text-white flex items-center gap-2">
<AtSign className="w-5 h-5 text-[#38bdac]" />
@用户
</DialogTitle>
</DialogHeader>
<p className="text-gray-400 text-sm"> {'{{@用户ID:昵称}}'}</p>
<div className="space-y-2">
<Input
className="bg-[#0a1628] border-gray-700 text-white placeholder:text-gray-500"
placeholder="搜索昵称或 ID..."
value={mentionUserSearch}
onChange={(e) => setMentionUserSearch(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && loadMentionUsers()}
/>
<Button
type="button"
variant="outline"
size="sm"
onClick={loadMentionUsers}
disabled={mentionUserLoading}
className="border-gray-600 text-gray-300 hover:bg-gray-700/50 bg-transparent w-full"
>
{mentionUserLoading ? <RefreshCw className="w-4 h-4 animate-spin" /> : <Search className="w-4 h-4" />}
{mentionUserLoading ? '加载中...' : '搜索'}
</Button>
</div>
<div className="flex-1 overflow-y-auto min-h-[200px] border border-gray-700 rounded-md bg-[#0a1628]">
{mentionUserList.length === 0 && !mentionUserLoading && (
<div className="p-4 text-center text-gray-500 text-sm"></div>
)}
{mentionUserList.map((user) => (
<button
key={user.id}
type="button"
onClick={() => insertMentionUser(user)}
className="w-full px-4 py-2 text-left hover:bg-[#38bdac]/20 border-b border-gray-700/50 last:border-0 flex justify-between items-center"
>
<span className="text-white truncate">{user.nickname}</span>
<span className="text-gray-500 text-xs font-mono shrink-0 ml-2">{user.id}</span>
</button>
))}
</div>
</DialogContent>
</Dialog>
<Tabs defaultValue="chapters" className="space-y-6"> <Tabs defaultValue="chapters" className="space-y-6">
<TabsList className="bg-[#0f2137] border border-gray-700/50 p-1"> <TabsList className="bg-[#0f2137] border border-gray-700/50 p-1">
<TabsTrigger value="chapters" className="data-[state=active]:bg-[#38bdac]/20 data-[state=active]:text-[#38bdac] text-gray-400"> <TabsTrigger value="chapters" className="data-[state=active]:bg-[#38bdac]/20 data-[state=active]:text-[#38bdac] text-gray-400">

View File

@@ -1,6 +1,7 @@
package handler package handler
import ( import (
"encoding/json"
"net/http" "net/http"
"strconv" "strconv"
"strings" "strings"
@@ -17,10 +18,11 @@ var excludeParts = []string{"序言", "尾声", "附录"}
// BookAllChapters GET /api/book/all-chapters 返回所有章节(列表,来自 chapters 表) // BookAllChapters GET /api/book/all-chapters 返回所有章节(列表,来自 chapters 表)
// 排序须与管理端 PUT /api/db/book action=reorder 一致:按 sort_order 升序,同序按 id // 排序须与管理端 PUT /api/db/book action=reorder 一致:按 sort_order 升序,同序按 id
// COALESCE 处理 sort_order 为 NULL 的旧数据,避免错位 // 免费判断system_config.free_chapters / chapter_config.freeChapters 优先于 chapters.is_free
// 支持 excludeFixed=1排除序言、尾声、附录目录页固定模块不参与中间篇章 // 支持 excludeFixed=1排除序言、尾声、附录目录页固定模块不参与中间篇章
func BookAllChapters(c *gin.Context) { func BookAllChapters(c *gin.Context) {
q := database.DB().Model(&model.Chapter{}) db := database.DB()
q := db.Model(&model.Chapter{})
if c.Query("excludeFixed") == "1" { if c.Query("excludeFixed") == "1" {
for _, p := range excludeParts { for _, p := range excludeParts {
q = q.Where("part_title NOT LIKE ?", "%"+p+"%") q = q.Where("part_title NOT LIKE ?", "%"+p+"%")
@@ -31,6 +33,15 @@ func BookAllChapters(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"success": true, "data": []interface{}{}}) c.JSON(http.StatusOK, gin.H{"success": true, "data": []interface{}{}})
return return
} }
freeIDs := getFreeChapterIDs(db)
for i := range list {
if freeIDs[list[i].ID] {
t := true
z := float64(0)
list[i].IsFree = &t
list[i].Price = &z
}
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": list}) c.JSON(http.StatusOK, gin.H{"success": true, "data": list})
} }
@@ -63,7 +74,43 @@ func BookChapterByMID(c *gin.Context) {
}) })
} }
// getFreeChapterIDs 从 system_config 读取免费章节 ID 列表free_chapters 或 chapter_config.freeChapters
func getFreeChapterIDs(db *gorm.DB) map[string]bool {
ids := make(map[string]bool)
for _, key := range []string{"free_chapters", "chapter_config"} {
var row model.SystemConfig
if err := db.Where("config_key = ?", key).First(&row).Error; err != nil {
continue
}
var val interface{}
if err := json.Unmarshal(row.ConfigValue, &val); err != nil {
continue
}
if key == "free_chapters" {
if arr, ok := val.([]interface{}); ok {
for _, v := range arr {
if s, ok := v.(string); ok {
ids[s] = true
}
}
}
} else if key == "chapter_config" {
if m, ok := val.(map[string]interface{}); ok {
if arr, ok := m["freeChapters"].([]interface{}); ok {
for _, v := range arr {
if s, ok := v.(string); ok {
ids[s] = true
}
}
}
}
}
}
return ids
}
// findChapterAndRespond 按条件查章节并返回统一格式 // findChapterAndRespond 按条件查章节并返回统一格式
// 免费判断优先级system_config.free_chapters / chapter_config.freeChapters > chapters.is_free/price
func findChapterAndRespond(c *gin.Context, whereFn func(*gorm.DB) *gorm.DB) { func findChapterAndRespond(c *gin.Context, whereFn func(*gorm.DB) *gorm.DB) {
var ch model.Chapter var ch model.Chapter
db := database.DB() db := database.DB()
@@ -85,14 +132,19 @@ func findChapterAndRespond(c *gin.Context, whereFn func(*gorm.DB) *gorm.DB) {
"mid": ch.MID, "mid": ch.MID,
"sectionTitle": ch.SectionTitle, "sectionTitle": ch.SectionTitle,
} }
if ch.IsFree != nil { isFreeFromConfig := getFreeChapterIDs(db)[ch.ID]
out["isFree"] = *ch.IsFree if isFreeFromConfig {
} out["isFree"] = true
if ch.Price != nil { out["price"] = float64(0)
out["price"] = *ch.Price } else {
// 价格为 0 元则自动视为免费 if ch.IsFree != nil {
if *ch.Price == 0 { out["isFree"] = *ch.IsFree
out["isFree"] = true }
if ch.Price != nil {
out["price"] = *ch.Price
if *ch.Price == 0 {
out["isFree"] = true
}
} }
} }
c.JSON(http.StatusOK, out) c.JSON(http.StatusOK, out)