qc_item_param.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. from __future__ import annotations
  2. import json
  3. from datetime import datetime
  4. from typing import Any, Dict, List, Optional
  5. from sqlalchemy.orm import Session
  6. from app.core.utils import generate_uuid
  7. from app.models.qc_param import BizQcItemParam
  8. def _row_to_dict(r: BizQcItemParam) -> Dict[str, Any]:
  9. return {
  10. "id": r.id,
  11. "paramName": r.param_name,
  12. "paramCode": r.param_code,
  13. "paramUnit": r.param_unit or "",
  14. "paramType": r.param_type or "text",
  15. "options": r.options or "",
  16. "defaultValue": r.default_value or "",
  17. "requiredFlag": r.required_flag or "0",
  18. "orderNum": r.order_num if r.order_num is not None else 0,
  19. }
  20. def _parse_options_list(options_raw: Any) -> List[str]:
  21. if not options_raw:
  22. return []
  23. if isinstance(options_raw, list):
  24. arr = options_raw
  25. else:
  26. try:
  27. arr = json.loads(str(options_raw))
  28. except json.JSONDecodeError:
  29. raise ValueError("单选选项格式无效")
  30. if not isinstance(arr, list):
  31. raise ValueError("单选选项格式无效")
  32. cleaned = [str(x).strip() for x in arr if str(x).strip()]
  33. return cleaned
  34. def _validate_param(p: Dict[str, Any], index: int) -> None:
  35. label = (p.get("paramName") or "").strip() or f"第{index + 1}个参数"
  36. param_type = (p.get("paramType") or "text").strip()
  37. if param_type != "select":
  38. return
  39. opts = _parse_options_list(p.get("options"))
  40. if not opts:
  41. raise ValueError(f"「{label}」为单选类型,请至少配置一个选项")
  42. if len(opts) != len(set(opts)):
  43. raise ValueError(f"「{label}」的选项不能重复")
  44. def list_params_by_item(
  45. db: Session, item_source: str, item_id: str, tenant_no: str, *, user_info=None
  46. ) -> List[Dict[str, Any]]:
  47. q = db.query(BizQcItemParam).filter(
  48. BizQcItemParam.item_source == item_source,
  49. BizQcItemParam.item_id == item_id,
  50. BizQcItemParam.tenant_no == tenant_no,
  51. BizQcItemParam.del_flag == 0,
  52. )
  53. if user_info:
  54. from app.core.data_scope import apply_data_scope
  55. q = apply_data_scope(q, BizQcItemParam, user_info, db, tenant_no)
  56. rows = q.order_by(BizQcItemParam.order_num.asc()).all()
  57. return [_row_to_dict(r) for r in rows]
  58. def save_params_for_item(
  59. db: Session,
  60. item_source: str,
  61. item_id: str,
  62. params: List[Dict[str, Any]],
  63. tenant_no: str,
  64. user_id: Optional[str] = None,
  65. ) -> List[Dict[str, Any]]:
  66. for idx, p in enumerate(params):
  67. _validate_param(p, idx)
  68. now = datetime.now()
  69. db.query(BizQcItemParam).filter(
  70. BizQcItemParam.item_source == item_source,
  71. BizQcItemParam.item_id == item_id,
  72. BizQcItemParam.tenant_no == tenant_no,
  73. BizQcItemParam.del_flag == 0,
  74. ).update(
  75. {"del_flag": 1, "update_by": user_id, "update_time": now},
  76. synchronize_session="fetch",
  77. )
  78. db.flush()
  79. for idx, p in enumerate(params):
  80. param_type = (p.get("paramType") or "text").strip()
  81. options_val = None
  82. default_val = None
  83. if param_type == "select":
  84. opts = _parse_options_list(p.get("options"))
  85. options_val = json.dumps(opts, ensure_ascii=False)
  86. default_val = opts[0] if opts else None
  87. obj = BizQcItemParam(
  88. id=generate_uuid(),
  89. item_source=item_source,
  90. item_id=item_id,
  91. param_name=p.get("paramName", ""),
  92. param_code=p.get("paramCode", ""),
  93. param_unit=p.get("paramUnit") or None,
  94. param_type=param_type,
  95. options=options_val,
  96. default_value=default_val,
  97. required_flag=p.get("requiredFlag", "0"),
  98. tenant_no=tenant_no,
  99. order_num=p.get("orderNum", idx),
  100. create_by=user_id,
  101. create_dept_id="",
  102. create_time=now,
  103. update_by=user_id,
  104. update_time=now,
  105. del_flag=0,
  106. )
  107. db.add(obj)
  108. db.commit()
  109. return list_params_by_item(db, item_source, item_id, tenant_no)