69bd56671c
## 这两个页面是漏的,不是新需求
Step 2 我说了「记录类型后台可配」,接口加了(GET/POST/DELETE
/api/admin/record-types)但 React 页面根本没建;品种那次同样只加了接口。
也就是说「可配」这件事在后台上一直是点不到的。补上。
## 品种管理
猫/狗切换,按首字母分段列出(和小程序端的 A-Z 索引对得上)。
首字母是手填的输入框,配了一句说明:多音字自己定(藏獒 Z、柴犬 C)。
不做自动转拼音——Go 没有标准拼音库,而且多音字自动转常出错,
错了以后用户在小程序里按字母索引就找不到那个品种。
## 记录事项
按分组列出 24 种,「表单字段」那列把 DSL 渲染成人话
(体重·数值kg / 状态·单选★),★ 表示这个单选落 category。
字段配置的写法说明直接放在编辑弹窗里,不是写进文档:这东西一年用两次,
去翻文档的成本比它本身还高。
内置那 9 种打了「内置」标签、隐藏删除按钮、code 输入框禁用 —— 但真正的
拦截在 service 层,前端只是别让人白点。
## 报错原样透出
两个页面的保存失败都把后端消息显示出来,不写成「保存失败」。
后端那些消息是特意写具体的(第几行、错在哪、几个档案在用),
包成一句「失败」等于把它们扔了。
## 验证(预生产库实跑 service 层)
品种 首字母两位/中文 → 拒;物种 bird → 拒;同物种重名「布偶猫」→ 拒
有 1 个档案在用时删 → 拒并报出数量;没人用 → 删成功
事项 两个字段都落 category → 「第 2 行」;options 没选项 → 「第 1 行」;
类型写成 num → 「第 1 行类型 num 不认识」;缺名称 → 「第 1 行缺名称」;
第二个加 :- → 通过
tsc --noEmit 通过;npm run build 后重启,/admin/ 返回的资源哈希
和新构建一致(go:embed 是编译期打包的,不重启看不到新页面)
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
167 lines
6.1 KiB
TypeScript
167 lines
6.1 KiB
TypeScript
import axios from 'axios'
|
|
|
|
const TOKEN_KEY = 'pets_admin_token'
|
|
const REFRESH_KEY = 'pets_admin_refresh'
|
|
|
|
export function getToken() {
|
|
return localStorage.getItem(TOKEN_KEY) || ''
|
|
}
|
|
export function getRefreshToken() {
|
|
return localStorage.getItem(REFRESH_KEY) || ''
|
|
}
|
|
export function setToken(t: string, refresh?: string) {
|
|
localStorage.setItem(TOKEN_KEY, t)
|
|
if (refresh) localStorage.setItem(REFRESH_KEY, refresh)
|
|
}
|
|
export function clearToken() {
|
|
localStorage.removeItem(TOKEN_KEY)
|
|
localStorage.removeItem(REFRESH_KEY)
|
|
}
|
|
|
|
const http = axios.create({ baseURL: '/api' })
|
|
|
|
http.interceptors.request.use((cfg) => {
|
|
const t = getToken()
|
|
if (t) cfg.headers.Authorization = `Bearer ${t}`
|
|
return cfg
|
|
})
|
|
|
|
// access token 只有 2 小时,过期后拿 refresh token 换新的。
|
|
// 用单飞(single-flight)保证并发请求只触发一次刷新,否则刷新令牌会被并发轮换掉。
|
|
let refreshing: Promise<string> | null = null
|
|
|
|
function refreshAccessToken(): Promise<string> {
|
|
if (!refreshing) {
|
|
const rt = getRefreshToken()
|
|
refreshing = (
|
|
rt
|
|
? axios.post('/api/admin/refresh', { refresh_token: rt }).then((r) => {
|
|
const body = r.data
|
|
if (!body || body.code !== 0) throw new Error(body?.message || '续期失败')
|
|
setToken(body.data.token, body.data.refresh_token)
|
|
return body.data.token as string
|
|
})
|
|
: Promise.reject(new Error('没有刷新令牌'))
|
|
).finally(() => {
|
|
refreshing = null
|
|
})
|
|
}
|
|
return refreshing
|
|
}
|
|
|
|
function logout() {
|
|
clearToken()
|
|
if (location.pathname !== '/admin/login') location.href = '/admin/login'
|
|
}
|
|
|
|
// 这几个接口本身就可能返回 40100(密码错、刷新令牌失效),不能再触发刷新,否则会绕圈
|
|
const NO_REFRESH = ['/admin/login', '/admin/refresh', '/admin/logout']
|
|
|
|
// 统一响应 {code,message,data}:成功返回 data,失败抛错
|
|
http.interceptors.response.use(
|
|
async (resp) => {
|
|
const body = resp.data
|
|
if (body && typeof body === 'object' && 'code' in body) {
|
|
if (body.code === 0) return body.data
|
|
if (body.code === 40100) {
|
|
const cfg = resp.config as typeof resp.config & { _retried?: boolean }
|
|
const skip = NO_REFRESH.some((p) => (cfg.url || '').startsWith(p))
|
|
if (!skip && !cfg._retried) {
|
|
cfg._retried = true
|
|
try {
|
|
const t = await refreshAccessToken()
|
|
cfg.headers.Authorization = `Bearer ${t}`
|
|
return await http.request(cfg)
|
|
} catch {
|
|
/* 续期失败,落到下面退出登录 */
|
|
}
|
|
}
|
|
if (!skip) logout()
|
|
}
|
|
return Promise.reject(new Error(body.message || '请求失败'))
|
|
}
|
|
return body
|
|
},
|
|
(err) => Promise.reject(err),
|
|
)
|
|
|
|
export interface Page<T> {
|
|
list: T[]
|
|
total: number
|
|
page: number
|
|
page_size: number
|
|
}
|
|
|
|
export const api = {
|
|
login: (username: string, password: string) =>
|
|
http.post<any, { token: string; refresh_token: string; expires_in: number; admin: any }>(
|
|
'/admin/login',
|
|
{ username, password },
|
|
),
|
|
logout: () => http.post('/admin/logout', { refresh_token: getRefreshToken() }),
|
|
me: () => http.get<any, any>('/admin/me'),
|
|
stats: () => http.get<any, { users: number; pets: number; posts: number; records: number }>('/admin/stats'),
|
|
|
|
users: (params: any) => http.get<any, Page<any>>('/admin/users', { params }),
|
|
setUserDisabled: (id: number, disabled: boolean) =>
|
|
http.put(`/admin/users/${id}/disabled`, { disabled }),
|
|
|
|
pets: (params: any) => http.get<any, Page<any>>('/admin/pets', { params }),
|
|
|
|
posts: (params: any) => http.get<any, Page<any>>('/admin/posts', { params }),
|
|
setPostStatus: (id: number, status: string) => http.put(`/admin/posts/${id}/status`, { status }),
|
|
|
|
comments: (params: any) => http.get<any, Page<any>>('/admin/comments', { params }),
|
|
deleteComment: (id: number) => http.delete(`/admin/comments/${id}`),
|
|
|
|
articles: (params: any) => http.get<any, Page<any>>('/admin/articles', { params }),
|
|
saveArticle: (a: any) => http.post('/admin/articles', a),
|
|
deleteArticle: (id: number) => http.delete(`/admin/articles/${id}`),
|
|
|
|
memberships: (params: any) => http.get<any, Page<any>>('/admin/memberships', { params }),
|
|
|
|
careTemplateMeta: () => http.get<any, any>('/admin/care-templates/meta'),
|
|
careTemplate: (species: string, stage: string) =>
|
|
http.get<any, { species: string; stage: string; items: any[] }>('/admin/care-templates', {
|
|
params: { species, stage },
|
|
}),
|
|
saveCareTemplate: (species: string, stage: string, items: any[]) =>
|
|
http.put<any, { items: any[] }>('/admin/care-templates', { species, stage, items }),
|
|
genCareTemplate: (species: string, stage: string) =>
|
|
http.post<any, { species: string; stage: string; items: any[] }>('/admin/care-templates/generate', {
|
|
species,
|
|
stage,
|
|
}),
|
|
|
|
feedback: (params: any) => http.get<any, Page<any>>('/admin/feedback', { params }),
|
|
setFeedbackHandled: (id: string, handled: boolean) =>
|
|
http.put(`/admin/feedback/${id}/handled`, { handled }),
|
|
|
|
aiQuota: () =>
|
|
http.get<any, { enabled: boolean; daily_chat: number; daily_symptom: number; daily_plan: number }>(
|
|
'/admin/ai-quota',
|
|
),
|
|
saveAIQuota: (c: any) => http.put<any, any>('/admin/ai-quota', c),
|
|
|
|
// 记录类型(小程序「记一笔」的那些事项)
|
|
recordTypes: () => http.get<any, any[]>('/admin/record-types'),
|
|
saveRecordType: (t: any) => http.post('/admin/record-types', t),
|
|
deleteRecordType: (id: string) => http.delete(`/admin/record-types/${id}`),
|
|
|
|
// 品种
|
|
breeds: (species?: string) =>
|
|
http.get<any, any[]>('/admin/breeds', { params: species ? { species } : {} }),
|
|
saveBreed: (b: any) => http.post('/admin/breeds', b),
|
|
deleteBreed: (id: string) => http.delete(`/admin/breeds/${id}`),
|
|
|
|
communityBot: () =>
|
|
http.get<any, { enabled: boolean; daily_count: number; start_hour: number; end_hour: number }>(
|
|
'/admin/community-bot',
|
|
),
|
|
saveCommunityBot: (c: any) => http.put<any, any>('/admin/community-bot', c),
|
|
genCommunityPosts: (count: number) =>
|
|
http.post<any, { made: number }>('/admin/community-bot/generate', { count }),
|
|
}
|
|
|
|
export default http
|