summaryrefslogtreecommitdiff
path: root/frontend/src/pages/AdminPage.svelte
blob: 2a102667d8d0f2110db71622fc693ff42dfbbaf6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
<script lang="ts">
  import Page from '../components/Page.svelte';
  import Status from '../components/Status.svelte';
  import Modal from '../components/Modal.svelte';
  import {
    listAdminUsers,
    patchAdminUser,
    createInvitation,
    listInvitations,
    deleteInvitation,
    getAdminAudit,
    postAdminUserPassword
  } from '../lib/client';
  import { extractStatusMessage } from '../lib/state';
  import { Button } from '$lib/components/ui/button';
  import { Input } from '$lib/components/ui/input';
  import { Alert } from '$lib/components/ui/alert';
  import { Badge } from '$lib/components/ui/badge';
  import { Label } from '$lib/components/ui/label';
  import * as Select from '$lib/components/ui/select';
  import * as Tabs from '$lib/components/ui/tabs';
  import * as Card from '$lib/components/ui/card';
  import * as Table from '$lib/components/ui/table';
  import { fmtDateTime } from '../lib/format';
  import type { User, Invitation } from '../lib/types';

  let tab = $state<'users' | 'invites' | 'audit'>('users');


  let users: User[] = $state([]);
  let usersBusy = $state(true);
  let usersErr = $state<string | null>(null);
  let resetFor = $state<User | null>(null);
  let resetToken = $state('');
  let resetting = $state(false);
  let adminOpsErr = $state<string | null>(null);
  let inviteCopied = $state(false);

  let invites: Invitation[] = $state([]);
  let inviteBusy = $state(true);
  let inviteErr = $state<string | null>(null);
  let inviteEmail = $state('');
  let inviteHours = $state(72);
  let creatingInvite = $state(false);
  let newInvite = $state<{ token: string; expires_at: string } | null>(null);
  let gotToken = $state(false);

  let audit: { actor?: string | null; action: string; target?: string | null; status: string; time: string; detail?: string | null }[] = $state([]);
  let auditBusy = $state(true);
  let auditErr = $state<string | null>(null);

  $effect(() => {
    void loadTab(tab);
  });

  async function loadTab(t: 'users' | 'invites' | 'audit') {
    if (t === 'users') await loadUsers();
    else if (t === 'invites') await loadInvites();
    else await loadAudit();
  }

  async function loadUsers() {
    usersBusy = true;
    usersErr = null;
    try {
      const { items } = await listAdminUsers();
      users = items;
    } catch (e) {
      usersErr = extractStatusMessage(e);
    } finally {
      usersBusy = false;
    }
  }

  async function loadInvites() {
    inviteBusy = true;
    inviteErr = null;
    try {
      const { items } = await listInvitations();
      invites = items;
    } catch (e) {
      inviteErr = extractStatusMessage(e);
    } finally {
      inviteBusy = false;
    }
  }

  async function loadAudit() {
    auditBusy = true;
    auditErr = null;
    try {
      const res = await getAdminAudit();
      audit = res.items;
    } catch (e) {
      auditErr = extractStatusMessage(e);
    } finally {
      auditBusy = false;
    }
  }

  async function patchUser(u: User, patch: { active?: boolean; role?: 'admin' | 'member'; daily_run_limit?: number | null; ai_enabled?: boolean }) {
    adminOpsErr = null;
    try {
      const fresh = await patchAdminUser(u.id, patch);
      users = users.map((x) => (x.id === fresh.id ? fresh : x));
    } catch (e) {
      adminOpsErr = extractStatusMessage(e);
    }
  }

  async function issueReset(u: User) {
    resetFor = u;
    resetToken = '';
    adminOpsErr = null;
    resetting = true;
    try {
      const res = await postAdminUserPassword(u.id);
      resetToken = res.reset_token;
    } catch (e) {
      adminOpsErr = extractStatusMessage(e);
      resetFor = null;
    } finally {
      resetting = false;
    }
  }

  async function makeInvite(e: SubmitEvent) {
    e.preventDefault();
    creatingInvite = true;
    inviteErr = null;
    newInvite = null;
    try {
      const res = await createInvitation({
        email: inviteEmail.trim() || undefined,
        expires_hours: inviteHours
      });
      newInvite = res;
      inviteEmail = '';
      await loadInvites();
    } catch (err) {
      inviteErr = extractStatusMessage(err);
    } finally {
      creatingInvite = false;
    }
  }

  async function revokeInvite(i: Invitation) {
    adminOpsErr = null;
    try {
      await deleteInvitation(i.id);
      await loadInvites();
    } catch (e) {
      adminOpsErr = extractStatusMessage(e);
    }
  }

  async function copy(text: string) {
    try {
      await navigator.clipboard.writeText(text);
      inviteCopied = true;
    } catch {
      /* clipboard unavailable; user will select manually */
    }
  }

  const inviteUrl = $derived(
    newInvite
      ? `${window.location.origin}${window.location.pathname}#/register?invite=${encodeURIComponent(newInvite.token)}`
      : ''
  );
  const resetUrl = $derived(
    resetToken
      ? `${window.location.origin}${window.location.pathname}#/reset?token=${encodeURIComponent(resetToken)}`
      : ''
  );
</script>

<Page title="管理员" subtitle="用户与邀请管理、安全审计。不会直接查看他人策略代码">
  {#snippet actions()}
    <Tabs.Root value={tab} onValueChange={(v) => (tab = v as 'users' | 'invites' | 'audit')}>
      <Tabs.List variant="line">
        <Tabs.Trigger value="users">用户</Tabs.Trigger>
        <Tabs.Trigger value="invites">邀请与恢复</Tabs.Trigger>
        <Tabs.Trigger value="audit">审计日志</Tabs.Trigger>
      </Tabs.List>
    </Tabs.Root>
  {/snippet}

  <div class="flex flex-col gap-3">
    <Status busy={false} error={adminOpsErr} empty={null} />

    {#if tab === 'users'}
      <Card.Root size="sm" class="p-4 flex flex-col gap-3">
        <h2 class="text-lg font-semibold">用户</h2>
        <Status busy={usersBusy} error={usersErr} busyText="载入用户…" empty={null} />
        {#if !usersBusy && !usersErr && users.length > 0}
          <Table.Root>
            <Table.Header>
              <Table.Row>
                <Table.Head>邮箱</Table.Head>
                <Table.Head>姓名</Table.Head>
                <Table.Head>角色</Table.Head>
                <Table.Head>状态</Table.Head>
                <Table.Head>AI 权限</Table.Head>
                <Table.Head>日回测上限</Table.Head>
                <Table.Head>操作</Table.Head>
              </Table.Row>
            </Table.Header>
            <Table.Body>
              {#each users as u (u.id)}
                <Table.Row>
                  <Table.Cell>{u.email}</Table.Cell>
                  <Table.Cell>{u.name}</Table.Cell>
                  <Table.Cell>
                    <Select.Root
                      type="single"
                      value={u.role}
                      onValueChange={(v) => void patchUser(u, { role: v as 'admin' | 'member' })}
                    >
                      <Select.Trigger data-testid="role-select" class="w-32">{u.role === 'admin' ? '管理员' : '成员'}</Select.Trigger>
                      <Select.Content>
                        <Select.Item value="member">成员</Select.Item>
                        <Select.Item value="admin">管理员</Select.Item>
                      </Select.Content>
                    </Select.Root>
                  </Table.Cell>
                  <Table.Cell>
                    <Badge variant={u.active ? 'secondary' : 'destructive'}>{u.active ? '启用' : '停用'}</Badge>
                  </Table.Cell>
                  <Table.Cell>
                    <label class="inline-flex items-center gap-1">
                      <input type="checkbox" checked={u.ai_enabled ?? false} onchange={(e) => void patchUser(u, { ai_enabled: (e.target as HTMLInputElement).checked })} />
                    </label>
                  </Table.Cell>
                  <Table.Cell>
                    <Input
                      class="tabular-nums w-24"
                      type="number"
                      min="0"
                      max="200"
                      value={u.daily_run_limit ?? 5}
                      onchange={(e) => void patchUser(u, { daily_run_limit: Number((e.target as HTMLInputElement).value) })}
                    />
                  </Table.Cell>
                  <Table.Cell>
                    <div class="flex items-center gap-2 flex-wrap">
                      <Button variant={u.active ? 'destructive' : 'outline'} size="sm" onclick={() => void patchUser(u, { active: !u.active })}>
                        {u.active ? '停用' : '启用'}
                      </Button>
                      <Button variant="outline" size="sm" disabled={resetting} onclick={() => void issueReset(u)}>生成恢复</Button>
                    </div>
                  </Table.Cell>
                </Table.Row>
              {/each}
            </Table.Body>
          </Table.Root>
        {/if}
        <p class="text-sm text-muted-foreground">停用账户会立即吊销其会话并阻止其回测与 AI 请求。角色不能作用于他人项目,私阅策略代码不提供。</p>
      </Card.Root>
    {:else if tab === 'invites'}
      <Card.Root size="sm" class="p-4 flex flex-col gap-3">
        <h2 class="text-lg font-semibold">签发邀请</h2>
        <form onsubmit={makeInvite} class="flex flex-wrap items-end gap-3">
          <div class="flex-[1_1_220px]">
            <Label for="inv-em">邮箱(可选备注)</Label>
            <Input id="inv-em" bind:value={inviteEmail} placeholder="📬 将线下告知受邀人,用于区分" />
          </div>
          <div class="w-[130px]">
            <Label for="inv-h">有效小时</Label>
            <Input id="inv-h" type="number" bind:value={inviteHours} min="1" max="720" />
          </div>
          <Button disabled={creatingInvite}>{creatingInvite ? '生成中…' : '生成邀请'}</Button>
        </form>
        <Status busy={false} error={inviteErr} empty={null} />
        {#if newInvite}
          <Alert variant="default">
            <div>
              <div class="text-sm">邀请令牌(只显示这一次,请立即复制):</div>
              <div class="font-mono text-sm break-all">{newInvite.token}</div>
              <div class="text-sm text-muted-foreground">到期:{fmtDateTime(newInvite.expires_at)} · 单次使用 · 注册页链接:</div>
              <div class="font-mono text-sm break-all" title="复制该完整链接给对方">{inviteUrl}</div>
              <Button variant="outline" size="sm" class="mt-1" onclick={() => void copy(inviteUrl)}>{inviteUrl && inviteCopied ? '已复制' : '复制链接'}</Button>
            </div>
          </Alert>
        {/if}
      </Card.Root>

      <Card.Root size="sm" class="p-4 flex flex-col gap-3">
        <h2 class="text-lg font-semibold">历史邀请</h2>
        <Status busy={inviteBusy} error={inviteErr} busyText="载入邀请…" empty={null} />
        {#if !inviteBusy && !inviteErr && invites.length === 0}
          <Status busy={false} empty="还没有邀请记录" />
        {/if}
        {#if !inviteBusy && invites.length > 0}
          <Table.Root>
            <Table.Header>
              <Table.Row>
                <Table.Head>邮箱备注</Table.Head>
                <Table.Head>角色</Table.Head>
                <Table.Head>创建时间</Table.Head>
                <Table.Head>过期</Table.Head>
                <Table.Head>状态</Table.Head>
                <Table.Head></Table.Head>
              </Table.Row>
            </Table.Header>
            <Table.Body>
              {#each invites as inv (inv.id)}
                <Table.Row>
                  <Table.Cell>{inv.email ?? '—'}</Table.Cell>
                  <Table.Cell>{inv.role === 'admin' ? '管理员' : '成员'}</Table.Cell>
                  <Table.Cell>{fmtDateTime(inv.created_at)}</Table.Cell>
                  <Table.Cell>{fmtDateTime(inv.expires_at)}</Table.Cell>
                  <Table.Cell>
                    {#if inv.used_at}<Badge variant="outline">已使用</Badge>
                    {:else if inv.revoked}<Badge variant="outline">已撤销</Badge>
                    {:else if inv.expires_at && new Date(inv.expires_at) < new Date()}<Badge variant="outline">已过期</Badge>
                    {:else}<Badge variant="secondary">有效</Badge>
                    {/if}
                  </Table.Cell>
                  <Table.Cell>
                    {#if !inv.used_at && !inv.revoked}
                      <Button variant="destructive" size="sm" onclick={() => void revokeInvite(inv)}>撤销</Button>
                    {/if}
                  </Table.Cell>
                </Table.Row>
              {/each}
            </Table.Body>
          </Table.Root>
        {/if}
        <p class="text-sm text-muted-foreground">恢复链接由“生成恢复”按钮产生,仅出现一次;不会自动发邮件。</p>
      </Card.Root>
    {:else}
      <Card.Root size="sm" class="p-4 flex flex-col gap-3">
        <h2 class="text-lg font-semibold">安全审计(收尾尾部)</h2>
        <Status busy={auditBusy} error={auditErr} busyText="载入审计记录…" empty={null} />
        {#if !auditBusy && !auditErr && audit.length === 0}
          <Status busy={false} empty="暂无审计事件" />
        {/if}
        {#if !auditBusy && audit.length > 0}
          <Table.Root>
            <Table.Header>
              <Table.Row>
                <Table.Head>时间</Table.Head>
                <Table.Head>行为者</Table.Head>
                <Table.Head>事件</Table.Head>
                <Table.Head>对象</Table.Head>
                <Table.Head>结果</Table.Head>
              </Table.Row>
            </Table.Header>
            <Table.Body>
              {#each audit as e, i (i)}
                <Table.Row>
                  <Table.Cell>{fmtDateTime(e.time)}</Table.Cell>
                  <Table.Cell>{e.actor ?? '—'}</Table.Cell>
                  <Table.Cell>{e.action}</Table.Cell>
                  <Table.Cell class="tabular-nums">{e.target ?? '—'}</Table.Cell>
                  <Table.Cell><Badge variant={e.status === 'ok' || e.status === 'success' ? 'secondary' : 'destructive'}>{e.status}</Badge></Table.Cell>
                </Table.Row>
              {/each}
            </Table.Body>
          </Table.Root>
        {/if}
        <p class="text-sm text-muted-foreground">审计仅记录操作行为与结果,不含密码/密钥/策略代码内容。</p>
      </Card.Root>
    {/if}
  </div>

  {#if resetFor}
    <Modal title={`为 ${resetFor.email} 生成密码恢复`} onClose={() => (resetFor = null)}>
      <div class="flex flex-col gap-3">
        <Alert variant="default">
          <div>
            <div>恢复链接(管理员线下告知对方,只出现一次):</div>
            <div class="font-mono text-sm break-all">{resetUrl}</div>
            <div class="text-sm text-muted-foreground">令牌 {resetToken.slice(0, 8)}… 会即刻失效前提示时间(见链接有效期)。</div>
          </div>
        </Alert>
        <p class="text-sm text-muted-foreground">单次有效、限时;重置会吊销对方的全部历史会话。</p>
      </div>
    </Modal>
  {/if}
</Page>