mirror of
https://github.com/chaitin/MonkeyCode.git
synced 2026-11-29 16:18:40 +08:00
恢复分组操作并将团队根节点改为虚拟分组
This commit is contained in:
1 parent
56aaed6957
commit
ea342fc0fd
47 files changed
+1856
-748
No files matched your search
@@ -1,250 +0,0 @@
|
||||
import { useCallback, useEffect, useState } from "react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Field, FieldLabel } from "@/components/ui/field"
|
||||
import { api } from "@/lib/api"
|
||||
|
||||
type Group = { id: string; parent_id: string | null; name: string }
|
||||
type Groups = {
|
||||
groups: Group[]
|
||||
memberships: { group_id: string; user_id: string }[]
|
||||
}
|
||||
type User = { id: string; name: string; email: string }
|
||||
const rootID = "00000000-0000-0000-0000-000000000001"
|
||||
const adminID = "00000000-0000-0000-0000-000000000002"
|
||||
const selectClass = "h-9 w-full rounded-md border bg-background px-3 text-sm"
|
||||
|
||||
export function GroupManager() {
|
||||
const [open, setOpen] = useState(false)
|
||||
return (
|
||||
<>
|
||||
<Button variant="outline" size="sm" onClick={() => setOpen(true)}>
|
||||
管理分组
|
||||
</Button>
|
||||
{open && <GroupEditor onClose={() => setOpen(false)} />}
|
||||
</>
|
||||
)
|
||||
}
|
||||
function GroupEditor({ onClose }: { onClose: () => void }) {
|
||||
const [data, setData] = useState<Groups | null>(null)
|
||||
const [users, setUsers] = useState<User[]>([])
|
||||
const [id, setID] = useState("")
|
||||
const [name, setName] = useState("")
|
||||
const [parent, setParent] = useState(rootID)
|
||||
const [members, setMembers] = useState<string[]>([])
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [error, setError] = useState("")
|
||||
const [notice, setNotice] = useState("")
|
||||
const load = useCallback(
|
||||
() =>
|
||||
Promise.all([
|
||||
api<Groups>("/api/admin/v1/groups"),
|
||||
api<{ users: User[] }>("/api/admin/v1/users"),
|
||||
]).then(([g, u]) => {
|
||||
setData(g)
|
||||
setUsers(u.users)
|
||||
}),
|
||||
[]
|
||||
)
|
||||
useEffect(() => {
|
||||
void load().catch((e: Error) => setError(e.message))
|
||||
}, [load])
|
||||
const select = (value: string) => {
|
||||
const g = data?.groups.find((item) => item.id === value)
|
||||
setID(value)
|
||||
setName(g?.name ?? "")
|
||||
setParent(g?.parent_id ?? rootID)
|
||||
setMembers(
|
||||
data?.memberships
|
||||
.filter((m) => m.group_id === value)
|
||||
.map((m) => m.user_id) ?? []
|
||||
)
|
||||
setError("")
|
||||
setNotice("")
|
||||
}
|
||||
const save = async (action: "group" | "members" | "delete") => {
|
||||
setBusy(true)
|
||||
setError("")
|
||||
setNotice("")
|
||||
try {
|
||||
if (action === "group") {
|
||||
const result = await api<{ id: string }>(
|
||||
`/api/admin/v1/groups${id ? `/${id}` : ""}`,
|
||||
{
|
||||
method: id ? "PATCH" : "POST",
|
||||
body: JSON.stringify({ name, parent_id: parent }),
|
||||
}
|
||||
)
|
||||
setID(result.id)
|
||||
}
|
||||
if (action === "members")
|
||||
await api(`/api/admin/v1/groups/${id}/members`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({ user_ids: members }),
|
||||
})
|
||||
if (action === "delete") {
|
||||
await api(`/api/admin/v1/groups/${id}`, { method: "DELETE" })
|
||||
setID("")
|
||||
setName("")
|
||||
setMembers([])
|
||||
}
|
||||
await load()
|
||||
setNotice(action === "delete" ? "空分组已删除" : "分组设置已保存")
|
||||
} catch (e) {
|
||||
setError((e as Error).message)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
const fixed = id === rootID || id === adminID
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
onOpenChange={(v) => {
|
||||
if (!v && !busy) onClose()
|
||||
}}
|
||||
>
|
||||
<DialogContent className="max-h-[85vh] overflow-y-auto sm:max-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>成员分组管理</DialogTitle>
|
||||
<DialogDescription>
|
||||
管理资源授权分组。成员的计费归属请在费用设置中调整。
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
{error && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{notice && (
|
||||
<p role="status" className="text-sm text-muted-foreground">
|
||||
{notice}
|
||||
</p>
|
||||
)}
|
||||
{!data ? (
|
||||
<p>正在读取分组…</p>
|
||||
) : (
|
||||
<div className="space-y-5">
|
||||
<Field>
|
||||
<FieldLabel htmlFor="managed-group">选择分组</FieldLabel>
|
||||
<select
|
||||
id="managed-group"
|
||||
className={selectClass}
|
||||
value={id}
|
||||
onChange={(e) => select(e.target.value)}
|
||||
>
|
||||
<option value="">新建分组</option>
|
||||
{data.groups.map((g) => (
|
||||
<option key={g.id} value={g.id}>
|
||||
{g.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<form
|
||||
className="space-y-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault()
|
||||
void save("group")
|
||||
}}
|
||||
>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="group-name">分组名称</FieldLabel>
|
||||
<Input
|
||||
id="group-name"
|
||||
value={name}
|
||||
required
|
||||
maxLength={100}
|
||||
disabled={fixed}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="group-parent">父分组</FieldLabel>
|
||||
<select
|
||||
id="group-parent"
|
||||
className={selectClass}
|
||||
value={parent}
|
||||
disabled={fixed}
|
||||
onChange={(e) => setParent(e.target.value)}
|
||||
>
|
||||
{data.groups
|
||||
.filter((g) => g.id !== id)
|
||||
.map((g) => (
|
||||
<option key={g.id} value={g.id}>
|
||||
{g.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Button type="submit" disabled={busy || fixed || !name.trim()}>
|
||||
{id ? "保存名称与位置" : "创建分组"}
|
||||
</Button>
|
||||
</form>
|
||||
{id && !fixed && (
|
||||
<div className="space-y-3 border-t pt-4">
|
||||
<p className="text-sm font-medium">授权成员</p>
|
||||
<fieldset className="max-h-64 space-y-2 overflow-y-auto rounded-md border p-3">
|
||||
<legend className="sr-only">分组授权成员</legend>
|
||||
{users.map((u) => (
|
||||
<label
|
||||
key={u.id}
|
||||
className="flex items-center gap-2 text-sm"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={members.includes(u.id)}
|
||||
onChange={(e) =>
|
||||
setMembers(
|
||||
e.target.checked
|
||||
? [...members, u.id]
|
||||
: members.filter((v) => v !== u.id)
|
||||
)
|
||||
}
|
||||
/>
|
||||
{u.name}
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{u.email}
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
<div className="flex justify-between gap-3">
|
||||
<Button disabled={busy} onClick={() => void save("members")}>
|
||||
保存授权成员
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={
|
||||
busy ||
|
||||
members.length > 0 ||
|
||||
data.groups.some((g) => g.parent_id === id)
|
||||
}
|
||||
onClick={() => void save("delete")}
|
||||
>
|
||||
删除空分组
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
仍有计费归属用户或资源授权的分组不能删除,请先迁移相关引用。
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
{fixed && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
系统分组按用户身份自动维护。
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
import { useState, type FormEvent } from "react"
|
||||
import { useTranslation } from "react-i18next"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
import { Field, FieldLabel } from "@/components/ui/field"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
|
||||
import { api } from "@/lib/api"
|
||||
import {
|
||||
ROOT_GROUP_ID,
|
||||
descendantIDs,
|
||||
type MemberGroup,
|
||||
} from "@/lib/member-groups"
|
||||
import { groupActionKeys, type ActiveGroupAction } from "@/lib/member-groups"
|
||||
|
||||
const submitKeys = {
|
||||
"add-subgroup": "createGroup",
|
||||
rename: "saveChanges",
|
||||
"adjust-members": "applyChanges",
|
||||
move: "moveAction",
|
||||
delete: "deleteAction",
|
||||
}
|
||||
|
||||
export function GroupActionDialog({
|
||||
action,
|
||||
group,
|
||||
groups,
|
||||
users,
|
||||
onClose,
|
||||
onSaved,
|
||||
}: ActiveGroupAction & {
|
||||
groups: MemberGroup[]
|
||||
users: Array<{ id: string; name: string; email: string }>
|
||||
onClose: () => void
|
||||
onSaved: (group: MemberGroup | null) => void
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
const [name, setName] = useState(action === "rename" ? group.name : "")
|
||||
const [memberIDs, setMemberIDs] = useState(group.member_ids)
|
||||
const [query, setQuery] = useState("")
|
||||
const [parentID, setParentID] = useState("")
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [error, setError] = useState("")
|
||||
const excluded = descendantIDs(groups, group.id)
|
||||
const targets = groups.filter(
|
||||
(candidate) =>
|
||||
!excluded.has(candidate.id) && candidate.id !== group.parent_id
|
||||
)
|
||||
const normalized = query.trim().toLocaleLowerCase()
|
||||
const visible = users.filter((user) =>
|
||||
`${user.name} ${user.email}`.toLocaleLowerCase().includes(normalized)
|
||||
)
|
||||
const titleKey = groupActionKeys[action]
|
||||
const hasChildren = groups.some(
|
||||
(candidate) => candidate.parent_id === group.id
|
||||
)
|
||||
|
||||
const targetPath = (candidate: MemberGroup) => {
|
||||
const names = [candidate.name]
|
||||
const visited = new Set([candidate.id])
|
||||
let parent = groups.find((item) => item.id === candidate.parent_id)
|
||||
while (parent && !visited.has(parent.id)) {
|
||||
names.unshift(parent.name)
|
||||
visited.add(parent.id)
|
||||
parent = groups.find((item) => item.id === parent?.parent_id)
|
||||
}
|
||||
return names.join(" / ")
|
||||
}
|
||||
|
||||
const submit = async (event: FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault()
|
||||
if (saving) return
|
||||
setSaving(true)
|
||||
setError("")
|
||||
try {
|
||||
const path = `/api/admin/v1/groups/${group.id}`
|
||||
let updated: MemberGroup | null = null
|
||||
if (action === "delete") {
|
||||
await api<void>(path, { method: "DELETE" })
|
||||
} else if (action === "add-subgroup") {
|
||||
updated = await api<MemberGroup>("/api/admin/v1/groups", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
name: name.trim(),
|
||||
parent_id: group.id === ROOT_GROUP_ID ? null : group.id,
|
||||
}),
|
||||
})
|
||||
} else if (action === "adjust-members") {
|
||||
updated = await api<MemberGroup>(`${path}/members`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({ member_ids: memberIDs }),
|
||||
})
|
||||
} else {
|
||||
updated = await api<MemberGroup>(path, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify(
|
||||
action === "rename"
|
||||
? { name: name.trim() }
|
||||
: { parent_id: parentID === ROOT_GROUP_ID ? null : parentID }
|
||||
),
|
||||
})
|
||||
}
|
||||
onSaved(updated)
|
||||
} catch (reason) {
|
||||
setError((reason as Error).message)
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
onOpenChange={(open) => {
|
||||
if (!open && !saving) onClose()
|
||||
}}
|
||||
>
|
||||
<DialogContent
|
||||
className="max-h-[calc(100dvh-2rem)] overflow-y-auto sm:max-w-lg"
|
||||
closeLabel={t("common.close")}
|
||||
showCloseButton={!saving}
|
||||
>
|
||||
<form
|
||||
className="flex flex-col gap-6"
|
||||
onSubmit={submit}
|
||||
aria-busy={saving}
|
||||
>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t(`pages.membersAndGroups.${titleKey}`)}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{t(`pages.membersAndGroups.${titleKey}DialogDescription`, {
|
||||
group: group.name,
|
||||
})}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
{error && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{(action === "add-subgroup" || action === "rename") && (
|
||||
<Field>
|
||||
<FieldLabel htmlFor="group-name">
|
||||
{t("pages.membersAndGroups.groupName")}
|
||||
</FieldLabel>
|
||||
<Input
|
||||
id="group-name"
|
||||
value={name}
|
||||
onChange={(event) => setName(event.target.value)}
|
||||
required
|
||||
maxLength={100}
|
||||
autoFocus
|
||||
disabled={saving}
|
||||
placeholder={t("pages.membersAndGroups.groupNamePlaceholder")}
|
||||
/>
|
||||
</Field>
|
||||
)}
|
||||
{action === "adjust-members" && (
|
||||
<div className="flex flex-col gap-3">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("pages.membersAndGroups.directMembersHint")}
|
||||
</p>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="group-member-search" className="sr-only">
|
||||
{t("pages.membersAndGroups.searchMembers")}
|
||||
</FieldLabel>
|
||||
<Input
|
||||
id="group-member-search"
|
||||
value={query}
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
placeholder={t(
|
||||
"pages.membersAndGroups.searchMembersPlaceholder"
|
||||
)}
|
||||
type="search"
|
||||
autoFocus
|
||||
/>
|
||||
</Field>
|
||||
<div
|
||||
className="flex max-h-80 flex-col gap-2 overflow-y-auto"
|
||||
role="group"
|
||||
aria-label={t("pages.membersAndGroups.selectMembers")}
|
||||
>
|
||||
{visible.map((user) => (
|
||||
<Field
|
||||
key={user.id}
|
||||
orientation="horizontal"
|
||||
className="min-w-0 rounded-md p-2 hover:bg-muted"
|
||||
>
|
||||
<Checkbox
|
||||
id={`group-member-${user.id}`}
|
||||
checked={memberIDs.includes(user.id)}
|
||||
disabled={saving}
|
||||
onCheckedChange={(checked) =>
|
||||
setMemberIDs((current) =>
|
||||
checked
|
||||
? [...current, user.id]
|
||||
: current.filter((id) => id !== user.id)
|
||||
)
|
||||
}
|
||||
/>
|
||||
<FieldLabel
|
||||
htmlFor={`group-member-${user.id}`}
|
||||
className="min-w-0 flex-1 cursor-pointer flex-col items-start gap-0"
|
||||
>
|
||||
<span className="max-w-full truncate">{user.name}</span>
|
||||
<span className="max-w-full truncate text-xs text-muted-foreground">
|
||||
{user.email}
|
||||
</span>
|
||||
</FieldLabel>
|
||||
</Field>
|
||||
))}
|
||||
{!visible.length && (
|
||||
<p className="py-6 text-center text-sm text-muted-foreground">
|
||||
{t("pages.membersAndGroups.noMembersFound")}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{action === "move" && (
|
||||
<Field>
|
||||
<FieldLabel>
|
||||
{t("pages.membersAndGroups.targetParentGroup")}
|
||||
</FieldLabel>
|
||||
{targets.length ? (
|
||||
<RadioGroup
|
||||
value={parentID}
|
||||
onValueChange={setParentID}
|
||||
disabled={saving}
|
||||
className="max-h-72 overflow-y-auto"
|
||||
aria-label={t("pages.membersAndGroups.targetParentGroup")}
|
||||
>
|
||||
{targets.map((candidate) => (
|
||||
<Field
|
||||
key={candidate.id}
|
||||
orientation="horizontal"
|
||||
className="min-w-0 rounded-md p-2 hover:bg-muted"
|
||||
>
|
||||
<RadioGroupItem
|
||||
id={`group-parent-${candidate.id}`}
|
||||
value={candidate.id}
|
||||
/>
|
||||
<FieldLabel
|
||||
htmlFor={`group-parent-${candidate.id}`}
|
||||
className="min-w-0 flex-1 cursor-pointer break-words"
|
||||
>
|
||||
{targetPath(candidate)}
|
||||
</FieldLabel>
|
||||
</Field>
|
||||
))}
|
||||
</RadioGroup>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("pages.membersAndGroups.noMoveTargets")}
|
||||
</p>
|
||||
)}
|
||||
</Field>
|
||||
)}
|
||||
{action === "delete" && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t(
|
||||
`pages.membersAndGroups.${hasChildren ? "deleteChildrenHint" : "deleteMembersHint"}`
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
<DialogFooter>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={saving}
|
||||
onClick={onClose}
|
||||
>
|
||||
{t("pages.membersAndGroups.cancelAction")}
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
variant={action === "delete" ? "destructive" : "default"}
|
||||
disabled={
|
||||
saving ||
|
||||
((action === "rename" || action === "add-subgroup") &&
|
||||
!name.trim()) ||
|
||||
(action === "move" && !parentID) ||
|
||||
(action === "delete" && hasChildren)
|
||||
}
|
||||
>
|
||||
{saving
|
||||
? t("common.saving")
|
||||
: t(`pages.membersAndGroups.${submitKeys[action]}`)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
import { useState } from "react"
|
||||
import {
|
||||
Add01Icon,
|
||||
Delete02Icon,
|
||||
Edit02Icon,
|
||||
Folder02Icon,
|
||||
FolderIcon,
|
||||
MoreHorizontalIcon,
|
||||
MoveIcon,
|
||||
UserMultiple02Icon,
|
||||
} from "@hugeicons/core-free-icons"
|
||||
import { HugeiconsIcon } from "@hugeicons/react"
|
||||
import { useTranslation } from "react-i18next"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Collapsible,
|
||||
CollapsibleContent,
|
||||
CollapsibleTrigger,
|
||||
} from "@/components/ui/collapsible"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import {
|
||||
groupActionKeys,
|
||||
type GroupAction,
|
||||
type ActiveGroupAction,
|
||||
ROOT_GROUP_ID,
|
||||
groupMemberIDs,
|
||||
descendantIDs,
|
||||
type MemberGroup,
|
||||
} from "@/lib/member-groups"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const actionIcons = {
|
||||
"add-subgroup": Add01Icon,
|
||||
rename: Edit02Icon,
|
||||
"adjust-members": UserMultiple02Icon,
|
||||
move: MoveIcon,
|
||||
delete: Delete02Icon,
|
||||
}
|
||||
|
||||
type Props = {
|
||||
group: MemberGroup
|
||||
groups: MemberGroup[]
|
||||
users: Array<{ id: string; role: "admin" | "user" }>
|
||||
selectedID: string
|
||||
onSelect: (id: string) => void
|
||||
onAction: (action: ActiveGroupAction) => void
|
||||
level?: number
|
||||
}
|
||||
|
||||
export function GroupTreeItem({
|
||||
group,
|
||||
groups,
|
||||
users,
|
||||
selectedID,
|
||||
onSelect,
|
||||
onAction,
|
||||
level = 0,
|
||||
}: Props) {
|
||||
const { t } = useTranslation()
|
||||
const [expanded, setExpanded] = useState(true)
|
||||
const open =
|
||||
expanded ||
|
||||
(selectedID !== group.id && descendantIDs(groups, group.id).has(selectedID))
|
||||
const children = groups.filter((child) => child.parent_id === group.id)
|
||||
const isRoot = group.id === ROOT_GROUP_ID
|
||||
const actions: GroupAction[] = isRoot
|
||||
? ["add-subgroup"]
|
||||
: ["add-subgroup", "rename", "adjust-members", "move", "delete"]
|
||||
const count = groupMemberIDs(groups, users, group.id).size
|
||||
const label = (
|
||||
<>
|
||||
<HugeiconsIcon
|
||||
icon={children.length && open ? Folder02Icon : FolderIcon}
|
||||
strokeWidth={2}
|
||||
/>
|
||||
<span className="truncate">{group.name}</span>
|
||||
</>
|
||||
)
|
||||
const selectButton = (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
aria-pressed={selectedID === group.id}
|
||||
className="min-w-0 flex-1 justify-start font-normal hover:bg-transparent! aria-expanded:bg-transparent!"
|
||||
style={{ paddingInlineStart: `${level * 1.25 + 0.5}rem` }}
|
||||
onClick={() => onSelect(group.id)}
|
||||
/>
|
||||
)
|
||||
|
||||
return (
|
||||
<li>
|
||||
<Collapsible open={open} onOpenChange={setExpanded}>
|
||||
<div
|
||||
className={cn(
|
||||
"group/group-row flex items-center rounded-md hover:bg-muted",
|
||||
selectedID === group.id && "bg-muted"
|
||||
)}
|
||||
>
|
||||
{children.length ? (
|
||||
<CollapsibleTrigger render={selectButton}>
|
||||
{label}
|
||||
</CollapsibleTrigger>
|
||||
) : (
|
||||
<Button {...selectButton.props}>{label}</Button>
|
||||
)}
|
||||
<span className="px-2 text-xs text-muted-foreground tabular-nums">
|
||||
{count}
|
||||
</span>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger
|
||||
render={
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
className="shrink-0 cursor-pointer"
|
||||
aria-label={`${group.name} · ${t("pages.membersAndGroups.groupActions")}`}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<HugeiconsIcon icon={MoreHorizontalIcon} strokeWidth={2} />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuGroup>
|
||||
{actions
|
||||
.filter((action) => action !== "delete")
|
||||
.map((action) => (
|
||||
<DropdownMenuItem
|
||||
key={action}
|
||||
onClick={() => onAction({ action, group })}
|
||||
>
|
||||
<HugeiconsIcon
|
||||
icon={actionIcons[action]}
|
||||
strokeWidth={2}
|
||||
/>
|
||||
{t(`pages.membersAndGroups.${groupActionKeys[action]}`)}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuGroup>
|
||||
{!isRoot && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuGroup>
|
||||
<DropdownMenuItem
|
||||
variant="destructive"
|
||||
onClick={() => onAction({ action: "delete", group })}
|
||||
>
|
||||
<HugeiconsIcon icon={Delete02Icon} strokeWidth={2} />
|
||||
{t("pages.membersAndGroups.deleteGroup")}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuGroup>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
{children.length > 0 && (
|
||||
<CollapsibleContent>
|
||||
<ul className="flex flex-col gap-1">
|
||||
{children.map((child) => (
|
||||
<GroupTreeItem
|
||||
key={child.id}
|
||||
group={child}
|
||||
groups={groups}
|
||||
users={users}
|
||||
selectedID={selectedID}
|
||||
onSelect={onSelect}
|
||||
onAction={onAction}
|
||||
level={level + 1}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
</CollapsibleContent>
|
||||
)}
|
||||
</Collapsible>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ROOT_GROUP, useSubjects } from "@/lib/resources"
|
||||
import { useSubjects } from "@/lib/resources"
|
||||
import { useRef, useState, type ChangeEvent } from "react"
|
||||
import {
|
||||
ArrowDown01Icon,
|
||||
@@ -117,7 +117,7 @@ export function SkillImportWizard({
|
||||
const [selectedTagIds, setSelectedTagIds] = useState<string[]>([])
|
||||
const [authorizationOpen, setAuthorizationOpen] = useState(false)
|
||||
const [authorization, setAuthorization] = useState<AuthorizationSelection>({
|
||||
groupIds: [ROOT_GROUP],
|
||||
groupIds: [],
|
||||
memberIds: [],
|
||||
})
|
||||
const requestId = useRef(0)
|
||||
|
||||
@@ -462,6 +462,12 @@ export const ar = {
|
||||
"هل تريد حذف قاعدة «{{rule}}»؟ لا يمكن التراجع عن هذا الإجراء.",
|
||||
},
|
||||
membersAndGroups: {
|
||||
directMembersHint:
|
||||
"يتغير الانضمام المباشر فقط. يظل أعضاء المجموعات الفرعية ظاهرين هنا.",
|
||||
deleteChildrenHint:
|
||||
"انقل المجموعات الفرعية أو احذفها قبل حذف هذه المجموعة.",
|
||||
deleteMembersHint:
|
||||
"ستُحفظ حسابات الأعضاء. ستُزال عضويات هذه المجموعة وصلاحيات مواردها.",
|
||||
title: "الأعضاء والمجموعات",
|
||||
description: "أدِر الأعضاء والمجموعات وصلاحيات وصولهم إلى الموارد.",
|
||||
groupsTitle: "المجموعات",
|
||||
|
||||
@@ -481,6 +481,12 @@ export const deDE = {
|
||||
"„{{rule}}“ löschen? Diese Aktion kann nicht rückgängig gemacht werden.",
|
||||
},
|
||||
membersAndGroups: {
|
||||
directMembersHint:
|
||||
"Nur direkte Mitgliedschaften werden geändert. Mitglieder von Untergruppen bleiben sichtbar.",
|
||||
deleteChildrenHint:
|
||||
"Verschieben oder löschen Sie zuerst die Untergruppen.",
|
||||
deleteMembersHint:
|
||||
"Mitgliedskonten bleiben erhalten. Mitgliedschaften und Ressourcenrechte dieser Gruppe werden entfernt.",
|
||||
title: "Mitglieder und Gruppen",
|
||||
description:
|
||||
"Verwalten Sie Mitglieder, Gruppen und deren Zugriff auf Ressourcen.",
|
||||
|
||||
@@ -609,6 +609,12 @@ export const enUS = {
|
||||
'Delete "{{rule}}"? This action cannot be undone.',
|
||||
},
|
||||
membersAndGroups: {
|
||||
directMembersHint:
|
||||
"Only direct membership is changed; members of subgroups remain visible here.",
|
||||
deleteChildrenHint:
|
||||
"Move or delete subgroups before deleting this group.",
|
||||
deleteMembersHint:
|
||||
"Member accounts are kept. Memberships and resource grants for this group will be removed.",
|
||||
title: "Members & Groups",
|
||||
description: "Manage members, groups, and their access to resources.",
|
||||
groupsTitle: "Groups",
|
||||
|
||||
@@ -478,6 +478,12 @@ export const es419 = {
|
||||
'¿Eliminar "{{rule}}"? Esta acción no se puede deshacer.',
|
||||
},
|
||||
membersAndGroups: {
|
||||
directMembersHint:
|
||||
"Solo se cambia la membresía directa. Los miembros de subgrupos seguirán visibles.",
|
||||
deleteChildrenHint:
|
||||
"Mueve o elimina los subgrupos antes de eliminar este grupo.",
|
||||
deleteMembersHint:
|
||||
"Las cuentas se conservan. Se eliminarán las membresías y los permisos de recursos de este grupo.",
|
||||
title: "Miembros y grupos",
|
||||
description: "Administra miembros, grupos y su acceso a los recursos.",
|
||||
groupsTitle: "Grupos",
|
||||
|
||||
@@ -476,6 +476,12 @@ export const frFR = {
|
||||
"Supprimer « {{rule}} » ? Cette action est irréversible.",
|
||||
},
|
||||
membersAndGroups: {
|
||||
directMembersHint:
|
||||
"Seules les appartenances directes sont modifiées. Les membres des sous-groupes restent visibles.",
|
||||
deleteChildrenHint:
|
||||
"Déplacez ou supprimez les sous-groupes avant de supprimer ce groupe.",
|
||||
deleteMembersHint:
|
||||
"Les comptes sont conservés. Les appartenances et les autorisations de ressources de ce groupe seront supprimées.",
|
||||
title: "Membres et groupes",
|
||||
description:
|
||||
"Gérez les membres, les groupes et leurs accès aux ressources.",
|
||||
|
||||
@@ -469,6 +469,11 @@ export const jaJP = {
|
||||
"「{{rule}}」を削除しますか?この操作は元に戻せません。",
|
||||
},
|
||||
membersAndGroups: {
|
||||
directMembersHint:
|
||||
"直接所属するメンバーのみ変更します。子グループのメンバーは引き続き表示されます。",
|
||||
deleteChildrenHint: "先に子グループを移動または削除してください。",
|
||||
deleteMembersHint:
|
||||
"メンバーのアカウントは保持されます。このグループの所属情報とリソース権限は削除されます。",
|
||||
title: "メンバーとグループ",
|
||||
description: "メンバー、グループ、リソースへのアクセス範囲を管理します。",
|
||||
groupsTitle: "グループ",
|
||||
|
||||
@@ -463,6 +463,12 @@ export const koKR = {
|
||||
'"{{rule}}" 규칙을 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다.',
|
||||
},
|
||||
membersAndGroups: {
|
||||
directMembersHint:
|
||||
"직접 소속된 멤버만 변경합니다. 하위 그룹의 멤버는 계속 표시됩니다.",
|
||||
deleteChildrenHint:
|
||||
"이 그룹을 삭제하기 전에 하위 그룹을 이동하거나 삭제하세요.",
|
||||
deleteMembersHint:
|
||||
"멤버 계정은 유지됩니다. 이 그룹의 소속 관계와 리소스 권한은 삭제됩니다.",
|
||||
title: "구성원 및 그룹",
|
||||
description: "구성원, 그룹 및 리소스 접근 범위를 관리합니다.",
|
||||
groupsTitle: "그룹",
|
||||
|
||||
@@ -475,6 +475,11 @@ export const ruRU = {
|
||||
"Удалить правило «{{rule}}»? Это действие нельзя отменить.",
|
||||
},
|
||||
membersAndGroups: {
|
||||
directMembersHint:
|
||||
"Изменяется только прямое членство. Участники подгрупп по-прежнему отображаются здесь.",
|
||||
deleteChildrenHint: "Сначала переместите или удалите подгруппы.",
|
||||
deleteMembersHint:
|
||||
"Аккаунты участников сохранятся. Членство и разрешения на ресурсы этой группы будут удалены.",
|
||||
title: "Участники и группы",
|
||||
description: "Управляйте участниками, группами и их доступом к ресурсам.",
|
||||
groupsTitle: "Группы",
|
||||
|
||||
@@ -576,6 +576,10 @@ export const zhCN = {
|
||||
deleteDialogDescription: "确定删除“{{rule}}”吗?此操作无法撤销。",
|
||||
},
|
||||
membersAndGroups: {
|
||||
directMembersHint:
|
||||
"仅调整直接加入本组的成员;子分组成员仍会显示在本组中。",
|
||||
deleteChildrenHint: "请先移动或删除子分组,再删除此分组。",
|
||||
deleteMembersHint: "成员账号会保留;本组的成员关系与资源授权将一并移除。",
|
||||
title: "成员与分组",
|
||||
description: "管理成员、分组及其资源访问范围。",
|
||||
groupsTitle: "分组",
|
||||
|
||||
@@ -447,6 +447,9 @@ export const zhTW = {
|
||||
deleteDialogDescription: "確定刪除「{{rule}}」嗎?此操作無法復原。",
|
||||
},
|
||||
membersAndGroups: {
|
||||
directMembersHint: "僅調整直接加入本組的成員;子分組成員仍會顯示於本組。",
|
||||
deleteChildrenHint: "請先移動或刪除子分組,再刪除此分組。",
|
||||
deleteMembersHint: "成員帳號會保留;本組的成員關係與資源授權將一併移除。",
|
||||
title: "成員與群組",
|
||||
description: "管理成員、群組及其資源存取範圍。",
|
||||
groupsTitle: "群組",
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
export type MemberGroup = {
|
||||
id: string
|
||||
parent_id: string | null
|
||||
name: string
|
||||
member_ids: string[]
|
||||
}
|
||||
|
||||
export const ROOT_GROUP_ID = "team"
|
||||
|
||||
export function descendantIDs(groups: MemberGroup[], id: string): Set<string> {
|
||||
const children = new Map<string, string[]>()
|
||||
for (const group of groups) {
|
||||
if (group.parent_id) {
|
||||
const siblings = children.get(group.parent_id) ?? []
|
||||
siblings.push(group.id)
|
||||
children.set(group.parent_id, siblings)
|
||||
}
|
||||
}
|
||||
const ids = new Set([id])
|
||||
for (const current of ids) {
|
||||
for (const child of children.get(current) ?? []) ids.add(child)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
export function groupMemberIDs(
|
||||
groups: MemberGroup[],
|
||||
users: Array<{ id: string; role: "admin" | "user" }>,
|
||||
id: string
|
||||
): Set<string> {
|
||||
if (id === ROOT_GROUP_ID) {
|
||||
return new Set(users.map((user) => user.id))
|
||||
}
|
||||
const ids = descendantIDs(groups, id)
|
||||
return new Set(
|
||||
groups
|
||||
.filter((group) => ids.has(group.id))
|
||||
.flatMap((group) => group.member_ids)
|
||||
)
|
||||
}
|
||||
|
||||
export type GroupAction =
|
||||
"add-subgroup" | "rename" | "adjust-members" | "move" | "delete"
|
||||
export type ActiveGroupAction = { action: GroupAction; group: MemberGroup }
|
||||
|
||||
export const groupActionKeys: Record<GroupAction, string> = {
|
||||
"add-subgroup": "addSubgroup",
|
||||
rename: "renameGroup",
|
||||
"adjust-members": "adjustMembers",
|
||||
move: "moveGroup",
|
||||
delete: "deleteGroup",
|
||||
}
|
||||
@@ -5,7 +5,6 @@ import type {
|
||||
AuthorizationGroupNode,
|
||||
AuthorizationMember,
|
||||
} from "@/lib/authorization-groups"
|
||||
export const ROOT_GROUP = "00000000-0000-0000-0000-000000000001"
|
||||
export type Grant = {
|
||||
user_id?: string | null
|
||||
group_id?: string | null
|
||||
@@ -159,7 +158,7 @@ export function useSubjects() {
|
||||
children: tree(g.id),
|
||||
}))
|
||||
setGroups(tree())
|
||||
setMembers(data.users.map((u) => ({ ...u, groupId: ROOT_GROUP })))
|
||||
setMembers(data.users.map((u) => ({ ...u, groupId: "" })))
|
||||
})
|
||||
.catch((e) => {
|
||||
if (!cancelled) setError(e.message)
|
||||
|
||||
@@ -1,10 +1,5 @@
|
||||
import { useEffect, useMemo, useState, type FormEvent } from "react"
|
||||
import {
|
||||
Add01Icon,
|
||||
Folder02Icon,
|
||||
FolderIcon,
|
||||
MoreHorizontalIcon,
|
||||
} from "@hugeicons/core-free-icons"
|
||||
import { Add01Icon, MoreHorizontalIcon } from "@hugeicons/core-free-icons"
|
||||
import { HugeiconsIcon } from "@hugeicons/react"
|
||||
import { useTranslation } from "react-i18next"
|
||||
|
||||
@@ -46,10 +41,16 @@ import {
|
||||
ItemSeparator,
|
||||
ItemTitle,
|
||||
} from "@/components/ui/item"
|
||||
import { GroupManager } from "@/components/group-manager"
|
||||
import { useAuth } from "@/hooks/use-auth"
|
||||
import { api } from "@/lib/api"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { GroupActionDialog } from "@/components/members/group-action-dialog"
|
||||
import { GroupTreeItem } from "@/components/members/group-tree"
|
||||
import {
|
||||
type ActiveGroupAction,
|
||||
ROOT_GROUP_ID,
|
||||
groupMemberIDs,
|
||||
type MemberGroup,
|
||||
} from "@/lib/member-groups"
|
||||
|
||||
type User = {
|
||||
id: string
|
||||
@@ -62,13 +63,16 @@ type User = {
|
||||
last_login_at?: string
|
||||
}
|
||||
|
||||
type GroupID = "all" | User["role"]
|
||||
|
||||
export function MembersAndGroupsPage() {
|
||||
const { i18n, t } = useTranslation()
|
||||
const { user: currentUser } = useAuth()
|
||||
const [users, setUsers] = useState<User[]>([])
|
||||
const [selectedGroupID, setSelectedGroupID] = useState<GroupID>("all")
|
||||
const [selectedGroupID, setSelectedGroupID] = useState(ROOT_GROUP_ID)
|
||||
const [teamName, setTeamName] = useState("Monkey AI")
|
||||
const [groups, setGroups] = useState<MemberGroup[]>([])
|
||||
const [activeGroupAction, setActiveGroupAction] =
|
||||
useState<ActiveGroupAction | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [query, setQuery] = useState("")
|
||||
const [error, setError] = useState("")
|
||||
const [savingID, setSavingID] = useState("")
|
||||
@@ -84,9 +88,23 @@ export function MembersAndGroupsPage() {
|
||||
})
|
||||
|
||||
const load = () => {
|
||||
api<{ users: User[] }>("/api/admin/v1/users")
|
||||
.then((result) => setUsers(result.users))
|
||||
Promise.all([
|
||||
api<{ users: User[] }>("/api/admin/v1/users"),
|
||||
api<{ groups: MemberGroup[] }>("/api/admin/v1/groups"),
|
||||
api<{
|
||||
settings: Array<{ key: string; value: { workspace_name?: string } }>
|
||||
}>("/api/admin/v1/settings"),
|
||||
])
|
||||
.then(([members, result, { settings }]) => {
|
||||
setUsers(members.users)
|
||||
setGroups(result.groups)
|
||||
setTeamName(
|
||||
settings.find((item) => item.key === "branding")?.value
|
||||
.workspace_name || "Monkey AI"
|
||||
)
|
||||
})
|
||||
.catch((reason: Error) => setError(reason.message))
|
||||
.finally(() => setLoading(false))
|
||||
}
|
||||
|
||||
useEffect(load, [])
|
||||
@@ -123,14 +141,15 @@ export function MembersAndGroupsPage() {
|
||||
|
||||
const visibleUsers = useMemo(() => {
|
||||
const normalizedQuery = query.trim().toLocaleLowerCase()
|
||||
const memberIDs = groupMemberIDs(groups, users, selectedGroupID)
|
||||
return users.filter(
|
||||
(user) =>
|
||||
(selectedGroupID === "all" || user.role === selectedGroupID) &&
|
||||
memberIDs.has(user.id) &&
|
||||
(!normalizedQuery ||
|
||||
user.name.toLocaleLowerCase().includes(normalizedQuery) ||
|
||||
user.email.toLocaleLowerCase().includes(normalizedQuery))
|
||||
)
|
||||
}, [query, selectedGroupID, users])
|
||||
}, [groups, query, selectedGroupID, users])
|
||||
|
||||
const createUser = async (event: FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault()
|
||||
@@ -169,22 +188,18 @@ export function MembersAndGroupsPage() {
|
||||
i18n.resolvedLanguage ?? i18n.language,
|
||||
{ dateStyle: "medium" }
|
||||
)
|
||||
const groups: Array<{ id: GroupID; label: string; count: number }> = [
|
||||
{
|
||||
id: "all",
|
||||
label: t("pages.membersAndGroups.groupNames.rootGroup"),
|
||||
count: users.length,
|
||||
},
|
||||
{
|
||||
id: "admin",
|
||||
label: t("pages.membersAndGroups.groupNames.administrators"),
|
||||
count: users.filter((user) => user.role === "admin").length,
|
||||
},
|
||||
{
|
||||
id: "user",
|
||||
label: t("pages.membersAndGroups.membersTitle"),
|
||||
count: users.filter((user) => user.role === "user").length,
|
||||
},
|
||||
const root: MemberGroup = {
|
||||
id: ROOT_GROUP_ID,
|
||||
parent_id: null,
|
||||
name: teamName,
|
||||
member_ids: [],
|
||||
}
|
||||
const displayGroups = [
|
||||
root,
|
||||
...groups.map((group) => ({
|
||||
...group,
|
||||
parent_id: group.parent_id ?? ROOT_GROUP_ID,
|
||||
})),
|
||||
]
|
||||
|
||||
return (
|
||||
@@ -193,40 +208,25 @@ export function MembersAndGroupsPage() {
|
||||
<Card className="min-h-64 md:min-h-0">
|
||||
<CardHeader>
|
||||
<CardTitle>{t("pages.membersAndGroups.groupsTitle")}</CardTitle>
|
||||
<CardAction>
|
||||
<GroupManager />
|
||||
</CardAction>
|
||||
</CardHeader>
|
||||
<CardContent className="min-h-0 flex-1 overflow-y-auto">
|
||||
<ul
|
||||
className="flex flex-col gap-1"
|
||||
aria-label={t("pages.membersAndGroups.groupsTitle")}
|
||||
>
|
||||
{groups.map((group, index) => (
|
||||
<li key={group.id}>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
aria-pressed={selectedGroupID === group.id}
|
||||
className={cn(
|
||||
"w-full justify-start font-normal hover:bg-muted",
|
||||
index > 0 && "ps-8",
|
||||
selectedGroupID === group.id && "bg-muted"
|
||||
)}
|
||||
onClick={() => setSelectedGroupID(group.id)}
|
||||
>
|
||||
<HugeiconsIcon
|
||||
icon={group.id === "all" ? Folder02Icon : FolderIcon}
|
||||
strokeWidth={2}
|
||||
/>
|
||||
<span className="truncate">{group.label}</span>
|
||||
<span className="ms-auto text-xs text-muted-foreground tabular-nums">
|
||||
{group.count}
|
||||
</span>
|
||||
</Button>
|
||||
</li>
|
||||
))}
|
||||
{displayGroups
|
||||
.filter((group) => group.parent_id === null)
|
||||
.map((group) => (
|
||||
<GroupTreeItem
|
||||
key={group.id}
|
||||
group={group}
|
||||
groups={displayGroups}
|
||||
users={users}
|
||||
selectedID={selectedGroupID}
|
||||
onSelect={setSelectedGroupID}
|
||||
onAction={setActiveGroupAction}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
</CardContent>
|
||||
</Card>
|
||||
@@ -264,6 +264,14 @@ export function MembersAndGroupsPage() {
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{loading && (
|
||||
<p
|
||||
role="status"
|
||||
className="py-6 text-center text-sm text-muted-foreground"
|
||||
>
|
||||
{t("common.loading")}
|
||||
</p>
|
||||
)}
|
||||
<ItemGroup className="gap-2">
|
||||
{visibleUsers.map((user) => {
|
||||
const isDisabled = user.status === "disabled"
|
||||
@@ -378,7 +386,7 @@ export function MembersAndGroupsPage() {
|
||||
</Item>
|
||||
)
|
||||
})}
|
||||
{visibleUsers.length === 0 && (
|
||||
{!loading && visibleUsers.length === 0 && (
|
||||
<p className="py-12 text-center text-sm text-muted-foreground">
|
||||
{t("pages.membersAndGroups.noMembersFound")}
|
||||
</p>
|
||||
@@ -388,6 +396,40 @@ export function MembersAndGroupsPage() {
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{activeGroupAction && (
|
||||
<GroupActionDialog
|
||||
key={`${activeGroupAction.action}-${activeGroupAction.group.id}`}
|
||||
{...activeGroupAction}
|
||||
groups={displayGroups}
|
||||
users={users}
|
||||
onClose={() => setActiveGroupAction(null)}
|
||||
onSaved={(updated) => {
|
||||
if (updated) {
|
||||
setGroups((current) =>
|
||||
current.some((group) => group.id === updated.id)
|
||||
? current.map((group) =>
|
||||
group.id === updated.id ? updated : group
|
||||
)
|
||||
: [...current, updated]
|
||||
)
|
||||
setSelectedGroupID(updated.id)
|
||||
} else {
|
||||
setGroups((current) =>
|
||||
current.filter(
|
||||
(group) => group.id !== activeGroupAction.group.id
|
||||
)
|
||||
)
|
||||
if (selectedGroupID === activeGroupAction.group.id)
|
||||
setSelectedGroupID(
|
||||
activeGroupAction.group.parent_id ?? ROOT_GROUP_ID
|
||||
)
|
||||
}
|
||||
setError("")
|
||||
setActiveGroupAction(null)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
<Dialog open={createOpen} onOpenChange={setCreateOpen}>
|
||||
<DialogContent>
|
||||
<form className="flex flex-col gap-6" onSubmit={createUser}>
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { api } from "@/lib/api"
|
||||
import {
|
||||
base,
|
||||
ROOT_GROUP,
|
||||
grants,
|
||||
selection,
|
||||
match,
|
||||
@@ -121,7 +120,7 @@ export function RulesPage() {
|
||||
const [authorizationOpen, setAuthorizationOpen] = useState(false)
|
||||
const [forcedScopeOpen, setForcedScopeOpen] = useState(false)
|
||||
const [forcedScope, setForcedScope] = useState<AuthorizationSelection>({
|
||||
groupIds: [ROOT_GROUP],
|
||||
groupIds: [],
|
||||
memberIds: [],
|
||||
})
|
||||
const editingRule = rules.find((rule) => rule.id === editingRuleId)
|
||||
@@ -129,7 +128,7 @@ export function RulesPage() {
|
||||
const resetRuleOptions = () => {
|
||||
setForcedScopeOpen(false)
|
||||
setAuthorization({ groupIds: [], memberIds: [] })
|
||||
setForcedScope({ groupIds: [ROOT_GROUP], memberIds: [] })
|
||||
setForcedScope({ groupIds: [], memberIds: [] })
|
||||
}
|
||||
|
||||
const handleDialogOpenChange = (open: boolean) => {
|
||||
@@ -147,9 +146,7 @@ export function RulesPage() {
|
||||
|
||||
setAuthorization(rule.authorization)
|
||||
setEditingRuleId(rule.id)
|
||||
setForcedScope(
|
||||
rule.forcedScope ?? { groupIds: [ROOT_GROUP], memberIds: [] }
|
||||
)
|
||||
setForcedScope(rule.forcedScope ?? { groupIds: [], memberIds: [] })
|
||||
setForcedScopeOpen(false)
|
||||
setDialogOpen(true)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { api } from "@/lib/api"
|
||||
import {
|
||||
base,
|
||||
ROOT_GROUP,
|
||||
grants,
|
||||
selection,
|
||||
match,
|
||||
@@ -171,7 +170,7 @@ export function SkillsPage() {
|
||||
const [authorizationOpen, setAuthorizationOpen] = useState(false)
|
||||
const [tagsOpen, setTagsOpen] = useState(false)
|
||||
const [authorization, setAuthorization] = useState<AuthorizationSelection>({
|
||||
groupIds: [ROOT_GROUP],
|
||||
groupIds: [],
|
||||
memberIds: [],
|
||||
})
|
||||
const [draft, setDraft] = useState<SkillDraft>(EMPTY_SKILL_DRAFT)
|
||||
@@ -188,7 +187,7 @@ export function SkillsPage() {
|
||||
packageRequestId.current += 1
|
||||
setAuthorizationOpen(false)
|
||||
setTagsOpen(false)
|
||||
setAuthorization({ groupIds: [ROOT_GROUP], memberIds: [] })
|
||||
setAuthorization({ groupIds: [], memberIds: [] })
|
||||
setDraft(EMPTY_SKILL_DRAFT)
|
||||
setPackageAnalysis(null)
|
||||
setPackageFile(null)
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { api } from "@/lib/api"
|
||||
import {
|
||||
base,
|
||||
ROOT_GROUP,
|
||||
grants,
|
||||
selection,
|
||||
match,
|
||||
@@ -191,7 +190,7 @@ export function ToolsPage() {
|
||||
const [centralizedAuthorized, setCentralizedAuthorized] = useState(false)
|
||||
const [authorizationOpen, setAuthorizationOpen] = useState(false)
|
||||
const [authorization, setAuthorization] = useState<AuthorizationSelection>({
|
||||
groupIds: [ROOT_GROUP],
|
||||
groupIds: [],
|
||||
memberIds: [],
|
||||
})
|
||||
const [testingServerId, setTestingServerId] = useState<string | null>(null)
|
||||
@@ -262,7 +261,7 @@ export function ToolsPage() {
|
||||
setAuthorizationMethod("oauth")
|
||||
setCentralizedAuthorized(false)
|
||||
setAuthorizationOpen(false)
|
||||
setAuthorization({ groupIds: [ROOT_GROUP], memberIds: [] })
|
||||
setAuthorization({ groupIds: [], memberIds: [] })
|
||||
}
|
||||
|
||||
const handleDialogOpenChange = (open: boolean) => {
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import assert from "node:assert/strict"
|
||||
import test from "node:test"
|
||||
import { ROOT_GROUP_ID, descendantIDs, groupMemberIDs } from "../src/lib/member-groups.ts"
|
||||
|
||||
const groups = [
|
||||
{ id: "parent", parent_id: null, name: "研发", member_ids: ["a"] },
|
||||
{ id: "child", parent_id: "parent", name: "前端", member_ids: ["a", "b"] },
|
||||
{ id: "other", parent_id: null, name: "产品", member_ids: ["c"] },
|
||||
]
|
||||
const users = [{ id: "a", role: "user" }, { id: "b", role: "admin" }, { id: "c", role: "user" }]
|
||||
|
||||
test("父分组成员包含后代且跨组去重,移动后更新继承", () => {
|
||||
assert.deepEqual([...groupMemberIDs(groups, users, "parent")].sort(), ["a", "b"])
|
||||
const moved = groups.map((group) => group.id === "child" ? { ...group, parent_id: "other" } : group)
|
||||
assert.deepEqual([...groupMemberIDs(moved, users, "parent")], ["a"])
|
||||
assert.deepEqual([...groupMemberIDs(moved, users, "other")].sort(), ["a", "b", "c"])
|
||||
})
|
||||
|
||||
test("虚拟团队根节点包含全部用户,空数据库也可显示成员", () => {
|
||||
assert.equal(groupMemberIDs([], users, ROOT_GROUP_ID).size, 3)
|
||||
assert.equal(groupMemberIDs(groups, users, ROOT_GROUP_ID).size, 3)
|
||||
assert.deepEqual([...groupMemberIDs(groups, users, "other")], ["c"])
|
||||
assert.equal(groupMemberIDs(groups, users, "missing").size, 0)
|
||||
})
|
||||
|
||||
test("分组成员仅由关联决定,不根据角色和顶层位置自动加入", () => {
|
||||
const empty = { id: "custom", name: "管理员", parent_id: null, member_ids: [] }
|
||||
assert.equal(groupMemberIDs([...groups, empty], users, empty.id).size, 0)
|
||||
const moved = groups.map((group) => group.id === "child" ? { ...group, parent_id: null } : group)
|
||||
assert.deepEqual([...groupMemberIDs(moved, users, "parent")], ["a"])
|
||||
assert.deepEqual([...groupMemberIDs(moved, users, "child")].sort(), ["a", "b"])
|
||||
})
|
||||
|
||||
test("移动目标排除自身和全部后代,并可处理重复访问", () => {
|
||||
assert.deepEqual([...descendantIDs(groups, "parent")], ["parent", "child"])
|
||||
assert.deepEqual([...descendantIDs([...groups, { id: "parent", parent_id: "child", member_ids: [] }], "parent")], ["parent", "child"])
|
||||
})
|
||||
@@ -152,6 +152,6 @@ export MONKEYAI_S3_SECRET_KEY='测试访问密钥密码'
|
||||
go test ./... -count=1
|
||||
```
|
||||
|
||||
集成测试创建独立随机 schema,测试结束后删除该 schema,不重置其他 schema;必须使用测试数据库和测试 Bucket。测试包括版本 1 的 up/down/up、Cookie 管理员身份与 Agent Bearer 身份、权限差异、配置 ETag、技能字节上传/重建/下载、专家委托、撤权、真实 MCP HTTP 协议、用户目录隔离及本地 OAuth state/PKCE 回调防重放。测试可能留下不可变技能对象,仅位于测试 Bucket。
|
||||
集成测试创建独立随机 schema,测试结束后删除该 schema,不重置其他 schema;必须使用测试数据库和测试 Bucket。测试包括版本 1 的 up/down/up、版本 2 的计费升级、版本 3 的旧系统分组升级与授权和额度保留、虚拟团队根节点及分组操作、Cookie 管理员身份与 Agent Bearer 身份、权限差异、配置 ETag、技能字节上传/重建/下载、专家委托、撤权、真实 MCP HTTP 协议、用户目录隔离及本地 OAuth state/PKCE 回调防重放。测试可能留下不可变技能对象,仅位于测试 Bucket。
|
||||
|
||||
各业务服务显式注册到 `internal/app`。`resource.CRUD` 只接收服务端定义的表名和字段白名单,业务约束及关系事务由 `rule`、`skill`、`expert`、`mcp` 提供。Agent 配置在同一个 PostgreSQL Repeatable Read 视图中聚合,读取失败会使整个请求失败。
|
||||
+180
-152
@@ -135,12 +135,12 @@ paths:
|
||||
properties:
|
||||
id:
|
||||
type: string
|
||||
format: uuid
|
||||
description: 分组 UUID 或虚拟团队标识 team。
|
||||
parent_id:
|
||||
type:
|
||||
- string
|
||||
- 'null'
|
||||
format: uuid
|
||||
description: 父分组 UUID、team 或 null(仅虚拟团队节点)。
|
||||
name:
|
||||
type: string
|
||||
credits:
|
||||
@@ -163,7 +163,7 @@ paths:
|
||||
type: string
|
||||
group_id:
|
||||
type: string
|
||||
format: uuid
|
||||
description: 计费分组 UUID;无指定归属时为 team。
|
||||
credits:
|
||||
anyOf:
|
||||
- $ref: '#/components/schemas/CreditAmount'
|
||||
@@ -207,12 +207,12 @@ paths:
|
||||
properties:
|
||||
id:
|
||||
type: string
|
||||
format: uuid
|
||||
description: 分组 UUID 或虚拟团队标识 team。
|
||||
parent_id:
|
||||
type:
|
||||
- string
|
||||
- 'null'
|
||||
format: uuid
|
||||
description: 父分组 UUID、team 或 null(仅虚拟团队节点)。
|
||||
name:
|
||||
type: string
|
||||
credits:
|
||||
@@ -235,7 +235,7 @@ paths:
|
||||
type: string
|
||||
group_id:
|
||||
type: string
|
||||
format: uuid
|
||||
description: 计费分组 UUID;无指定归属时为 team。
|
||||
credits:
|
||||
anyOf:
|
||||
- $ref: '#/components/schemas/CreditAmount'
|
||||
@@ -282,7 +282,7 @@ paths:
|
||||
- group
|
||||
id:
|
||||
type: string
|
||||
format: uuid
|
||||
description: 用户或分组 UUID;团队默认额度使用 team。
|
||||
credits:
|
||||
anyOf:
|
||||
- $ref: '#/components/schemas/CreditAmount'
|
||||
@@ -778,177 +778,141 @@ paths:
|
||||
- reason
|
||||
/api/admin/v1/groups:
|
||||
get:
|
||||
summary: 查询真实分组和成员授权关系
|
||||
summary: 查询成员分组
|
||||
description: 返回全部未删除分组及直接成员。团队根节点不入库,名称由 branding.workspace_name 设置提供;parent_id 为 null 的分组均为团队根节点的直属子分组,不预置任何分组。
|
||||
responses:
|
||||
'200':
|
||||
description: 请求成功
|
||||
"200":
|
||||
description: 分组列表
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
groups:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
properties:
|
||||
id:
|
||||
type: string
|
||||
format: uuid
|
||||
parent_id:
|
||||
type:
|
||||
- string
|
||||
- 'null'
|
||||
format: uuid
|
||||
name:
|
||||
type: string
|
||||
memberships:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
properties:
|
||||
group_id:
|
||||
type: string
|
||||
format: uuid
|
||||
user_id:
|
||||
type: string
|
||||
format: uuid
|
||||
'400':
|
||||
description: 参数不合法
|
||||
'401':
|
||||
description: 未登录
|
||||
'403':
|
||||
description: 权限不足
|
||||
'409':
|
||||
description: 修订号、幂等键或交易状态冲突
|
||||
$ref: "#/components/schemas/MemberGroupsResponse"
|
||||
"401":
|
||||
$ref: "#/components/responses/Unauthorized"
|
||||
"403":
|
||||
$ref: "#/components/responses/Forbidden"
|
||||
"500":
|
||||
$ref: "#/components/responses/ResourceError500"
|
||||
post:
|
||||
summary: 创建分组
|
||||
responses:
|
||||
'200':
|
||||
description: 请求成功
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
id:
|
||||
type: string
|
||||
format: uuid
|
||||
'400':
|
||||
description: 参数不合法
|
||||
'401':
|
||||
description: 未登录
|
||||
'403':
|
||||
description: 权限不足
|
||||
'409':
|
||||
description: 修订号、幂等键或交易状态冲突
|
||||
summary: 创建子分组
|
||||
description: 名称去除首尾空白后须为 1—100 个字符,同级名称不区分大小写且不能重复。parent_id 为 null 或省略时,创建团队根节点的直属子分组。
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
name:
|
||||
type: string
|
||||
parent_id:
|
||||
type: string
|
||||
format: uuid
|
||||
required:
|
||||
- name
|
||||
- parent_id
|
||||
$ref: "#/components/schemas/CreateMemberGroupInput"
|
||||
responses:
|
||||
"201":
|
||||
description: 已创建分组
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/MemberGroup"
|
||||
"400":
|
||||
$ref: "#/components/responses/ResourceError400"
|
||||
"401":
|
||||
$ref: "#/components/responses/Unauthorized"
|
||||
"403":
|
||||
$ref: "#/components/responses/Forbidden"
|
||||
"404":
|
||||
$ref: "#/components/responses/ResourceError404"
|
||||
"409":
|
||||
$ref: "#/components/responses/ResourceError409"
|
||||
"500":
|
||||
$ref: "#/components/responses/ResourceError500"
|
||||
/api/admin/v1/groups/{groupID}:
|
||||
parameters:
|
||||
- in: path
|
||||
name: groupID
|
||||
schema:
|
||||
type: string
|
||||
format: uuid
|
||||
required: true
|
||||
- in: path
|
||||
name: groupID
|
||||
required: true
|
||||
description: 分组 UUID。
|
||||
schema:
|
||||
type: string
|
||||
format: uuid
|
||||
patch:
|
||||
summary: 改名或移动分组,禁止父子环
|
||||
summary: 修改分组名称或上级分组
|
||||
description: 至少指定 name 或 parent_id。parent_id 为 null 表示移动到团队根节点下,省略则保留原上级。不能移动到自身或后代中;更换上级会改变成员继承的资源授权。
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/MemberGroupInput"
|
||||
responses:
|
||||
'200':
|
||||
description: 请求成功
|
||||
"200":
|
||||
description: 已更新分组
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
id:
|
||||
type: string
|
||||
format: uuid
|
||||
'400':
|
||||
description: 参数不合法
|
||||
'401':
|
||||
description: 未登录
|
||||
'403':
|
||||
description: 权限不足
|
||||
'409':
|
||||
description: 修订号、幂等键或交易状态冲突
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
name:
|
||||
type: string
|
||||
parent_id:
|
||||
type: string
|
||||
format: uuid
|
||||
required:
|
||||
- name
|
||||
- parent_id
|
||||
$ref: "#/components/schemas/MemberGroup"
|
||||
"400":
|
||||
$ref: "#/components/responses/ResourceError400"
|
||||
"401":
|
||||
$ref: "#/components/responses/Unauthorized"
|
||||
"403":
|
||||
$ref: "#/components/responses/Forbidden"
|
||||
"404":
|
||||
$ref: "#/components/responses/ResourceError404"
|
||||
"409":
|
||||
$ref: "#/components/responses/ResourceError409"
|
||||
"500":
|
||||
$ref: "#/components/responses/ResourceError500"
|
||||
delete:
|
||||
summary: 删除无引用的自定义分组
|
||||
summary: 删除分组
|
||||
description: 有子分组或成员计费归属引用时返回 409。软删除分组、移除直接成员关系并清除本组资源授权,保留成员账号。
|
||||
responses:
|
||||
'204':
|
||||
description: 删除成功
|
||||
'400':
|
||||
description: 参数不合法
|
||||
'401':
|
||||
description: 未登录
|
||||
'403':
|
||||
description: 权限不足
|
||||
'409':
|
||||
description: 修订号、幂等键或交易状态冲突
|
||||
"204":
|
||||
description: 已删除,无响应体。
|
||||
"400":
|
||||
$ref: "#/components/responses/ResourceError400"
|
||||
"401":
|
||||
$ref: "#/components/responses/Unauthorized"
|
||||
"403":
|
||||
$ref: "#/components/responses/Forbidden"
|
||||
"404":
|
||||
$ref: "#/components/responses/ResourceError404"
|
||||
"409":
|
||||
$ref: "#/components/responses/ResourceError409"
|
||||
"500":
|
||||
$ref: "#/components/responses/ResourceError500"
|
||||
/api/admin/v1/groups/{groupID}/members:
|
||||
parameters:
|
||||
- in: path
|
||||
name: groupID
|
||||
schema:
|
||||
type: string
|
||||
format: uuid
|
||||
required: true
|
||||
- in: path
|
||||
name: groupID
|
||||
required: true
|
||||
description: 分组 UUID。
|
||||
schema:
|
||||
type: string
|
||||
format: uuid
|
||||
put:
|
||||
summary: 更新分组授权成员,计费归属保持独立
|
||||
responses:
|
||||
'204':
|
||||
description: 更新成功
|
||||
'400':
|
||||
description: 参数不合法
|
||||
'401':
|
||||
description: 未登录
|
||||
'403':
|
||||
description: 权限不足
|
||||
'409':
|
||||
description: 修订号、幂等键或交易状态冲突
|
||||
summary: 替换分组直接成员
|
||||
description: 仅调整直接成员关系,不改变用户角色或子分组成员。空数组清空直接成员,重复 ID 自动去重。所有数据库分组均通过显式成员关系管理。
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
user_ids:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
format: uuid
|
||||
required:
|
||||
- user_ids
|
||||
$ref: "#/components/schemas/MemberGroupMembersInput"
|
||||
responses:
|
||||
"200":
|
||||
description: 已更新成员关系
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/MemberGroup"
|
||||
"400":
|
||||
$ref: "#/components/responses/ResourceError400"
|
||||
"401":
|
||||
$ref: "#/components/responses/Unauthorized"
|
||||
"403":
|
||||
$ref: "#/components/responses/Forbidden"
|
||||
"404":
|
||||
$ref: "#/components/responses/ResourceError404"
|
||||
"409":
|
||||
$ref: "#/components/responses/ResourceError409"
|
||||
"500":
|
||||
$ref: "#/components/responses/ResourceError500"
|
||||
/api/admin/v1/users/{userID}/billing-group:
|
||||
parameters:
|
||||
- in: path
|
||||
@@ -3462,6 +3426,68 @@ components:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ErrorResponse"
|
||||
schemas:
|
||||
CreateMemberGroupInput:
|
||||
allOf:
|
||||
- $ref: "#/components/schemas/MemberGroupInput"
|
||||
- type: object
|
||||
required: [name]
|
||||
MemberGroupMembersInput:
|
||||
type: object
|
||||
required: [member_ids]
|
||||
properties:
|
||||
member_ids:
|
||||
type: array
|
||||
maxItems: 10000
|
||||
description: 完整的直接成员 ID 列表,空数组表示清空,重复 ID 自动去重;用户须存在且未删除。
|
||||
items:
|
||||
type: string
|
||||
format: uuid
|
||||
MemberGroupInput:
|
||||
type: object
|
||||
minProperties: 1
|
||||
anyOf:
|
||||
- required: [name]
|
||||
- required: [parent_id]
|
||||
properties:
|
||||
name:
|
||||
type: string
|
||||
minLength: 1
|
||||
maxLength: 100
|
||||
description: 去除首尾空白后不能为空;同级名称不区分大小写且不能重复。
|
||||
parent_id:
|
||||
type: [string, "null"]
|
||||
format: uuid
|
||||
description: 新上级分组 ID,必须是有效分组;null 表示团队根节点,更新时省略则保留原值。
|
||||
MemberGroupsResponse:
|
||||
type: object
|
||||
required: [groups]
|
||||
properties:
|
||||
groups:
|
||||
type: array
|
||||
description: 未删除的分组列表,按创建时间和 ID 排序。
|
||||
items:
|
||||
$ref: "#/components/schemas/MemberGroup"
|
||||
MemberGroup:
|
||||
type: object
|
||||
required: [id, parent_id, name, member_ids]
|
||||
properties:
|
||||
id:
|
||||
type: string
|
||||
format: uuid
|
||||
description: 分组唯一标识。
|
||||
parent_id:
|
||||
type: [string, "null"]
|
||||
format: uuid
|
||||
description: 上级分组 ID;null 表示该分组直属团队根节点。
|
||||
name:
|
||||
type: string
|
||||
description: 分组显示名称。
|
||||
member_ids:
|
||||
type: array
|
||||
description: 未删除用户的直接分组关系,不含子分组成员,也不按用户角色自动分配。
|
||||
items:
|
||||
type: string
|
||||
format: uuid
|
||||
CreditAmount:
|
||||
type: string
|
||||
pattern: ^-?\d+(\.\d{1,6})?$
|
||||
@@ -3482,6 +3508,8 @@ components:
|
||||
BillingPolicy:
|
||||
type: object
|
||||
properties:
|
||||
root_credits:
|
||||
$ref: "#/components/schemas/CreditAmount"
|
||||
revision:
|
||||
type: integer
|
||||
enabled:
|
||||
@@ -3544,7 +3572,7 @@ components:
|
||||
format: uuid
|
||||
group_id:
|
||||
type: string
|
||||
format: uuid
|
||||
description: 计费分组 UUID;未指定归属时为空字符串。
|
||||
period_start_at:
|
||||
type: string
|
||||
format: date-time
|
||||
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/config"
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/database"
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/expert"
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/group"
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/httpapi"
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/identity"
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/mcp"
|
||||
@@ -123,6 +124,7 @@ func newApplicationHandler(ctx context.Context, logger *slog.Logger, pool *pgxpo
|
||||
admin := chi.NewRouter()
|
||||
admin.Use(identities.RequireAdmin)
|
||||
identities.RegisterAdmin(admin)
|
||||
group.NewService(pool).WithAccountPreserver(charges).RegisterAdmin(admin)
|
||||
settings.RegisterAdmin(admin)
|
||||
charges.RegisterAdmin(admin)
|
||||
keys.RegisterAdmin(admin)
|
||||
|
||||
@@ -108,6 +108,32 @@ func TestBillingIntegration(t *testing.T) {
|
||||
if err = pool.QueryRow(ctx, `SELECT id FROM users WHERE email='billing-http@example.com'`).Scan(&user); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
groups := must("GET", "/api/admin/v1/groups", nil, "")
|
||||
if len(groups["groups"].([]any)) != 0 {
|
||||
t.Fatal("启动应用不应初始化分组")
|
||||
}
|
||||
quotas := must("GET", "/api/admin/v1/billing/quotas", nil, "")
|
||||
team := resource.Object(quotas["groups"].([]any)[0].(map[string]any))
|
||||
if team.String("id") != "team" || team["parent_id"] != nil {
|
||||
t.Fatalf("团队额度根节点: %v", team)
|
||||
}
|
||||
must("PUT", "/api/admin/v1/billing/quotas", resource.Object{"revision": quotas.Int("revision"), "changes": []resource.Object{{"subject_type": "group", "id": "team", "credits": "12345"}}}, "")
|
||||
updated := must("GET", "/api/admin/v1/billing/quotas", nil, "")
|
||||
if resource.Object(updated["users"].([]any)[0].(map[string]any)).String("effective_credits") != "12345" {
|
||||
t.Fatalf("团队额度继承: %v", updated)
|
||||
}
|
||||
top := must("POST", "/api/admin/v1/groups", resource.Object{"name": "研发", "parent_id": nil}, "")
|
||||
if top["parent_id"] != nil {
|
||||
t.Fatalf("顶层分组入库父级不为 null: %v", top)
|
||||
}
|
||||
must("PATCH", "/api/admin/v1/groups/"+top.String("id"), resource.Object{"name": "研发组"}, "")
|
||||
must("PUT", "/api/admin/v1/groups/"+top.String("id")+"/members", resource.Object{"member_ids": []string{user}}, "")
|
||||
must("PUT", "/api/admin/v1/users/"+user+"/billing-group", resource.Object{"group_id": top.String("id")}, "")
|
||||
if code, _, _ := call("DELETE", "/api/admin/v1/groups/"+top.String("id"), nil, "", ""); code != 409 {
|
||||
t.Fatalf("计费归属引用应阻止删除: %d", code)
|
||||
}
|
||||
must("PUT", "/api/admin/v1/users/"+user+"/billing-group", resource.Object{"group_id": nil}, "")
|
||||
must("DELETE", "/api/admin/v1/groups/"+top.String("id"), nil, "")
|
||||
hash := sha256.Sum256([]byte("billing-oauth-test"))
|
||||
if _, err = pool.Exec(ctx, `INSERT INTO oauth_tokens(user_id,client_id,access_token_hash,refresh_token_hash,access_expires_at,refresh_expires_at) VALUES($1,'test',$2,'billing-refresh',now()+interval '1 hour',now()+interval '2 hours')`, user, hex.EncodeToString(hash[:])); err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -288,11 +288,12 @@ func TestResourceIntegration(t *testing.T) {
|
||||
if code, _, _ := call("GET", "/api/v1/connectors/"+conn.String("id")+"/tools", nil, "b", ""); code != 404 {
|
||||
t.Fatalf("工具目录越权: %d", code)
|
||||
}
|
||||
rootRule := must("POST", "/api/admin/v1/rules", resource.Object{"name": "强制规则", "content": "强制", "grants": []resource.Object{{"group_id": "00000000-0000-0000-0000-000000000001", "usage_requirement": "required"}}}, "", "")
|
||||
_ = rootRule
|
||||
allGroup := must("POST", "/api/admin/v1/groups", resource.Object{"name": "资源测试组", "parent_id": nil}, "", "")
|
||||
must("PUT", "/api/admin/v1/groups/"+allGroup.String("id")+"/members", resource.Object{"member_ids": users}, "", "")
|
||||
must("POST", "/api/admin/v1/rules", resource.Object{"name": "强制规则", "content": "强制", "grants": []resource.Object{{"group_id": allGroup.String("id"), "usage_requirement": "required"}}}, "", "")
|
||||
resolved = must("POST", "/api/v1/resources/resolve", resource.Object{}, "b", "")
|
||||
if len(resolved["rules"].([]any)) != 1 {
|
||||
t.Fatal("根组强制规则缺失")
|
||||
t.Fatal("显式分组的强制规则缺失")
|
||||
}
|
||||
must("PUT", "/api/admin/v1/experts/"+expert.String("id"), resource.Object{"name": "专家", "description": "测试", "prompt": "审查代码", "rule_ids": []string{rule.String("id")}, "skill_ids": []string{skill.String("id")}, "providers": []any{}, "grants": []any{}}, "", `"1"`)
|
||||
if code, _, _ := call("GET", "/api/v1/experts/"+expert.String("id")+"/skills/"+skill.String("id")+"/package", nil, "a", ""); code != 404 {
|
||||
@@ -317,7 +318,7 @@ func TestResourceIntegration(t *testing.T) {
|
||||
}))
|
||||
defer independent.Close()
|
||||
p2 := must("POST", "/api/admin/v1/connector-providers", resource.Object{"name": "独立 MCP", "identifier": "independent", "url": independent.URL, "authorization_mode": "independent", "authorization_method": "http_header"}, "", "")
|
||||
c2 := must("POST", "/api/admin/v1/connectors", resource.Object{"name": "独立连接", "description": "按用户隔离", "provider_id": p2.String("id"), "grants": []resource.Object{{"group_id": "00000000-0000-0000-0000-000000000001", "usage_requirement": "optional"}}}, "", "")
|
||||
c2 := must("POST", "/api/admin/v1/connectors", resource.Object{"name": "独立连接", "description": "按用户隔离", "provider_id": p2.String("id"), "grants": []resource.Object{{"group_id": allGroup.String("id"), "usage_requirement": "optional"}}}, "", "")
|
||||
for i, name := range []string{"a", "b"} {
|
||||
must("PUT", "/api/v1/connectors/"+c2.String("id")+"/credential", resource.Object{"http_headers": resource.Object{"X-Account": "Tool-" + name}}, name, "")
|
||||
must("POST", "/api/v1/connectors/"+c2.String("id")+"/test", nil, name, "")
|
||||
@@ -389,7 +390,7 @@ func TestResourceIntegration(t *testing.T) {
|
||||
// 父分组授权覆盖后代成员,删除父分组后不再继承失效授权。
|
||||
adminUser := must("GET", "/api/admin/v1/me", nil, "", "")
|
||||
parentID, childID := resource.ID(), resource.ID()
|
||||
if _, err = pool.Exec(ctx, `INSERT INTO groups(id,parent_id,name) VALUES($1,'00000000-0000-0000-0000-000000000001','测试父分组'),($2,$1,'测试子分组')`, parentID, childID); err != nil {
|
||||
if _, err = pool.Exec(ctx, `INSERT INTO groups(id,parent_id,name) VALUES($1,NULL,'测试父分组'),($2,$1,'测试子分组')`, parentID, childID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = pool.Exec(ctx, `INSERT INTO group_users(group_id,user_id,assigned_by_user_id) VALUES($1,$2,$3)`, childID, users[0], adminUser.String("id")); err != nil {
|
||||
@@ -415,8 +416,8 @@ func TestResourceIntegration(t *testing.T) {
|
||||
t.Fatal("仍继承已删除分组的授权")
|
||||
}
|
||||
|
||||
// 可丢弃测试库按版本逆序撤销,再完整初始化。
|
||||
for i := len(migrations) - 1; i >= 0; i-- {
|
||||
// 虚拟根的数据转换不可逆;可丢弃测试库从初始结构重建。
|
||||
for i := 1; i >= 0; i-- {
|
||||
down, err := os.ReadFile(strings.Replace(migrations[i], ".up.sql", ".down.sql", 1))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -93,6 +93,42 @@ func testModelSharing(t *testing.T, pool *pgxpool.Pool, handler http.Handler, us
|
||||
assertAccess(users[0], ids[0], true)
|
||||
assertAccess(users[1], ids[0], false)
|
||||
assertAccess(adminID, ids[0], false)
|
||||
parentGroup, childGroup := resource.ID(), resource.ID()
|
||||
if _, err := pool.Exec(ctx, `INSERT INTO groups(id,parent_id,name) VALUES($1,NULL,'模型测试组'),($2,$1,'模型测试子组')`, parentGroup, childGroup); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := pool.Exec(ctx, `INSERT INTO resource_access_grants(resource_type,resource_id,group_id,access_level,granted_by_user_id) VALUES('model',$1,$2,'read_only',$3)`, ids[0], parentGroup, users[0]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertAccess(users[1], ids[0], false)
|
||||
assertAccess(adminID, ids[0], false)
|
||||
assertGroupModels := func(want int) {
|
||||
t.Helper()
|
||||
available, err := repo.ListAvailable(ctx, users[1], false)
|
||||
if err != nil || len(available) != want {
|
||||
t.Fatalf("分组模型可见数=%d,预期 %d,err=%v", len(available), want, err)
|
||||
}
|
||||
}
|
||||
assertGroupModels(0)
|
||||
if _, err := pool.Exec(ctx, `INSERT INTO group_users(group_id,user_id,assigned_by_user_id) VALUES($1,$2,$3)`, childGroup, users[1], adminID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertAccess(users[1], ids[0], true)
|
||||
assertGroupModels(1)
|
||||
if _, err := pool.Exec(ctx, `UPDATE groups SET parent_id=NULL WHERE id=$1`, childGroup); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertAccess(users[1], ids[0], false)
|
||||
assertGroupModels(0)
|
||||
if _, err := pool.Exec(ctx, `DELETE FROM resource_access_grants WHERE group_id=$1`, parentGroup); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := pool.Exec(ctx, `DELETE FROM group_users WHERE group_id=$1`, childGroup); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := pool.Exec(ctx, `DELETE FROM groups WHERE id=ANY($1::uuid[])`, []string{parentGroup, childGroup}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
call("GET", "/models/"+ids[0], "b", nil, 404)
|
||||
call("PUT", "/models/"+ids[0], "b", input, 404)
|
||||
call("DELETE", "/models/"+ids[0], "sharing-admin", nil, 404)
|
||||
|
||||
@@ -165,21 +165,29 @@ func (s *Service) saveSettings(w http.ResponseWriter, r *http.Request) {
|
||||
s.settings(w, r)
|
||||
}
|
||||
func (s *Service) quotas(w http.ResponseWriter, r *http.Request) {
|
||||
groups, err := resource.Rows(r.Context(), s.pool, `SELECT jsonb_build_object('id',g.id,'parent_id',g.parent_id,'name',g.name,'credits',q.credits_per_cycle::text) FROM groups g LEFT JOIN billing_quotas q ON q.group_id=g.id AND q.deleted_at IS NULL WHERE g.deleted_at IS NULL ORDER BY g.name,g.id`)
|
||||
if err != nil {
|
||||
resource.Fail(w, err)
|
||||
return
|
||||
}
|
||||
users, err := resource.Rows(r.Context(), s.pool, `WITH RECURSIVE ancestors AS (SELECT id child,id ancestor,parent_id,0 depth FROM groups WHERE deleted_at IS NULL UNION ALL SELECT a.child,g.id,g.parent_id,a.depth+1 FROM ancestors a JOIN groups g ON g.id=a.parent_id WHERE g.deleted_at IS NULL AND a.depth<100) SELECT jsonb_build_object('id',u.id,'name',u.name,'email',u.email,'status',u.status,'group_id',COALESCE(u.billing_group_id,CASE WHEN u.role='admin' THEN $2::uuid ELSE $1::uuid END),'credits',q.credits_per_cycle::text,'effective_credits',COALESCE(q.credits_per_cycle,g.credits_per_cycle,15000)::text,'inherited_from',CASE WHEN q.id IS NOT NULL THEN u.id ELSE COALESCE(g.ancestor,$1::uuid) END,'external_user_id',wb.external_user_id) FROM users u LEFT JOIN billing_quotas q ON q.user_id=u.id AND q.deleted_at IS NULL LEFT JOIN LATERAL (SELECT b.credits_per_cycle,a.ancestor FROM ancestors a JOIN billing_quotas b ON b.group_id=a.ancestor AND b.deleted_at IS NULL WHERE a.child=COALESCE(u.billing_group_id,CASE WHEN u.role='admin' THEN $2::uuid ELSE $1::uuid END) ORDER BY a.depth LIMIT 1) g ON true LEFT JOIN wallet_user_bindings wb ON wb.user_id=u.id WHERE u.deleted_at IS NULL ORDER BY u.name,u.id`, rootGroup, adminGroup)
|
||||
if err != nil {
|
||||
resource.Fail(w, err)
|
||||
return
|
||||
}
|
||||
p, err := s.Policy(r.Context())
|
||||
if err != nil {
|
||||
resource.Fail(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
groups, err := resource.Rows(r.Context(), s.pool, `SELECT jsonb_build_object('id',g.id,'parent_id',COALESCE(g.parent_id::text,'team'),'name',g.name,'credits',q.credits_per_cycle::text) FROM groups g LEFT JOIN billing_quotas q ON q.group_id=g.id AND q.deleted_at IS NULL WHERE g.deleted_at IS NULL ORDER BY g.name,g.id`)
|
||||
if err != nil {
|
||||
resource.Fail(w, err)
|
||||
return
|
||||
}
|
||||
users, err := resource.Rows(r.Context(), s.pool, `WITH RECURSIVE ancestors AS (SELECT id child,id ancestor,parent_id,0 depth FROM groups WHERE deleted_at IS NULL UNION ALL SELECT a.child,g.id,g.parent_id,a.depth+1 FROM ancestors a JOIN groups g ON g.id=a.parent_id WHERE g.deleted_at IS NULL AND a.depth<100) SELECT jsonb_build_object('id',u.id,'name',u.name,'email',u.email,'status',u.status,'group_id',COALESCE(u.billing_group_id::text,$1::text),'credits',q.credits_per_cycle::text,'effective_credits',COALESCE(q.credits_per_cycle,g.credits_per_cycle,$2::numeric)::text,'inherited_from',CASE WHEN q.id IS NOT NULL THEN u.id::text ELSE COALESCE(g.ancestor::text,$1::text) END,'external_user_id',wb.external_user_id) FROM users u LEFT JOIN billing_quotas q ON q.user_id=u.id AND q.deleted_at IS NULL LEFT JOIN LATERAL (SELECT b.credits_per_cycle,a.ancestor FROM ancestors a JOIN billing_quotas b ON b.group_id=a.ancestor AND b.deleted_at IS NULL WHERE a.child=u.billing_group_id ORDER BY a.depth LIMIT 1) g ON true LEFT JOIN wallet_user_bindings wb ON wb.user_id=u.id WHERE u.deleted_at IS NULL ORDER BY u.name,u.id`, rootGroup, p.RootCredits.String())
|
||||
if err != nil {
|
||||
resource.Fail(w, err)
|
||||
return
|
||||
}
|
||||
var teamName string
|
||||
err = s.pool.QueryRow(r.Context(), `SELECT COALESCE((SELECT NULLIF(value->>'workspace_name','') FROM settings WHERE key='branding'),'Monkey AI')`).Scan(&teamName)
|
||||
if err != nil {
|
||||
resource.Fail(w, err)
|
||||
return
|
||||
}
|
||||
groups = append([]resource.Object{{"id": rootGroup, "parent_id": nil, "name": teamName, "credits": p.RootCredits.String()}}, groups...)
|
||||
_, end := p.period(s.now())
|
||||
resource.JSON(w, 200, map[string]any{"groups": groups, "users": users, "revision": p.Revision, "effective_at": end})
|
||||
}
|
||||
@@ -232,9 +240,22 @@ func (s *Service) saveQuotas(w http.ResponseWriter, r *http.Request) {
|
||||
resource.Fail(w, resource.Invalid("额度需为非负积分或 null"))
|
||||
return
|
||||
}
|
||||
if v.ID == rootGroup && amount == nil {
|
||||
resource.Fail(w, resource.Invalid("根分组必须设置额度"))
|
||||
return
|
||||
if v.Type == "group" && v.ID == rootGroup {
|
||||
if amount == nil {
|
||||
resource.Fail(w, resource.Invalid("团队必须设置额度"))
|
||||
return
|
||||
}
|
||||
before := p.RootCredits
|
||||
p.RootCredits = *amount
|
||||
if _, err = tx.Exec(r.Context(), `UPDATE settings SET value=jsonb_set(value,'{root_credits}',to_jsonb($1::text)) WHERE key='billing'`, amount.String()); err != nil {
|
||||
resource.Fail(w, err)
|
||||
return
|
||||
}
|
||||
if err = audit(r.Context(), tx, u.ID, "configure_quota", "", map[string]any{"subject_type": "team", "before": before, "after": amount}); err != nil {
|
||||
resource.Fail(w, err)
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
var exists bool
|
||||
err = tx.QueryRow(r.Context(), `SELECT CASE WHEN $2='group' THEN EXISTS(SELECT 1 FROM groups WHERE id=$1 AND deleted_at IS NULL) ELSE EXISTS(SELECT 1 FROM users WHERE id=$1 AND deleted_at IS NULL) END`, v.ID, v.Type).Scan(&exists)
|
||||
|
||||
@@ -12,8 +12,7 @@ import (
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
const rootGroup = "00000000-0000-0000-0000-000000000001"
|
||||
const adminGroup = "00000000-0000-0000-0000-000000000002"
|
||||
const rootGroup = "team"
|
||||
|
||||
type Price struct {
|
||||
Input Amount `json:"input"`
|
||||
@@ -23,6 +22,7 @@ type Price struct {
|
||||
Tool Amount `json:"tool"`
|
||||
}
|
||||
type Policy struct {
|
||||
RootCredits Amount `json:"root_credits"`
|
||||
Input Amount `json:"input_credits_per_million_tokens"`
|
||||
Cached Amount `json:"cached_input_credits_per_million_tokens"`
|
||||
Output Amount `json:"output_credits_per_million_tokens"`
|
||||
@@ -36,7 +36,7 @@ type Policy struct {
|
||||
}
|
||||
|
||||
func defaultPolicy() Policy {
|
||||
return Policy{Input: 100 * Amount(scale), Cached: 20 * Amount(scale), Output: 400 * Amount(scale), Cycle: "monthly", Mode: "local"}
|
||||
return Policy{RootCredits: 15000 * Amount(scale), Input: 100 * Amount(scale), Cached: 20 * Amount(scale), Output: 400 * Amount(scale), Cycle: "monthly", Mode: "local"}
|
||||
}
|
||||
func (p Policy) period(now time.Time) (time.Time, time.Time) {
|
||||
zone, _ := time.LoadLocation("Asia/Shanghai")
|
||||
@@ -77,10 +77,6 @@ func (s *Service) Initialize(ctx context.Context) error {
|
||||
p := defaultPolicy()
|
||||
b, _ := json.Marshal(p)
|
||||
_, err := s.pool.Exec(ctx, `INSERT INTO settings(key,value,updated_by_user_id) SELECT 'billing',$1,id FROM users WHERE role='admin' AND deleted_at IS NULL ORDER BY created_at LIMIT 1 ON CONFLICT(key) DO NOTHING`, b)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = s.pool.Exec(ctx, `INSERT INTO billing_quotas(subject_type,group_id,credits_per_cycle,updated_by_user_id) SELECT 'group',$1,15000,id FROM users WHERE role='admin' AND deleted_at IS NULL ORDER BY created_at LIMIT 1 ON CONFLICT(group_id) WHERE subject_type='group' AND deleted_at IS NULL DO NOTHING`, rootGroup)
|
||||
return err
|
||||
}
|
||||
func (s *Service) policy(ctx context.Context, q resource.Queryer, lock bool) (Policy, error) {
|
||||
@@ -162,12 +158,13 @@ func accountRow(ctx context.Context, q resource.Queryer, user string, start time
|
||||
func effectiveQuota(ctx context.Context, q resource.Queryer, user string) (Amount, string, string, error) {
|
||||
var value, group, source string
|
||||
err := q.QueryRow(ctx, `WITH RECURSIVE chain AS (
|
||||
SELECT g.id,g.parent_id,0 depth FROM users u JOIN groups g ON g.id=COALESCE(u.billing_group_id,CASE WHEN u.role='admin' THEN $3::uuid ELSE $2::uuid END) WHERE u.id=$1 AND g.deleted_at IS NULL
|
||||
SELECT g.id,g.parent_id,0 depth FROM users u JOIN groups g ON g.id=u.billing_group_id WHERE u.id=$1 AND g.deleted_at IS NULL
|
||||
UNION ALL SELECT g.id,g.parent_id,c.depth+1 FROM groups g JOIN chain c ON g.id=c.parent_id WHERE g.deleted_at IS NULL AND c.depth<100
|
||||
), choices AS (
|
||||
SELECT credits_per_cycle,-1 depth,user_id::text source FROM billing_quotas WHERE user_id=$1 AND deleted_at IS NULL
|
||||
UNION ALL SELECT q.credits_per_cycle,c.depth,c.id::text FROM chain c JOIN billing_quotas q ON q.group_id=c.id AND q.deleted_at IS NULL
|
||||
) SELECT COALESCE((SELECT credits_per_cycle::text FROM choices ORDER BY depth LIMIT 1),'15000'),COALESCE((SELECT id::text FROM chain WHERE depth=0),$2::text),COALESCE((SELECT source FROM choices ORDER BY depth LIMIT 1),$2::text)`, user, rootGroup, adminGroup).Scan(&value, &group, &source)
|
||||
UNION ALL SELECT COALESCE((value->>'root_credits')::numeric,15000),101,$2::text FROM settings WHERE key='billing'
|
||||
) SELECT COALESCE((SELECT credits_per_cycle::text FROM choices ORDER BY depth LIMIT 1),'15000'),COALESCE((SELECT id::text FROM chain WHERE depth=0),''),COALESCE((SELECT source FROM choices ORDER BY depth LIMIT 1),$2::text)`, user, rootGroup).Scan(&value, &group, &source)
|
||||
if err != nil {
|
||||
return 0, "", "", err
|
||||
}
|
||||
@@ -192,7 +189,7 @@ func (s *Service) ensureAccount(ctx context.Context, tx pgx.Tx, user string, p P
|
||||
return a, err
|
||||
}
|
||||
var account string
|
||||
err = tx.QueryRow(ctx, `INSERT INTO credit_accounts(user_id,balance,quota,group_id,period_start_at,period_end_at,last_refreshed_at) VALUES($1,$2,$2,$3,$4,$5,$6) RETURNING id`, user, quota.String(), group, start, end, s.now()).Scan(&account)
|
||||
err = tx.QueryRow(ctx, `INSERT INTO credit_accounts(user_id,balance,quota,group_id,period_start_at,period_end_at,last_refreshed_at) VALUES($1,$2,$2,NULLIF($3,'')::uuid,$4,$5,$6) RETURNING id`, user, quota.String(), group, start, end, s.now()).Scan(&account)
|
||||
if err != nil {
|
||||
return a, err
|
||||
}
|
||||
|
||||
@@ -182,7 +182,7 @@ func TestConcurrentReservations(t *testing.T) {
|
||||
if _, err := s.pool.Exec(ctx, `UPDATE models SET advanced_config='{"context_window_tokens":10,"max_output_tokens":4}' WHERE id=$1`, model); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.pool.Exec(ctx, `UPDATE billing_quotas SET credits_per_cycle=10 WHERE group_id=$1`, rootGroup); err != nil {
|
||||
if _, err := s.pool.Exec(ctx, `UPDATE settings SET value=jsonb_set(value,'{root_credits}','"10"') WHERE key='billing'`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
@@ -225,7 +225,7 @@ func TestQuotaInheritanceAndNoRefill(t *testing.T) {
|
||||
s, user, _ := fixture(t)
|
||||
ctx := t.Context()
|
||||
g := resource.ID()
|
||||
_, err := s.pool.Exec(ctx, `INSERT INTO groups(id,parent_id,name) VALUES($1,$2,'研发');`, g, rootGroup)
|
||||
_, err := s.pool.Exec(ctx, `INSERT INTO groups(id,parent_id,name) VALUES($1,NULL,'研发');`, g)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -462,7 +462,7 @@ func TestQuotaChangePreservesUnopenedAccount(t *testing.T) {
|
||||
if err = s.PreserveAccounts(ctx, tx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `UPDATE billing_quotas SET credits_per_cycle=1 WHERE group_id=$1`, rootGroup); err != nil {
|
||||
if _, err = tx.Exec(ctx, `UPDATE settings SET value=jsonb_set(value,'{root_credits}','"1"') WHERE key='billing'`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
|
||||
@@ -177,7 +177,7 @@ func (s *Service) Begin(ctx context.Context, r Request) (Reservation, error) {
|
||||
if mode == "remote" {
|
||||
state = "created"
|
||||
}
|
||||
_, err = tx.Exec(ctx, `INSERT INTO billing_transactions(id,user_id,account_id,session_id,category,resource_id,connector_id,item_name,user_name,user_email,group_id,mode,status,reserve,pricing,idempotency_key,request_hash,started_at) VALUES($1,$2,$3,NULLIF($4,'')::uuid,$5,$6,NULLIF($7,'')::uuid,$8,$9,$10,$11,$12,$13,$14,$15,NULLIF($16,''),$17,$18)`, id, r.UserID, a.ID, r.SessionID, r.Category, r.ResourceID, r.ConnectorID, item, name, email, a.GroupID, mode, state, reserve.String(), snapshot, r.IdempotencyKey, r.RequestHash, s.now())
|
||||
_, err = tx.Exec(ctx, `INSERT INTO billing_transactions(id,user_id,account_id,session_id,category,resource_id,connector_id,item_name,user_name,user_email,group_id,mode,status,reserve,pricing,idempotency_key,request_hash,started_at) VALUES($1,$2,$3,NULLIF($4,'')::uuid,$5,$6,NULLIF($7,'')::uuid,$8,$9,$10,NULLIF($11,'')::uuid,$12,$13,$14,$15,NULLIF($16,''),$17,$18)`, id, r.UserID, a.ID, r.SessionID, r.Category, r.ResourceID, r.ConnectorID, item, name, email, a.GroupID, mode, state, reserve.String(), snapshot, r.IdempotencyKey, r.RequestHash, s.now())
|
||||
if err != nil {
|
||||
return Reservation{}, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package group
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/identity"
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/resource"
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
func (s *Service) RegisterAdmin(router chi.Router) {
|
||||
router.Get("/groups", func(w http.ResponseWriter, r *http.Request) {
|
||||
groups, err := s.List(r.Context())
|
||||
if err != nil {
|
||||
resource.Fail(w, err)
|
||||
return
|
||||
}
|
||||
resource.JSON(w, http.StatusOK, map[string]any{"groups": groups})
|
||||
})
|
||||
save := func(w http.ResponseWriter, r *http.Request) {
|
||||
var in Input
|
||||
if err := resource.Decode(w, r, &in); err != nil {
|
||||
resource.Fail(w, err)
|
||||
return
|
||||
}
|
||||
user, _ := identity.UserFromContext(r.Context())
|
||||
id := chi.URLParam(r, "groupID")
|
||||
group, err := s.Save(r.Context(), user.ID, id, in)
|
||||
if err != nil {
|
||||
resource.Fail(w, err)
|
||||
return
|
||||
}
|
||||
status := http.StatusOK
|
||||
if id == "" {
|
||||
status = http.StatusCreated
|
||||
}
|
||||
resource.JSON(w, status, group)
|
||||
}
|
||||
router.Post("/groups", save)
|
||||
router.Patch("/groups/{groupID}", save)
|
||||
router.Put("/groups/{groupID}/members", func(w http.ResponseWriter, r *http.Request) {
|
||||
var in struct {
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
if err := resource.Decode(w, r, &in); err != nil {
|
||||
resource.Fail(w, err)
|
||||
return
|
||||
}
|
||||
user, _ := identity.UserFromContext(r.Context())
|
||||
group, err := s.SetMembers(r.Context(), user.ID, chi.URLParam(r, "groupID"), in.MemberIDs)
|
||||
if err != nil {
|
||||
resource.Fail(w, err)
|
||||
return
|
||||
}
|
||||
resource.JSON(w, http.StatusOK, group)
|
||||
})
|
||||
router.Delete("/groups/{groupID}", func(w http.ResponseWriter, r *http.Request) {
|
||||
user, _ := identity.UserFromContext(r.Context())
|
||||
if err := s.Delete(r.Context(), user.ID, chi.URLParam(r, "groupID")); err != nil {
|
||||
resource.Fail(w, err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
package group
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"slices"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/resource"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type Group struct {
|
||||
ID string `json:"id"`
|
||||
ParentID *string `json:"parent_id"`
|
||||
Name string `json:"name"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
|
||||
type Input struct {
|
||||
Name *string `json:"name"`
|
||||
ParentID json.RawMessage `json:"parent_id"`
|
||||
}
|
||||
|
||||
type AccountPreserver interface {
|
||||
PreserveAccounts(context.Context, pgx.Tx) error
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
pool *pgxpool.Pool
|
||||
accounts AccountPreserver
|
||||
}
|
||||
|
||||
func (s *Service) WithAccountPreserver(accounts AccountPreserver) *Service {
|
||||
s.accounts = accounts
|
||||
return s
|
||||
}
|
||||
|
||||
func NewService(pool *pgxpool.Pool) *Service { return &Service{pool: pool} }
|
||||
|
||||
const selectSQL = `SELECT g.id,g.parent_id,g.name,ARRAY(
|
||||
SELECT gu.user_id::text FROM group_users gu JOIN users u ON u.id=gu.user_id
|
||||
WHERE gu.group_id=g.id AND gu.removed_at IS NULL AND u.deleted_at IS NULL ORDER BY gu.user_id
|
||||
) FROM groups g WHERE g.deleted_at IS NULL`
|
||||
|
||||
func (s *Service) List(ctx context.Context) ([]Group, error) {
|
||||
rows, err := s.pool.Query(ctx, selectSQL+` ORDER BY g.created_at,g.id`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
groups := []Group{}
|
||||
for rows.Next() {
|
||||
var group Group
|
||||
if err := rows.Scan(&group.ID, &group.ParentID, &group.Name, &group.MemberIDs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
groups = append(groups, group)
|
||||
}
|
||||
return groups, rows.Err()
|
||||
}
|
||||
|
||||
func get(ctx context.Context, tx pgx.Tx, id string) (Group, error) {
|
||||
var group Group
|
||||
err := tx.QueryRow(ctx, selectSQL+` AND g.id=$1`, id).Scan(&group.ID, &group.ParentID, &group.Name, &group.MemberIDs)
|
||||
return group, err
|
||||
}
|
||||
|
||||
func (s *Service) begin(ctx context.Context) (pgx.Tx, error) {
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// 串行化分组写入,避免并发移动绕过祖先校验形成环。
|
||||
if _, err = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(741209)`); err != nil {
|
||||
_ = tx.Rollback(ctx)
|
||||
return nil, err
|
||||
}
|
||||
if s.accounts != nil {
|
||||
if err = s.accounts.PreserveAccounts(ctx, tx); err != nil {
|
||||
_ = tx.Rollback(ctx)
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return tx, nil
|
||||
}
|
||||
|
||||
func conflict(message string) error {
|
||||
return &resource.Error{Status: 409, Code: "group_conflict", Message: message}
|
||||
}
|
||||
|
||||
func (s *Service) Save(ctx context.Context, actor, id string, in Input) (Group, error) {
|
||||
if in.Name == nil && len(in.ParentID) == 0 {
|
||||
return Group{}, resource.Invalid("请指定分组名称或上级分组")
|
||||
}
|
||||
if in.Name != nil {
|
||||
*in.Name = strings.TrimSpace(*in.Name)
|
||||
if *in.Name == "" || utf8.RuneCountInString(*in.Name) > 100 {
|
||||
return Group{}, resource.Invalid("分组名称须为 1—100 个字符")
|
||||
}
|
||||
}
|
||||
var parentID *string
|
||||
if len(in.ParentID) > 0 {
|
||||
if err := json.Unmarshal(in.ParentID, &parentID); err != nil {
|
||||
return Group{}, resource.Invalid("parent_id 必须是分组 ID 或 null")
|
||||
}
|
||||
}
|
||||
create := id == ""
|
||||
if create && in.Name == nil {
|
||||
return Group{}, resource.Invalid("创建分组需要名称")
|
||||
}
|
||||
tx, err := s.begin(ctx)
|
||||
if err != nil {
|
||||
return Group{}, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
var group Group
|
||||
if !create {
|
||||
group, err = get(ctx, tx, id)
|
||||
if err != nil {
|
||||
return Group{}, err
|
||||
}
|
||||
}
|
||||
if parentID != nil {
|
||||
parent, err := get(ctx, tx, *parentID)
|
||||
if err != nil {
|
||||
return Group{}, err
|
||||
}
|
||||
var cycle bool
|
||||
err = tx.QueryRow(ctx, `WITH RECURSIVE ancestors(id,parent_id) AS (
|
||||
SELECT id,parent_id FROM groups WHERE id=$1 AND deleted_at IS NULL
|
||||
UNION SELECT g.id,g.parent_id FROM groups g JOIN ancestors a ON g.id=a.parent_id WHERE g.deleted_at IS NULL
|
||||
) SELECT EXISTS(SELECT 1 FROM ancestors WHERE id=NULLIF($2,'')::uuid)`, parent.ID, id).Scan(&cycle)
|
||||
if err != nil {
|
||||
return Group{}, err
|
||||
}
|
||||
if cycle {
|
||||
return Group{}, conflict("不能移动到自身或子分组中")
|
||||
}
|
||||
}
|
||||
if len(in.ParentID) > 0 {
|
||||
group.ParentID = parentID
|
||||
}
|
||||
if in.Name != nil {
|
||||
group.Name = *in.Name
|
||||
}
|
||||
var duplicate bool
|
||||
err = tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM groups WHERE deleted_at IS NULL AND parent_id IS NOT DISTINCT FROM $1::uuid AND lower(name)=lower($2) AND id IS DISTINCT FROM NULLIF($3,'')::uuid)`, group.ParentID, group.Name, id).Scan(&duplicate)
|
||||
if err != nil {
|
||||
return Group{}, err
|
||||
}
|
||||
if duplicate {
|
||||
return Group{}, conflict("同一上级分组下已存在该名称")
|
||||
}
|
||||
action := "update"
|
||||
if create {
|
||||
action = "create"
|
||||
err = tx.QueryRow(ctx, `INSERT INTO groups(parent_id,name,created_by_user_id) VALUES($1,$2,$3) RETURNING id`, group.ParentID, group.Name, actor).Scan(&id)
|
||||
} else {
|
||||
_, err = tx.Exec(ctx, `UPDATE groups SET parent_id=$2,name=$3,updated_at=now() WHERE id=$1`, id, group.ParentID, group.Name)
|
||||
}
|
||||
if err != nil {
|
||||
return Group{}, err
|
||||
}
|
||||
group, err = get(ctx, tx, id)
|
||||
if err != nil {
|
||||
return Group{}, err
|
||||
}
|
||||
if err = resource.Audit(ctx, tx, actor, "group", id, action); err != nil {
|
||||
return Group{}, err
|
||||
}
|
||||
return group, tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func (s *Service) SetMembers(ctx context.Context, actor, id string, ids []string) (Group, error) {
|
||||
if ids == nil || len(ids) > 10000 {
|
||||
return Group{}, resource.Invalid("member_ids 必须是数组,最多包含 10000 个成员")
|
||||
}
|
||||
slices.Sort(ids)
|
||||
ids = slices.Compact(ids)
|
||||
tx, err := s.begin(ctx)
|
||||
if err != nil {
|
||||
return Group{}, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
group, err := get(ctx, tx, id)
|
||||
if err != nil {
|
||||
return Group{}, err
|
||||
}
|
||||
rows, err := tx.Query(ctx, `SELECT id FROM users WHERE id=ANY($1::uuid[]) AND deleted_at IS NULL FOR SHARE`, ids)
|
||||
if err != nil {
|
||||
return Group{}, err
|
||||
}
|
||||
count := 0
|
||||
for rows.Next() {
|
||||
count++
|
||||
}
|
||||
err = rows.Err()
|
||||
rows.Close()
|
||||
if err != nil {
|
||||
return Group{}, err
|
||||
}
|
||||
if count != len(ids) {
|
||||
return Group{}, resource.Invalid("所选成员不存在或已删除")
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `UPDATE group_users SET removed_at=now() WHERE group_id=$1 AND removed_at IS NULL AND NOT(user_id=ANY($2::uuid[]))`, id, ids); err != nil {
|
||||
return Group{}, err
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `INSERT INTO group_users(group_id,user_id,assigned_by_user_id) SELECT $1,unnest($2::uuid[]),$3 ON CONFLICT (group_id,user_id) WHERE removed_at IS NULL DO NOTHING`, id, ids, actor); err != nil {
|
||||
return Group{}, err
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `UPDATE groups SET updated_at=now() WHERE id=$1`, id); err != nil {
|
||||
return Group{}, err
|
||||
}
|
||||
group, err = get(ctx, tx, id)
|
||||
if err != nil {
|
||||
return Group{}, err
|
||||
}
|
||||
if err = resource.Audit(ctx, tx, actor, "group", id, "members"); err != nil {
|
||||
return Group{}, err
|
||||
}
|
||||
return group, tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func (s *Service) Delete(ctx context.Context, actor, id string) error {
|
||||
tx, err := s.begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
if _, err := get(ctx, tx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
var children bool
|
||||
if err = tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM groups WHERE parent_id=$1 AND deleted_at IS NULL)`, id).Scan(&children); err != nil {
|
||||
return err
|
||||
}
|
||||
if children {
|
||||
return conflict("请先移动或删除子分组")
|
||||
}
|
||||
var assigned bool
|
||||
if err = tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM users WHERE billing_group_id=$1 AND deleted_at IS NULL)`, id).Scan(&assigned); err != nil {
|
||||
return err
|
||||
}
|
||||
if assigned {
|
||||
return conflict("请先迁移成员的计费归属")
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `UPDATE groups SET deleted_at=now(),updated_at=now() WHERE id=$1`, id); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `UPDATE group_users SET removed_at=now() WHERE group_id=$1 AND removed_at IS NULL`, id); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `DELETE FROM resource_access_grants WHERE group_id=$1`, id); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = resource.Audit(ctx, tx, actor, "group", id, "delete"); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
@@ -0,0 +1,351 @@
|
||||
package group
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/identity"
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/resource"
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
func TestGroups(t *testing.T) {
|
||||
dsn := os.Getenv("MONKEYAI_TEST_DATABASE_URL")
|
||||
if dsn == "" {
|
||||
t.Skip("设置 MONKEYAI_TEST_DATABASE_URL 运行分组集成测试")
|
||||
}
|
||||
ctx := t.Context()
|
||||
root, err := pgxpool.New(ctx, dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer root.Close()
|
||||
schema := "test_groups_" + strings.ReplaceAll(resource.ID(), "-", "")
|
||||
if _, err = root.Exec(ctx, "CREATE SCHEMA "+schema); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer root.Exec(context.Background(), "DROP SCHEMA "+schema+" CASCADE")
|
||||
config, err := pgxpool.ParseConfig(dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
config.ConnConfig.RuntimeParams["search_path"] = schema
|
||||
pool, err := pgxpool.NewWithConfig(ctx, config)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer pool.Close()
|
||||
migration, err := os.ReadFile(filepath.Join("..", "..", "migrations", "000001_initial_create_schema.up.sql"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = pool.Exec(ctx, string(migration)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
billingMigration, err := os.ReadFile("../../migrations/000002_billing_create_transactions.up.sql")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = pool.Exec(ctx, string(billingMigration)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
actor, member := resource.ID(), resource.ID()
|
||||
if _, err = pool.Exec(ctx, `INSERT INTO users(id,name,email,role) VALUES($1,'管理员','admin@example.com','admin'),($2,'成员','member@example.com','user')`, actor, member); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for token, id := range map[string]string{"admin-session": actor, "member-session": member} {
|
||||
hash := fmt.Sprintf("%x", sha256.Sum256([]byte(token)))
|
||||
if _, err = pool.Exec(ctx, `INSERT INTO browser_sessions(token_hash,user_id,authentication_method,expires_at) VALUES($1,$2,'password',now()+interval '1 hour')`, hash, id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
service := NewService(pool)
|
||||
router := chi.NewRouter()
|
||||
router.Use(identity.NewService(pool, nil, "http://localhost", "http://localhost").RequireAdmin)
|
||||
service.RegisterAdmin(router)
|
||||
call := func(method, path string, body any, token string) *httptest.ResponseRecorder {
|
||||
data, _ := json.Marshal(body)
|
||||
req := httptest.NewRequest(method, path, bytes.NewReader(data))
|
||||
if token != "" {
|
||||
req.AddCookie(&http.Cookie{Name: "monkeyai_session", Value: token})
|
||||
}
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, req)
|
||||
return response
|
||||
}
|
||||
must := func(method, path string, body any, status int) Group {
|
||||
t.Helper()
|
||||
response := call(method, path, body, "admin-session")
|
||||
if response.Code != status {
|
||||
t.Fatalf("%s %s: %d %s,预期 %d", method, path, response.Code, response.Body.String(), status)
|
||||
}
|
||||
var group Group
|
||||
if status != 204 {
|
||||
_ = json.Unmarshal(response.Body.Bytes(), &group)
|
||||
}
|
||||
return group
|
||||
}
|
||||
groups, err := service.List(ctx)
|
||||
if err != nil || len(groups) != 0 {
|
||||
t.Fatalf("初始化不应创建分组: %v, %v", groups, err)
|
||||
}
|
||||
testLegacyGroups(t, pool, actor, member)
|
||||
rootID := resource.ID()
|
||||
create := func(name string, parent any) Group {
|
||||
t.Helper()
|
||||
return must("POST", "/groups", map[string]any{"name": name, "parent_id": parent}, 201)
|
||||
}
|
||||
for _, method := range []string{"GET", "POST", "PATCH", "PUT", "DELETE"} {
|
||||
path := "/groups"
|
||||
if method == "PATCH" || method == "DELETE" {
|
||||
path += "/" + rootID
|
||||
}
|
||||
if method == "PUT" {
|
||||
path += "/" + rootID + "/members"
|
||||
}
|
||||
for token, status := range map[string]int{"": 401, "member-session": 403} {
|
||||
if response := call(method, path, map[string]any{}, token); response.Code != status {
|
||||
t.Fatalf("%s 权限校验 = %d,预期 %d", method, response.Code, status)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, body := range []any{nil, []any{}, map[string]any{}, map[string]any{"name": " ", "parent_id": rootID}, map[string]any{"name": strings.Repeat("组", 101), "parent_id": rootID}} {
|
||||
must("POST", "/groups", body, 400)
|
||||
}
|
||||
parent := create(" 研发 ", nil)
|
||||
if parent.Name != "研发" || parent.MemberIDs == nil {
|
||||
t.Fatalf("新分组返回错误: %+v", parent)
|
||||
}
|
||||
child := create("前端", parent.ID)
|
||||
other := create("产品", nil)
|
||||
must("POST", "/groups", map[string]any{"name": "研发", "parent_id": nil}, 409)
|
||||
must("PATCH", "/groups/"+other.ID, map[string]any{"name": "研发"}, 409)
|
||||
must("PATCH", "/groups/"+parent.ID, map[string]any{"parent_id": child.ID}, 409)
|
||||
must("PATCH", "/groups/"+parent.ID, map[string]any{"parent_id": parent.ID}, 409)
|
||||
must("PATCH", "/groups/"+parent.ID, map[string]any{"parent_id": resource.ID()}, 404)
|
||||
must("DELETE", "/groups/"+parent.ID, nil, 409)
|
||||
implicit := must("POST", "/groups", map[string]any{"name": "未指定上级"}, 201)
|
||||
if implicit.ParentID != nil || parent.ParentID != nil || other.ParentID != nil {
|
||||
t.Fatal("顶层分组 parent_id 应为 null")
|
||||
}
|
||||
must("PUT", "/groups/"+implicit.ID+"/members", map[string]any{"member_ids": []string{actor}}, 200)
|
||||
must("DELETE", "/groups/"+implicit.ID, nil, 204)
|
||||
moved := must("PATCH", "/groups/"+other.ID, map[string]any{"parent_id": parent.ID}, 200)
|
||||
if moved.ParentID == nil || *moved.ParentID != parent.ID {
|
||||
t.Fatal("顶层分组不能移动")
|
||||
}
|
||||
moved = must("PATCH", "/groups/"+other.ID, map[string]any{"name": "产品组"}, 200)
|
||||
if moved.ParentID == nil || *moved.ParentID != parent.ID {
|
||||
t.Fatal("仅改名时不应更改上级")
|
||||
}
|
||||
moved = must("PATCH", "/groups/"+other.ID, map[string]any{"parent_id": nil}, 200)
|
||||
if moved.ParentID != nil {
|
||||
t.Fatal("显式 null 未将分组移回团队根节点")
|
||||
}
|
||||
must("PATCH", "/groups/"+other.ID, map[string]any{"parent_id": 1}, 400)
|
||||
must("POST", "/groups", map[string]any{"name": "虚拟根不能入库", "parent_id": "team"}, 400)
|
||||
|
||||
child = must("PUT", "/groups/"+child.ID+"/members", map[string]any{"member_ids": []string{member, member, actor}}, 200)
|
||||
if len(child.MemberIDs) != 2 {
|
||||
t.Fatalf("成员未去重: %v", child.MemberIDs)
|
||||
}
|
||||
must("PUT", "/groups/"+child.ID+"/members", map[string]any{"member_ids": []string{resource.ID()}}, 400)
|
||||
must("PUT", "/groups/"+child.ID+"/members", map[string]any{}, 400)
|
||||
must("PUT", "/groups/"+child.ID+"/members", map[string]any{"member_ids": nil}, 400)
|
||||
must("PUT", "/groups/"+child.ID+"/members", map[string]any{"member_ids": []string{"invalid"}}, 400)
|
||||
groups, err = NewService(pool).List(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
persisted := groups[slices.IndexFunc(groups, func(g Group) bool { return g.ID == child.ID })]
|
||||
if len(persisted.MemberIDs) != 2 {
|
||||
t.Fatal("失败的成员更新没有回滚")
|
||||
}
|
||||
resourceID := resource.ID()
|
||||
if _, err = pool.Exec(ctx, `INSERT INTO resource_access_grants(resource_type,resource_id,group_id,access_level,usage_requirement,granted_by_user_id) VALUES('rule',$1,$2,'read_only','optional',$3)`, resourceID, parent.ID, actor); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
allowed := func(want bool) {
|
||||
t.Helper()
|
||||
got, err := resource.Allowed(ctx, pool, "rule", resourceID, member)
|
||||
if err != nil || got != want {
|
||||
t.Fatalf("父分组授权=%v, err=%v,预期 %v", got, err, want)
|
||||
}
|
||||
}
|
||||
privateResource := resource.ID()
|
||||
if _, err = pool.Exec(ctx, `INSERT INTO resource_access_grants(resource_type,resource_id,group_id,access_level,usage_requirement,granted_by_user_id) VALUES('rule',$1,$2,'read_only','optional',$3)`, privateResource, other.ID, actor); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, user := range []string{actor, member} {
|
||||
ok, err := resource.Allowed(ctx, pool, "rule", privateResource, user)
|
||||
if err != nil || ok {
|
||||
t.Fatalf("未加入顶层分组的用户不应继承授权: %v, %v", ok, err)
|
||||
}
|
||||
}
|
||||
allowed(true)
|
||||
must("PATCH", "/groups/"+child.ID, map[string]any{"parent_id": other.ID}, 200)
|
||||
allowed(false)
|
||||
must("PATCH", "/groups/"+child.ID, map[string]any{"parent_id": parent.ID, "name": "客户端"}, 200)
|
||||
allowed(true)
|
||||
must("PUT", "/groups/"+child.ID+"/members", map[string]any{"member_ids": []string{}}, 200)
|
||||
allowed(false)
|
||||
must("PUT", "/groups/"+child.ID+"/members", map[string]any{"member_ids": []string{member}}, 200)
|
||||
allowed(true)
|
||||
if _, err = pool.Exec(ctx, `INSERT INTO resource_access_grants(resource_type,resource_id,group_id,access_level,usage_requirement,granted_by_user_id) VALUES('rule',$1,$2,'read_only','optional',$3)`, resourceID, child.ID, actor); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
must("DELETE", "/groups/"+child.ID, nil, 204)
|
||||
allowed(false)
|
||||
must("DELETE", "/groups/"+child.ID, nil, 404)
|
||||
var memberships, grants, accounts, audits int
|
||||
if err = pool.QueryRow(ctx, `SELECT (SELECT count(*) FROM group_users WHERE group_id=$1 AND removed_at IS NULL),(SELECT count(*) FROM resource_access_grants WHERE group_id=$1),(SELECT count(*) FROM users WHERE deleted_at IS NULL),(SELECT count(*) FROM audits WHERE target_id=$1)`, child.ID).Scan(&memberships, &grants, &accounts, &audits); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if memberships != 0 || grants != 0 || accounts != 2 || audits < 4 {
|
||||
t.Fatalf("删除清理或操作记录错误: %d %d %d %d", memberships, grants, accounts, audits)
|
||||
}
|
||||
must("DELETE", "/groups/"+parent.ID, nil, 204)
|
||||
must("POST", "/groups", map[string]any{"name": "已删除父组", "parent_id": parent.ID}, 404)
|
||||
|
||||
// 相互移动并发执行时,只允许其中一次成功。
|
||||
a, b := create("并发 A", nil), create("并发 B", nil)
|
||||
codes := make(chan int, 2)
|
||||
for _, pair := range [][2]string{{a.ID, b.ID}, {b.ID, a.ID}} {
|
||||
go func() {
|
||||
codes <- call("PATCH", "/groups/"+pair[0], map[string]any{"parent_id": pair[1]}, "admin-session").Code
|
||||
}()
|
||||
}
|
||||
got := []int{<-codes, <-codes}
|
||||
slices.Sort(got)
|
||||
if !slices.Equal(got, []int{200, 409}) {
|
||||
t.Fatalf("并发移动结果: %v", got)
|
||||
}
|
||||
response := call("GET", "/groups", nil, "admin-session")
|
||||
var list struct {
|
||||
Groups []Group `json:"groups"`
|
||||
}
|
||||
if response.Code != 200 || json.Unmarshal(response.Body.Bytes(), &list) != nil {
|
||||
t.Fatalf("读取分组失败: %s", response.Body.String())
|
||||
}
|
||||
for _, group := range list.Groups {
|
||||
if group.ID == child.ID || group.ID == parent.ID {
|
||||
t.Fatal("列表仍包含已删除的分组")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testLegacyGroups(t *testing.T, pool *pgxpool.Pool, actor, member string) {
|
||||
t.Helper()
|
||||
ctx := t.Context()
|
||||
upgrade, err := os.ReadFile(filepath.Join("..", "..", "migrations", "000003_group_virtual_root.up.sql"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// 新库执行增量迁移也不能初始化分组。
|
||||
if _, err = pool.Exec(ctx, string(upgrade)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
groups, err := NewService(pool).List(ctx)
|
||||
if err != nil || len(groups) != 0 {
|
||||
t.Fatalf("新库迁移创建了分组: %v %v", groups, err)
|
||||
}
|
||||
root, admin := "00000000-0000-0000-0000-000000000001", "00000000-0000-0000-0000-000000000002"
|
||||
custom, nested, item := resource.ID(), resource.ID(), resource.ID()
|
||||
if _, err = pool.Exec(ctx, `INSERT INTO groups(id,parent_id,name) VALUES($1,NULL,'旧团队'),($2,$1,'管理员'),($3,$1,'旧业务组'),($4,$2,'旧管理员子组')`, root, admin, custom, nested); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = pool.Exec(ctx, `CREATE UNIQUE INDEX groups_one_active_root_key ON groups ((true)) WHERE parent_id IS NULL AND deleted_at IS NULL`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = pool.Exec(ctx, `INSERT INTO group_users(group_id,user_id,assigned_by_user_id) VALUES($1,$2,$3)`, nested, member, actor); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = pool.Exec(ctx, `INSERT INTO resource_access_grants(resource_type,resource_id,group_id,access_level,usage_requirement,granted_by_user_id) VALUES('rule',$1,$2,'read_only','optional',$4),('rule',$1,$3,'read_write','required',$4)`, item, root, admin, actor); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = pool.Exec(ctx, `INSERT INTO resource_access_grants(resource_type,resource_id,user_id,access_level,usage_requirement,granted_by_user_id) VALUES('rule',$1,$2,'read_only','optional',$3)`, item, member, actor); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = pool.Exec(ctx, `INSERT INTO settings(key,value,updated_by_user_id) VALUES('billing','{}',$1)`, actor); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = pool.Exec(ctx, `INSERT INTO billing_quotas(subject_type,group_id,credits_per_cycle,updated_by_user_id) VALUES('group',$1,222,$3),('group',$2,77,$3)`, root, admin, actor); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = pool.Exec(ctx, `UPDATE users SET billing_group_id=$1 WHERE id=$2`, root, member); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var account string
|
||||
if err = pool.QueryRow(ctx, `INSERT INTO credit_accounts(user_id,balance,quota,group_id,period_start_at,period_end_at,last_refreshed_at) VALUES($1,42,222,$2,now(),now()+interval '1 month',now()) RETURNING id`, member, root).Scan(&account); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = pool.Exec(ctx, `INSERT INTO credit_ledger_entries(account_id,user_id,entry_type,category,item_name,credit_delta,balance_after,occurred_at,group_id,sequence) VALUES($1,$2,'grant','other','旧周期额度',42,42,now(),$3,1)`, account, member, root); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = pool.Exec(ctx, string(upgrade)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
groups, err = NewService(pool).List(ctx)
|
||||
if err != nil || len(groups) != 2 {
|
||||
t.Fatalf("旧库升级后的分组: %v %v", groups, err)
|
||||
}
|
||||
var rootCredits, adminCredits, childCredits, balance, legacy string
|
||||
var billingGroup, accountGroup, ledgerGroup *string
|
||||
if err = pool.QueryRow(ctx, `SELECT (SELECT value->>'root_credits' FROM settings WHERE key='billing'),(SELECT credits_per_cycle::text FROM billing_quotas WHERE user_id=$1),(SELECT credits_per_cycle::text FROM billing_quotas WHERE group_id=$2),(SELECT billing_group_id::text FROM users WHERE id=$3)`, actor, nested, member).Scan(&rootCredits, &adminCredits, &childCredits, &billingGroup); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if rootCredits != "222.000000" || adminCredits != "77.000000" || childCredits != "77.000000" || billingGroup != nil {
|
||||
t.Fatalf("旧额度迁移错误: %s %s %s %v", rootCredits, adminCredits, childCredits, billingGroup)
|
||||
}
|
||||
if err = pool.QueryRow(ctx, `SELECT a.balance::text,a.group_id::text,e.group_id::text,e.metadata->>'legacy_group_id' FROM credit_accounts a JOIN credit_ledger_entries e ON e.account_id=a.id WHERE a.id=$1`, account).Scan(&balance, &accountGroup, &ledgerGroup, &legacy); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if balance != "42.000000" || accountGroup != nil || ledgerGroup != nil || legacy != root {
|
||||
t.Fatalf("旧账户流水迁移错误: %s %v %v %s", balance, accountGroup, ledgerGroup, legacy)
|
||||
}
|
||||
if _, err = pool.Exec(ctx, `UPDATE credit_ledger_entries SET balance_after=0 WHERE account_id=$1`, account); err == nil {
|
||||
t.Fatal("迁移后流水防修改触发器未恢复")
|
||||
}
|
||||
for _, group := range groups {
|
||||
if group.ParentID != nil || group.ID == root || group.ID == admin {
|
||||
t.Fatalf("旧系统分组未移除或子分组未提升: %+v", group)
|
||||
}
|
||||
}
|
||||
var count int
|
||||
if err = pool.QueryRow(ctx, `SELECT count(*) FROM resource_access_grants WHERE resource_id=$1 AND user_id IN ($2,$3) AND access_level='read_write' AND usage_requirement='required'`, item, actor, member).Scan(&count); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if count != 2 {
|
||||
t.Fatalf("旧授权展开或合并错误: %d", count)
|
||||
}
|
||||
if err = pool.QueryRow(ctx, `SELECT count(*) FROM group_users WHERE group_id=$1 AND user_id=$2 AND removed_at IS NULL`, nested, member).Scan(&count); err != nil || count != 1 {
|
||||
t.Fatalf("自定义组成员关系丢失: %d %v", count, err)
|
||||
}
|
||||
if _, err = pool.Exec(ctx, string(upgrade)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = pool.Exec(ctx, `DELETE FROM resource_access_grants WHERE resource_id=$1`, item); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = pool.Exec(ctx, `DELETE FROM group_users WHERE group_id=$1`, nested); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = pool.Exec(ctx, `DELETE FROM billing_quotas WHERE group_id IN ($1,$2)`, custom, nested); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = pool.Exec(ctx, `DELETE FROM groups WHERE id IN ($1,$2)`, custom, nested); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
)
|
||||
|
||||
func (s *Service) RegisterAdmin(router chi.Router) {
|
||||
s.registerGroups(router)
|
||||
router.Put("/users/{userID}/billing-group", s.billingGroup)
|
||||
router.Get("/me", func(w http.ResponseWriter, r *http.Request) {
|
||||
user, _ := UserFromContext(r.Context())
|
||||
writeJSON(w, http.StatusOK, user)
|
||||
|
||||
@@ -3,69 +3,12 @@ package identity
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
type group struct {
|
||||
ID string `json:"id"`
|
||||
ParentID *string `json:"parent_id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
func (s *Service) registerGroups(r chi.Router) {
|
||||
r.Get("/groups", s.listGroups)
|
||||
r.Post("/groups", s.saveGroup)
|
||||
r.Patch("/groups/{groupID}", s.saveGroup)
|
||||
r.Delete("/groups/{groupID}", s.deleteGroup)
|
||||
r.Put("/users/{userID}/billing-group", s.billingGroup)
|
||||
r.Put("/groups/{groupID}/members", s.groupMembers)
|
||||
}
|
||||
func (s *Service) listGroups(w http.ResponseWriter, r *http.Request) {
|
||||
rows, err := s.db.Query(r.Context(), `SELECT id,parent_id,name FROM groups WHERE deleted_at IS NULL ORDER BY name,id`)
|
||||
if err != nil {
|
||||
writeError(w, 500, "group_error", "读取分组失败")
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
groups := []group{}
|
||||
for rows.Next() {
|
||||
var g group
|
||||
if err = rows.Scan(&g.ID, &g.ParentID, &g.Name); err != nil {
|
||||
writeError(w, 500, "group_error", "读取分组失败")
|
||||
return
|
||||
}
|
||||
groups = append(groups, g)
|
||||
}
|
||||
if rows.Err() != nil {
|
||||
writeError(w, 500, "group_error", "读取分组失败")
|
||||
return
|
||||
}
|
||||
memberships := []map[string]string{}
|
||||
rel, err := s.db.Query(r.Context(), `SELECT group_id,user_id FROM group_users WHERE removed_at IS NULL`)
|
||||
if err != nil {
|
||||
writeError(w, 500, "group_error", "读取成员关系失败")
|
||||
return
|
||||
}
|
||||
defer rel.Close()
|
||||
for rel.Next() {
|
||||
var g, u string
|
||||
if err = rel.Scan(&g, &u); err != nil {
|
||||
writeError(w, 500, "group_error", "读取成员关系失败")
|
||||
return
|
||||
}
|
||||
memberships = append(memberships, map[string]string{"group_id": g, "user_id": u})
|
||||
}
|
||||
if rel.Err() != nil {
|
||||
writeError(w, 500, "group_error", "读取成员关系失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"groups": groups, "memberships": memberships})
|
||||
}
|
||||
func groupInput(w http.ResponseWriter, r *http.Request, v any) error {
|
||||
d := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20))
|
||||
d.DisallowUnknownFields()
|
||||
@@ -96,95 +39,6 @@ func groupAudit(ctx context.Context, tx pgx.Tx, user User, action, id string, da
|
||||
_, err = tx.Exec(ctx, `INSERT INTO audits(actor_type,actor_user_id,actor_name,actor_email,action,category,target_type,target_id,request_params,result,occurred_at) VALUES('user',$1,$2,$3,$4,'identity','group',$5,$6,'success',now())`, user.ID, user.Name, user.Email, action, id, b)
|
||||
return err
|
||||
}
|
||||
func (s *Service) saveGroup(w http.ResponseWriter, r *http.Request) {
|
||||
var in struct {
|
||||
Name string `json:"name"`
|
||||
ParentID string `json:"parent_id"`
|
||||
}
|
||||
if groupInput(w, r, &in) != nil || strings.TrimSpace(in.Name) == "" || len(in.Name) > 100 || in.ParentID == "" {
|
||||
writeError(w, 400, "invalid_group", "请填写分组名称和父分组")
|
||||
return
|
||||
}
|
||||
ctx := r.Context()
|
||||
id := chi.URLParam(r, "groupID")
|
||||
if id == "00000000-0000-0000-0000-000000000001" || id == "00000000-0000-0000-0000-000000000002" {
|
||||
writeError(w, 409, "fixed_group", "系统分组不可改动")
|
||||
return
|
||||
}
|
||||
tx, err := s.groupTx(r)
|
||||
if err != nil {
|
||||
writeError(w, 500, "group_error", "保存分组失败")
|
||||
return
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
var parent string
|
||||
err = tx.QueryRow(ctx, `SELECT id FROM groups WHERE id=$1 AND deleted_at IS NULL`, in.ParentID).Scan(&parent)
|
||||
if err != nil {
|
||||
writeError(w, 400, "invalid_parent", "父分组无效")
|
||||
return
|
||||
}
|
||||
if id != "" {
|
||||
var cycle bool
|
||||
err = tx.QueryRow(ctx, `WITH RECURSIVE children AS (SELECT id FROM groups WHERE id=$1 UNION SELECT g.id FROM groups g JOIN children c ON g.parent_id=c.id WHERE g.deleted_at IS NULL) SELECT EXISTS(SELECT 1 FROM children WHERE id=$2)`, id, in.ParentID).Scan(&cycle)
|
||||
if err != nil || cycle {
|
||||
writeError(w, 400, "group_cycle", "不能移动到自身或后代分组")
|
||||
return
|
||||
}
|
||||
}
|
||||
u, _ := UserFromContext(ctx)
|
||||
if id == "" {
|
||||
err = tx.QueryRow(ctx, `INSERT INTO groups(name,parent_id,created_by_user_id) VALUES($1,$2,$3) RETURNING id`, strings.TrimSpace(in.Name), in.ParentID, u.ID).Scan(&id)
|
||||
} else {
|
||||
err = tx.QueryRow(ctx, `UPDATE groups SET name=$2,parent_id=$3,updated_at=now() WHERE id=$1 AND deleted_at IS NULL RETURNING id`, id, strings.TrimSpace(in.Name), in.ParentID).Scan(&id)
|
||||
}
|
||||
if err == nil {
|
||||
err = groupAudit(ctx, tx, u, "save_group", id, in)
|
||||
}
|
||||
if err == nil {
|
||||
err = tx.Commit(ctx)
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, 400, "group_error", "保存分组失败,请检查字段")
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]string{"id": id})
|
||||
}
|
||||
func (s *Service) deleteGroup(w http.ResponseWriter, r *http.Request) {
|
||||
id := chi.URLParam(r, "groupID")
|
||||
if id == "00000000-0000-0000-0000-000000000001" || id == "00000000-0000-0000-0000-000000000002" {
|
||||
writeError(w, 409, "fixed_group", "系统分组不可删除")
|
||||
return
|
||||
}
|
||||
ctx := r.Context()
|
||||
tx, err := s.groupTx(r)
|
||||
if err != nil {
|
||||
writeError(w, 500, "group_error", "删除分组失败")
|
||||
return
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
var used bool
|
||||
err = tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM groups WHERE parent_id=$1 AND deleted_at IS NULL) OR EXISTS(SELECT 1 FROM users WHERE billing_group_id=$1 AND deleted_at IS NULL) OR EXISTS(SELECT 1 FROM group_users WHERE group_id=$1 AND removed_at IS NULL) OR EXISTS(SELECT 1 FROM resource_access_grants WHERE group_id=$1)`, id).Scan(&used)
|
||||
if err != nil || used {
|
||||
writeError(w, 409, "group_in_use", "请先迁移子分组、成员计费归属、成员关系和资源授权")
|
||||
return
|
||||
}
|
||||
tag, err := tx.Exec(ctx, `UPDATE groups SET deleted_at=now(),updated_at=now() WHERE id=$1 AND deleted_at IS NULL`, id)
|
||||
if err == nil && tag.RowsAffected() != 1 {
|
||||
err = errors.New("分组不存在")
|
||||
}
|
||||
u, _ := UserFromContext(ctx)
|
||||
if err == nil {
|
||||
err = groupAudit(ctx, tx, u, "delete_group", id, map[string]any{})
|
||||
}
|
||||
if err == nil {
|
||||
err = tx.Commit(ctx)
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, 400, "group_error", "删除分组失败")
|
||||
return
|
||||
}
|
||||
w.WriteHeader(204)
|
||||
}
|
||||
func (s *Service) billingGroup(w http.ResponseWriter, r *http.Request) {
|
||||
var in struct {
|
||||
GroupID *string `json:"group_id"`
|
||||
@@ -226,55 +80,3 @@ func (s *Service) billingGroup(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
w.WriteHeader(204)
|
||||
}
|
||||
func (s *Service) groupMembers(w http.ResponseWriter, r *http.Request) {
|
||||
var in struct {
|
||||
UserIDs []string `json:"user_ids"`
|
||||
}
|
||||
if groupInput(w, r, &in) != nil || len(in.UserIDs) > 1000 {
|
||||
writeError(w, 400, "invalid_members", "成员列表无效")
|
||||
return
|
||||
}
|
||||
id := chi.URLParam(r, "groupID")
|
||||
if id == "00000000-0000-0000-0000-000000000001" || id == "00000000-0000-0000-0000-000000000002" {
|
||||
writeError(w, 409, "fixed_group", "系统分组成员按身份计算")
|
||||
return
|
||||
}
|
||||
ctx := r.Context()
|
||||
tx, err := s.groupTx(r)
|
||||
if err != nil {
|
||||
writeError(w, 500, "group_error", "保存成员失败")
|
||||
return
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
var found string
|
||||
if err = tx.QueryRow(ctx, `SELECT id FROM groups WHERE id=$1 AND deleted_at IS NULL`, id).Scan(&found); err != nil {
|
||||
writeError(w, 404, "group_not_found", "分组不存在")
|
||||
return
|
||||
}
|
||||
_, err = tx.Exec(ctx, `UPDATE group_users SET removed_at=now() WHERE group_id=$1 AND removed_at IS NULL`, id)
|
||||
u, _ := UserFromContext(ctx)
|
||||
for _, user := range in.UserIDs {
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
var active bool
|
||||
err = tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM users WHERE id=$1 AND deleted_at IS NULL)`, user).Scan(&active)
|
||||
if err == nil && !active {
|
||||
err = errors.New("用户不存在")
|
||||
}
|
||||
if err == nil {
|
||||
_, err = tx.Exec(ctx, `INSERT INTO group_users(group_id,user_id,assigned_by_user_id) VALUES($1,$2,$3)`, id, user, u.ID)
|
||||
}
|
||||
}
|
||||
if err == nil {
|
||||
err = groupAudit(ctx, tx, u, "assign_members", id, in)
|
||||
}
|
||||
if err == nil {
|
||||
err = tx.Commit(ctx)
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, 400, "group_error", "保存成员失败,请检查重复或无效用户")
|
||||
return
|
||||
}
|
||||
w.WriteHeader(204)
|
||||
}
|
||||
@@ -214,7 +214,7 @@ func (p *Postgres) ListAvailable(ctx context.Context, userID string, isAdmin boo
|
||||
func (p *Postgres) Resolve(ctx context.Context, userID, id string) (Model, error) {
|
||||
item, err := scanModel(database.Reader(ctx, p.pool).QueryRow(ctx, `
|
||||
WITH RECURSIVE user_groups(group_id) AS (
|
||||
SELECT id FROM groups WHERE deleted_at IS NULL AND (parent_id IS NULL OR (id='00000000-0000-0000-0000-000000000002' AND EXISTS(SELECT 1 FROM users WHERE id=$1 AND role='admin')) OR id IN(SELECT group_id FROM group_users WHERE user_id=$1 AND removed_at IS NULL))
|
||||
SELECT id FROM groups WHERE deleted_at IS NULL AND id IN(SELECT group_id FROM group_users WHERE user_id=$1 AND removed_at IS NULL)
|
||||
UNION
|
||||
SELECT parent.id
|
||||
FROM groups g
|
||||
@@ -295,7 +295,7 @@ const modelSelect = `
|
||||
|
||||
const availableModelSelect = `
|
||||
WITH RECURSIVE user_groups(group_id) AS (
|
||||
SELECT id FROM groups WHERE deleted_at IS NULL AND (parent_id IS NULL OR (id='00000000-0000-0000-0000-000000000002' AND EXISTS(SELECT 1 FROM users WHERE id=$1 AND role='admin')) OR id IN(SELECT group_id FROM group_users WHERE user_id=$1 AND removed_at IS NULL))
|
||||
SELECT id FROM groups WHERE deleted_at IS NULL AND id IN(SELECT group_id FROM group_users WHERE user_id=$1 AND removed_at IS NULL)
|
||||
UNION
|
||||
SELECT parent.id
|
||||
FROM groups g
|
||||
|
||||
@@ -146,9 +146,9 @@ func Row(ctx context.Context, q Queryer, sql string, args ...any) (Object, error
|
||||
return o, err
|
||||
}
|
||||
|
||||
// 根组和管理员组按有效身份计算,其他分组沿父链继承。
|
||||
// 用户仅属于显式加入的分组及其未删除的上级分组。
|
||||
const GroupsSQL = `WITH RECURSIVE user_groups(group_id) AS (
|
||||
SELECT id FROM groups WHERE deleted_at IS NULL AND (parent_id IS NULL OR (id='00000000-0000-0000-0000-000000000002' AND EXISTS(SELECT 1 FROM users WHERE id=$1 AND role='admin')) OR id IN (SELECT group_id FROM group_users WHERE user_id=$1 AND removed_at IS NULL))
|
||||
SELECT id FROM groups WHERE deleted_at IS NULL AND id IN (SELECT group_id FROM group_users WHERE user_id=$1 AND removed_at IS NULL)
|
||||
UNION SELECT parent.id FROM groups g JOIN user_groups ug ON ug.group_id=g.id JOIN groups parent ON parent.id=g.parent_id WHERE g.deleted_at IS NULL AND parent.deleted_at IS NULL
|
||||
) `
|
||||
|
||||
|
||||
@@ -66,10 +66,6 @@ CREATE TABLE groups (
|
||||
CONSTRAINT groups_not_own_parent_check CHECK (parent_id IS DISTINCT FROM id)
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX groups_one_active_root_key
|
||||
ON groups ((true))
|
||||
WHERE parent_id IS NULL AND deleted_at IS NULL;
|
||||
|
||||
CREATE INDEX groups_parent_idx
|
||||
ON groups (parent_id)
|
||||
WHERE deleted_at IS NULL;
|
||||
@@ -651,7 +647,6 @@ CREATE UNIQUE INDEX rules_user_name_key ON rules(owner_user_id,lower(btrim(name)
|
||||
CREATE UNIQUE INDEX connectors_system_name_key ON connectors(lower(btrim(name))) WHERE ownership_type='system' AND deleted_at IS NULL;
|
||||
CREATE UNIQUE INDEX connectors_user_name_key ON connectors(owner_user_id,lower(btrim(name))) WHERE ownership_type='user' AND deleted_at IS NULL;
|
||||
CREATE UNIQUE INDEX experts_name_key ON experts(lower(btrim(name))) WHERE deleted_at IS NULL;
|
||||
INSERT INTO groups(id,parent_id,name) VALUES ('00000000-0000-0000-0000-000000000001',NULL,'所有用户'),('00000000-0000-0000-0000-000000000002','00000000-0000-0000-0000-000000000001','管理员');
|
||||
|
||||
|
||||
CREATE TABLE browser_sessions (
|
||||
|
||||
@@ -90,7 +90,7 @@ CREATE TABLE billing_migration_issues (
|
||||
);
|
||||
INSERT INTO billing_quotas(subject_type,group_id,credits_per_cycle,updated_by_user_id)
|
||||
SELECT 'group','00000000-0000-0000-0000-000000000001',CASE WHEN (s.value->>'root_credits') ~ '^\d+(\.\d{1,6})?$' THEN (s.value->>'root_credits')::numeric ELSE 15000 END,s.updated_by_user_id
|
||||
FROM settings s WHERE s.key='billing' AND NOT EXISTS(SELECT 1 FROM billing_quotas WHERE group_id='00000000-0000-0000-0000-000000000001' AND deleted_at IS NULL);
|
||||
FROM settings s WHERE s.key='billing' AND EXISTS(SELECT 1 FROM groups WHERE id='00000000-0000-0000-0000-000000000001') AND NOT EXISTS(SELECT 1 FROM billing_quotas WHERE group_id='00000000-0000-0000-0000-000000000001' AND deleted_at IS NULL);
|
||||
CREATE TEMP TABLE billing_legacy_quotas ON COMMIT DROP AS
|
||||
SELECT e.key,e.value,s.updated_by_user_id,
|
||||
CASE WHEN g.id IS NOT NULL AND u.id IS NULL THEN 'group' WHEN u.id IS NOT NULL AND g.id IS NULL THEN 'user' END subject_type,
|
||||
@@ -108,7 +108,7 @@ INSERT INTO billing_quotas(subject_type,group_id,user_id,credits_per_cycle,updat
|
||||
SELECT l.subject_type,l.group_id,l.user_id,l.credits,l.updated_by_user_id FROM billing_legacy_quotas l
|
||||
WHERE l.subject_type IS NOT NULL AND l.credits IS NOT NULL AND NOT EXISTS(SELECT 1 FROM billing_quotas q WHERE q.deleted_at IS NULL AND (q.group_id=l.group_id OR q.user_id=l.user_id));
|
||||
|
||||
UPDATE settings SET value=value-'root_credits'-'quota_overrides'-'remote_billing_api_key'-'remote_billing_base_url',revision=revision+1 WHERE key='billing';
|
||||
UPDATE settings SET value=value-'quota_overrides'-'remote_billing_api_key'-'remote_billing_base_url',revision=revision+1 WHERE key='billing';
|
||||
CREATE FUNCTION billing_immutable_ledger() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION '计费流水不可修改或删除,请使用冲正'; END $$;
|
||||
CREATE TRIGGER credit_ledger_immutable BEFORE UPDATE OR DELETE ON credit_ledger_entries FOR EACH ROW EXECUTE FUNCTION billing_immutable_ledger();
|
||||
COMMIT;
|
||||
@@ -0,0 +1,4 @@
|
||||
DO $$
|
||||
BEGIN
|
||||
RAISE EXCEPTION '旧系统分组授权已转换为用户授权,无法无损回滚;请恢复升级前的数据库备份';
|
||||
END $$;
|
||||
@@ -0,0 +1,89 @@
|
||||
BEGIN;
|
||||
|
||||
LOCK TABLE groups, group_users, resource_access_grants, users, settings, billing_quotas, credit_accounts, billing_transactions, credit_ledger_entries IN SHARE ROW EXCLUSIVE MODE;
|
||||
|
||||
DROP INDEX IF EXISTS groups_one_active_root_key;
|
||||
|
||||
-- 将旧系统组的有效授权保留为当前成员的直接授权,不再按角色自动扩展。
|
||||
WITH RECURSIVE descendants(root_id, id) AS (
|
||||
SELECT id, id FROM groups
|
||||
WHERE id IN ('00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000002')
|
||||
AND deleted_at IS NULL
|
||||
UNION
|
||||
SELECT d.root_id, g.id FROM groups g
|
||||
JOIN descendants d ON g.parent_id = d.id
|
||||
WHERE g.deleted_at IS NULL
|
||||
), members(group_id, user_id) AS (
|
||||
SELECT g.id, u.id FROM groups g CROSS JOIN users u
|
||||
WHERE g.id = '00000000-0000-0000-0000-000000000001'
|
||||
AND g.deleted_at IS NULL AND u.deleted_at IS NULL
|
||||
UNION
|
||||
SELECT g.id, u.id FROM groups g CROSS JOIN users u
|
||||
WHERE g.id = '00000000-0000-0000-0000-000000000002'
|
||||
AND g.deleted_at IS NULL AND u.deleted_at IS NULL AND u.role = 'admin'
|
||||
UNION
|
||||
SELECT d.root_id, gu.user_id FROM descendants d
|
||||
JOIN group_users gu ON gu.group_id = d.id AND gu.removed_at IS NULL
|
||||
JOIN users u ON u.id = gu.user_id AND u.deleted_at IS NULL
|
||||
)
|
||||
INSERT INTO resource_access_grants (
|
||||
resource_type, resource_id, user_id, access_level,
|
||||
usage_requirement, granted_by_user_id, created_at
|
||||
)
|
||||
SELECT g.resource_type, g.resource_id, m.user_id,
|
||||
CASE WHEN bool_or(g.access_level = 'read_write') THEN 'read_write' ELSE 'read_only' END,
|
||||
CASE WHEN bool_or(g.usage_requirement = 'required') THEN 'required' ELSE 'optional' END,
|
||||
min(g.granted_by_user_id::text)::uuid, min(g.created_at)
|
||||
FROM resource_access_grants g
|
||||
JOIN members m ON m.group_id = g.group_id
|
||||
GROUP BY g.resource_type, g.resource_id, m.user_id
|
||||
ON CONFLICT (resource_type, resource_id, user_id) WHERE user_id IS NOT NULL
|
||||
DO UPDATE SET
|
||||
access_level = CASE WHEN resource_access_grants.access_level = 'read_write' OR EXCLUDED.access_level = 'read_write' THEN 'read_write' ELSE 'read_only' END,
|
||||
usage_requirement = CASE WHEN resource_access_grants.usage_requirement = 'required' OR EXCLUDED.usage_requirement = 'required' THEN 'required' ELSE 'optional' END,
|
||||
updated_at = now();
|
||||
|
||||
-- 团队额度改存计费设置;管理员组的既有额度转为当前成员或直属子组的显式额度。
|
||||
UPDATE settings s SET value=jsonb_set(s.value,'{root_credits}',to_jsonb(q.credits_per_cycle::text)), revision=revision+1
|
||||
FROM billing_quotas q
|
||||
WHERE s.key='billing' AND q.group_id='00000000-0000-0000-0000-000000000001' AND q.deleted_at IS NULL;
|
||||
|
||||
INSERT INTO billing_quotas(subject_type,user_id,credits_per_cycle,updated_by_user_id)
|
||||
SELECT 'user',u.id,q.credits_per_cycle,q.updated_by_user_id FROM users u CROSS JOIN billing_quotas q
|
||||
WHERE q.group_id='00000000-0000-0000-0000-000000000002' AND q.deleted_at IS NULL
|
||||
AND u.deleted_at IS NULL
|
||||
AND (u.billing_group_id=q.group_id OR (u.billing_group_id IS NULL AND u.role='admin'))
|
||||
ON CONFLICT (user_id) WHERE subject_type='user' AND deleted_at IS NULL DO NOTHING;
|
||||
|
||||
INSERT INTO billing_quotas(subject_type,group_id,credits_per_cycle,updated_by_user_id)
|
||||
SELECT 'group',g.id,q.credits_per_cycle,q.updated_by_user_id FROM groups g JOIN billing_quotas q ON q.group_id=g.parent_id
|
||||
WHERE q.group_id='00000000-0000-0000-0000-000000000002' AND q.deleted_at IS NULL AND g.deleted_at IS NULL
|
||||
ON CONFLICT (group_id) WHERE subject_type='group' AND deleted_at IS NULL DO NOTHING;
|
||||
|
||||
UPDATE users SET billing_group_id=NULL
|
||||
WHERE billing_group_id IN ('00000000-0000-0000-0000-000000000001','00000000-0000-0000-0000-000000000002');
|
||||
UPDATE credit_accounts SET group_id=NULL
|
||||
WHERE group_id IN ('00000000-0000-0000-0000-000000000001','00000000-0000-0000-0000-000000000002');
|
||||
UPDATE billing_transactions SET group_id=NULL
|
||||
WHERE group_id IN ('00000000-0000-0000-0000-000000000001','00000000-0000-0000-0000-000000000002');
|
||||
-- 仅迁移分组引用,流水金额、顺序、余额及业务标识保持不变。
|
||||
ALTER TABLE credit_ledger_entries DISABLE TRIGGER credit_ledger_immutable;
|
||||
UPDATE credit_ledger_entries SET metadata=metadata || jsonb_build_object('legacy_group_id',group_id),group_id=NULL
|
||||
WHERE group_id IN ('00000000-0000-0000-0000-000000000001','00000000-0000-0000-0000-000000000002');
|
||||
ALTER TABLE credit_ledger_entries ENABLE TRIGGER credit_ledger_immutable;
|
||||
DELETE FROM billing_quotas
|
||||
WHERE group_id IN ('00000000-0000-0000-0000-000000000001','00000000-0000-0000-0000-000000000002');
|
||||
|
||||
UPDATE groups SET parent_id = NULL, updated_at = now()
|
||||
WHERE parent_id IN ('00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000002');
|
||||
|
||||
DELETE FROM group_users
|
||||
WHERE group_id IN ('00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000002');
|
||||
|
||||
DELETE FROM resource_access_grants
|
||||
WHERE group_id IN ('00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000002');
|
||||
|
||||
DELETE FROM groups
|
||||
WHERE id IN ('00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000002');
|
||||
|
||||
COMMIT;
|
||||
@@ -1,12 +1,17 @@
|
||||
# 数据库初始化
|
||||
# 数据库迁移
|
||||
|
||||
本次按重新部署要求,将原版本 000001—000004 与资源模型整合为一版:
|
||||
- `000001_initial_create_schema`:完整初始结构,包含身份、OAuth、调用密钥、模型、资源、计费及审计;不预置任何分组。
|
||||
- `000002_billing_create_transactions`:计费账户、额度与流水。
|
||||
- `000003_group_virtual_root`:将旧部署的系统分组转换为虚拟团队根节点的结构。新库同样执行此版本,不会创建分组。
|
||||
|
||||
- `000001_initial_create_schema.up.sql`:完整最终结构,包含身份、OAuth、调用密钥、模型、资源、计费及审计。
|
||||
- `000001_initial_create_schema.down.sql`:依赖逆序撤销全部表,仅供可丢弃测试数据库验证。
|
||||
运行 `migrate -path migrations -database "$MONKEYAI_DATABASE_URL" up`。成功后应为 `version=3, dirty=false`,再次执行为 `no change`。已有版本 1 或 2 的数据库执行增量升级,无需清库或 `force`。
|
||||
|
||||
必须连接**新的 PostgreSQL 数据库或数据目录**。仅重新创建容器并继续挂载旧目录不会重新执行版本 1;不要对旧库使用 `force 1` 代替初始化。此仓库改动不会清空现有数据库。
|
||||
团队根节点仅用于界面展示,名称读取 `settings` 中 `branding` 的 `workspace_name`,不写入 `groups`。`parent_id IS NULL` 的记录均为团队根节点的直属子分组;成员关系通过 `group_users` 显式维护,不根据用户角色自动建组或分配。
|
||||
|
||||
初始化:`migrate -path migrations -database "$MONKEYAI_DATABASE_URL" up`。首次成功后应为 `version=1, dirty=false`,再次执行为 `no change`。迁移镜像只包含这一对 SQL。
|
||||
版本 3 升级会移除旧版固定 ID 的根组和管理员组,将它们的子分组提升到团队下,保留自定义分组、成员账号和自定义组的成员关系。旧系统组的资源授权转换为升级时有效成员的直接用户授权,保留强制规则和读写权限;后续新用户或角色变化不会自动获得这些授权。用户原有的直接授权和其他分组授权会保留。
|
||||
|
||||
本次单版重置仅适用于本轮重新部署,后续正式发布的 schema 变更恢复追加版本。字符串统一使用 `text`,候选值使用 `CHECK`,名称按 `lower(btrim(name))` 约束唯一。
|
||||
升级前应备份数据库。系统分组及其授权转换无法无损还原,因此版本 3 的 down 脚本明确拒绝回滚,需要恢复升级前备份。版本 1 的 down 脚本仅供可丢弃测试数据库验证。
|
||||
|
||||
后续 schema 变更追加迁移版本。字符串统一使用 `text`,候选值使用 `CHECK`。
|
||||
|
||||
团队额度存入计费设置,旧管理员组额度转为当前相关用户及直属子分组的显式额度。旧系统组计费归属置空,历史账户金额保持不变,流水的旧分组 ID 留在 metadata 中。
|
||||
@@ -51,7 +51,7 @@ func TestMigrations(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
if versions["000001"] != "initial_create_schema" || versions["000002"] != "billing_create_transactions" {
|
||||
if versions["000001"] != "initial_create_schema" || versions["000002"] != "billing_create_transactions" || versions["000003"] != "group_virtual_root" {
|
||||
t.Error("必须保留初始化迁移及计费增量迁移")
|
||||
}
|
||||
for key, directions := range pairs {
|
||||
|
||||
@@ -48,7 +48,7 @@
|
||||
|
||||
系统规则的强制启用与普通资源分享具有相同的“资源—用户或分组”关系,因此统一保存在 `resource_access_grants`,不再设计规则专用关系表。`access_level` 表示被授权者能对资源做什么,`usage_requirement` 表示被授权者能否自行决定是否使用,两者保持正交。`required` 目前只适用于系统规则,表示规则必须应用且用户不可自行移除;个人规则及其他资源只能使用 `optional`。
|
||||
|
||||
系统初始化时创建且仅创建一个根分组,管理接口不提供新建、移动或删除根分组的能力。根分组通过 `parent_id` 为空识别。管理员分组同样由系统初始化,并使用系统预设 ID 识别,其成员根据 `users.role = 'admin'` 动态确定,不写入 `group_users`。`groups` 不额外保存分组类型或系统标识字段。
|
||||
系统不初始化任何分组。团队根节点仅用于展示,不写入 `groups`,名称读取 `branding.workspace_name`;所有 `parent_id` 为空的记录都是团队根节点的直属子分组。管理员角色不产生分组或成员关系,所有真实分组的直接成员均通过 `group_users` 维护。团队根节点可新建子分组,其名称在团队设置中修改。
|
||||
|
||||
### 2.5 S3 文件存储
|
||||
|
||||
@@ -168,21 +168,21 @@ flowchart LR
|
||||
|
||||
### 5.3 `groups`:分组
|
||||
|
||||
用于组织用户、承载授权范围并形成额度继承树。系统初始化时创建唯一根分组和管理员分组;管理端只能在已有分组下创建子分组。
|
||||
用于组织用户、承载授权范围并形成额度继承树。不预置分组;管理端可在虚拟团队根节点或已有分组下创建子分组。
|
||||
|
||||
| 字段 | PostgreSQL 类型 | 必填 | 默认值 | 说明 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `id` | `uuid` | 是 | 自动生成 | 分组 ID;根分组和管理员分组使用系统预设 ID。 |
|
||||
| `parent_id` | `uuid` | 否 | `NULL` | 父分组 ID;唯一根分组为空,其他分组必须有父分组。 |
|
||||
| `id` | `uuid` | 是 | 自动生成 | 分组 ID,均由创建操作生成。 |
|
||||
| `parent_id` | `uuid` | 否 | `NULL` | 父分组 ID;为空时表示直属虚拟团队根节点。 |
|
||||
| `name` | `text` | 是 | 无 | 分组显示名称。 |
|
||||
| `created_by_user_id` | `uuid` | 否 | `NULL` | 创建者用户 ID;系统初始化的根分组和管理员分组为空。 |
|
||||
| `created_by_user_id` | `uuid` | 否 | `NULL` | 创建者用户 ID。 |
|
||||
| `created_at` | `timestamptz` | 是 | 当前时间 | 创建时间。 |
|
||||
| `updated_at` | `timestamptz` | 是 | 当前时间 | 名称或层级最近更新时间。 |
|
||||
| `deleted_at` | `timestamptz` | 否 | `NULL` | 普通分组的软删除时间;根分组和管理员分组不可删除。 |
|
||||
| `deleted_at` | `timestamptz` | 否 | `NULL` | 分组软删除时间;删除前须迁移子分组及成员计费归属。 |
|
||||
|
||||
### 5.4 `group_users`:分组用户关系
|
||||
|
||||
记录用户被直接分配到的普通分组;父分组用户数量通过后代分组汇总。根分组包含所有用户,管理员分组成员由 `users.role` 动态确定,两者均不写入本表。
|
||||
记录真实分组的直接成员;父分组成员与后代成员合并去重。虚拟团队根节点显示所有用户,不产生分组关系记录;用户角色不影响所属分组。
|
||||
|
||||
| 字段 | PostgreSQL 类型 | 必填 | 默认值 | 说明 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
@@ -618,7 +618,7 @@ Expert 关联 Connector Provider 类型,不直接绑定包含账号与凭证
|
||||
|
||||
### 10.1 `billing_quotas`:额度覆盖设置
|
||||
|
||||
没有额度记录表示继承最近上级分组;根分组必须有记录。
|
||||
没有额度记录表示继承最近上级分组,最终回落计费设置中的 `root_credits`。虚拟团队根节点不在本表创建额度记录。
|
||||
|
||||
| 字段 | PostgreSQL 类型 | 必填 | 默认值 | 说明 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
|
||||
@@ -59,7 +59,7 @@
|
||||
- 父分组授权覆盖后代分组用户;同一资源命中多个授权时取并集,规则的 `required` 优先于 `optional`。
|
||||
- Provider 描述连接方式,不参与资源访问授权。系统 Provider 可见不等于其 Connector 可用。
|
||||
|
||||
提供真实的授权对象查询。初始化根分组和管理员分组,并在可用性查询中明确“所有有效用户属于根分组、管理员分组按角色计算”,避免新用户缺少手工成员关系而收不到“所有用户”资源。其他已有分组按 `group_users` 和父子关系解析。现有模型查询同步使用这套分组语义,避免模型与其他资源的授权结果不同。本次不依赖组织架构编辑器才能完成授权。
|
||||
提供真实的授权对象查询。不预置分组,团队根节点仅作展示;资源授权按 `group_users` 的直接关系及未删除的上级分组解析,不按顶层位置或管理员角色自动授予。模型与其他资源使用同样的分组语义。新资源不默认引用旧系统根组,管理员须显式选择授权成员或真实分组。
|
||||
|
||||
### 3.2 技能与规则
|
||||
|
||||
@@ -328,7 +328,7 @@ B、C、D 完成各自闭环后再集成 E,F 完成才标记本次功能交付
|
||||
|
||||
必要验证覆盖:
|
||||
|
||||
- 用户 A 有权限、B 无权限;父组、根组、管理员组和撤权后的配置差异。
|
||||
- 用户 A 有权限、B 无权限;父组继承、无父级分组的成员隔离、角色不隐式授予分组权限,以及撤权后的配置差异。
|
||||
- 资源和授权同时保存失败时回滚,关联资源删除返回引用信息。
|
||||
- 无变化配置返回 304;规则正文、技能包、专家依赖、工具目录或授权变化返回新版本;下载地址签名不会造成版本抖动。
|
||||
- ZIP 路径、链接、重复项、超额展开、损坏摘要;批量部分失败和重复提交后的结果核对。
|
||||
@@ -364,7 +364,7 @@ B、C、D 完成各自闭环后再集成 E,F 完成才标记本次功能交付
|
||||
## 11. 实施验收记录(2026-09-07)
|
||||
|
||||
- 后端 `go test ./... -count=1`、`go vet ./...` 通过;测试显式连接独立 PostgreSQL 与 RustFS,集成测试未跳过。
|
||||
- 集成测试验证规则保存、行级修订冲突、用户与父子分组授权、根组强制规则、配置 ETag/304、技能上传与包重建、专家复制与依赖、委托下载和撤权、模板图标权限、真实 MCP HTTP 握手/发现、独立认证工具目录隔离,以及 OAuth state/PKCE 与回调防重放。
|
||||
- 集成测试验证规则保存、行级修订冲突、用户与父子分组授权、用户及分组强制规则、配置 ETag/304、技能上传与包重建、专家复制与依赖、委托下载和撤权、模板图标权限、真实 MCP HTTP 握手/发现、独立认证工具目录隔离,以及 OAuth state/PKCE 与回调防重放。
|
||||
- 非对象 JSON 与多个 JSON 文档返回 400;技能包元数据摘要被篡改时,下载和编辑清单返回 502,不返回损坏内容。
|
||||
- RustFS 测试覆盖重复建桶初始化、上传、读取、Bucket 可访问性和对象删除。重启测试 RustFS 后再次下载浏览器上传并编辑的技能,包摘要、正文和附件一致。
|
||||
- 前端 `pnpm test` 全部 38 项通过,`pnpm lint`、`pnpm build` 通过。构建仍有已有的大 chunk 提示,不影响构建成功。
|
||||
@@ -384,3 +384,5 @@ B、C、D 完成各自闭环后再集成 E,F 完成才标记本次功能交付
|
||||
- 本地 OAuth 协议模拟器已覆盖授权事务和防重放;生产 OAuth 应用的回调登记、完整生产备份恢复演练和新部署环境冒烟由部署环境执行。
|
||||
|
||||
重新部署步骤见 `../README.md`,必须使用新数据库或新 PostgreSQL 数据目录,不能把已有版本 1 的库强行标记成新的结构。
|
||||
|
||||
2026-09-07 分组规则修订已实现:使用虚拟团队根节点,旧系统组授权转为升级时成员的直接授权,后续新增用户不自动获得这些授权。
|
||||
@@ -37,10 +37,10 @@
|
||||
|
||||
### 3.1 额度、余额与分组
|
||||
|
||||
- **分组额度是用户默认额度模板**。用户各自拥有积分账户,分组不另设共享消费池。截图中根分组 15,000、管理员分组 50,000 可以同时成立。
|
||||
- 用户显式额度优先;否则沿用户的计费归属分组向上查找最近显式额度,最终回落根分组。`null` 表示继承,`0` 表示该周期没有可消费额度,负值非法。
|
||||
- 当前授权关系允许用户属于多个分组。推荐单独设置一个“计费归属分组”,授权关系仍可多选。未指定时管理员默认归属管理员分组,其他用户归属根分组;不得把多组额度相加,也不得按数据库返回顺序选一个。
|
||||
- 分组页补齐创建、改名、移动、删除及成员归属维护的最小能力,复用根分组与管理员分组语义。禁止环和删除根分组;删除仍有子组或计费归属用户的分组时要求先迁移。
|
||||
- **分组额度是用户默认额度模板**。用户各自拥有积分账户,分组不另设共享消费池。团队默认额度 15,000、自定义分组额度 50,000 可以同时成立。
|
||||
- 用户显式额度优先;否则沿用户的计费归属分组向上查找最近显式额度,最终回落团队默认额度(计费设置 `root_credits`)。`null` 表示继承,`0` 表示该周期没有可消费额度,负值非法。
|
||||
- 当前授权关系允许用户属于多个分组。推荐单独设置一个“计费归属分组”,授权关系仍可多选。未指定时统一继承团队默认额度,用户角色不决定计费分组;不得把多组额度相加,也不得按数据库返回顺序选一个。
|
||||
- 分组页补齐创建、改名、移动、删除及成员归属维护的最小能力,团队根节点仅用于展示,不入库,不预置管理员组。禁止环;删除仍有子组或计费归属用户的分组时要求先迁移。
|
||||
- 额度配置、分组迁移和角色变化默认在下个周期影响额度,不因修改配置重新发放当期积分。确需当期补发或回收时使用独立的“调整当期积分”,必须填写原因、记录审计;回收不得侵占已冻结积分。
|
||||
- 新用户首次开户按当期完整额度发放一次,不按天折算。被停用用户不能发起新调用;恢复启用不再次发放同周期额度。
|
||||
- 余额分为账面剩余、冻结和可用:`可用积分 = 账面剩余 - 冻结积分`。界面明确显示三个口径,避免将“每月额度”等同于“当前余额”。
|
||||
@@ -239,7 +239,7 @@ flowchart TD
|
||||
## 8. 迁移和发布策略
|
||||
|
||||
- 当前仓库曾为重新部署收敛到初始化迁移 `000001`,那是前一个资源任务的特定安排。本次默认保留已有数据,追加 `billing` 增量迁移;不沿用旧方案去清空数据库或重写已执行迁移。
|
||||
- 配置 JSON 中的 `root_credits` 迁入真实根分组额度;仅迁移能验证用户/分组存在的 UUID 覆盖。`engineering`、`member-01` 等模拟 ID 输出迁移报告,由管理员处理,不按名称猜归属。
|
||||
- 团队默认额度保存在配置 JSON 的 `root_credits` 中,版本 3 将旧真实根分组额度迁回该设置;仅迁移能验证用户/分组存在的 UUID 覆盖。`engineering`、`member-01` 等模拟 ID 输出迁移报告,由管理员处理,不按名称猜归属。
|
||||
- 同时存在额度表和旧 JSON 时,先输出差异,表中已生效配置优先;冲突不能静默覆盖。旧字段在切换读取来源后停止写入。
|
||||
- 已有账户及流水保留,补齐当前周期标识;未知历史价格或外部身份只标记未知,不用现价重算历史账单。
|
||||
- 首次启用正式扣费前,完成根额度、账户初始化及真实用量采集验证,记录启用时间;不追扣启用前调用。该开关属于发布控制,与“本地/远程”商业模式分开。
|
||||
@@ -264,7 +264,7 @@ P1 完成的是配置和额度能力;P2 完成模型本地计费;只有 P3
|
||||
|
||||
| 场景 | 预期 |
|
||||
| --- | --- |
|
||||
| 根 15,000、管理员组 50,000、用户继承/覆盖/零额度 | 按确定的计费归属逐级解析,不相加、不随机取组 |
|
||||
| 团队 15,000、自定义分组 50,000、用户继承/覆盖/零额度 | 按确定的计费归属逐级解析,不相加、不随机取组 |
|
||||
| 两张卡片有草稿,只保存价格;两名管理员同时编辑 | 不携带其他卡片草稿,不静默覆盖冲突版本 |
|
||||
| 余额 10,并发多个各预留 4 的请求 | 最多两个获准执行,账户和冻结额合法 |
|
||||
| 示例输入 10,000、缓存 4,000、输出 2,000 | 价格 100/20/400、倍率 1 时,最终 1.48 积分 |
|
||||
@@ -321,3 +321,5 @@ P1 完成的是配置和额度能力;P2 完成模型本地计费;只有 P3
|
||||
|
||||
|
||||
PR 交付状态(2026-09-07):已同步 `origin/main`(`fbaed233`),合并保留用户模型/分享接口与新增计费/MCP 网关接口,解决 OpenAPI 冲突。同步后重新通过后端完整 PostgreSQL/RustFS 集成测试、`go vet ./...`、前端 38 项测试、lint、生产构建,以及两份 OpenAPI 的重复键与本地引用校验。P1–P3 和 P5 本地验收完成,进入 PR 交付阶段;P4 真实钱包联调继续保持待完成,默认扣费开关关闭。
|
||||
|
||||
2026-09-07 分组规则修订已实现:团队根节点不入库、不预置分组;旧系统分组授权及额度随版本 3 迁移,分组操作继续保留用户当期账户额度。
|
||||
Reference in new issue
Block a user