models.py
46.6 KB
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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
import uuid
from datetime import datetime
from sqlalchemy import Column, Integer, String, BigInteger, Text, DateTime, Numeric, Index, UniqueConstraint, Boolean
from sqlalchemy.dialects.mysql import LONGTEXT
# 消息正文可能承载完整回答,MySQL 的 TEXT 上限为 65535 字节(中文约 2.1 万字)存在溢出风险,
# 故在 MySQL 方言下升为 LONGTEXT;其他方言仍回落到 Text,保持可移植性。
LongText = Text().with_variant(LONGTEXT, "mysql")
from sqlalchemy.orm import relationship
from src.database.session import Base
def uuid_str() -> str:
return str(uuid.uuid4())
class AuditByMixin:
"""审计「操作人」字段,与各表已有的 created_at/updated_at 组成统一四字段规范。
【全局建表规范】任何业务表都必须含四字段:created_at, created_by, updated_at, updated_by。
无操作用户时 created_by/updated_by 默认 'system';无时间时 created_at/updated_at 默认当前时间。
本 Mixin 只提供两个「人」字段(时间字段由各表按需定义),通过多继承挂到每个表上。
"""
created_by = Column(String(64), nullable=False, default="system", server_default="system", comment="创建人 wiki_oa_user.id 或 system")
updated_by = Column(String(64), nullable=False, default="system", server_default="system", comment="修改人 wiki_oa_user.id 或 system")
class WikiFile(AuditByMixin, Base):
__tablename__ = 'wiki_files'
__table_args__ = (
Index("idx_wiki_files_name", "name"),
Index("idx_wiki_files_status", "status"),
Index("idx_wiki_files_created_at", "created_at"),
Index("idx_wiki_files_kb", "kb_id"),
)
id = Column(String(36), primary_key=True, default=uuid_str)
name = Column(String(255), nullable=False)
format = Column(String(50), nullable=False)
size = Column(BigInteger, nullable=False)
word_count = Column(Integer, nullable=False, default=0)
status = Column(String(50), nullable=False, default='Pending') # Pending, Uploading, Ingesting, Indexed, Failed
# 权限隔离(Phase 2 知识库命名空间用):归属知识库与上传者。存量文件回填为公共基础库。
kb_id = Column(String(36), nullable=True, comment="归属知识库 wiki_kb_info.id;空=公共基础库")
uploaded_by = Column(String(36), nullable=True, comment="上传者 wiki_oa_user.id")
# 原始文件真实落盘路径(项目根相对,如 ware/kb/dept/<kbId>/raw/md/report_<fileId>.md)。
# 允许同名上传后,路径的唯一真相源——预览/下载/删除/摄入摄出一律以此为准,不再用 name 反推。
raw_path = Column(String(512), nullable=True, comment="原始文件项目根相对落盘路径(含 uuid,保证唯一)")
input_tokens = Column(Integer, nullable=False, default=0)
output_tokens = Column(Integer, nullable=False, default=0)
total_tokens = Column(Integer, nullable=False, default=0)
cached_input_tokens = Column(Integer, nullable=False, default=0) # 命中上下文缓存的 input token(⊆ input_tokens)
ingest_duration = Column(Numeric(10, 2), nullable=False, default=0.00)
ingest_time = Column(DateTime, nullable=True)
vlm_total_tokens = Column(Integer, nullable=False, default=0) # VLM 解析阶段(PDF/PPT)消耗的 token
ingest_mode = Column(String(32), nullable=True) # 摄入路线:3-phase(整篇)/ 3-phase-chunked(长文分块)
error_message = Column(Text, nullable=True)
created_at = Column(DateTime, default=datetime.now)
updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)
# 关联关系(用于 ORM 级联,数据库层约束由应用层手动管理以保持异步兼容性)
pages = relationship("WikiFilePage", back_populates="wiki_file", cascade="all, delete-orphan", lazy="noload", primaryjoin="WikiFile.id == WikiFilePage.file_id", foreign_keys="[WikiFilePage.file_id]")
logs = relationship("WikiOperationLog", back_populates="wiki_file", cascade="all, delete-orphan", lazy="noload", primaryjoin="WikiFile.id == WikiOperationLog.file_id", foreign_keys="[WikiOperationLog.file_id]")
class WikiFilePage(AuditByMixin, Base):
__tablename__ = 'wiki_file_pages'
__table_args__ = (
UniqueConstraint("file_id", "page_path", name="uq_wiki_file_pages_file_path"),
Index("idx_wiki_file_pages_file", "file_id"),
)
id = Column(String(36), primary_key=True, default=uuid_str)
file_id = Column(String(36), nullable=False)
page_path = Column(String(512), nullable=False)
created_at = Column(DateTime, default=datetime.now)
wiki_file = relationship("WikiFile", back_populates="pages", primaryjoin="WikiFilePage.file_id == WikiFile.id", foreign_keys=[file_id])
class WikiOperationLog(AuditByMixin, Base):
__tablename__ = 'wiki_operation_logs'
__table_args__ = (
Index("idx_wiki_operation_logs_file_created", "file_id", "created_at"),
Index("idx_wiki_operation_logs_operation_created", "operation", "created_at"),
)
id = Column(String(36), primary_key=True, default=uuid_str)
# file_id 允许为 NULL(查询日志等无关联文件的操作),关联文件删除时日志保留(SET NULL)
file_id = Column(String(36), nullable=True)
file_name = Column(String(255), nullable=True)
operation = Column(String(50), nullable=False)
details = Column(Text, nullable=True)
created_at = Column(DateTime, default=datetime.now)
wiki_file = relationship("WikiFile", back_populates="logs", primaryjoin="WikiOperationLog.file_id == WikiFile.id", foreign_keys=[file_id])
class WikiQueryLog(AuditByMixin, Base):
"""问答全量审计日志:每次请求一行,同时覆盖前端会话模式与外部无状态接口。"""
__tablename__ = 'wiki_query_logs'
__table_args__ = (
Index("idx_wiki_query_logs_session_created", "session_id", "created_at"),
Index("idx_wiki_query_logs_status_created", "status", "created_at"),
Index("idx_wiki_query_logs_user_created", "user_id", "created_at"),
)
id = Column(String(36), primary_key=True, default=uuid_str)
# 会话 ID:会话模式下等于 wiki_sessions.id;外部无状态调用为 NULL
session_id = Column(String(100), nullable=True)
# 归属用户 ID:外部无状态调用为 NULL
user_id = Column(String(36), nullable=True)
# 调用来源:web=前端会话 / api=外部接口
source = Column(String(20), nullable=False, default='web')
# 调用方 IP(兼容 IPv6),外部接口开放后的追责依据
client_ip = Column(String(45), nullable=True)
query_text = Column(Text, nullable=False)
history = Column(Text, nullable=True) # 会话模式不再写入(历史由 wiki_session_messages 承担),仅外部调用可选保留
answer_text = Column(Text, nullable=True)
# 工具调用极简轨迹 JSON:工具名/目标文件/成功与否,不含返回正文
tool_calls_json = Column(Text, nullable=True)
model_name = Column(String(50), nullable=True)
total_tokens = Column(Integer, nullable=False, default=0)
input_tokens = Column(Integer, nullable=False, default=0)
output_tokens = Column(Integer, nullable=False, default=0)
# 命中上下文缓存的 input token(⊆ input_tokens),用于观测 sys_prompt 前缀缓存命中率
cached_input_tokens = Column(Integer, nullable=False, default=0)
duration_ms = Column(Integer, nullable=False, default=0)
status = Column(String(50), nullable=False, default='Success') # Success, Error
error_message = Column(Text, nullable=True)
created_at = Column(DateTime, default=datetime.now)
class WikiMemoryLog(AuditByMixin, Base):
"""记忆子系统事件/错误日志:mem0 与情景检索的失败在此留痕,供管理员排查修复。
记忆是「越用越聪明」的核心,静默降级会让故障无人发现;本表让每次失败都有据可查。
"""
__tablename__ = "wiki_memory_logs"
__table_args__ = (
Index("idx_wiki_memory_logs_level_created", "level", "created_at"),
Index("idx_wiki_memory_logs_user_created", "user_id", "created_at"),
{"comment": "记忆子系统(mem0/情景检索)事件与错误日志"},
)
id = Column(String(36), primary_key=True, default=uuid_str, comment="主键 UUID")
level = Column(String(20), nullable=False, default="error", comment="级别:error/warning/info")
scope = Column(String(64), nullable=False, comment="出错环节:mem0.add/mem0.search/mem0.clear/episodic.index/episodic.search/materialize 等")
user_id = Column(String(36), nullable=True, comment="相关用户 ID(可空)")
session_id = Column(String(100), nullable=True, comment="相关会话 ID(可空)")
message = Column(Text, nullable=True, comment="错误摘要 / 异常信息")
created_at = Column(DateTime, default=datetime.now, comment="创建时间")
class RagFile(AuditByMixin, Base):
__tablename__ = "rag_documents"
__table_args__ = (
Index("idx_rag_documents_status", "status"),
Index("idx_rag_documents_hash", "content_hash"),
Index("idx_rag_documents_name_status", "name", "status"),
Index("idx_rag_documents_created_at", "created_at"),
{"comment": "RAG 文档表,记录进入独立 RAG 索引的源文件及索引统计信息"},
)
id = Column(String(36), primary_key=True, default=uuid_str, comment="文档主键 UUID")
name = Column(String(255), nullable=False, comment="源文件名称")
format = Column("file_type", String(50), nullable=False, comment="源文件类型或扩展名")
size = Column(BigInteger, nullable=False, default=0, comment="源文件大小,单位字节")
word_count = Column(Integer, nullable=False, default=0, comment="文档解析后的估算字数")
status = Column(String(50), nullable=False, default="Pending", comment="索引状态:Pending/Ingesting/Indexed/Failed 等")
source_path = Column(String(1024), nullable=False, comment="源文件在本地或对象存储中的路径")
content_hash = Column(String(128), nullable=True, comment="源文件内容哈希,用于去重或变更检测")
metadata_json = Column(Text, nullable=True, comment="文档级扩展元数据 JSON")
parser_version = Column(String(50), nullable=True, comment="解析器版本")
chunker_version = Column(String(50), nullable=True, comment="切片器版本")
block_count = Column(Integer, nullable=False, default=0, comment="解析得到的原始块数量")
chunk_count = Column(Integer, nullable=False, default=0, comment="切片总数")
parent_chunk_count = Column(Integer, nullable=False, default=0, comment="父级切片数量")
child_chunk_count = Column(Integer, nullable=False, default=0, comment="子级切片数量")
index_duration_ms = Column(Integer, nullable=False, default=0, comment="最近一次索引耗时,单位毫秒")
# VLM 整页解析的资源消耗(落库统计)
vlm_page_count = Column(Integer, nullable=False, default=0, comment="VLM 整页解析页数")
vlm_total_tokens = Column(Integer, nullable=False, default=0, comment="VLM 解析消耗的 token 总数")
vlm_duration_ms = Column(Integer, nullable=False, default=0, comment="VLM 解析耗时,单位毫秒")
error_code = Column(String(100), nullable=True, comment="索引失败时的错误码")
error_detail_json = Column(Text, nullable=True, comment="索引失败时的结构化错误详情 JSON")
error_message = Column(Text, nullable=True, comment="索引失败时的错误摘要")
created_at = Column(DateTime, default=datetime.now, comment="记录创建时间")
updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="记录更新时间")
index_started_at = Column(DateTime, nullable=True, comment="最近一次索引开始时间")
indexed_at = Column(DateTime, nullable=True, comment="最近一次索引成功完成时间")
chunks = relationship("RagChunk", back_populates="file", cascade="all, delete-orphan", lazy="noload", primaryjoin="RagFile.id == RagChunk.file_id", foreign_keys="[RagChunk.file_id]")
index_runs = relationship("RagIndexRun", back_populates="file", cascade="all, delete-orphan", lazy="noload", primaryjoin="RagFile.id == RagIndexRun.file_id", foreign_keys="[RagIndexRun.file_id]")
class RagChunk(AuditByMixin, Base):
"""精简后的切片表:只保留引擎层的列——身份、层级、定位、内容、状态。
业务标签(brand/business_category/sub_business/page_type/intent_type 等)一律不设列:
它们由 src/rag/resources/taxonomy.yaml 声明,随领域变化,写死成列意味着换个知识域
索引就多出一堆死列。全部收进 metadata_json,检索侧读 Qdrant payload
(见 infra/vector_store._payload,同样按 taxonomy 动态构造)。"""
__tablename__ = "rag_chunks"
__table_args__ = (
UniqueConstraint("chunk_id", name="uq_rag_chunks_chunk_id"),
Index("idx_rag_chunks_document_level_status", "document_id", "chunk_level", "status"),
Index("idx_rag_chunks_document_level_index", "document_id", "chunk_level", "chunk_index"),
Index("idx_rag_chunks_parent", "parent_chunk_id"),
Index("idx_rag_chunks_status", "status"),
{"comment": "RAG 切片表,保存文档切片内容、层级关系、定位信息和轻量检索字段"},
)
id = Column(String(36), primary_key=True, default=uuid_str, comment="切片主键 UUID")
chunk_id = Column(String(64), nullable=False, comment="业务切片 ID,同时对应向量 payload 中的 chunk_id")
file_id = Column("document_id", String(36), nullable=False, comment="所属 RAG 文档 ID")
parent_chunk_id = Column(String(64), nullable=True, comment="父级切片 ID,用于父子层级检索")
chunk_level = Column(String(20), nullable=False, comment="切片层级:parent 或 child")
chunk_index = Column(Integer, nullable=False, default=0, comment="切片在文档中的顺序")
content = Column(Text, nullable=False, comment="切片文本内容")
content_hash = Column(String(128), nullable=False, comment="切片内容哈希")
token_estimate = Column(Integer, nullable=False, default=0, comment="切片 token 估算值")
title_path = Column(String(1024), nullable=True, comment="标题层级路径")
source_name = Column(String(255), nullable=False, comment="来源文件名或来源标题")
page_start = Column(Integer, nullable=True, comment="切片起始页码")
page_end = Column(Integer, nullable=True, comment="切片结束页码")
row_start = Column(Integer, nullable=True, comment="表格类内容起始行号")
row_end = Column(Integer, nullable=True, comment="表格类内容结束行号")
prev_chunk_id = Column(String(64), nullable=True, comment="前一个相邻切片 ID")
next_chunk_id = Column(String(64), nullable=True, comment="后一个相邻切片 ID")
status = Column(String(50), nullable=False, default="active", comment="切片状态:active/deleted 等")
content_kind = Column(String(50), nullable=True, comment="内容类型,如 text/table/image 等")
section_title = Column(String(255), nullable=True, comment="切片所在章节标题")
parse_status = Column(String(50), nullable=True, comment="切片解析状态或质量标记")
qdrant_point_id = Column(String(64), nullable=True, comment="对应的 Qdrant point ID")
metadata_json = Column(Text, nullable=True, comment="切片扩展元数据 JSON")
created_at = Column(DateTime, default=datetime.now, comment="记录创建时间")
file = relationship("RagFile", back_populates="chunks", primaryjoin="RagChunk.file_id == RagFile.id", foreign_keys=[file_id])
class RagIndexRun(AuditByMixin, Base):
__tablename__ = "rag_index_runs"
__table_args__ = (
Index("idx_rag_index_runs_document_created", "document_id", "created_at"),
Index("idx_rag_index_runs_status_created", "status", "created_at"),
{"comment": "RAG 索引任务运行记录表,保存每次索引执行的统计和错误信息"},
)
id = Column(String(36), primary_key=True, default=uuid_str, comment="索引运行记录主键 UUID")
file_id = Column("document_id", String(36), nullable=False, comment="所属 RAG 文档 ID")
status = Column(String(50), nullable=False, comment="本次索引运行状态")
parser_version = Column(String(50), nullable=True, comment="本次使用的解析器版本")
chunker_version = Column(String(50), nullable=True, comment="本次使用的切片器版本")
block_count = Column(Integer, nullable=False, default=0, comment="本次解析得到的原始块数量")
parent_chunk_count = Column(Integer, nullable=False, default=0, comment="本次生成的父级切片数量")
child_chunk_count = Column(Integer, nullable=False, default=0, comment="本次生成的子级切片数量")
vector_count = Column(Integer, nullable=False, default=0, comment="本次写入或更新的向量数量")
duration_ms = Column(Integer, nullable=False, default=0, comment="本次索引耗时,单位毫秒")
vlm_page_count = Column(Integer, nullable=False, default=0, comment="本次 VLM 整页解析页数")
vlm_total_tokens = Column(Integer, nullable=False, default=0, comment="本次 VLM 解析消耗 token 数")
error_code = Column(String(100), nullable=True, comment="本次索引失败时的错误码")
error_detail_json = Column(Text, nullable=True, comment="本次索引失败时的结构化错误详情 JSON")
error_message = Column(Text, nullable=True, comment="本次索引失败时的错误摘要")
created_at = Column(DateTime, default=datetime.now, comment="记录创建时间")
file = relationship("RagFile", back_populates="index_runs", primaryjoin="RagIndexRun.file_id == RagFile.id", foreign_keys=[file_id])
class RagQueryLog(AuditByMixin, Base):
__tablename__ = "rag_query_logs"
__table_args__ = (
Index("idx_rag_query_logs_session_status_created", "session_id", "status", "created_at"),
Index("idx_rag_query_logs_status_created", "status", "created_at"),
{"comment": "RAG 查询日志表,记录用户查询、改写、检索过程、引用和回答结果"},
)
id = Column(String(36), primary_key=True, default=uuid_str, comment="查询日志主键 UUID")
session_id = Column(String(100), nullable=True, comment="会话 ID")
query_text = Column(Text, nullable=False, comment="用户原始查询")
rewritten_query = Column(Text, nullable=True, comment="查询改写后的文本")
intent_result_json = Column(Text, nullable=True, comment="意图识别结果 JSON")
retrieval_plan_json = Column(Text, nullable=True, comment="检索计划 JSON")
query_plan_json = Column(Text, nullable=True, comment="查询规划 JSON")
filters_json = Column(Text, nullable=True, comment="实际使用的过滤条件 JSON")
ranked_json = Column(Text, nullable=True, comment="排序后的候选结果 JSON")
sources_json = Column(Text, nullable=True, comment="回答引用来源 JSON")
adopted_chunk_ids_json = Column(Text, nullable=True, comment="最终采用的切片 ID 列表 JSON")
citation_map_json = Column(Text, nullable=True, comment="引用编号到切片或来源的映射 JSON")
answer_text = Column(Text, nullable=True, comment="最终回答文本")
model_name = Column(String(100), nullable=True, comment="生成回答使用的模型名称")
total_tokens = Column(Integer, nullable=False, default=0, comment="本次查询消耗 token 总数")
duration_ms = Column(Integer, nullable=False, default=0, comment="本次查询耗时,单位毫秒")
status = Column(String(50), nullable=False, default="Success", comment="查询状态:Success/Error 等")
error_message = Column(Text, nullable=True, comment="查询失败时的错误信息")
created_at = Column(DateTime, default=datetime.now, comment="记录创建时间")
# ==================== OA 权限系统(RBAC + 数据范围) ====================
# 表前缀:OA/RBAC 用 wiki_oa_,知识库用 wiki_kb_。
# 统一约定:主键 id CHAR(36) uuid;逻辑删除 del_flag(0/1);业务启停 status;
# 审计四字段 created_at/created_by/updated_at/updated_by(人默认 'system'、时间默认 now,
# created_by/updated_by 由 AuditByMixin 统一提供,见文件顶部)。
# 枚举取值集中定义于 src/services/oa/enums.py(前端镜像 frontend/src/lib/oaEnums.ts)。
class WikiOaDept(AuditByMixin, Base):
"""部门树:中心/部/驻店支,ancestors 存逗号祖先 id 路径以便子树查询。"""
__tablename__ = "wiki_oa_dept"
__table_args__ = (
Index("idx_oa_dept_parent", "parent_id"),
Index("idx_oa_dept_name", "dept_name"),
{"comment": "部门树(RBAC 组织维度)"},
)
id = Column(String(36), primary_key=True, default=uuid_str, comment="部门主键 UUID")
parent_id = Column(String(36), nullable=True, comment="上级部门 id,顶级为空")
ancestors = Column(String(500), nullable=True, comment="逗号分隔祖先 id 路径,子树查询用(层级唯一真相源)")
dept_name = Column(String(100), nullable=False, comment="部门名称")
dept_category = Column(String(20), nullable=False, default="hq", comment="hq=总部 / outsource=外包 / store=驻店(已停用)")
duty = Column(Text, nullable=True, comment="部门职责(来源:总部组织架构表)")
order_num = Column(Integer, nullable=False, default=0, comment="排序")
# 负责人不再单独存字段:由角色(center_lead/dept_lead + 该节点在岗者)派生,避免维护空字段
status = Column(String(20), nullable=False, default="active", comment="active/disabled")
del_flag = Column(Integer, nullable=False, default=0, comment="逻辑删除 0正常/1已删")
created_at = Column(DateTime, default=datetime.now, comment="创建时间")
updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间")
class WikiOaPost(AuditByMixin, Base):
"""岗位目录:挂在部门下,duty 存岗位职责(画像生成原料)。"""
__tablename__ = "wiki_oa_post"
__table_args__ = (
Index("idx_oa_post_dept", "dept_id"),
Index("idx_oa_post_name", "post_name"),
{"comment": "岗位目录(HR 职务,与角色解耦)"},
)
id = Column(String(36), primary_key=True, default=uuid_str, comment="岗位主键 UUID")
dept_id = Column(String(36), nullable=True, comment="所属部门 wiki_oa_dept.id")
post_name = Column(String(100), nullable=False, comment="岗位名称")
duty = Column(Text, nullable=True, comment="岗位职责(画像生成原料)")
order_num = Column(Integer, nullable=False, default=0, comment="排序")
status = Column(String(20), nullable=False, default="active", comment="active/disabled")
del_flag = Column(Integer, nullable=False, default=0, comment="逻辑删除 0正常/1已删")
created_at = Column(DateTime, default=datetime.now, comment="创建时间")
updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间")
class WikiOaUser(AuditByMixin, Base):
"""用户/员工:账号=手机号,权限只经角色,岗位经 user_post 关联。取代旧 wiki_users。"""
__tablename__ = "wiki_oa_user"
__table_args__ = (
UniqueConstraint("username", name="uk_oa_user_username"),
Index("idx_oa_user_dept", "dept_id"),
Index("idx_oa_user_phone", "phone"),
{"comment": "用户表(RBAC 身份主体)"},
)
id = Column(String(36), primary_key=True, default=uuid_str, comment="用户主键 UUID")
username = Column(String(50), nullable=False, comment="登录账号,统一使用手机号")
phone = Column(String(20), nullable=True, comment="手机号")
display_name = Column(String(50), nullable=False, comment="姓名")
email = Column(String(100), nullable=True, comment="邮箱,不作登录用")
avatar_url = Column(String(500), nullable=True, comment="头像/照片 URL")
password_hash = Column(String(255), nullable=False, comment="密码哈希(hashlib.scrypt)")
password_salt = Column(String(64), nullable=False, comment="每用户独立随机盐")
dept_id = Column(String(36), nullable=True, comment="所属部门 wiki_oa_dept.id")
store_name = Column(String(100), nullable=True, comment="负责门店,驻店人员专用")
is_superadmin = Column(Integer, nullable=False, default=0, comment="超级管理员 0/1,全权限免校验")
must_change_pwd = Column(Integer, nullable=False, default=1, comment="首登强制改密 0/1")
status = Column(String(20), nullable=False, default="active", comment="active=启用 / disabled=停用(拒登录)")
del_flag = Column(Integer, nullable=False, default=0, comment="逻辑删除 0正常/1已删")
external_id = Column(String(128), nullable=True, comment="外部 OA/SSO 主体标识,预留")
last_login_at = Column(DateTime, nullable=True, comment="最后登录时间")
created_at = Column(DateTime, default=datetime.now, comment="创建时间")
updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间")
class WikiOaUserPost(AuditByMixin, Base):
"""用户↔岗位(M:N)。"""
__tablename__ = "wiki_oa_user_post"
__table_args__ = (
UniqueConstraint("user_id", "post_id", name="uk_oa_user_post"),
Index("idx_oa_up_user", "user_id"),
Index("idx_oa_up_post", "post_id"), # 按岗位反查在岗人员的 JOIN(复合唯一键无法服务 post_id 单列)
{"comment": "用户↔岗位关联"},
)
id = Column(String(36), primary_key=True, default=uuid_str)
user_id = Column(String(36), nullable=False, comment="wiki_oa_user.id")
post_id = Column(String(36), nullable=False, comment="wiki_oa_post.id")
created_at = Column(DateTime, default=datetime.now)
class WikiOaPostRole(AuditByMixin, Base):
"""岗位默认角色:入职按岗自动授角色。"""
__tablename__ = "wiki_oa_post_role"
__table_args__ = (
UniqueConstraint("post_id", "role_id", name="uk_oa_post_role"),
{"comment": "岗位→默认角色映射"},
)
id = Column(String(36), primary_key=True, default=uuid_str)
post_id = Column(String(36), nullable=False, comment="wiki_oa_post.id")
role_id = Column(String(36), nullable=False, comment="wiki_oa_role.id")
created_at = Column(DateTime, default=datetime.now)
class WikiOaRole(AuditByMixin, Base):
"""角色:权限集合 + 数据范围。"""
__tablename__ = "wiki_oa_role"
__table_args__ = (
UniqueConstraint("role_code", name="uk_oa_role_code"),
{"comment": "角色(权限集合 + data_scope 数据范围)"},
)
id = Column(String(36), primary_key=True, default=uuid_str, comment="角色主键 UUID")
role_code = Column(String(64), nullable=False, comment="角色编码(唯一)")
role_name = Column(String(64), nullable=False, comment="角色名称")
data_scope = Column(Integer, nullable=False, default=5, comment="1全部/2自定义/3本部门/4本部门及以下/5仅本人")
order_num = Column(Integer, nullable=False, default=0, comment="排序")
is_builtin = Column(Integer, nullable=False, default=0, comment="内置角色 0/1,内置不可删")
status = Column(String(20), nullable=False, default="active", comment="active/disabled")
del_flag = Column(Integer, nullable=False, default=0, comment="逻辑删除 0正常/1已删")
remark = Column(String(255), nullable=True, comment="备注")
created_at = Column(DateTime, default=datetime.now, comment="创建时间")
updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间")
class WikiOaUserRole(AuditByMixin, Base):
"""用户↔角色(M:N)。"""
__tablename__ = "wiki_oa_user_role"
__table_args__ = (
UniqueConstraint("user_id", "role_id", name="uk_oa_user_role"),
Index("idx_oa_ur_user", "user_id"),
{"comment": "用户↔角色关联"},
)
id = Column(String(36), primary_key=True, default=uuid_str)
user_id = Column(String(36), nullable=False, comment="wiki_oa_user.id")
role_id = Column(String(36), nullable=False, comment="wiki_oa_role.id")
created_at = Column(DateTime, default=datetime.now)
class WikiOaSource(AuditByMixin, Base):
"""权限资源树:菜单/页面/按钮/接口统一,perm 为权限标识串。"""
__tablename__ = "wiki_oa_source"
__table_args__ = (
Index("idx_oa_source_parent", "parent_id"),
Index("idx_oa_source_perm", "perm"),
{"comment": "权限资源树(菜单/页面/按钮/接口)"},
)
id = Column(String(36), primary_key=True, default=uuid_str, comment="资源主键 UUID")
parent_id = Column(String(36), nullable=True, comment="资源树父级 id")
source_name = Column(String(100), nullable=False, comment="资源名称")
source_type = Column(String(10), nullable=False, default="C", comment="M目录/C菜单/P页面/F按钮/A接口")
perm = Column(String(100), nullable=True, comment="权限标识串,如 wiki:file:upload")
route_path = Column(String(200), nullable=True, comment="前端路由")
component = Column(String(200), nullable=True, comment="前端组件路径")
icon = Column(String(100), nullable=True, comment="菜单图标")
order_num = Column(Integer, nullable=False, default=0, comment="排序")
visible = Column(Integer, nullable=False, default=1, comment="菜单是否显示 0/1")
status = Column(String(20), nullable=False, default="active", comment="active/disabled")
del_flag = Column(Integer, nullable=False, default=0, comment="逻辑删除 0正常/1已删")
created_at = Column(DateTime, default=datetime.now, comment="创建时间")
updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间")
class WikiOaRoleSource(AuditByMixin, Base):
"""角色↔资源(M:N),角色被授予的权限点。"""
__tablename__ = "wiki_oa_role_source"
__table_args__ = (
UniqueConstraint("role_id", "source_id", name="uk_oa_role_source"),
Index("idx_oa_rs_role", "role_id"),
{"comment": "角色↔权限资源关联"},
)
id = Column(String(36), primary_key=True, default=uuid_str)
role_id = Column(String(36), nullable=False, comment="wiki_oa_role.id")
source_id = Column(String(36), nullable=False, comment="wiki_oa_source.id")
created_at = Column(DateTime, default=datetime.now)
class WikiOaRoleDept(AuditByMixin, Base):
"""角色自定义数据范围部门(data_scope=2 时生效)。"""
__tablename__ = "wiki_oa_role_dept"
__table_args__ = (
UniqueConstraint("role_id", "dept_id", name="uk_oa_role_dept"),
{"comment": "角色自定义数据范围部门"},
)
id = Column(String(36), primary_key=True, default=uuid_str)
role_id = Column(String(36), nullable=False, comment="wiki_oa_role.id")
dept_id = Column(String(36), nullable=False, comment="wiki_oa_dept.id")
created_at = Column(DateTime, default=datetime.now)
class WikiOaOperLog(AuditByMixin, Base):
"""系统操作审计日志:记录所有系统级写操作(增删改、授权等),便于追责与回溯。"""
__tablename__ = "wiki_oa_oper_log"
__table_args__ = (
Index("idx_oa_operlog_created", "created_at"),
Index("idx_oa_operlog_module", "module"),
Index("idx_oa_operlog_operator", "operator_id"),
{"comment": "系统操作审计日志"},
)
id = Column(String(36), primary_key=True, default=uuid_str, comment="日志主键 UUID")
operator_id = Column(String(36), nullable=True, comment="操作人 wiki_oa_user.id")
operator_name = Column(String(50), nullable=True, comment="操作人姓名(冗余,便于查看)")
module = Column(String(32), nullable=False, comment="模块:user/role/dept/post/source/kb")
action = Column(String(32), nullable=False, comment="动作:create/update/delete/batchDelete/assignRole/...")
target_type = Column(String(32), nullable=True, comment="目标类型")
target_id = Column(String(64), nullable=True, comment="目标 id")
target_name = Column(String(128), nullable=True, comment="目标名称(冗余)")
detail = Column(Text, nullable=True, comment="变更明细 JSON(旧值/新值或参数)")
client_ip = Column(String(45), nullable=True, comment="操作方 IP(兼容 IPv6)")
result = Column(String(16), nullable=False, default="success", comment="success/fail")
created_at = Column(DateTime, default=datetime.now, comment="操作时间")
class WikiKbInfo(AuditByMixin, Base):
"""知识库注册:公共基础库 / 部门库 / 个人库;root_dir 为物理目录(便于迁移)。"""
__tablename__ = "wiki_kb_info"
__table_args__ = (
Index("idx_kb_type", "kb_type"),
Index("idx_kb_owner", "owner_user_id"),
Index("idx_kb_dept", "dept_id"),
{"comment": "知识库注册表"},
)
id = Column(String(36), primary_key=True, default=uuid_str, comment="知识库主键 UUID")
kb_type = Column(String(20), nullable=False, comment="base=公共基础库 / dept=部门库 / personal=个人库")
kb_name = Column(String(100), nullable=False, comment="知识库名称")
owner_user_id = Column(String(36), nullable=True, comment="个人库归属用户 wiki_oa_user.id")
dept_id = Column(String(36), nullable=True, comment="部门库归属部门 wiki_oa_dept.id")
root_dir = Column(String(300), nullable=False, comment="物理目录(命名空间根,便于隔离迁移)")
status = Column(String(20), nullable=False, default="active", comment="active/disabled")
del_flag = Column(Integer, nullable=False, default=0, comment="逻辑删除 0正常/1已删")
created_at = Column(DateTime, default=datetime.now, comment="创建时间")
updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间")
class WikiKbGrant(AuditByMixin, Base):
"""知识库授权(Owner/Guest 双授权:一节点一级别一行)。
被授权方泛化为 (grantee_type, grantee_id),当前只用 dept(组织节点)。
**授权任一组织节点 = 授其整棵子树**:授中心=中心下全体,授叶子部门=该部门;
因中心是纯分组概念,语义唯一、无 include_sub 开关。一次可授多个节点(各落一行)。
user/post/role 为未来扩展位(点对点分享 / 按岗按角色),当前 UI 不产生。
access ∈ owner/guest:owner 授所有者(读写全套),guest 授访客(只读)。
同一节点可同时挂 owner 与 guest 两行,用户有效级别“交集取大”(owner 胜),
由 src/services/oa/perms.py::resolve_kb_access 统一裁决。
"""
__tablename__ = "wiki_kb_grant"
__table_args__ = (
UniqueConstraint("kb_id", "grantee_type", "grantee_id", "access", name="uk_kb_grant"),
Index("idx_kb_grant_grantee", "grantee_type", "grantee_id"),
{"comment": "知识库授权(Owner/Guest 双授权,一节点一级别一行)"},
)
id = Column(String(36), primary_key=True, default=uuid_str, comment="授权主键 UUID")
kb_id = Column(String(36), nullable=False, comment="目标知识库 wiki_kb_info.id")
grantee_type = Column(String(16), nullable=False, default="dept", comment="被授权方类型 dept(组织节点)/user/post/role,当前仅用 dept,其余为扩展位")
grantee_id = Column(String(36), nullable=False, comment="被授权方 id(按 grantee_type 指向对应表)")
access = Column(String(16), nullable=False, default="guest", comment="owner=所有者(读写) / guest=访客(只读)")
granted_by = Column(String(36), nullable=True, comment="授权人 wiki_oa_user.id")
status = Column(String(20), nullable=False, default="active", comment="active=生效 / revoked=已撤销")
del_flag = Column(Integer, nullable=False, default=0, comment="逻辑删除 0正常/1已删")
created_at = Column(DateTime, default=datetime.now, comment="创建时间")
updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间")
class WikiSkill(AuditByMixin, Base):
"""Agent 技能注册表:内置技能(llm-query/ingest/lint)+ 管理员上传技能。
技能本体是 <dir_path>/SKILL.md(带 YAML frontmatter,正文为给 LLM 的工作流提示词)。
上传技能落 ware/skills/<name>/,内置技能仍在 skills/<name>/(is_builtin=1,只读、始终生效)。
启用后的上传技能其 name/description 会作为「可用技能目录」注入问答 Agent,
模型据 description 命中时调用 load_skill 工具加载全文(被动使用,不做手动选择)。
"""
__tablename__ = "wiki_skill"
__table_args__ = (
UniqueConstraint("name", name="uk_wiki_skill_name"),
Index("idx_wiki_skill_enabled", "enabled"),
{"comment": "Agent 技能注册表(内置 + 上传)"},
)
id = Column(String(36), primary_key=True, default=uuid_str, comment="技能主键 UUID")
name = Column(String(100), nullable=False, comment="技能唯一标识 slug(同时作落盘目录名)")
display_name = Column(String(150), nullable=True, comment="技能展示名(前端列表显示)")
description = Column(Text, nullable=True, comment="技能触发描述(供模型判断是否命中加载)")
source_type = Column(String(16), nullable=False, default="md", comment="来源类型:md=单文件 / zip=压缩包 / builtin=内置")
dir_path = Column(String(300), nullable=False, comment="技能目录(相对项目根,如 ware/skills/<name> 或 skills/<name>)")
enabled = Column(Integer, nullable=False, default=0, comment="是否启用 0停用/1启用(内置恒为1)")
is_builtin = Column(Integer, nullable=False, default=0, comment="是否内置 0上传/1内置(内置只读,不可删除/停用)")
scope = Column(String(20), nullable=False, default="query", comment="作用范围:query=问答 Agent(预留多智能体)")
file_size = Column(BigInteger, nullable=False, default=0, comment="技能原始文件字节数(zip 为压缩包大小)")
uploaded_by = Column(String(36), nullable=True, comment="上传者 wiki_oa_user.id(内置为空)")
del_flag = Column(Integer, nullable=False, default=0, comment="逻辑删除 0正常/1已删")
created_at = Column(DateTime, default=datetime.now, comment="创建时间")
updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间")
class WikiSkillTbGrant(AuditByMixin, Base):
"""技能「能力授权」:平台侧权威的权限来源,逐调用被受管能力网关校验,技能无法自行扩权。
一张表统管两类授权,用 grant_type 区分:
- db_table:target=表名,ops=r(只读 SELECT)/ rw(含增删改);决定该技能能操作哪些表、能否写。
- net_host:target=外部域名(支持后缀匹配),ops=call;决定该技能能调用哪些外部接口。
未授权的技能默认无任何库/网络权限。
注意:本表管的是「技能↔数据表/外部域名」的**能力边界**,与「技能↔部门」的**使用授权**
(WikiSkillDeptGrant / wiki_skill_dept_grant)是两码事,勿混淆。表名 tb=table(能力)。
"""
__tablename__ = "wiki_skill_tb_grant"
__table_args__ = (
UniqueConstraint("skill_id", "grant_type", "target", name="uk_skill_tb_grant"),
Index("idx_skill_tb_grant_skill", "skill_id"),
{"comment": "技能能力授权(DB 表权限 / 外部接口域名白名单)"},
)
id = Column(String(36), primary_key=True, default=uuid_str, comment="授权主键 UUID")
skill_id = Column(String(36), nullable=False, comment="wiki_skill.id")
grant_type = Column(String(16), nullable=False, comment="db_table=数据表 / net_host=外部域名")
target = Column(String(200), nullable=False, comment="db_table→表名;net_host→域名(支持后缀匹配)")
ops = Column(String(16), nullable=False, default="r", comment="db_table→r/rw;net_host→call")
del_flag = Column(Integer, nullable=False, default=0, comment="逻辑删除 0正常/1已删")
created_at = Column(DateTime, default=datetime.now, comment="创建时间")
updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间")
class WikiSkillDeptGrant(AuditByMixin, Base):
"""技能「部门使用授权」:管理员指定哪些部门可使用某技能(启用之外的第二个维度)。
被授权方泛化为 (grantee_type, grantee_id),当前只用 dept(组织节点)。
**授权任一组织节点 = 授其整棵子树**:授中心=中心下全体可用、授叶子部门=该部门可用;
因中心是纯分组概念,语义唯一、无 include_sub 开关。一次可授多个节点(各落一行)。
默认无任何行:除超级管理员外,未被授权的部门在问答中看不到、也用不了该技能。
内置/系统技能(llm-query 等)不受本表约束,恒可用。
注意:与 WikiSkillTbGrant(wiki_skill_tb_grant,技能能力边界)是两张不同的表,勿混淆。
"""
__tablename__ = "wiki_skill_dept_grant"
__table_args__ = (
UniqueConstraint("skill_id", "grantee_type", "grantee_id", name="uk_skill_dept_grant"),
Index("idx_skill_dept_grant_grantee", "grantee_type", "grantee_id"),
{"comment": "技能部门使用授权(授组织节点=其整棵子树可用)"},
)
id = Column(String(36), primary_key=True, default=uuid_str, comment="授权主键 UUID")
skill_id = Column(String(36), nullable=False, comment="目标技能 wiki_skill.id")
grantee_type = Column(String(16), nullable=False, default="dept", comment="被授权方类型 dept(组织节点),预留 user/post/role")
grantee_id = Column(String(36), nullable=False, comment="被授权方 id(dept→wiki_oa_dept.id)")
granted_by = Column(String(36), nullable=True, comment="授权人 wiki_oa_user.id")
status = Column(String(20), nullable=False, default="active", comment="active=生效 / revoked=已撤销")
del_flag = Column(Integer, nullable=False, default=0, comment="逻辑删除 0正常/1已删")
created_at = Column(DateTime, default=datetime.now, comment="创建时间")
updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间")
# ==================== 智能化模块:用户画像 · 分层记忆 ====================
# 说明:user_id 一律指向 wiki_oa_user.id(本版本清空重建,不迁移旧数据)。
class WikiUserProfile(AuditByMixin, Base):
"""用户画像与长期记忆表:一人一行,profile_md 与 long_mem_core_md 均为 markdown 文本。"""
__tablename__ = "wiki_user_profiles"
__table_args__ = (
UniqueConstraint("user_id", name="uk_wiki_user_profiles_user"),
{"comment": "用户画像与长期记忆核心摘要表(user.md + long_mem_core.md)"},
)
id = Column(String(36), primary_key=True, default=uuid_str, comment="主键 UUID")
user_id = Column(String(36), nullable=False, comment="归属用户 ID,一人一行")
profile_md = Column(Text, nullable=True, comment="user.md 岗位画像(markdown,前端只读展示)")
long_mem_core_md = Column(Text, nullable=True, comment="长期记忆核心摘要:MEM0_ENABLED 时为 mem0 核心记忆的注入缓存(派生只读,权威源在 mem0);否则为 DB 自沉淀的长期记忆")
profile_version = Column(Integer, nullable=False, default=1, comment="画像版本号,每次重生成 +1")
profile_generated = Column(Boolean, nullable=False, default=False, comment="首登画像是否已生成")
reflected_upto_at = Column(DateTime, nullable=True, comment="长期沉淀游标:只反思该时间之后产生的会话")
reflect_turns = Column(Integer, nullable=False, default=0, comment="自上次沉淀以来累计问答轮数,达阈值触发")
updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间")
class WikiSession(AuditByMixin, Base):
"""会话表:id 即 session_id,承载滚动摘要与摘要游标。"""
__tablename__ = "wiki_sessions"
__table_args__ = (
Index("idx_wiki_sessions_user_updated", "user_id", "updated_at"),
{"comment": "会话表(含滚动摘要与摘要游标)"},
)
id = Column(String(36), primary_key=True, default=uuid_str, comment="会话主键 UUID,即 session_id")
user_id = Column(String(36), nullable=False, comment="归属用户 ID,隔离键")
title = Column(String(200), nullable=True, comment="会话标题,由首个问题自动生成")
summary = Column(Text, nullable=True, comment="滚动摘要:已滑出窗口的旧对话压缩结果")
summary_upto_seq = Column(Integer, nullable=False, default=0, comment="摘要游标:已被摘要覆盖到的最大 seq,0=尚未摘过")
total_turns = Column(Integer, nullable=False, default=0, comment="该会话累计问答轮数")
status = Column(String(20), nullable=False, default="active", comment="状态:active=进行中 / archived=已归档 / deleted=已删除")
created_at = Column(DateTime, default=datetime.now, comment="创建时间")
updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="最后活跃时间")
class WikiSessionMessage(AuditByMixin, Base):
"""会话消息表:逐条存储,是滑动窗口的取数来源。"""
__tablename__ = "wiki_session_messages"
__table_args__ = (
UniqueConstraint("session_id", "seq", name="uk_wiki_session_messages_session_seq"),
Index("idx_wiki_session_messages_user_session", "user_id", "session_id"),
{"comment": "会话消息表(逐条,滑动窗口取数来源)"},
)
id = Column(String(36), primary_key=True, default=uuid_str, comment="消息主键 UUID")
session_id = Column(String(36), nullable=False, comment="所属会话 ID,关联 wiki_sessions.id")
user_id = Column(String(36), nullable=False, comment="冗余归属用户 ID,隔离校验免 JOIN")
seq = Column(Integer, nullable=False, comment="会话内消息序号,从 1 递增,一条消息占一个 seq")
role = Column(String(20), nullable=False, comment="角色:user=用户提问 / assistant=助手回答")
content = Column(LongText, nullable=True, comment="消息正文")
tokens = Column(Integer, nullable=False, default=0, comment="该条消息 token 数,供滑窗阈值判定")
reasoning_json = Column(
Text,
nullable=True,
comment="思考过程 JSON(含每步 time、工具返回摘要正文),仅供前端重放,禁止回灌进 prompt",
)
duration_ms = Column(Integer, nullable=False, default=0, comment="该轮回答总耗时毫秒,供前端重放显示秒数")
created_at = Column(DateTime, default=datetime.now, comment="创建时间")