WebHooker/app/composables/useGroups.ts
RhenCloud e59b10f739
refactor(admin): unify webui fetch/copy/format helpers; fix audit tab load and delete-group count
- apiFetch + shared needLogin (any 401 shows the login card) replaces six
  duplicated fetch/401/error-handling blocks in the admin composables
- useCopy composable: clipboard + execCommand fallback with timed reset,
  used by MembersPanel and WebhookPanel
- utils/format.ts (fmtTime/splitList/parseMatch) removes inline duplicates
  across SendLogs, AuditLog, RouteEditor and GroupEditor
- fix: load the audit log when the audit tab becomes active (client-side
  navigation never remounted the page, leaving the list empty on first visit)
- fix: fetch the real route count for a group before confirming deletion
  instead of reusing the currently open group's route list
2026-08-14 07:18:55 +08:00

76 lines
2 KiB
TypeScript

import type { Group, GroupRole } from "~/types";
export function useGroupsApi() {
const { needLogin } = useAuthState();
const groups = ref<Group[]>([]);
const isSuper = ref(false);
/** groupId → role of the signed-in user (absent for super admins). */
const roles = ref<Record<string, GroupRole>>({});
const loading = ref(false);
const error = ref("");
function roleOf(groupId: string): GroupRole | undefined {
return isSuper.value ? "owner" : roles.value[groupId];
}
function canEditGroup(groupId: string): boolean {
const r = roleOf(groupId);
return isSuper.value || r === "owner";
}
function canEditRoutes(groupId: string): boolean {
const r = roleOf(groupId);
return isSuper.value || r === "owner" || r === "admin";
}
async function load(): Promise<void> {
loading.value = true;
error.value = "";
needLogin.value = false;
try {
const data = await apiFetch<{
groups?: Group[];
isSuper?: boolean;
roles?: Record<string, GroupRole>;
}>("/admin/api/groups");
groups.value = data.groups ?? [];
isSuper.value = data.isSuper ?? false;
roles.value = data.roles ?? {};
} catch (err) {
if (!needLogin.value) error.value = err instanceof Error ? err.message : String(err);
} finally {
loading.value = false;
}
}
async function save(next: Group[]): Promise<void> {
await apiFetch("/admin/api/groups", {
method: "PUT",
body: JSON.stringify({ groups: next }),
});
groups.value = next;
}
/** Rename a group; routes, webhook secret and invites follow automatically. */
async function rename(oldId: string, newId: string): Promise<void> {
await apiFetch(`/admin/api/groups/${encodeURIComponent(oldId)}/rename`, {
method: "PUT",
body: JSON.stringify({ newId }),
});
}
return {
groups,
isSuper,
roles,
roleOf,
canEditGroup,
canEditRoutes,
loading,
needLogin,
error,
load,
save,
rename,
};
}