agent_service.py
9.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
import secrets
from typing import Optional
from sqlalchemy import and_
from sqlalchemy.orm import Session
from app.model.agent import Agent, AgentPosition, AgentSkill, AgentStatus
from app.model.official_site_agent_display import OfficialSiteAgentDisplay
from app.model.position_tag import PositionTag
from app.model.skill import Skill
from app.model.wecom_sync import WeComBot
from app.schema.agent import (
AgentCreate,
AgentDetailResponse,
AgentPositionItem,
AgentSkillItem,
AgentStatusUpdate,
AgentUpdate,
AgentUserItem,
)
class AgentService:
def __init__(self, db: Session):
self.db = db
def create(self, data: AgentCreate) -> Agent:
self._ensure_name_unique(data.name)
managed_user_row_id = self._resolve_managed_user_row_id(data.managed_user_id)
self._validate_references(data.position_ids, data.skill_codes, managed_user_row_id)
self._ensure_managed_user_available(managed_user_row_id)
agent = Agent(
name=data.name,
code=self._generate_internal_code(),
description=data.description,
status=data.status,
managed_user_id=managed_user_row_id,
)
self.db.add(agent)
self.db.flush()
self._replace_positions(agent.id, data.position_ids)
self._replace_skills(agent.id, data.skill_codes)
self.db.commit()
self.db.refresh(agent)
return agent
def update(self, agent_id: int, data: AgentUpdate) -> Agent:
agent = self._get_agent_or_404(agent_id)
self._ensure_name_unique(data.name, exclude_agent_id=agent_id)
target_position_ids = data.position_ids if data.position_ids is not None else sorted(item.position_id for item in agent.positions)
target_skill_codes = data.skill_codes if data.skill_codes is not None else sorted(item.skill_code for item in agent.skills)
target_managed_user_id = (
self._resolve_managed_user_row_id(data.managed_user_id)
if data.managed_user_id is not None
else agent.managed_user_id
)
self._validate_references(target_position_ids, target_skill_codes, target_managed_user_id)
if target_managed_user_id is not None:
self._ensure_managed_user_available(target_managed_user_id, exclude_agent_id=agent_id)
agent.name = data.name
agent.description = data.description
agent.status = data.status
agent.managed_user_id = target_managed_user_id
if data.position_ids is not None:
self.db.query(AgentPosition).filter(AgentPosition.agent_id == agent_id).delete()
self._replace_positions(agent_id, data.position_ids)
if data.skill_codes is not None:
self.db.query(AgentSkill).filter(AgentSkill.agent_id == agent_id).delete()
self._replace_skills(agent_id, data.skill_codes)
self._sync_display_snapshots(agent)
self.db.commit()
self.db.refresh(agent)
return agent
def delete(self, agent_id: int) -> Agent:
agent = self._get_agent_or_404(agent_id)
from datetime import datetime, timezone
self.db.query(AgentPosition).filter(AgentPosition.agent_id == agent_id).delete()
self.db.query(AgentSkill).filter(AgentSkill.agent_id == agent_id).delete()
agent.managed_user_id = None
agent.is_deleted = True
agent.deleted_at = datetime.now(timezone.utc)
self.db.commit()
self.db.refresh(agent)
return agent
def get_detail(self, agent_id: int) -> AgentDetailResponse:
agent = self._get_agent_or_404(agent_id)
position_ids = sorted(ap.position_id for ap in agent.positions)
skill_codes = sorted(sk.skill_code for sk in agent.skills)
positions = []
if position_ids:
position_map = {item.id: item.name for item in self.db.query(PositionTag).filter(PositionTag.id.in_(position_ids)).all()}
positions = [AgentPositionItem(id=position_id, name=position_map.get(position_id, "")) for position_id in position_ids]
skills = []
if skill_codes:
skill_map = {item.skill_code: item.skill_name for item in self.db.query(Skill).filter(Skill.skill_code.in_(skill_codes)).all()}
skills = [AgentSkillItem(skill_code=skill_code, skill_name=skill_map.get(skill_code, "")) for skill_code in skill_codes]
managed_user = None
if agent.managed_user_id is not None:
bot = self.db.query(WeComBot).filter(WeComBot.id == agent.managed_user_id).first()
if bot:
managed_user = AgentUserItem(user_id=str(bot.bot_id or ""), user_name=bot.bot_name)
return AgentDetailResponse(
agent_id=agent.id,
name=agent.name,
description=agent.description,
positions=positions,
skills=skills,
managed_user=managed_user,
status=agent.status,
created_at=agent.created_at,
updated_at=agent.updated_at,
)
def list_agents(self, page: int = 1, page_size: int = 20, keyword: Optional[str] = None, position_id: Optional[int] = None, status: Optional[AgentStatus] = None):
query = self.db.query(Agent).filter(Agent.is_deleted == False)
if keyword:
query = query.filter(and_(Agent.is_deleted == False, Agent.name.like(f"%{keyword}%")))
if position_id is not None:
query = query.join(AgentPosition).filter(AgentPosition.position_id == position_id, Agent.is_deleted == False)
if status is not None:
query = query.filter(Agent.status == status)
total = query.count()
items = query.offset((page - 1) * page_size).limit(page_size).all()
return total, items
def update_status(self, agent_id: int, data: AgentStatusUpdate) -> Agent:
agent = self._get_agent_or_404(agent_id)
agent.status = data.status
self._sync_display_snapshots(agent)
self.db.commit()
self.db.refresh(agent)
return agent
def _sync_display_snapshots(self, agent: Agent) -> None:
self.db.query(OfficialSiteAgentDisplay).filter(
OfficialSiteAgentDisplay.agent_id == agent.id
).update(
{
OfficialSiteAgentDisplay.agent_name: agent.name,
OfficialSiteAgentDisplay.status: agent.status.value,
},
synchronize_session=False,
)
def _replace_positions(self, agent_id: int, position_ids: list[int]) -> None:
for pid in position_ids:
self.db.add(AgentPosition(agent_id=agent_id, position_id=pid))
def _replace_skills(self, agent_id: int, skill_codes: list[str]) -> None:
for sc in skill_codes:
self.db.add(AgentSkill(agent_id=agent_id, skill_code=sc))
def _validate_references(self, position_ids: list[int], skill_codes: list[str], managed_user_id: Optional[int]) -> None:
positions = self.db.query(PositionTag).filter(PositionTag.id.in_(position_ids)).all() if position_ids else []
found_position_ids = {item.id for item in positions}
missing_position_ids = sorted(set(position_ids) - found_position_ids)
if missing_position_ids:
raise ValueError(f"岗位不存在: {missing_position_ids}")
skills = self.db.query(Skill).filter(Skill.skill_code.in_(skill_codes)).all() if skill_codes else []
found_skill_codes = {item.skill_code for item in skills}
missing_skill_codes = sorted(set(skill_codes) - found_skill_codes)
if missing_skill_codes:
raise ValueError(f"技能不存在: {missing_skill_codes}")
if managed_user_id is not None:
bot = self.db.query(WeComBot).filter(WeComBot.id == managed_user_id).first()
if not bot:
raise ValueError(f"员工不存在: [{managed_user_id}]")
def _resolve_managed_user_row_id(self, managed_user_id: str) -> int:
bot = self.db.query(WeComBot).filter(WeComBot.bot_id == str(managed_user_id)).first()
if not bot:
raise ValueError(f"员工不存在: [{managed_user_id}]")
return bot.id
def _get_agent_or_404(self, agent_id: int) -> Agent:
agent = self.db.query(Agent).filter(Agent.id == agent_id, Agent.is_deleted == False).first()
if not agent:
raise ValueError("Agent不存在")
return agent
def _ensure_name_unique(self, name: str, exclude_agent_id: Optional[int] = None) -> None:
query = self.db.query(Agent).filter(Agent.name == name, Agent.is_deleted == False)
if exclude_agent_id is not None:
query = query.filter(Agent.id != exclude_agent_id)
if query.first():
raise ValueError("Agent名称已存在")
def _ensure_managed_user_available(self, managed_user_id: int, exclude_agent_id: Optional[int] = None) -> None:
query = self.db.query(Agent).filter(
Agent.managed_user_id == managed_user_id,
Agent.is_deleted == False,
)
if exclude_agent_id is not None:
query = query.filter(Agent.id != exclude_agent_id)
occupied = query.first()
if occupied:
raise ValueError(f"该员工已绑定其他Agent: [{managed_user_id}]")
def _generate_internal_code(self) -> str:
for _ in range(20):
candidate = f"agent_{secrets.token_hex(6)}"
if not self.db.query(Agent).filter(Agent.code == candidate).first():
return candidate
raise ValueError("生成内部标识失败,请稍后重试")