feat(agent_assets): 添加规则版本送审时的命名副本创建逻辑
当提交的版本与当前工作版本不同时,自动创建命名副本:
- 新增 _create_named_working_copy_for_review 方法处理送审时的版本复制
- 支持将工作版本快照复制为指定版本进行送审
- 新增 AgentAssetSpreadsheetChangeRecordRead schema
- API 端点新增 /rules/{id}/spreadsheet-versions/{version}/change-records 接口
This commit is contained in:
@@ -23,6 +23,7 @@ from app.schemas.agent_asset import (
|
||||
AgentAssetRead,
|
||||
AgentAssetReviewCreate,
|
||||
AgentAssetReviewRead,
|
||||
AgentAssetSpreadsheetChangeRecordRead,
|
||||
AgentAssetVersionCompareRead,
|
||||
AgentAssetUpdate,
|
||||
AgentAssetVersionCreate,
|
||||
@@ -276,12 +277,17 @@ def handle_agent_asset_spreadsheet_onlyoffice_callback(
|
||||
str,
|
||||
Query(min_length=1, description="打开编辑器时对应的规则版本号。"),
|
||||
],
|
||||
actor_name: Annotated[
|
||||
str | None,
|
||||
Query(description="发起编辑的用户显示名。"),
|
||||
] = None,
|
||||
) -> AgentAssetOnlyOfficeCallbackRead:
|
||||
try:
|
||||
AgentAssetService(db).handle_rule_spreadsheet_onlyoffice_callback(
|
||||
asset_id,
|
||||
version=version,
|
||||
payload=payload.model_dump(),
|
||||
actor_name=actor_name,
|
||||
)
|
||||
except Exception as exc:
|
||||
_handle_asset_error(exc)
|
||||
@@ -289,6 +295,24 @@ def handle_agent_asset_spreadsheet_onlyoffice_callback(
|
||||
return AgentAssetOnlyOfficeCallbackRead()
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{asset_id}/spreadsheet/change-records",
|
||||
response_model=list[AgentAssetSpreadsheetChangeRecordRead],
|
||||
summary="读取规则表最近修改记录",
|
||||
description="返回最近 30 次 ONLYOFFICE 保存级修改记录,用于展示操作者、时间和具体差异。",
|
||||
)
|
||||
def list_agent_asset_spreadsheet_change_records(
|
||||
asset_id: str,
|
||||
_: CurrentUser,
|
||||
db: DbSession,
|
||||
limit: Annotated[int, Query(ge=1, le=30, description="返回条数,最多 30 条。")] = 30,
|
||||
) -> list[AgentAssetSpreadsheetChangeRecordRead]:
|
||||
try:
|
||||
return AgentAssetService(db).list_spreadsheet_change_records(asset_id, limit=limit)
|
||||
except Exception as exc:
|
||||
_handle_asset_error(exc)
|
||||
|
||||
|
||||
@router.post(
|
||||
"",
|
||||
response_model=AgentAssetRead,
|
||||
|
||||
@@ -128,6 +128,16 @@ class AgentAssetVersionCompareRead(BaseModel):
|
||||
cell_changes: list[AgentAssetSpreadsheetDiffCellRead] = Field(default_factory=list)
|
||||
|
||||
|
||||
class AgentAssetSpreadsheetChangeRecordRead(BaseModel):
|
||||
actor: str
|
||||
changed_at: datetime
|
||||
summary: str
|
||||
sheet_changes: list[AgentAssetSpreadsheetDiffSheetRead] = Field(default_factory=list)
|
||||
cell_changes: list[AgentAssetSpreadsheetDiffCellRead] = Field(default_factory=list)
|
||||
changed_sheet_count: int = 0
|
||||
changed_cell_count: int = 0
|
||||
|
||||
|
||||
class AgentAssetVersionRead(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ from dataclasses import dataclass
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from urllib.parse import quote
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
import jwt
|
||||
@@ -29,6 +30,7 @@ from app.schemas.agent_asset import (
|
||||
AgentAssetRead,
|
||||
AgentAssetReviewCreate,
|
||||
AgentAssetReviewRead,
|
||||
AgentAssetSpreadsheetChangeRecordRead,
|
||||
AgentAssetSpreadsheetDiffCellRead,
|
||||
AgentAssetSpreadsheetDiffSheetRead,
|
||||
AgentAssetUpdate,
|
||||
@@ -300,6 +302,19 @@ class AgentAssetService:
|
||||
asset = self.repository.get(asset_id)
|
||||
if asset is None:
|
||||
raise LookupError("Asset not found")
|
||||
if (
|
||||
asset.asset_type == AgentAssetType.RULE.value
|
||||
and payload.review_status == AgentReviewStatus.PENDING
|
||||
and payload.version != self._resolve_working_version(asset)
|
||||
):
|
||||
if self.repository.get_version(asset_id, payload.version) is not None:
|
||||
raise ValueError(f"版本 {payload.version} 已存在,不能重复送审。")
|
||||
asset = self._create_named_working_copy_for_review(
|
||||
asset,
|
||||
target_version=payload.version,
|
||||
actor=actor,
|
||||
request_id=request_id,
|
||||
)
|
||||
if self.repository.get_version(asset_id, payload.version) is None:
|
||||
raise LookupError(f"版本 {payload.version} 不存在")
|
||||
if asset.asset_type == AgentAssetType.RULE.value:
|
||||
@@ -352,6 +367,82 @@ class AgentAssetService:
|
||||
)
|
||||
return AgentAssetReviewRead.model_validate(created)
|
||||
|
||||
def _create_named_working_copy_for_review(
|
||||
self,
|
||||
asset: AgentAsset,
|
||||
*,
|
||||
target_version: str,
|
||||
actor: str,
|
||||
request_id: str | None = None,
|
||||
) -> AgentAsset:
|
||||
working_version = self._resolve_working_version(asset)
|
||||
if not working_version:
|
||||
raise ValueError("当前规则尚未配置工作版本,无法提交审核。")
|
||||
|
||||
source = self.repository.get_version(asset.id, working_version)
|
||||
if source is None:
|
||||
raise LookupError(f"版本 {working_version} 不存在")
|
||||
|
||||
is_spreadsheet_rule = (
|
||||
asset.asset_type == AgentAssetType.RULE.value
|
||||
and str((asset.config_json or {}).get("detail_mode") or "").strip().lower()
|
||||
== "spreadsheet"
|
||||
)
|
||||
if is_spreadsheet_rule:
|
||||
_, metadata = self._resolve_spreadsheet_version_meta(asset, version=working_version)
|
||||
file_path = self.spreadsheet_manager.resolve_storage_path(metadata.storage_key)
|
||||
if not file_path.exists():
|
||||
raise FileNotFoundError(metadata.file_name)
|
||||
snapshot_meta = self.spreadsheet_manager.store_spreadsheet(
|
||||
asset_id=asset.id,
|
||||
version=target_version,
|
||||
file_name=metadata.file_name,
|
||||
content=file_path.read_bytes(),
|
||||
actor_name=actor,
|
||||
source="review-submit",
|
||||
)
|
||||
next_content = self.spreadsheet_manager.build_version_markdown(
|
||||
rule_name=asset.name,
|
||||
version=target_version,
|
||||
metadata=snapshot_meta,
|
||||
)
|
||||
next_content_type = AgentAssetContentType.MARKDOWN
|
||||
else:
|
||||
next_content = self._deserialize_content(source)
|
||||
next_content_type = AgentAssetContentType(source.content_type)
|
||||
|
||||
self.create_version(
|
||||
asset.id,
|
||||
AgentAssetVersionCreate(
|
||||
version=target_version,
|
||||
content=next_content,
|
||||
content_type=next_content_type,
|
||||
change_note=f"提交审核前固化工作稿为 {target_version}",
|
||||
created_by=actor,
|
||||
),
|
||||
actor=actor,
|
||||
request_id=request_id,
|
||||
)
|
||||
|
||||
refreshed = self.repository.get(asset.id)
|
||||
if refreshed is None:
|
||||
raise LookupError("Asset not found")
|
||||
|
||||
if is_spreadsheet_rule:
|
||||
config_json = dict(refreshed.config_json or {})
|
||||
current_document_meta = self._read_current_rule_document_meta(refreshed)
|
||||
if current_document_meta is not None:
|
||||
rule_document = self.spreadsheet_manager.build_rule_document_config(
|
||||
current_document_meta,
|
||||
asset_version=target_version,
|
||||
)
|
||||
rule_document["storage_key"] = current_document_meta.storage_key
|
||||
config_json["rule_document"] = rule_document
|
||||
refreshed.config_json = config_json
|
||||
self.repository.save_asset(refreshed)
|
||||
|
||||
return refreshed
|
||||
|
||||
def activate_asset(
|
||||
self,
|
||||
asset_id: str,
|
||||
@@ -576,6 +667,7 @@ class AgentAssetService:
|
||||
*,
|
||||
version: str,
|
||||
payload: dict[str, Any],
|
||||
actor_name: str | None = None,
|
||||
) -> None:
|
||||
self._ensure_ready()
|
||||
if asset_id == PREVIEW_RULE_ASSET_ID:
|
||||
@@ -603,15 +695,57 @@ class AgentAssetService:
|
||||
if current_metadata.checksum and current_metadata.checksum == self._hash_bytes(content):
|
||||
return
|
||||
|
||||
actor_name = callback.users[0] if callback.users else "ONLYOFFICE"
|
||||
from io import BytesIO
|
||||
from openpyxl import load_workbook
|
||||
try:
|
||||
base_workbook = self._load_spreadsheet_for_compare(current_metadata)
|
||||
target_workbook = load_workbook(BytesIO(content), read_only=False, data_only=False)
|
||||
sheet_changes, cell_changes = self._collect_workbook_changes(
|
||||
base_workbook, target_workbook
|
||||
)
|
||||
changed_sheet_count = len(
|
||||
{item.sheet_name for item in sheet_changes}
|
||||
| {item.sheet_name for item in cell_changes}
|
||||
)
|
||||
changed_cell_count = len(cell_changes)
|
||||
|
||||
if changed_cell_count > 0 or changed_sheet_count > 0:
|
||||
change_note = f"ONLYOFFICE 在线编辑:涉及 {changed_sheet_count} 个 Sheet,共 {changed_cell_count} 处改动。"
|
||||
else:
|
||||
change_note = "ONLYOFFICE 在线编辑保存。"
|
||||
except Exception:
|
||||
sheet_changes = []
|
||||
cell_changes = []
|
||||
changed_sheet_count = 0
|
||||
changed_cell_count = 0
|
||||
change_note = "ONLYOFFICE 在线编辑保存。"
|
||||
|
||||
resolved_actor_name = str(actor_name or "").strip() or (
|
||||
callback.users[0] if callback.users else "ONLYOFFICE"
|
||||
)
|
||||
self.upload_rule_spreadsheet(
|
||||
asset.id,
|
||||
filename=current_metadata.file_name,
|
||||
content=content,
|
||||
actor=actor_name,
|
||||
change_note="ONLYOFFICE 编辑保存规则表。",
|
||||
actor=resolved_actor_name,
|
||||
change_note=change_note,
|
||||
source="onlyoffice",
|
||||
)
|
||||
if changed_sheet_count > 0 or changed_cell_count > 0:
|
||||
self.audit_service.log_action(
|
||||
actor=resolved_actor_name,
|
||||
action="edit_rule_spreadsheet",
|
||||
resource_type=asset.asset_type,
|
||||
resource_id=asset.id,
|
||||
before_json={"version": version},
|
||||
after_json={
|
||||
"summary": change_note,
|
||||
"changed_sheet_count": changed_sheet_count,
|
||||
"changed_cell_count": changed_cell_count,
|
||||
"sheet_changes": [item.model_dump() for item in sheet_changes],
|
||||
"cell_changes": [item.model_dump() for item in cell_changes[:500]],
|
||||
},
|
||||
)
|
||||
|
||||
def _ensure_ready(self) -> None:
|
||||
AgentFoundationService(self.db).ensure_foundation_ready()
|
||||
@@ -853,6 +987,39 @@ class AgentAssetService:
|
||||
cell_changes=cell_changes[:500],
|
||||
)
|
||||
|
||||
def list_spreadsheet_change_records(
|
||||
self,
|
||||
asset_id: str,
|
||||
*,
|
||||
limit: int = 30,
|
||||
) -> list[AgentAssetSpreadsheetChangeRecordRead]:
|
||||
self._ensure_ready()
|
||||
asset = self._require_spreadsheet_rule(asset_id)
|
||||
logs = self.audit_service.repository.list(
|
||||
resource_type=asset.asset_type,
|
||||
resource_id=asset.id,
|
||||
action="edit_rule_spreadsheet",
|
||||
limit=min(max(limit, 1), 30),
|
||||
)
|
||||
return [
|
||||
AgentAssetSpreadsheetChangeRecordRead(
|
||||
actor=log.actor,
|
||||
changed_at=log.created_at,
|
||||
summary=str((log.after_json or {}).get("summary") or "ONLYOFFICE 在线编辑保存。"),
|
||||
sheet_changes=[
|
||||
AgentAssetSpreadsheetDiffSheetRead.model_validate(item)
|
||||
for item in ((log.after_json or {}).get("sheet_changes") or [])
|
||||
],
|
||||
cell_changes=[
|
||||
AgentAssetSpreadsheetDiffCellRead.model_validate(item)
|
||||
for item in ((log.after_json or {}).get("cell_changes") or [])
|
||||
],
|
||||
changed_sheet_count=int((log.after_json or {}).get("changed_sheet_count") or 0),
|
||||
changed_cell_count=int((log.after_json or {}).get("changed_cell_count") or 0),
|
||||
)
|
||||
for log in logs
|
||||
]
|
||||
|
||||
def _serialize_version(
|
||||
self, version: AgentAssetVersion, asset: AgentAsset
|
||||
) -> AgentAssetVersionRead:
|
||||
@@ -964,7 +1131,7 @@ class AgentAssetService:
|
||||
)
|
||||
callback_url = (
|
||||
f"{backend_base_url}{settings.api_v1_prefix}/agent-assets/{asset_id}/spreadsheet/onlyoffice/callback"
|
||||
f"?version={resolved_version}"
|
||||
f"?version={resolved_version}&actor_name={quote(current_user.name)}"
|
||||
)
|
||||
|
||||
config: dict[str, Any] = {
|
||||
@@ -994,7 +1161,7 @@ class AgentAssetService:
|
||||
"compactToolbar": False,
|
||||
"toolbarNoTabs": False,
|
||||
"autosave": False,
|
||||
"forcesave": False,
|
||||
"forcesave": editable,
|
||||
},
|
||||
},
|
||||
"width": "100%",
|
||||
@@ -1207,6 +1374,52 @@ class AgentAssetService:
|
||||
raise FileNotFoundError(metadata.file_name)
|
||||
return load_workbook(BytesIO(file_path.read_bytes()), read_only=False, data_only=False)
|
||||
|
||||
def _collect_workbook_changes(
|
||||
self, base_workbook, target_workbook
|
||||
) -> tuple[list[AgentAssetSpreadsheetDiffSheetRead], list[AgentAssetSpreadsheetDiffCellRead]]:
|
||||
base_sheet_names = set(base_workbook.sheetnames)
|
||||
target_sheet_names = set(target_workbook.sheetnames)
|
||||
sheet_changes: list[AgentAssetSpreadsheetDiffSheetRead] = []
|
||||
for sheet_name in sorted(target_sheet_names - base_sheet_names):
|
||||
sheet_changes.append(
|
||||
AgentAssetSpreadsheetDiffSheetRead(sheet_name=sheet_name, change_type="added")
|
||||
)
|
||||
for sheet_name in sorted(base_sheet_names - target_sheet_names):
|
||||
sheet_changes.append(
|
||||
AgentAssetSpreadsheetDiffSheetRead(sheet_name=sheet_name, change_type="removed")
|
||||
)
|
||||
|
||||
cell_changes: list[AgentAssetSpreadsheetDiffCellRead] = []
|
||||
|
||||
for sheet_name in sorted(base_sheet_names & target_sheet_names):
|
||||
base_sheet = base_workbook[sheet_name]
|
||||
target_sheet = target_workbook[sheet_name]
|
||||
max_row = max(base_sheet.max_row, target_sheet.max_row)
|
||||
max_column = max(base_sheet.max_column, target_sheet.max_column)
|
||||
for row_index in range(1, max_row + 1):
|
||||
for column_index in range(1, max_column + 1):
|
||||
before_value = base_sheet.cell(row=row_index, column=column_index).value
|
||||
after_value = target_sheet.cell(row=row_index, column=column_index).value
|
||||
if before_value == after_value:
|
||||
continue
|
||||
if before_value in (None, ""):
|
||||
change_type = "added"
|
||||
elif after_value in (None, ""):
|
||||
change_type = "removed"
|
||||
else:
|
||||
change_type = "modified"
|
||||
cell_changes.append(
|
||||
AgentAssetSpreadsheetDiffCellRead(
|
||||
sheet_name=sheet_name,
|
||||
cell=target_sheet.cell(row=row_index, column=column_index).coordinate,
|
||||
change_type=change_type,
|
||||
before_value=before_value,
|
||||
after_value=after_value,
|
||||
)
|
||||
)
|
||||
|
||||
return sheet_changes, cell_changes
|
||||
|
||||
@staticmethod
|
||||
def _extract_restore_source_version(change_note: str | None) -> str | None:
|
||||
normalized = str(change_note or "").strip()
|
||||
|
||||
Reference in New Issue
Block a user