scope_sync.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. """
  2. 费控制度成员联动同步工具
  3. 部门停用/员工解约时自动移除相关制度中的成员引用。
  4. 员工调部门/部门新增员工时自动创建本地额度记录。
  5. """
  6. from app.api.v1.module_system.auth.schema import AuthSchema
  7. from app.core.alipay import AlipayClient
  8. from app.core.logger import log
  9. from app.plugin.module_payment.expense.institution.crud import InstitutionCRUD
  10. async def _sync_employee_quota(
  11. auth: AuthSchema, enterprise_id: str, employee_id: str, department_ids: list[str], is_add: bool
  12. ) -> None:
  13. """根据员工所属部门,同步本地额度记录
  14. 扫描所有按部门模式的制度,如果该制度引用了员工所属部门,
  15. 则为员工创建(或删除)本地 pay_expense_quota 记录。
  16. """
  17. if not employee_id:
  18. return
  19. from app.plugin.module_payment.expense.quota.model import QuotaModel
  20. from app.plugin.module_payment.expense.quota.enums import QuotaStatusEnum
  21. from sqlalchemy import insert, delete as sa_delete, select
  22. try:
  23. crud = InstitutionCRUD(auth)
  24. institutions = await crud.list(
  25. search={
  26. "enterprise_id": enterprise_id,
  27. "status__ne": "INSTITUTION_DELETE",
  28. "applicable_scope": "department",
  29. },
  30. order_by=[{"id": "desc"}],
  31. )
  32. if not institutions:
  33. return
  34. for inst in institutions:
  35. inst_id = inst.institution_id
  36. scope_owner_ids_str = getattr(inst, "scope_owner_id_list", None) or getattr(inst, "department_id", None)
  37. if not inst_id:
  38. continue
  39. # 判断该制度的部门是否匹配员工部门
  40. matched = False
  41. if scope_owner_ids_str:
  42. import json
  43. try:
  44. scope_ids = json.loads(scope_owner_ids_str) if isinstance(scope_owner_ids_str, str) else scope_owner_ids_str
  45. except (json.JSONDecodeError, TypeError):
  46. scope_ids = [str(scope_owner_ids_str)] if scope_owner_ids_str else []
  47. for dept_id in department_ids:
  48. if dept_id in scope_ids:
  49. matched = True
  50. break
  51. else:
  52. continue
  53. if not matched:
  54. continue
  55. tenant_id = auth.user.tenant_id if auth.user else 1
  56. if is_add:
  57. # 员工加入部门 → 创建额度记录
  58. check = select(QuotaModel).where(
  59. QuotaModel.employee_id == employee_id,
  60. QuotaModel.institution_id == inst_id,
  61. )
  62. existing = await auth.db.execute(check)
  63. if existing.scalar_one_or_none():
  64. continue
  65. stmt = insert(QuotaModel).values(
  66. employee_id=employee_id,
  67. institution_id=inst_id,
  68. out_biz_no=f"scope_{inst_id}_{employee_id}",
  69. total_amount=0,
  70. available_amount=0,
  71. status=QuotaStatusEnum.QUOTA_PENDING.value,
  72. enterprise_id=enterprise_id,
  73. tenant_id=tenant_id,
  74. )
  75. await auth.db.execute(stmt)
  76. log.info(
  77. f"部门联动 - 新增员工额度: employee_id={employee_id}, "
  78. f"institution_id={inst_id}"
  79. )
  80. else:
  81. # 员工离开部门 → 删除额度记录
  82. del_stmt = sa_delete(QuotaModel).where(
  83. QuotaModel.employee_id == employee_id,
  84. QuotaModel.institution_id == inst_id,
  85. )
  86. await auth.db.execute(del_stmt)
  87. log.info(
  88. f"部门联动 - 删除员工额度: employee_id={employee_id}, "
  89. f"institution_id={inst_id}"
  90. )
  91. await auth.db.flush()
  92. except Exception as e:
  93. log.error(f"部门联动同步额度失败(不影响主体操作): {e}")
  94. async def sync_employee_add_to_department_institutions(
  95. auth: AuthSchema,
  96. enterprise_id: str,
  97. employee_id: str,
  98. department_ids: list[str],
  99. ) -> None:
  100. """员工加入部门时,为引用该部门的制度创建本地额度记录"""
  101. await _sync_employee_quota(auth, enterprise_id, employee_id, department_ids, is_add=True)
  102. async def sync_employee_remove_from_department_institutions(
  103. auth: AuthSchema,
  104. enterprise_id: str,
  105. employee_id: str,
  106. department_ids: list[str],
  107. ) -> None:
  108. """员工离开部门时,从引用该部门的制度中删除本地额度记录"""
  109. await _sync_employee_quota(auth, enterprise_id, employee_id, department_ids, is_add=False)
  110. async def remove_department_from_institution_scopes(
  111. auth: AuthSchema,
  112. enterprise_id: str,
  113. department_id: str,
  114. ) -> None:
  115. """
  116. 当部门被停用时,扫描所有引用该部门的制度,移除该部门
  117. 此方法被 department/service.py 的停用方法调用
  118. """
  119. try:
  120. crud = InstitutionCRUD(auth)
  121. institutions = await crud.list(
  122. search={"enterprise_id": enterprise_id, "status__ne": "INSTITUTION_DELETE"},
  123. order_by=[{"id": "desc"}],
  124. )
  125. if not institutions:
  126. return
  127. for inst in institutions:
  128. inst_id = inst.institution_id
  129. if not inst_id:
  130. continue
  131. from .service import InstitutionScopeService
  132. await InstitutionScopeService.scope_modify_service(
  133. auth=auth,
  134. institution_id=inst_id,
  135. data={
  136. "enterprise_id": enterprise_id,
  137. "adapter_type": "EMPLOYEE_DEPARTMENT",
  138. "delete_owner_id_list": [department_id],
  139. },
  140. )
  141. log.info(f"已从制度 {inst_id} 中移除停用部门 {department_id}")
  142. except Exception as e:
  143. log.error(f"移除部门失败(不影响主体操作): {e}")
  144. async def remove_employee_from_institution_scopes(
  145. auth: AuthSchema,
  146. enterprise_id: str,
  147. employee_id: str,
  148. ) -> None:
  149. """
  150. 当员工被解约时,扫描所有按员工模式引用该员工的制度,移除该员工
  151. 此方法被 employee/service.py 的删除方法调用
  152. """
  153. try:
  154. crud = InstitutionCRUD(auth)
  155. institutions = await crud.list(
  156. search={"enterprise_id": enterprise_id, "status__ne": "INSTITUTION_DELETE"},
  157. order_by=[{"id": "desc"}],
  158. )
  159. if not institutions:
  160. return
  161. for inst in institutions:
  162. inst_id = inst.institution_id
  163. if not inst_id:
  164. continue
  165. from .service import InstitutionScopeService
  166. await InstitutionScopeService.scope_modify_service(
  167. auth=auth,
  168. institution_id=inst_id,
  169. data={
  170. "enterprise_id": enterprise_id,
  171. "adapter_type": "EMPLOYEE_SELECT",
  172. "delete_owner_id_list": [employee_id],
  173. },
  174. )
  175. log.info(f"已从制度 {inst_id} 中移除解约员工 {employee_id}")
  176. except Exception as e:
  177. log.error(f"移除员工失败(不影响主体操作): {e}")