"""Version-bound manual review assignments and the assignee's private inbox.""" from __future__ import annotations from archive_store import new_id, tenant_scope, utc_now from knowledge_access import REVIEWER_PERMISSIONS, KnowledgeAccessDenied, current_access from knowledge_processing import redact from knowledge_review_policy import blocked_self_review_tenants, self_review_blocked REVIEWER = REVIEWER_PERMISSIONS ASSIGNOR = ('knowledge:review:assign',) MAINTAINER = (*ASSIGNOR, 'knowledge:read', 'im:content:read') ASSIGNMENT_SCHEMA = """ CREATE TABLE IF NOT EXISTS knowledge_review_assignment ( item_id TEXT PRIMARY KEY REFERENCES knowledge_item(id) ON DELETE CASCADE, assignment_id TEXT NOT NULL UNIQUE, revision INTEGER NOT NULL, assignee_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, assignor_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, assigned_at TEXT NOT NULL ); CREATE INDEX IF NOT EXISTS idx_knowledge_review_assignee ON knowledge_review_assignment(assignee_id,assigned_at DESC,item_id); """ ASSIGNMENT_COLUMNS = ("a.assignment_id,a.assignee_id,a.assignor_id,a.assigned_at," "COALESCE(NULLIF(b.source_name,''),u.username) assignee_name") ASSIGNMENT_PEOPLE = "JOIN users u ON u.id=a.assignee_id LEFT JOIN group_sso_bindings b ON b.user_id=u.id" PENDING = f"""SELECT k.*, {ASSIGNMENT_COLUMNS} FROM knowledge_review_assignment a JOIN knowledge_item k ON k.id=a.item_id AND k.revision=a.revision {ASSIGNMENT_PEOPLE} WHERE a.assignee_id=? AND k.status='draft'""" ITEM_FIELDS = ('id', 'title', 'question', 'answer', 'conditions', 'category', 'kind', 'content_type', 'status', 'revision', 'valid_until', 'vector_status', 'flags', 'updated_at') def public_assignment(row): return {'id': row['assignment_id'], **{k: row[k] for k in ('assignee_id', 'assignee_name', 'assigned_at')}} def assignments_for_items(db, item_ids): assignments = {} # Stay below SQLite's historical 999-variable limit for large assignment pages. batch_size = 500 for start in range(0, len(item_ids), batch_size): batch = item_ids[start:start + batch_size] placeholders = ','.join('?' for _ in batch) rows = db.execute(f"SELECT a.item_id,a.revision,{ASSIGNMENT_COLUMNS} FROM knowledge_review_assignment a " f"{ASSIGNMENT_PEOPLE} WHERE a.item_id IN ({placeholders})", batch) assignments.update({(row['item_id'], row['revision']): public_assignment(row) for row in rows}) return assignments def _access_if_allowed(db, actor, required): try: return current_access(db, actor, required) except KnowledgeAccessDenied: return None def _covers(access, tenant): return access is not None and (access.tenants is None or tenant in access.tenants) class KnowledgeAssignments: def __init__(self, store): self.store = store self.database = store.database def _selected_rows(self, db, scope, items, actor): access = current_access(db, actor, ASSIGNOR) requested = tenant_scope(scope) clause, args = access.item_sql('k') rows = [] for item in items: row = db.execute(f"SELECT * FROM knowledge_item k WHERE k.id=? AND {requested.clause('k')} AND {clause}", [item['id'], *requested.params, *args]).fetchone() if row is None: raise KeyError('知识不存在或不在你的授权范围内') if row['revision'] != item['revision'] or row['status'] != 'draft': raise ValueError('只能分配当前版本的草稿,请刷新后重试') if not self.store._fresh(db, row['id'], row['tenant_id']): raise ValueError('来源已变化,请重新加工') rows.append(row) return rows def assignees(self, scope, items, actor): with self.database.connect() as db: db.execute('BEGIN') tenants = {row['tenant_id'] for row in self._selected_rows(db, scope, items, actor)} placeholders = ','.join('?' for _ in REVIEWER) candidates = db.execute(f"""SELECT u.id,u.username,COALESCE(NULLIF(b.source_name,''),u.username) name FROM users u LEFT JOIN group_sso_bindings b ON b.user_id=u.id WHERE u.active=1 AND u.role IN ( SELECT role_code FROM role_permissions WHERE permission_code IN ({placeholders}) GROUP BY role_code HAVING COUNT(*)=? ) ORDER BY u.username,u.id""", (*REVIEWER, len(REVIEWER))).fetchall() return {'items': [dict(row) for row in candidates if tenants.isdisjoint(blocked_self_review_tenants(db, row['id']))]} def assign(self, scope, items, assignee, actor, ip): with self.database.connect() as db: db.execute('BEGIN IMMEDIATE') rows = self._selected_rows(db, scope, items, actor) if assignee is not None: tenants = {row['tenant_id'] for row in rows} if (_access_if_allowed(db, assignee, REVIEWER) is None or not tenants.isdisjoint(blocked_self_review_tenants(db, assignee))): raise ValueError('该用户不可审核所选知识,请重新选择审核人') updated = 0 now = utc_now() for row in rows: item_id, revision = row['id'], row['revision'] previous = db.execute('SELECT * FROM knowledge_review_assignment WHERE item_id=?', (item_id,)).fetchone() if assignee is None: changed = db.execute('DELETE FROM knowledge_review_assignment WHERE item_id=? AND revision=?', (item_id, revision)).rowcount else: changed = db.execute("""INSERT INTO knowledge_review_assignment VALUES (?,?,?,?,?,?) ON CONFLICT(item_id) DO UPDATE SET assignment_id=excluded.assignment_id, revision=excluded.revision,assignee_id=excluded.assignee_id, assignor_id=excluded.assignor_id,assigned_at=excluded.assigned_at WHERE revision!=excluded.revision OR assignee_id!=excluded.assignee_id OR assignor_id!=excluded.assignor_id""", (item_id, new_id(), revision, assignee, actor, now)).rowcount if changed: updated += 1 old = previous['assignee_id'] if previous is not None and previous['revision'] == revision else None self.database._audit(db, actor, 'knowledge.review.withdraw' if assignee is None else 'knowledge.review.assign', f'item={item_id} revision={revision} previous={old} assignee={assignee}', ip) return {'updated': updated} def _pending(self, db, actor, *, item_id=None, extra_permissions=()): current_access(db, actor, (*REVIEWER, *extra_permissions)) sql = PENDING args = [actor] if item_id is not None: sql += ' AND k.id=?' args.append(item_id) sql += ' ORDER BY a.assigned_at DESC,k.id' assignors = {} for row in db.execute(sql, args): assignor = row['assignor_id'] if assignor not in assignors: assignors[assignor] = _access_if_allowed(db, assignor, ASSIGNOR) # The recipient can cross their normal scope only in this exact-item inbox. tenant = row['tenant_id'] if _covers(assignors[assignor], tenant) and self.store._fresh(db, row['id'], tenant): yield row def _assigned_item(self, db, actor, item_id, *, assignment_id=None, extra_permissions=()): row = next(self._pending(db, actor, item_id=item_id, extra_permissions=extra_permissions), None) if row is None or assignment_id is not None and row['assignment_id'] != assignment_id: raise KeyError('待审核知识不存在或分配已失效,请刷新') return row def _public_item(self, db, row): item = self.store.public(row) return {**{k: item[k] for k in ITEM_FIELDS}, 'review_assignment': public_assignment(row), 'self_review_blocked': self_review_blocked(db, row['assignee_id'], row['tenant_id'])} def _detail(self, db, row): item = self._public_item(db, row) item['sources'] = [{**dict(source), 'content': redact(source['content'])} for source in db.execute( 'SELECT role,content,sent_at FROM knowledge_source WHERE item_id=? ORDER BY sent_at,message_id', (row['id'],))] return item def inbox(self, actor, page, page_size): start = (page - 1) * page_size items, total = [], 0 with self.database.connect() as db: db.execute('BEGIN') for total, row in enumerate(self._pending(db, actor), 1): if start < total <= start + page_size: items.append(self._public_item(db, row)) return {'items': items, 'total': total} def detail(self, actor, item_id): with self.database.connect() as db: db.execute('BEGIN') return self._detail(db, self._assigned_item(db, actor, item_id)) def save(self, actor, item_id, values, assignment_id, ip): with self.database.connect() as db: db.execute('BEGIN IMMEDIATE') row = self._assigned_item(db, actor, item_id, assignment_id=assignment_id or '', extra_permissions=('knowledge:write',)) fields = self.store._edit_fields(values) self.store._save_item(db, row, values['revision'], fields, actor, ip) db.execute('UPDATE knowledge_review_assignment SET revision=revision+1 WHERE item_id=?', (item_id,)) return self._detail(db, self._assigned_item(db, actor, item_id)) def transition(self, actor, item_id, revision, assignment_id, action, ip, confirmed): if action == 'approve_publish': return self.store.approve_publish(None, item_id, revision, actor, ip, confirmed, assignment_id=assignment_id) if action not in {'approve', 'reject'}: raise ValueError('未知审核操作') with self.database.connect() as db: db.execute('BEGIN IMMEDIATE') row = self._assigned_item(db, actor, item_id, assignment_id=assignment_id or '', extra_permissions=('knowledge:reject',) if action == 'reject' else ()) status = self.store._transition_item(db, row, revision, action, actor, ip, confirmed is True) return {'status': status}