sample_transport_mode.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. """样本运输方式字典 sample_transport_mode:解析 / 自动入库(flush,不单独 commit)"""
  2. from __future__ import annotations
  3. from datetime import datetime
  4. from typing import Optional
  5. from sqlalchemy.orm import Session
  6. from app.core.utils import generate_uuid
  7. from app.models.models import SysDictData, SysDictType
  8. DICT_TYPE = "sample_transport_mode"
  9. def ensure_dict_type(db: Session, tenant_no: str, user_id: Optional[str]) -> None:
  10. exists = (
  11. db.query(SysDictType.id)
  12. .filter(
  13. SysDictType.dict_type == DICT_TYPE,
  14. SysDictType.tenant_no == tenant_no,
  15. SysDictType.del_flag == 0,
  16. )
  17. .first()
  18. )
  19. if exists:
  20. return
  21. db.add(
  22. SysDictType(
  23. id=generate_uuid(),
  24. dict_name="样本运输方式",
  25. dict_type=DICT_TYPE,
  26. tenant_no=tenant_no,
  27. order_num=0,
  28. remark="协议单运费批次运输方式",
  29. create_by=user_id,
  30. create_dept_id="",
  31. create_time=datetime.now(),
  32. update_by=user_id,
  33. update_time=datetime.now(),
  34. del_flag=0,
  35. )
  36. )
  37. db.flush()
  38. def resolve_transport_mode_value(
  39. db: Session, *, tenant_no: str, raw: str, user_id: Optional[str]
  40. ) -> str:
  41. text = (raw or "").strip()
  42. if not text:
  43. raise ValueError("运输方式不能为空")
  44. ensure_dict_type(db, tenant_no, user_id)
  45. by_value = (
  46. db.query(SysDictData)
  47. .filter(
  48. SysDictData.dict_type == DICT_TYPE,
  49. SysDictData.tenant_no == tenant_no,
  50. SysDictData.dict_value == text,
  51. SysDictData.del_flag == 0,
  52. )
  53. .first()
  54. )
  55. if by_value:
  56. return by_value.dict_value
  57. by_label = (
  58. db.query(SysDictData)
  59. .filter(
  60. SysDictData.dict_type == DICT_TYPE,
  61. SysDictData.tenant_no == tenant_no,
  62. SysDictData.dict_label == text,
  63. SysDictData.del_flag == 0,
  64. )
  65. .first()
  66. )
  67. if by_label:
  68. return by_label.dict_value
  69. value = text
  70. clash = (
  71. db.query(SysDictData.id)
  72. .filter(
  73. SysDictData.dict_type == DICT_TYPE,
  74. SysDictData.tenant_no == tenant_no,
  75. SysDictData.dict_value == value,
  76. SysDictData.del_flag == 0,
  77. )
  78. .first()
  79. )
  80. if clash:
  81. value = f"{text}_{generate_uuid()[:8]}"
  82. db.add(
  83. SysDictData(
  84. id=generate_uuid(),
  85. dict_label=text,
  86. dict_value=value,
  87. dict_type=DICT_TYPE,
  88. tenant_no=tenant_no,
  89. order_num=99,
  90. remark=None,
  91. create_by=user_id,
  92. create_dept_id="",
  93. create_time=datetime.now(),
  94. update_by=user_id,
  95. update_time=datetime.now(),
  96. del_flag=0,
  97. )
  98. )
  99. db.flush()
  100. return value