@allbluecn/admin-app 0.3.8 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/package.json +3 -3
  2. package/src/components/admin/developer-log.tsx +2 -2
  3. package/src/components/dependency/dependency-table.tsx +21 -3
  4. package/src/components/invitations/invitations-page.tsx +16 -4
  5. package/src/components/knowledge/public/kp-crud-page.tsx +208 -0
  6. package/src/components/market/market-app-form.tsx +1 -1
  7. package/src/components/user/settings-profile.tsx +1 -1
  8. package/src/components/user/user-create-dialog.tsx +1 -1
  9. package/src/components/user/user-detail/user-detail-dialogs.tsx +9 -9
  10. package/src/paraglide/messages/_index.js +8 -8
  11. package/src/paraglide/messages/admin_invitations_filter_showdisabled1.js +30 -0
  12. package/src/paraglide/messages/admin_users_action_deactivate.js +30 -0
  13. package/src/paraglide/messages/admin_users_dialog_deactivate_confirm.js +30 -0
  14. package/src/paraglide/messages/admin_users_dialog_deactivate_description.js +30 -0
  15. package/src/paraglide/messages/admin_users_dialog_deactivate_placeholder.js +30 -0
  16. package/src/paraglide/messages/admin_users_dialog_deactivate_title.js +30 -0
  17. package/src/paraglide/messages/admin_users_toast_deactivatefailed1.js +30 -0
  18. package/src/paraglide/messages/admin_users_toast_userdeactivated1.js +30 -0
  19. package/src/routes/_nav/knowledge-public/bookmarks/route.lazy.tsx +36 -111
  20. package/src/routes/_nav/knowledge-public/compliance/route.lazy.tsx +29 -105
  21. package/src/routes/_nav/knowledge-public/legal/route.lazy.tsx +30 -108
  22. package/src/routes/_nav/monitoring/errors/route.lazy.tsx +1 -1
  23. package/src/routes/_nav/monitoring/logs/route.lazy.tsx +1 -1
  24. package/src/routes/_nav/monitoring/metrics/route.lazy.tsx +1 -1
  25. package/src/routes/_nav/permissions/route.lazy.tsx +1 -1
  26. package/src/routes/_nav/sso/route.lazy.tsx +1 -1
  27. package/src/routes/_nav/users/$userId/route.lazy.tsx +10 -10
  28. package/src/server/knowledge/public/kp-factory.ts +134 -0
  29. package/src/server/serverFns/dependency/sync.ts +2 -2
  30. package/src/server/serverFns/knowledge/public/bookmarks/create.ts +23 -25
  31. package/src/server/serverFns/knowledge/public/bookmarks/delete.ts +2 -14
  32. package/src/server/serverFns/knowledge/public/bookmarks/detail.ts +2 -11
  33. package/src/server/serverFns/knowledge/public/bookmarks/list.ts +32 -38
  34. package/src/server/serverFns/knowledge/public/bookmarks/update.ts +23 -22
  35. package/src/server/serverFns/knowledge/public/compliance/create.ts +10 -15
  36. package/src/server/serverFns/knowledge/public/compliance/delete.ts +2 -14
  37. package/src/server/serverFns/knowledge/public/compliance/detail.ts +2 -11
  38. package/src/server/serverFns/knowledge/public/compliance/list.ts +24 -31
  39. package/src/server/serverFns/knowledge/public/compliance/update.ts +22 -22
  40. package/src/server/serverFns/knowledge/public/legal/create.ts +11 -15
  41. package/src/server/serverFns/knowledge/public/legal/delete.ts +2 -14
  42. package/src/server/serverFns/knowledge/public/legal/detail.ts +2 -11
  43. package/src/server/serverFns/knowledge/public/legal/list.ts +24 -32
  44. package/src/server/serverFns/knowledge/public/legal/update.ts +20 -22
  45. package/src/server/serverFns/user/{delete.ts → deactivate.ts} +2 -2
  46. package/src/paraglide/messages/admin_users_dialog_delete_confirm.js +0 -30
  47. package/src/paraglide/messages/admin_users_dialog_delete_description.js +0 -30
  48. package/src/paraglide/messages/admin_users_dialog_delete_placeholder.js +0 -30
  49. package/src/paraglide/messages/admin_users_dialog_delete_title.js +0 -30
  50. package/src/paraglide/messages/admin_users_toast_deletefailed1.js +0 -30
  51. package/src/paraglide/messages/admin_users_toast_userdeleted1.js +0 -30
  52. package/src/paraglide/messages/common_button_cancel.js +0 -29
  53. package/src/paraglide/messages/common_dependency_table_pagination_total.js +0 -29
@@ -225,7 +225,7 @@ function PermissionsPage(): React.ReactElement {
225
225
  }}
226
226
  title={m.enterprise_permissions_delete_confirm_title({ name: deletingRole?.name ?? '' })}
227
227
  description={m.enterprise_permissions_delete_confirm_description()}
228
- cancelLabel={m.common_button_cancel()}
228
+ cancelLabel={m.common_common_cancel()}
229
229
  confirmLabel={m.common_button_confirm()}
230
230
  confirmVariant="destructive"
231
231
  confirmDisabled={deleting}
@@ -168,7 +168,7 @@ function SsoConfigPage(): React.ReactElement {
168
168
  }}
169
169
  title={m.enterprise_sso_delete_confirm_title({ name: deletingProvider?.name ?? '' })}
170
170
  description={m.enterprise_sso_delete_confirm_description()}
171
- cancelLabel={m.common_button_cancel()}
171
+ cancelLabel={m.common_common_cancel()}
172
172
  confirmLabel={m.common_button_confirm()}
173
173
  confirmVariant="destructive"
174
174
  confirmDisabled={operating}
@@ -29,7 +29,7 @@ import { getUserDetailFn } from '@/server/serverFns/user/detail'
29
29
  import { updateUserRoleFn } from '@/server/serverFns/user/update-role'
30
30
  import { updateUserStatusFn } from '@/server/serverFns/user/update-status'
31
31
  import { resetUserPasswordFn } from '@/server/serverFns/user/reset-password'
32
- import { deleteUserFn } from '@/server/serverFns/user/delete'
32
+ import { deactivateUserFn } from '@/server/serverFns/user/deactivate'
33
33
  import { TableDetailLayout } from '@/components/data-table/table-detail-layout'
34
34
  import { Badge } from '@/components/ui/badge'
35
35
  import { Separator } from '@/components/ui/separator'
@@ -51,7 +51,7 @@ import {
51
51
  } from '@/components/ui/card'
52
52
  import { AdminUserErrorBoundary } from '@/components/user/user-detail/error-boundary'
53
53
  import {
54
- UserDeleteDialog,
54
+ UserDeactivateDialog,
55
55
  UserPasswordDialog,
56
56
  UserRoleDialog,
57
57
  UserStatusDialog,
@@ -138,7 +138,7 @@ function UserDetailPage() {
138
138
  const [roleDialog, setRoleDialog] = useState({ open: false, value: '' })
139
139
  const [statusDialog, setStatusDialog] = useState({ open: false, value: '' })
140
140
  const [passwordDialog, setPasswordDialog] = useState({ open: false, value: '' })
141
- const [deleteDialog, setDeleteDialog] = useState({ open: false, confirmName: '' })
141
+ const [deactivateDialog, setDeleteDialog] = useState({ open: false, confirmName: '' })
142
142
 
143
143
  // loader 对未知 id throw notFound(),此处仅作类型层面的防御性兜底
144
144
  if (!user) return null
@@ -200,7 +200,7 @@ function UserDetailPage() {
200
200
  {m['admin-users_action_resetPassword']()}
201
201
  </Button>
202
202
  <Button variant="destructive" size="sm" onClick={() => setDeleteDialog({ open: true, confirmName: '' })}>
203
- {m.common_button_delete()}
203
+ {m['admin-users_action_deactivate']()}
204
204
  </Button>
205
205
  </>
206
206
  }
@@ -383,19 +383,19 @@ function UserDetailPage() {
383
383
  })}
384
384
  />
385
385
 
386
- <UserDeleteDialog
387
- open={deleteDialog.open}
388
- confirmName={deleteDialog.confirmName}
386
+ <UserDeactivateDialog
387
+ open={deactivateDialog.open}
388
+ confirmName={deactivateDialog.confirmName}
389
389
  username={user.username}
390
390
  isPending={isPending}
391
391
  onOpenChange={(o) => setDeleteDialog((d) => ({ ...d, open: o }))}
392
392
  onConfirmNameChange={(v) => setDeleteDialog((d) => ({ ...d, confirmName: v }))}
393
393
  onSubmit={() => startTransition(async () => {
394
394
  try {
395
- await deleteUserFn({ data: { userId: user.id } })
396
- toast.success(m['admin-users_toast_userDeleted']())
395
+ await deactivateUserFn({ data: { userId: user.id } })
396
+ toast.success(m['admin-users_toast_userDeactivated']())
397
397
  await navigate({ to: '/users' })
398
- } catch { toast.error(m['admin-users_toast_deleteFailed']()) }
398
+ } catch { toast.error(m['admin-users_toast_deactivateFailed']()) }
399
399
  })}
400
400
  />
401
401
  </>
@@ -0,0 +1,134 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // AllBlue - 理想之海
3
+ // Copyright (C) 2026 AllBlue Contributors
4
+ //
5
+ // This program is free software: you can redistribute it and/or modify
6
+ // it under the terms of the GNU Affero General Public License as published by
7
+ // the Free Software Foundation, either version 3 of the License, or
8
+ // (at your option) any later version.
9
+ //
10
+ // This program is distributed in the hope that it will be useful,
11
+ // but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ // GNU Affero General Public License for more details.
14
+ //
15
+ // You should have received a copy of the GNU Affero General Public License
16
+ // along with this program. If not, see <https://www.gnu.org/licenses/>.
17
+
18
+ // S35(审计 A10 建议):knowledge-public 三域管理 serverFn 泛型工厂。
19
+ // bookmarks/compliance/legal 五类操作(create/update/delete/list/detail)骨架
20
+ // 完全同构(requireAdmin → 委托模型操作),差异仅在域 schema 与 data 映射——
21
+ // 收敛为本工厂后,各域文件退化为「域 schema + 工厂调用」,文件路径与 fn 名
22
+ // 不变(客户端 import 零改动)。
23
+ //
24
+ // 纯净性合规:本文件不是 serverFn 文件(无 createServerFn),值导出不受
25
+ // serverFn 纯净性口径约束;createServerFn 调用仍留在各域文件。
26
+ // delegate 用最小 any 面类型:prisma 泛型 delegate 与结构化最小面不可比,
27
+ // 真实类型安全由各域调用处的 prisma.<model> 具体参数与 select/where 白名单承担。
28
+
29
+ import { getPrisma } from '@allbluecn/database/get-prisma'
30
+ import { requireAdmin } from '@/server/auth-helpers'
31
+
32
+ /** 三域模型 delegate 的最小调用面(any 化理由见文件头) */
33
+ export type KpDelegate = Record<string, any>
34
+
35
+ type GetDelegate = (prisma: Awaited<ReturnType<typeof getPrisma>>) => KpDelegate
36
+
37
+ // ── delete:软删(isDeleted),P2025 转「未找到」──────────────────────────
38
+
39
+ export function kpDeleteHandler(getDelegate: GetDelegate) {
40
+ return async ({ data }: { data: { id: string } }) => {
41
+ const prisma = await getPrisma()
42
+ await requireAdmin()
43
+ // 直接软删,不存在由 P2025 转错误(省一次 findUnique 往返)
44
+ try {
45
+ await getDelegate(prisma).update({ where: { id: data.id }, data: { isDeleted: true } })
46
+ } catch (e) {
47
+ if ((e as { code?: string }).code === 'P2025') throw new Error('未找到')
48
+ throw e
49
+ }
50
+ return { success: true }
51
+ }
52
+ }
53
+
54
+ // ── detail:公开可见 + 未软删 ──────────────────────────────────────────────
55
+
56
+ export function kpDetailHandler(getDelegate: GetDelegate) {
57
+ return async ({ data }: { data: { id: string } }) => {
58
+ const prisma = await getPrisma()
59
+ await requireAdmin()
60
+ const item = await getDelegate(prisma).findFirst({
61
+ where: { id: data.id, visibility: 'public', isDeleted: false },
62
+ })
63
+ if (!item) throw new Error('未找到')
64
+ return item
65
+ }
66
+ }
67
+
68
+ // ── create:requireAdmin + 域 buildData(canonicalId 等域逻辑在回调内)────
69
+
70
+ export function kpCreateHandler<TData>(opts: {
71
+ getDelegate: GetDelegate
72
+ buildData: (data: TData, userId: string) => Record<string, unknown>
73
+ select?: Record<string, boolean>
74
+ }) {
75
+ return async ({ data }: { data: TData }) => {
76
+ const prisma = await getPrisma()
77
+ const session = await requireAdmin()
78
+ const userId = session.user?.id
79
+ if (!userId) throw new Error('Unauthorized')
80
+ return opts.getDelegate(prisma).create({
81
+ data: opts.buildData(data, userId),
82
+ select: opts.select ?? { id: true },
83
+ })
84
+ }
85
+ }
86
+
87
+ // ── update:findUnique 存在性 + 域 buildUpdateData(canonicalId 回退等在回调内)──
88
+
89
+ export function kpUpdateHandler<TData extends { id: string }>(opts: {
90
+ getDelegate: GetDelegate
91
+ buildUpdateData: (data: TData, existing: Record<string, any>) => Record<string, unknown>
92
+ select?: Record<string, boolean>
93
+ }) {
94
+ return async ({ data }: { data: TData }) => {
95
+ const prisma = await getPrisma()
96
+ await requireAdmin()
97
+ const { id, ...rest } = data
98
+ const existing = await opts.getDelegate(prisma).findUnique({ where: { id } })
99
+ if (!existing) throw new Error('未找到')
100
+ void rest
101
+ const updateData = opts.buildUpdateData(data, existing)
102
+ return opts.getDelegate(prisma).update({ where: { id }, data: updateData, select: opts.select ?? { id: true } })
103
+ }
104
+ }
105
+
106
+ // ── list:public + 未软删基线 + 域过滤(search OR 等)+ 分页 ────────────────
107
+
108
+ export function kpListHandler<TData extends { page: number; pageSize: number }>(opts: {
109
+ getDelegate: GetDelegate
110
+ /** 基线(visibility/isDeleted)之外的域条件,含 search 的 OR 子句 */
111
+ buildWhere: (data: TData) => Record<string, unknown>
112
+ select: Record<string, any>
113
+ orderBy?: Record<string, 'asc' | 'desc'>
114
+ /** 行后处理(如 bookmarks 的 category join → categoryIcon 拍平) */
115
+ postProcess?: (items: any[]) => unknown[]
116
+ }) {
117
+ return async ({ data }: { data: TData }) => {
118
+ const prisma = await getPrisma()
119
+ await requireAdmin()
120
+ const where = { visibility: 'public', isDeleted: false, ...opts.buildWhere(data) }
121
+ const [items, total] = await Promise.all([
122
+ opts.getDelegate(prisma).findMany({
123
+ where,
124
+ select: opts.select,
125
+ orderBy: opts.orderBy ?? { createdAt: 'desc' },
126
+ skip: (data.page - 1) * data.pageSize,
127
+ take: data.pageSize,
128
+ }),
129
+ opts.getDelegate(prisma).count({ where }),
130
+ ])
131
+ const rows = opts.postProcess ? opts.postProcess(items) : items
132
+ return { items: rows, total, page: data.page, pageSize: data.pageSize }
133
+ }
134
+ }
@@ -57,8 +57,8 @@ export const syncDependencyFn = createServerFn({ method: "POST" })
57
57
 
58
58
  const syncAllInput = z.object({
59
59
  /** 要同步的包名列表(前端传当前视图的全部包名,含未跟踪的会 upsert 创建) */
60
- // 上限 500 为滥用兜底(当前全仓去重依赖名 ~240);顺序同步耗时随数量线性增长,
61
- // 真正的超时治理需前端分批调用(见审计 A10 待决策)
60
+ // 前端按 50/批分批调用(dependency-table.tsx,A10 超时治理已落地);
61
+ // 此上限 500 为直连滥用的最终兜底
62
62
  names: z.array(packageNameSchema).max(500),
63
63
  })
64
64
 
@@ -17,9 +17,9 @@
17
17
 
18
18
  import { createServerFn } from '@tanstack/react-start'
19
19
  import { z } from 'zod'
20
- import { getPrisma } from '@allbluecn/database/get-prisma'
21
- import { requireAdmin, UnauthorizedError } from '@/server/auth-helpers'
22
- import { bookmarkCanonicalId, parseGithubUrl } from '@/server/knowledge/public/canonical-id'
20
+ import { bookmarkCanonicalId } from '@/server/knowledge/public/canonical-id'
21
+ import { parseGithubUrl } from '@/server/knowledge/public/canonical-id'
22
+ import { kpCreateHandler } from '@/server/knowledge/public/kp-factory'
23
23
 
24
24
  const createSchema = z.object({
25
25
  title: z.string().min(1).max(200),
@@ -37,26 +37,24 @@ const createSchema = z.object({
37
37
 
38
38
  export const adminCreateBookmarkFn = createServerFn({ method: 'POST' })
39
39
  .validator(createSchema)
40
- .handler(async ({ data }) => {
41
- const prisma = await getPrisma()
42
- const session = await requireAdmin()
43
- const userId = session.user?.id
44
- if (!userId) throw new UnauthorizedError()
45
- const gh = parseGithubUrl(data.url)
46
- return prisma.websiteBookmark.create({
47
- data: {
48
- canonicalId: bookmarkCanonicalId(data.url),
49
- title: data.title,
50
- url: data.url,
51
- categoryId: data.categoryId || null,
52
- summary: data.summary || null,
53
- tags: data.tags,
54
- visibility: 'public',
55
- userId,
56
- isGithub: !!gh,
57
- githubOwner: gh?.owner ?? null,
58
- githubRepo: gh?.repo ?? null,
40
+ .handler(
41
+ kpCreateHandler<z.infer<typeof createSchema>>({
42
+ getDelegate: (prisma) => prisma.websiteBookmark,
43
+ buildData: (data, userId) => {
44
+ const gh = parseGithubUrl(data.url)
45
+ return {
46
+ canonicalId: bookmarkCanonicalId(data.url),
47
+ title: data.title,
48
+ url: data.url,
49
+ categoryId: data.categoryId || null,
50
+ summary: data.summary || null,
51
+ tags: data.tags,
52
+ visibility: 'public',
53
+ userId,
54
+ isGithub: !!gh,
55
+ githubOwner: gh?.owner ?? null,
56
+ githubRepo: gh?.repo ?? null,
57
+ }
59
58
  },
60
- select: { id: true },
61
- })
62
- })
59
+ }),
60
+ )
@@ -17,20 +17,8 @@
17
17
 
18
18
  import { createServerFn } from '@tanstack/react-start'
19
19
  import { z } from 'zod'
20
- import { getPrisma } from '@allbluecn/database/get-prisma'
21
- import { requireAdmin } from '@/server/auth-helpers'
20
+ import { kpDeleteHandler } from '@/server/knowledge/public/kp-factory'
22
21
 
23
22
  export const adminDeleteBookmarkFn = createServerFn({ method: 'POST' })
24
23
  .validator(z.object({ id: z.string() }))
25
- .handler(async ({ data }) => {
26
- const prisma = await getPrisma()
27
- await requireAdmin()
28
- // 直接软删,不存在由 P2025 转错误(省一次 findUnique 往返)
29
- try {
30
- await prisma.websiteBookmark.update({ where: { id: data.id }, data: { isDeleted: true } })
31
- } catch (e) {
32
- if ((e as { code?: string }).code === 'P2025') throw new Error('未找到')
33
- throw e
34
- }
35
- return { success: true }
36
- })
24
+ .handler(kpDeleteHandler((prisma) => prisma.websiteBookmark))
@@ -17,17 +17,8 @@
17
17
 
18
18
  import { createServerFn } from '@tanstack/react-start'
19
19
  import { z } from 'zod'
20
- import { getPrisma } from '@allbluecn/database/get-prisma'
21
- import { requireAdmin } from '@/server/auth-helpers'
20
+ import { kpDetailHandler } from '@/server/knowledge/public/kp-factory'
22
21
 
23
22
  export const adminGetBookmarkDetailFn = createServerFn({ method: 'GET' })
24
23
  .validator(z.object({ id: z.string() }))
25
- .handler(async ({ data }) => {
26
- const prisma = await getPrisma()
27
- await requireAdmin()
28
- const item = await prisma.websiteBookmark.findFirst({
29
- where: { id: data.id, visibility: 'public', isDeleted: false },
30
- })
31
- if (!item) throw new Error('未找到')
32
- return item
33
- })
24
+ .handler(kpDetailHandler((prisma) => prisma.websiteBookmark))
@@ -15,11 +15,10 @@
15
15
  // You should have received a copy of the GNU Affero General Public License
16
16
  // along with this program. If not, see <https://www.gnu.org/licenses/>.
17
17
 
18
+
18
19
  import { createServerFn } from '@tanstack/react-start'
19
20
  import { z } from 'zod'
20
- import { getPrisma } from '@allbluecn/database/get-prisma'
21
- import { Prisma } from '@allbluecn/database'
22
- import { requireAdmin } from '@/server/auth-helpers'
21
+ import { kpListHandler } from '@/server/knowledge/public/kp-factory'
23
22
 
24
23
  const listSchema = z.object({
25
24
  search: z.string().optional(),
@@ -31,38 +30,33 @@ const listSchema = z.object({
31
30
 
32
31
  export const adminListBookmarksFn = createServerFn({ method: 'GET' })
33
32
  .validator(listSchema)
34
- .handler(async ({ data }) => {
35
- const prisma = await getPrisma()
36
- await requireAdmin()
37
- const where: Prisma.WebsiteBookmarkWhereInput = { visibility: 'public', isDeleted: false }
38
- if (data.search) {
39
- where.OR = [
40
- { title: { contains: data.search, mode: 'insensitive' } },
41
- { summary: { contains: data.search, mode: 'insensitive' } },
42
- { url: { contains: data.search, mode: 'insensitive' } },
43
- ]
44
- }
45
- if (data.categoryId) where.categoryId = data.categoryId
46
- if (data.isGithub !== undefined) where.isGithub = data.isGithub
47
- const [items, total] = await Promise.all([
48
- prisma.websiteBookmark.findMany({
49
- where,
50
- select: {
51
- id: true, canonicalId: true, title: true, url: true, categoryId: true,
52
- summary: true, faviconUrl: true, isGithub: true, githubStars: true,
53
- githubLatestVersion: true, githubVersionDate: true, githubRepoUpdatedAt: true,
54
- githubSyncedAt: true, tags: true, visibility: true, userId: true, createdAt: true,
55
- category: { select: { icon: true } },
56
- },
57
- orderBy: { createdAt: 'desc' },
58
- skip: (data.page - 1) * data.pageSize,
59
- take: data.pageSize,
60
- }),
61
- prisma.websiteBookmark.count({ where }),
62
- ])
63
- const mapped = items.map(({ category: _c, ...rest }) => ({
64
- ...rest,
65
- categoryIcon: _c?.icon ?? 'Folder',
66
- }))
67
- return { items: mapped, total, page: data.page, pageSize: data.pageSize }
68
- })
33
+ .handler(
34
+ kpListHandler<z.infer<typeof listSchema>>({
35
+ getDelegate: (prisma) => prisma.websiteBookmark,
36
+ buildWhere: (data) => {
37
+ const where: Record<string, unknown> = {}
38
+ if (data.search) {
39
+ where.OR = [
40
+ { title: { contains: data.search, mode: 'insensitive' } },
41
+ { summary: { contains: data.search, mode: 'insensitive' } },
42
+ { url: { contains: data.search, mode: 'insensitive' } },
43
+ ]
44
+ }
45
+ if (data.categoryId) where.categoryId = data.categoryId
46
+ if (data.isGithub !== undefined) where.isGithub = data.isGithub
47
+ return where
48
+ },
49
+ select: {
50
+ id: true, canonicalId: true, title: true, url: true, categoryId: true,
51
+ summary: true, faviconUrl: true, isGithub: true, githubStars: true,
52
+ githubLatestVersion: true, githubVersionDate: true, githubRepoUpdatedAt: true,
53
+ githubSyncedAt: true, tags: true, visibility: true, userId: true, createdAt: true,
54
+ category: { select: { icon: true } },
55
+ },
56
+ postProcess: (items) =>
57
+ items.map(({ category: _c, ...rest }) => ({
58
+ ...rest,
59
+ categoryIcon: _c?.icon ?? 'Folder',
60
+ })),
61
+ }),
62
+ )
@@ -15,12 +15,12 @@
15
15
  // You should have received a copy of the GNU Affero General Public License
16
16
  // along with this program. If not, see <https://www.gnu.org/licenses/>.
17
17
 
18
+
18
19
  import { createServerFn } from '@tanstack/react-start'
19
20
  import { z } from 'zod'
20
- import { getPrisma } from '@allbluecn/database/get-prisma'
21
- import { Prisma } from '@allbluecn/database'
22
- import { requireAdmin } from '@/server/auth-helpers'
23
- import { bookmarkCanonicalId, parseGithubUrl } from '@/server/knowledge/public/canonical-id'
21
+ import { bookmarkCanonicalId } from '@/server/knowledge/public/canonical-id'
22
+ import { parseGithubUrl } from '@/server/knowledge/public/canonical-id'
23
+ import { kpUpdateHandler } from '@/server/knowledge/public/kp-factory'
24
24
 
25
25
  const updateSchema = z.object({
26
26
  id: z.string(),
@@ -39,21 +39,22 @@ const updateSchema = z.object({
39
39
 
40
40
  export const adminUpdateBookmarkFn = createServerFn({ method: 'POST' })
41
41
  .validator(updateSchema)
42
- .handler(async ({ data }) => {
43
- const prisma = await getPrisma()
44
- await requireAdmin()
45
- const { id, ...rest } = data
46
- const existing = await prisma.websiteBookmark.findUnique({ where: { id } })
47
- if (!existing) throw new Error('未找到')
48
- const updateData: Prisma.WebsiteBookmarkUncheckedUpdateInput = { ...rest }
49
- // .url() 已排除空串,无需真值判断;局部变量保住 string 收窄
50
- const nextUrl = data.url
51
- if (nextUrl !== undefined && nextUrl !== existing.url) {
52
- const gh = parseGithubUrl(nextUrl)
53
- updateData.canonicalId = bookmarkCanonicalId(nextUrl)
54
- updateData.isGithub = !!gh
55
- updateData.githubOwner = gh?.owner ?? null
56
- updateData.githubRepo = gh?.repo ?? null
57
- }
58
- return prisma.websiteBookmark.update({ where: { id }, data: updateData, select: { id: true } })
59
- })
42
+ .handler(
43
+ kpUpdateHandler<z.infer<typeof updateSchema>>({
44
+ getDelegate: (prisma) => prisma.websiteBookmark,
45
+ buildUpdateData: (data, existing) => {
46
+ const { id: _id, ...rest } = data
47
+ const updateData: Record<string, unknown> = { ...rest }
48
+ // .url() 已排除空串,无需真值判断;局部变量保住 string 收窄
49
+ const nextUrl = data.url
50
+ if (nextUrl !== undefined && nextUrl !== existing.url) {
51
+ const gh = parseGithubUrl(nextUrl)
52
+ updateData.canonicalId = bookmarkCanonicalId(nextUrl)
53
+ updateData.isGithub = !!gh
54
+ updateData.githubOwner = gh?.owner ?? null
55
+ updateData.githubRepo = gh?.repo ?? null
56
+ }
57
+ return updateData
58
+ },
59
+ }),
60
+ )
@@ -17,9 +17,8 @@
17
17
 
18
18
  import { createServerFn } from '@tanstack/react-start'
19
19
  import { z } from 'zod'
20
- import { getPrisma } from '@allbluecn/database/get-prisma'
21
- import { requireAdmin, UnauthorizedError } from '@/server/auth-helpers'
22
20
  import { complianceCanonicalId } from '@/server/knowledge/public/canonical-id'
21
+ import { kpCreateHandler } from '@/server/knowledge/public/kp-factory'
23
22
 
24
23
  const createSchema = z.object({
25
24
  title: z.string().min(1).max(200),
@@ -36,26 +35,22 @@ const createSchema = z.object({
36
35
 
37
36
  export const adminCreateComplianceFn = createServerFn({ method: 'POST' })
38
37
  .validator(createSchema)
39
- .handler(async ({ data }) => {
40
- const prisma = await getPrisma()
41
- const session = await requireAdmin()
42
- const userId = session.user?.id
43
- if (!userId) throw new UnauthorizedError()
44
- return prisma.industryCompliance.create({
45
- data: {
38
+ .handler(
39
+ kpCreateHandler<z.infer<typeof createSchema>>({
40
+ getDelegate: (prisma) => prisma.industryCompliance,
41
+ buildData: (data, userId) => ({
46
42
  canonicalId: complianceCanonicalId({ title: data.title, code: data.code }),
47
43
  title: data.title,
48
44
  industry: data.industry,
49
45
  regulatoryBody: data.regulatoryBody || null,
50
46
  region: data.region || null,
51
- summary: data.summary || null,
52
- content: data.content || null,
47
+ summary: data.summary ?? null,
48
+ content: data.content ?? null,
53
49
  requirements: data.requirements,
54
50
  sourceUrl: data.sourceUrl || null,
55
51
  tags: data.tags,
56
52
  visibility: 'public',
57
53
  userId,
58
- },
59
- select: { id: true },
60
- })
61
- })
54
+ }),
55
+ }),
56
+ )
@@ -17,20 +17,8 @@
17
17
 
18
18
  import { createServerFn } from '@tanstack/react-start'
19
19
  import { z } from 'zod'
20
- import { getPrisma } from '@allbluecn/database/get-prisma'
21
- import { requireAdmin } from '@/server/auth-helpers'
20
+ import { kpDeleteHandler } from '@/server/knowledge/public/kp-factory'
22
21
 
23
22
  export const adminDeleteComplianceFn = createServerFn({ method: 'POST' })
24
23
  .validator(z.object({ id: z.string() }))
25
- .handler(async ({ data }) => {
26
- const prisma = await getPrisma()
27
- await requireAdmin()
28
- // 直接软删,不存在由 P2025 转错误(省一次 findUnique 往返)
29
- try {
30
- await prisma.industryCompliance.update({ where: { id: data.id }, data: { isDeleted: true } })
31
- } catch (e) {
32
- if ((e as { code?: string }).code === 'P2025') throw new Error('未找到')
33
- throw e
34
- }
35
- return { success: true }
36
- })
24
+ .handler(kpDeleteHandler((prisma) => prisma.industryCompliance))
@@ -17,17 +17,8 @@
17
17
 
18
18
  import { createServerFn } from '@tanstack/react-start'
19
19
  import { z } from 'zod'
20
- import { getPrisma } from '@allbluecn/database/get-prisma'
21
- import { requireAdmin } from '@/server/auth-helpers'
20
+ import { kpDetailHandler } from '@/server/knowledge/public/kp-factory'
22
21
 
23
22
  export const adminGetComplianceDetailFn = createServerFn({ method: 'GET' })
24
23
  .validator(z.object({ id: z.string() }))
25
- .handler(async ({ data }) => {
26
- const prisma = await getPrisma()
27
- await requireAdmin()
28
- const item = await prisma.industryCompliance.findFirst({
29
- where: { id: data.id, visibility: 'public', isDeleted: false },
30
- })
31
- if (!item) throw new Error('未找到')
32
- return item
33
- })
24
+ .handler(kpDetailHandler((prisma) => prisma.industryCompliance))
@@ -15,11 +15,10 @@
15
15
  // You should have received a copy of the GNU Affero General Public License
16
16
  // along with this program. If not, see <https://www.gnu.org/licenses/>.
17
17
 
18
+
18
19
  import { createServerFn } from '@tanstack/react-start'
19
20
  import { z } from 'zod'
20
- import { getPrisma } from '@allbluecn/database/get-prisma'
21
- import { Prisma } from '@allbluecn/database'
22
- import { requireAdmin } from '@/server/auth-helpers'
21
+ import { kpListHandler } from '@/server/knowledge/public/kp-factory'
23
22
 
24
23
  const listSchema = z.object({
25
24
  search: z.string().optional(),
@@ -31,31 +30,25 @@ const listSchema = z.object({
31
30
 
32
31
  export const adminListComplianceFn = createServerFn({ method: 'GET' })
33
32
  .validator(listSchema)
34
- .handler(async ({ data }) => {
35
- const prisma = await getPrisma()
36
- await requireAdmin()
37
- const where: Prisma.IndustryComplianceWhereInput = { visibility: 'public', isDeleted: false }
38
- if (data.search) {
39
- where.OR = [
40
- { title: { contains: data.search, mode: 'insensitive' } },
41
- { summary: { contains: data.search, mode: 'insensitive' } },
42
- ]
43
- }
44
- if (data.industry) where.industry = data.industry
45
- if (data.region) where.region = data.region
46
- const [items, total] = await Promise.all([
47
- prisma.industryCompliance.findMany({
48
- where,
49
- select: {
50
- id: true, canonicalId: true, title: true, industry: true,
51
- regulatoryBody: true, region: true, summary: true, requirements: true,
52
- sourceUrl: true, tags: true, visibility: true, userId: true, createdAt: true,
53
- },
54
- orderBy: { createdAt: 'desc' },
55
- skip: (data.page - 1) * data.pageSize,
56
- take: data.pageSize,
57
- }),
58
- prisma.industryCompliance.count({ where }),
59
- ])
60
- return { items, total, page: data.page, pageSize: data.pageSize }
61
- })
33
+ .handler(
34
+ kpListHandler<z.infer<typeof listSchema>>({
35
+ getDelegate: (prisma) => prisma.industryCompliance,
36
+ buildWhere: (data) => {
37
+ const where: Record<string, unknown> = {}
38
+ if (data.search) {
39
+ where.OR = [
40
+ { title: { contains: data.search, mode: 'insensitive' } },
41
+ { summary: { contains: data.search, mode: 'insensitive' } },
42
+ ]
43
+ }
44
+ if (data.industry) where.industry = data.industry
45
+ if (data.region) where.region = data.region
46
+ return where
47
+ },
48
+ select: {
49
+ id: true, canonicalId: true, title: true, industry: true,
50
+ regulatoryBody: true, region: true, summary: true, requirements: true,
51
+ sourceUrl: true, tags: true, visibility: true, userId: true, createdAt: true,
52
+ },
53
+ }),
54
+ )