production_waste_output.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. """生产任务步骤废弃物产出 — 只读汇总列表。"""
  2. from __future__ import annotations
  3. from typing import Any, Dict, Iterable, List, Optional, Set, Tuple
  4. from sqlalchemy import and_, or_
  5. from sqlalchemy.orm import Session
  6. from app.models.models import (
  7. BizOutputType,
  8. BizProductionTask,
  9. BizProductionTaskStep,
  10. BizProductionTaskStepOutput,
  11. BizProductionWorkOrder,
  12. )
  13. WASTE_OUTPUT_TYPE_CODE = "FQW"
  14. WASTE_OUTPUT_TYPE_NAME = "废弃物"
  15. def pick_waste_output_type_ids(rows: Iterable[Dict[str, Any]]) -> Set[str]:
  16. """从产出类型行中选出废弃物类型 id:优先 type_code=FQW,否则兜底 type_name=废弃物。"""
  17. rows = list(rows or [])
  18. by_code = {
  19. str(r.get("id") or "").strip()
  20. for r in rows
  21. if str(r.get("type_code") or "").strip() == WASTE_OUTPUT_TYPE_CODE
  22. and str(r.get("id") or "").strip()
  23. }
  24. if by_code:
  25. return by_code
  26. return {
  27. str(r.get("id") or "").strip()
  28. for r in rows
  29. if str(r.get("type_name") or "").strip() == WASTE_OUTPUT_TYPE_NAME
  30. and str(r.get("id") or "").strip()
  31. }
  32. def match_waste_output_keyword(
  33. keyword: Optional[str], output_name: Optional[str], output_barcode: Optional[str]
  34. ) -> bool:
  35. kw = (keyword or "").strip()
  36. if not kw:
  37. return True
  38. name = output_name or ""
  39. barcode = output_barcode or ""
  40. return kw in name or kw in barcode
  41. def resolve_waste_output_type_ids(db: Session, tenant_no: str) -> Set[str]:
  42. rows = (
  43. db.query(BizOutputType.id, BizOutputType.type_code, BizOutputType.type_name)
  44. .filter(BizOutputType.tenant_no == tenant_no, BizOutputType.del_flag == 0)
  45. .all()
  46. )
  47. return pick_waste_output_type_ids(
  48. [{"id": r.id, "type_code": r.type_code, "type_name": r.type_name} for r in rows]
  49. )
  50. def _fmt_dt(t) -> str:
  51. if t is None:
  52. return ""
  53. if hasattr(t, "strftime"):
  54. return t.strftime("%Y-%m-%d %H:%M:%S")
  55. return str(t)
  56. def _normalize_date_bound(value: str, *, end_of_day: bool = False) -> str:
  57. v = (value or "").strip()
  58. if not v:
  59. return v
  60. if len(v) <= 10:
  61. return f"{v} 23:59:59" if end_of_day else f"{v} 00:00:00"
  62. return v
  63. def list_production_waste_outputs(
  64. db: Session,
  65. *,
  66. tenant_no: str,
  67. page: int = 1,
  68. page_size: int = 10,
  69. keyword: Optional[str] = None,
  70. create_time_start: Optional[str] = None,
  71. create_time_end: Optional[str] = None,
  72. user_info=None,
  73. ) -> Tuple[List[Dict[str, Any]], int]:
  74. type_ids = resolve_waste_output_type_ids(db, tenant_no)
  75. if not type_ids:
  76. return [], 0
  77. q = (
  78. db.query(
  79. BizProductionTaskStepOutput,
  80. BizProductionTaskStep,
  81. BizProductionTask,
  82. BizProductionWorkOrder,
  83. )
  84. .join(
  85. BizProductionTaskStep,
  86. and_(
  87. BizProductionTaskStep.id == BizProductionTaskStepOutput.step_id,
  88. BizProductionTaskStep.del_flag == 0,
  89. ),
  90. )
  91. .join(
  92. BizProductionTask,
  93. and_(
  94. BizProductionTask.id == BizProductionTaskStep.task_id,
  95. BizProductionTask.del_flag == 0,
  96. BizProductionTask.tenant_no == tenant_no,
  97. ),
  98. )
  99. .outerjoin(
  100. BizProductionWorkOrder,
  101. and_(
  102. BizProductionWorkOrder.id == BizProductionTask.work_order_id,
  103. BizProductionWorkOrder.del_flag == 0,
  104. ),
  105. )
  106. .filter(
  107. BizProductionTaskStepOutput.tenant_no == tenant_no,
  108. BizProductionTaskStepOutput.del_flag == 0,
  109. BizProductionTaskStepOutput.output_type_id.in_(list(type_ids)),
  110. )
  111. )
  112. kw = (keyword or "").strip()
  113. if kw:
  114. like = f"%{kw}%"
  115. q = q.filter(
  116. or_(
  117. BizProductionTaskStepOutput.output_name.like(like),
  118. BizProductionTaskStepOutput.output_barcode.like(like),
  119. )
  120. )
  121. if create_time_start and create_time_start.strip():
  122. q = q.filter(
  123. BizProductionTaskStepOutput.create_time
  124. >= _normalize_date_bound(create_time_start.strip())
  125. )
  126. if create_time_end and create_time_end.strip():
  127. q = q.filter(
  128. BizProductionTaskStepOutput.create_time
  129. <= _normalize_date_bound(create_time_end.strip(), end_of_day=True)
  130. )
  131. if user_info is not None:
  132. from app.core.data_scope import apply_data_scope
  133. q = apply_data_scope(q, BizProductionTask, user_info, db, tenant_no)
  134. q = q.order_by(BizProductionTaskStepOutput.create_time.desc())
  135. total = q.count()
  136. page = max(1, int(page or 1))
  137. page_size = max(1, min(int(page_size or 10), 100))
  138. rows = q.offset((page - 1) * page_size).limit(page_size).all()
  139. items: List[Dict[str, Any]] = []
  140. for out, step, task, wo in rows:
  141. items.append(
  142. {
  143. "id": out.id,
  144. "outputName": out.output_name or "",
  145. "outputBarcode": out.output_barcode or "",
  146. "remark": out.remark or "",
  147. "createTime": _fmt_dt(out.create_time),
  148. "stepId": out.step_id or "",
  149. "processName": (step.process_name if step else None) or "",
  150. "taskId": (task.id if task else None) or "",
  151. "taskNo": (task.task_no if task else None) or "",
  152. "workOrderId": (wo.id if wo else None) or (task.work_order_id if task else "") or "",
  153. "workOrderNo": (wo.work_order_no if wo else None) or "",
  154. "sampleCode": (wo.sample_code if wo else None) or "",
  155. }
  156. )
  157. return items, total
  158. def total_pages(total: int, page_size: int) -> int:
  159. if page_size <= 0:
  160. return 0
  161. return (total + page_size - 1) // page_size