fix(培训配置): 修复保存培训配置状态丢失bug!
This commit is contained in:
1 parent
2ff9fdafe4
commit
a354bcac85
2 files changed
+103
-3
No files matched your search
@@ -161,6 +161,17 @@ def create_config(data: dict[str, Any], user_id: int | None) -> dict[str, Any]:
|
||||
|
||||
|
||||
def update_config(config_id: int, data: dict[str, Any], user_id: int | None) -> dict[str, Any]:
|
||||
"""
|
||||
更新培训配置并保持未替换资料绑定的稳定主键。
|
||||
|
||||
用途:管理端保存配置时复用既有资料行,避免员工安全培训进度按资料绑定 ID 记录后失去关联。
|
||||
Args:
|
||||
config_id: 要更新的培训配置 ID。
|
||||
data: 管理端提交的完整配置;既有资料必须携带且仅能携带当前配置下的 `id`。
|
||||
user_id: 当前管理员 ID,可为空。
|
||||
Returns:
|
||||
更新后的培训配置序列化结果。
|
||||
"""
|
||||
config = db.session.get(TrainingConfig, config_id)
|
||||
if not config:
|
||||
raise NotFoundError("Training config not found")
|
||||
@@ -168,7 +179,29 @@ def update_config(config_id: int, data: dict[str, Any], user_id: int | None) ->
|
||||
if "resources" in data:
|
||||
if not isinstance(data["resources"], list):
|
||||
raise ValidationError("resources must be an array", details={"field": "resources"})
|
||||
config.resources = [TrainingConfigResource(**_validate_resource(item)) for item in data["resources"]]
|
||||
|
||||
existing_resources = {resource.id: resource for resource in config.resources}
|
||||
submitted_resource_ids: set[int] = set()
|
||||
updated_resources: list[TrainingConfigResource] = []
|
||||
for item in data["resources"]:
|
||||
validated = _validate_resource(item)
|
||||
resource_id = item.get("id")
|
||||
if resource_id is None:
|
||||
updated_resources.append(TrainingConfigResource(**validated))
|
||||
continue
|
||||
|
||||
parsed_resource_id = _required_int(resource_id, "resources.id")
|
||||
if parsed_resource_id in submitted_resource_ids:
|
||||
raise ValidationError("resources contains duplicate id", details={"field": "resources.id"})
|
||||
submitted_resource_ids.add(parsed_resource_id)
|
||||
resource = existing_resources.get(parsed_resource_id)
|
||||
if not resource:
|
||||
raise ValidationError("Training config resource not found", details={"field": "resources.id"})
|
||||
for field, value in validated.items():
|
||||
setattr(resource, field, value)
|
||||
updated_resources.append(resource)
|
||||
|
||||
config.resources = updated_resources
|
||||
db.session.commit()
|
||||
return serialize_training_config(config)
|
||||
|
||||
|
||||
Reference in new issue
Block a user