kongdeqiang
2026-10-12 ed3c2513c35efa714f2a377aef55501dd15d1fec
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
<template>
  <div class="admin-page">
    <div class="admin-header">
      <n-button quaternary size="small" @click="$router.push('/files')">← 返回知识库</n-button>
      <h1 class="admin-title">全局知识库</h1>
      <n-tag type="info" size="small" :bordered="false">管理员</n-tag>
      <div class="admin-header-right">
        <n-button size="small" quaternary :loading="loading" @click="load">刷新</n-button>
      </div>
    </div>
 
    <div class="admin-body">
      <n-alert type="info" :bordered="false" class="admin-intro">
        这里上传的文档会成为<strong>全局知识库</strong>:入库后<strong>所有登录用户</strong>
        都能在自己的「知识库」面板里看到,并绑定到各自的会话参与检索。
        <br />
        全局知识库只有管理员能修改或删除 —— 普通用户只能绑定使用。
      </n-alert>
 
      <!-- 上传区 -->
      <div class="section-title">上传全局文档</div>
      <div
        class="drop-zone"
        :class="{ dragging, uploading }"
        @dragover.prevent="dragging = true"
        @dragleave.prevent="dragging = false"
        @drop.prevent="handleDrop"
        @click="pickFile"
      >
        <input
          ref="fileInputRef"
          type="file"
          class="hidden-input"
          multiple
          :accept="acceptAttr"
          @change="handleSelect"
        />
        <div class="drop-icon">↑</div>
        <div class="drop-title">
          {{ uploading ? `上传中 ${progress}%` : '拖拽文件到此处,或点击选择' }}
        </div>
        <div class="drop-hint">
          支持 {{ allowedExtensions.join(' / ') }},单文件不超过 50MB<br />
          上传后需要点「向量化入库」,其他用户才能检索到内容
        </div>
        <n-progress
          v-if="uploading"
          type="line"
          :percentage="progress"
          :show-indicator="false"
          class="drop-progress"
        />
      </div>
 
      <!-- 全局文档只能放进全局分类;这里传 allowGlobal 让管理员直接建全局分类 -->
      <div class="upload-category">
        <CategoryPicker
          v-model:value="categoryId"
          allow-global
          :disabled="uploading"
          placeholder="选择全局分类(可不选)"
        />
      </div>
 
      <!-- 列表区 -->
      <div class="list-header">
        <span class="section-title no-margin">全局知识库文档({{ files.length }})</span>
        <n-button v-if="files.some((f) => !f.ingested)" size="tiny" :loading="ingestingAll"
                  @click="ingestAll">
          全部向量化
        </n-button>
      </div>
 
      <n-spin v-if="loading" size="small" class="center-spin" />
 
      <div v-else-if="files.length === 0" class="empty-hint empty-block">
        还没有全局知识库文档<br />上传后记得点「向量化入库」
      </div>
 
      <div v-for="file in files" v-else :key="file.id" class="file-card">
        <div class="file-card-main">
          <div class="file-name">
            {{ file.filename }}
            <n-tag type="success" size="tiny" :bordered="false" class="global-tag">全局</n-tag>
          </div>
          <div class="file-meta">
            <span>{{ formatSize(file.fileSize) }}</span>
            <span class="sep">·</span>
            <span>{{ formatDate(file.createdAt) }}</span>
            <span class="sep">·</span>
            <span v-if="file.ingested" class="status-ok">
              已入库 {{ file.chunkCount }} 个片段
            </span>
            <span v-else-if="file.ingestMessage" class="status-fail">
              入库失败:{{ file.ingestMessage }}
            </span>
            <span v-else class="status-pending">未向量化(其他用户检索不到)</span>
          </div>
          <div v-if="file.collectionName" class="file-collection">
            集合名:<code>{{ file.collectionName }}</code>
          </div>
        </div>
 
        <div class="file-card-actions">
          <n-button v-if="!file.ingested" size="small" :loading="busyId === file.id"
                    @click="handleIngest(file)">
            向量化入库
          </n-button>
          <n-button v-else size="small" :loading="busyId === file.id" @click="handleIngest(file)">
            重新入库
          </n-button>
          <n-button size="small" quaternary @click="handleUnsetGlobal(file)">取消全局</n-button>
          <n-button size="small" type="error" quaternary @click="handleDelete(file)">删除</n-button>
        </div>
      </div>
 
      <!-- 我的私有文档:可一键升级为全局 -->
      <div class="list-header">
        <span class="section-title no-margin">我的私有文档({{ privateFiles.length }})</span>
      </div>
      <div v-if="privateFiles.length === 0" class="empty-hint empty-block">
        没有私有文档
      </div>
      <div v-for="file in privateFiles" v-else :key="file.id" class="file-card private">
        <div class="file-card-main">
          <div class="file-name">{{ file.filename }}</div>
          <div class="file-meta">
            <span>{{ formatSize(file.fileSize) }}</span>
            <span class="sep">·</span>
            <span v-if="file.ingested" class="status-ok">已入库 {{ file.chunkCount }} 个片段</span>
            <span v-else class="status-pending">未向量化</span>
          </div>
        </div>
        <div class="file-card-actions">
          <n-button size="small" :disabled="!file.ingested" :loading="busyId === file.id"
                    @click="handleSetGlobal(file)">
            升级为全局
          </n-button>
        </div>
      </div>
    </div>
  </div>
</template>
 
<script setup>
import { computed, onMounted, ref } from 'vue'
import { NAlert, NButton, NProgress, NSpin, NTag, useDialog, useMessage } from 'naive-ui'
import CategoryPicker from '@/components/CategoryPicker.vue'
import {
  deleteFile,
  ingestFile,
  listFiles,
  listGlobalFiles,
  setFileGlobal,
  uploadGlobalFile
} from '@/api/fileApi'
 
const message = useMessage()
const dialog = useDialog()
 
const loading = ref(false)
const ingestingAll = ref(false)
const uploading = ref(false)
const progress = ref(0)
const dragging = ref(false)
const busyId = ref(null)
const fileInputRef = ref(null)
const files = ref([])
const privateFiles = ref([])
/** 上传全局文档时选中的分类(只列/创建全局分类才合规) */
const categoryId = ref(null)
 
const allowedExtensions = ['txt', 'md', 'markdown', 'pdf', 'docx', 'csv', 'json', 'log', 'html']
const acceptAttr = computed(() => allowedExtensions.map((e) => `.${e}`).join(','))
 
onMounted(load)
 
async function load() {
  loading.value = true
  try {
    const [globals, mine] = await Promise.all([listGlobalFiles(), listFiles(null)])
    files.value = globals || []
    // 私有文档 = 我上传的且不是全局的
    privateFiles.value = (mine || []).filter((f) => !f.isGlobal && f.canManage)
  } catch (error) {
    message.error(error.message || '加载失败')
  } finally {
    loading.value = false
  }
}
 
// ---------------- 上传 ----------------
 
function pickFile() {
  if (uploading.value) return
  fileInputRef.value?.click()
}
 
function handleSelect(event) {
  const list = Array.from(event.target.files || [])
  event.target.value = ''
  doUpload(list)
}
 
function handleDrop(event) {
  dragging.value = false
  doUpload(Array.from(event.dataTransfer?.files || []))
}
 
async function doUpload(list) {
  if (list.length === 0) return
  uploading.value = true
  progress.value = 0
  let ok = 0
 
  try {
    for (let i = 0; i < list.length; i += 1) {
      const file = list[i]
      const ext = file.name.split('.').pop()?.toLowerCase() || ''
      if (!allowedExtensions.includes(ext)) {
        message.error(`${file.name}:不支持的类型 .${ext}`)
        continue
      }
      if (file.size > 50 * 1024 * 1024) {
        message.error(`${file.name}:超过 50MB 限制`)
        continue
      }
      try {
        const created = await uploadGlobalFile(
          file,
          (percent) => {
            progress.value = Math.round(((i + percent / 100) / list.length) * 100)
          },
          true,
          categoryId.value
        )
        files.value = [created, ...files.value]
        ok += 1
      } catch (error) {
        message.error(`${file.name}:${error.message || '上传失败'}`)
      }
    }
    if (ok > 0) {
      message.success(`已上传 ${ok} 个全局文档,别忘了点「向量化入库」`)
    }
  } finally {
    uploading.value = false
    progress.value = 0
  }
}
 
// ---------------- 入库 ----------------
 
async function handleIngest(file) {
  busyId.value = file.id
  try {
    const updated = await ingestFile(file.id)
    replaceFile(updated)
    message.success(`入库完成,${updated.chunkCount} 个片段,现已对全部用户可用`)
  } catch (error) {
    message.error(error.message || '向量化失败')
    await refreshQuietly()
  } finally {
    busyId.value = null
  }
}
 
async function ingestAll() {
  const pending = files.value.filter((f) => !f.ingested)
  if (pending.length === 0) return
  ingestingAll.value = true
  let ok = 0
  try {
    for (const file of pending) {
      try {
        const updated = await ingestFile(file.id)
        replaceFile(updated)
        ok += 1
      } catch (error) {
        message.error(`${file.filename}:${error.message || '失败'}`)
      }
    }
    if (ok > 0) message.success(`已完成 ${ok} 个文档的向量化`)
  } finally {
    ingestingAll.value = false
  }
}
 
// ---------------- 全局开关 ----------------
 
async function handleSetGlobal(file) {
  busyId.value = file.id
  try {
    const updated = await setFileGlobal(file.id, true)
    privateFiles.value = privateFiles.value.filter((f) => f.id !== file.id)
    files.value = [updated, ...files.value]
    message.success(`「${file.filename}」已设为全局知识库`)
  } catch (error) {
    message.error(error.message || '操作失败')
  } finally {
    busyId.value = null
  }
}
 
function handleUnsetGlobal(file) {
  dialog.warning({
    title: '取消全局',
    content: `取消后「${file.filename}」将不再对普通用户可见;` +
      '已经绑定了它的会话仍会继续检索到内容(集合名未变),' +
      '如需彻底停止,请让用户在会话里解绑。确定继续吗?',
    positiveText: '取消全局',
    negativeText: '再想想',
    onPositiveClick: async () => {
      busyId.value = file.id
      try {
        const updated = await setFileGlobal(file.id, false)
        files.value = files.value.filter((f) => f.id !== file.id)
        privateFiles.value = [updated, ...privateFiles.value]
        message.success('已取消全局')
      } catch (error) {
        message.error(error.message || '操作失败')
      } finally {
        busyId.value = null
      }
    }
  })
}
 
// ---------------- 删除 ----------------
 
function handleDelete(file) {
  dialog.warning({
    title: '删除全局文档',
    content: `确定删除「${file.filename}」吗?` +
      '磁盘文件与向量集合都会被清理,**所有用户**都将无法再检索到它。此操作不可恢复。',
    positiveText: '删除',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await deleteFile(file.id)
        files.value = files.value.filter((f) => f.id !== file.id)
        message.success('已删除')
      } catch (error) {
        message.error(error.message || '删除失败')
      }
    }
  })
}
 
// ---------------- 工具 ----------------
 
function replaceFile(updated) {
  const idx = files.value.findIndex((f) => f.id === updated.id)
  if (idx !== -1) {
    files.value[idx] = updated
  } else {
    files.value = [updated, ...files.value]
  }
}
 
async function refreshQuietly() {
  try {
    files.value = await listGlobalFiles()
  } catch {
    // 忽略
  }
}
 
function formatSize(bytes) {
  if (!bytes && bytes !== 0) return '-'
  if (bytes < 1024) return `${bytes} B`
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
  return `${(bytes / 1024 / 1024).toFixed(1)} MB`
}
 
function formatDate(value) {
  if (!value) return '-'
  try {
    return new Date(value).toLocaleString('zh-CN', {
      month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit'
    })
  } catch {
    return String(value)
  }
}
</script>
 
<style scoped>
.admin-page {
  height: 100vh;
  overflow-y: auto;
  background: var(--bg-page);
}
 
.admin-header {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 14px 24px;
  border-bottom: 1px solid var(--border-color);
  position: sticky;
  top: 0;
  background: var(--bg-page);
  z-index: 10;
}
 
.admin-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}
 
.admin-header-right {
  margin-left: auto;
}
 
.admin-body {
  max-width: 860px;
  margin: 0 auto;
  padding: 24px;
}
 
.admin-intro {
  margin-bottom: 20px;
  font-size: 12.5px;
  line-height: 1.9;
}
 
.section-title {
  font-size: 13px;
  font-weight: 600;
  margin: 22px 0 10px;
}
 
.section-title.no-margin {
  margin: 0;
}
 
.list-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 26px 0 10px;
}
 
.hidden-input {
  display: none;
}
 
.drop-zone {
  border: 1.5px dashed #d1d5db;
  border-radius: 10px;
  padding: 22px 16px;
  text-align: center;
  cursor: pointer;
  background: #fafafa;
  transition: border-color 0.15s ease, background 0.15s ease;
}
 
.drop-zone:hover {
  border-color: #9ca3af;
  background: #f5f5f5;
}
 
.drop-zone.dragging {
  border-color: #4b5563;
  background: #eef2f7;
}
 
.drop-zone.uploading {
  cursor: progress;
}
 
.drop-icon {
  font-size: 20px;
  color: var(--text-secondary);
  margin-bottom: 8px;
}
 
.drop-title {
  font-size: 13.5px;
  font-weight: 500;
}
 
.drop-hint {
  font-size: 12px;
  color: var(--text-muted);
  margin-top: 6px;
  line-height: 1.7;
}
 
.drop-progress {
  margin-top: 12px;
}
 
.upload-category {
  margin-top: 10px;
}
 
.center-spin {
  display: flex;
  justify-content: center;
  padding: 24px 0;
}
 
.empty-block {
  padding: 28px 0;
  line-height: 1.9;
}
 
.file-card {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
  padding: 14px 16px;
  border: 1px solid var(--border-color);
  border-radius: 10px;
  margin-bottom: 10px;
}
 
.file-card.private {
  background: #fafafa;
}
 
.file-card-main {
  min-width: 0;
  flex: 1;
}
 
.file-name {
  font-size: 13.5px;
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
 
.global-tag {
  margin-left: 8px;
  vertical-align: middle;
}
 
.file-meta {
  font-size: 11.5px;
  color: var(--text-muted);
  margin-top: 5px;
}
 
.sep {
  margin: 0 6px;
}
 
.status-ok {
  color: #0f766e;
}
 
.status-fail {
  color: #dc2626;
}
 
.status-pending {
  color: #b45309;
}
 
.file-collection {
  font-size: 11.5px;
  color: var(--text-muted);
  margin-top: 5px;
}
 
.file-collection code {
  background: var(--code-bg);
  padding: 1px 5px;
  border-radius: 4px;
}
 
.file-card-actions {
  display: flex;
  gap: 6px;
  flex-shrink: 0;
}
</style>