qrcode_channel_service.py
11.6 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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
from __future__ import annotations
from datetime import datetime, timedelta, timezone
from typing import Optional
from sqlalchemy import or_
from sqlalchemy.orm import Session as OrmSession
from app.infrastructure.file_parser import OSSClient
from app.model.agent import Agent, AgentPosition, AgentStatus
from app.model.agent_group import QrcodeChannel
from app.model.position_tag import PositionTag
from app.model.wecom_sync import WeComBot
from app.schema.qrcode_channel import (
QrcodeBatchStatusResponse,
QrcodeCreateResponse,
QrcodeDeleteResponse,
QrcodeDetailResponse,
QrcodeDisableResponse,
QrcodeEnableResponse,
QrcodeExportResponse,
QrcodeListItem,
QrcodeListResponse,
QrcodeUpdateResponse,
)
from app.service.agent_group_helper_service import WeComClient
class QrcodeChannelService:
def __init__(self, db: OrmSession, wecom: WeComClient, oss: Optional[OSSClient] = None):
self.db = db
self.wecom = wecom
self.oss = oss
def create(self, req) -> QrcodeCreateResponse:
position = self.db.query(PositionTag).filter(PositionTag.code == req.position_code).first()
if not position:
raise ValueError("岗位不存在")
if self.db.query(QrcodeChannel).filter(QrcodeChannel.position_id == position.id).first():
raise ValueError("该岗位已存在活码")
bot = self.db.query(WeComBot).filter(WeComBot.bot_id == req.employee_id).first()
if bot is None:
bot = self.db.query(WeComBot).filter(WeComBot.bot_id == req.wechat_user_id).first()
if bot is None or not bot.bot_id:
raise ValueError("员工不存在")
if req.wechat_user_id and str(req.wechat_user_id) != str(bot.bot_id):
raise ValueError("employee_id 和 wechat_user_id 不匹配")
if self.db.query(QrcodeChannel).filter(QrcodeChannel.wecom_bot_id == bot.id).first():
raise ValueError("该员工已绑定活码")
employee_id = str(bot.bot_id)
employee_name = bot.bot_name or employee_id
steward = self.db.query(Agent).filter(Agent.code == "steward", Agent.is_deleted == False).first()
position_agents = (
self.db.query(Agent)
.join(AgentPosition, AgentPosition.agent_id == Agent.id)
.filter(
AgentPosition.position_id == position.id,
Agent.is_deleted == False,
Agent.status == AgentStatus.enable,
)
.all()
)
agent_list = list(position_agents)
if steward and steward not in agent_list:
agent_list.insert(0, steward)
agent_ids = [a.id for a in agent_list]
agent_names = [a.name for a in agent_list]
channel_code = position.code
qrcode_url = self.wecom.create_qrcode(channel_code, req.welcome_message or "")
qr = QrcodeChannel(
qrcode_name=req.qrcode_name,
position_id=position.id,
position_name=position.name,
wecom_bot_id=bot.id,
employee_id=employee_id,
employee_name=employee_name,
channel_code=channel_code,
qrcode_url=qrcode_url,
agent_ids=agent_ids,
agent_names=agent_names,
remark=req.remark,
welcome_message=req.welcome_message,
created_by="admin",
)
self.db.add(qr)
self.db.commit()
self.db.refresh(qr)
return QrcodeCreateResponse(
qrcode_id=qr.id,
qrcode_name=qr.qrcode_name or "",
qrcode_url=qr.qrcode_url or "",
channel_code=qr.channel_code,
status=qr.status,
agent_ids=agent_ids,
agent_names=agent_names,
created_at=qr.created_at,
)
def update(self, qrcode_id: int, req) -> QrcodeUpdateResponse:
qr = self._get_or_404(qrcode_id)
qr.qrcode_name = req.qrcode_name
qr.remark = req.remark
qr.welcome_message = req.welcome_message
self.db.commit()
self.db.refresh(qr)
return QrcodeUpdateResponse(success=True, updated_at=qr.updated_at)
def get_detail(self, qrcode_id: int) -> QrcodeDetailResponse:
qr = self._get_or_404(qrcode_id)
position_agents = (
self.db.query(Agent)
.join(AgentPosition, AgentPosition.agent_id == Agent.id)
.filter(
AgentPosition.position_id == qr.position_id,
Agent.is_deleted == False,
Agent.status == AgentStatus.enable,
)
.all()
if qr.position_id is not None
else []
)
steward = self.db.query(Agent).filter(Agent.code == "steward", Agent.is_deleted == False).first()
agent_list = list(position_agents)
if steward and steward not in agent_list:
agent_list.insert(0, steward)
agent_ids = [a.id for a in agent_list]
agent_names = [a.name for a in agent_list]
return QrcodeDetailResponse(
qrcode_id=qr.id,
qrcode_name=qr.qrcode_name,
employee_id=qr.employee_id,
employee_name=qr.employee_name,
position_name=qr.position_name,
channel_code=qr.channel_code,
qrcode_url=qr.qrcode_url,
agent_ids=agent_ids,
agent_names=agent_names,
remark=qr.remark,
welcome_message=qr.welcome_message,
status=qr.status,
created_at=qr.created_at,
created_by=qr.created_by,
updated_at=qr.updated_at,
)
def list_qrcodes(
self,
page: int = 1,
page_size: int = 20,
status: Optional[str] = None,
keyword: Optional[str] = None,
) -> QrcodeListResponse:
query = self.db.query(QrcodeChannel)
if status:
query = query.filter(QrcodeChannel.status == status)
if keyword:
query = query.filter(
or_(
QrcodeChannel.employee_name.like(f"%{keyword}%"),
QrcodeChannel.position_name.like(f"%{keyword}%"),
QrcodeChannel.channel_code.like(f"%{keyword}%"),
)
)
total = query.count()
rows = query.order_by(QrcodeChannel.id.desc()).offset((page - 1) * page_size).limit(page_size).all()
items = []
for r in rows:
position_agents = (
self.db.query(Agent)
.join(AgentPosition, AgentPosition.agent_id == Agent.id)
.filter(
AgentPosition.position_id == r.position_id,
Agent.is_deleted == False,
Agent.status == AgentStatus.enable,
)
.all()
if r.position_id is not None
else []
)
steward = self.db.query(Agent).filter(Agent.code == "steward", Agent.is_deleted == False).first()
agent_list = list(position_agents)
if steward and steward not in agent_list:
agent_list.insert(0, steward)
agent_names = [a.name for a in agent_list]
operations = ["查看", "编辑"]
if r.status == "enable":
operations.append("停用")
else:
operations.append("启用")
items.append(
QrcodeListItem(
qrcode_id=r.id,
qrcode_name=r.qrcode_name,
employee_name=r.employee_name,
position_name=r.position_name,
channel_code=r.channel_code,
qrcode_url=r.qrcode_url,
agent_count=len(agent_list),
agent_names_preview=agent_names,
status=r.status,
created_at=r.created_at,
operations=operations,
)
)
return QrcodeListResponse(total=total, page=page, page_size=page_size, list=items)
def export(self, req) -> QrcodeExportResponse:
query = self.db.query(QrcodeChannel)
if req.filter_conditions:
if req.filter_conditions.get("position_name"):
query = query.filter(QrcodeChannel.position_name == req.filter_conditions["position_name"])
if req.filter_conditions.get("status"):
query = query.filter(QrcodeChannel.status == req.filter_conditions["status"])
rows = query.order_by(QrcodeChannel.id.asc()).all()
fields = req.export_fields or ["employee_name", "position_name", "channel_code", "status"]
lines = [",".join(fields)]
for r in rows:
vals = []
for f in fields:
if f == "employee_name":
vals.append(r.employee_name)
elif f == "position_name":
vals.append(r.position_name)
elif f == "channel_code":
vals.append(r.channel_code)
elif f == "status":
vals.append(r.status)
elif f == "agent_names":
vals.append(";".join(r.agent_names or []))
else:
vals.append("")
lines.append(",".join(vals))
csv_data = "\n".join(lines).encode("utf-8-sig")
now = datetime.now(timezone.utc)
file_name = f"qrcode_export_{now.strftime('%Y%m%d_%H%M%S')}.csv"
file_url = self.oss.upload(csv_data, file_name, "text/csv") if self.oss else f"https://oss.example.com/export/{file_name}"
return QrcodeExportResponse(file_url=file_url, file_name=file_name, total_count=len(rows), expires_at=now + timedelta(hours=24))
def disable(self, qrcode_id: int, reason: str) -> QrcodeDisableResponse:
qr = self._get_or_404(qrcode_id)
prev = qr.status
qr.status = "disable"
qr.disable_reason = reason
self.db.commit()
return QrcodeDisableResponse(success=True, disabled_at=datetime.now(timezone.utc), previous_status=prev)
def enable(self, qrcode_id: int) -> QrcodeEnableResponse:
qr = self._get_or_404(qrcode_id)
prev = qr.status
qr.status = "enable"
qr.disable_reason = None
self.db.commit()
return QrcodeEnableResponse(success=True, enabled_at=datetime.now(timezone.utc), previous_status=prev)
def batch_status(self, qrcode_ids: list[int], target_status: str, reason: Optional[str] = None) -> QrcodeBatchStatusResponse:
success = 0
failed = []
for qid in qrcode_ids:
try:
if target_status == "disable":
self.disable(qid, reason or "")
else:
self.enable(qid)
success += 1
except Exception as e:
failed.append({"qrcode_id": qid, "error": str(e)})
return QrcodeBatchStatusResponse(success_count=success, failed_count=len(failed), failed_list=failed)
def delete(self, qrcode_id: int) -> QrcodeDeleteResponse:
qr = self._get_or_404(qrcode_id)
self.db.delete(qr)
self.db.commit()
return QrcodeDeleteResponse(success=True, deleted_at=datetime.now(timezone.utc))
def _get_or_404(self, qrcode_id: int) -> QrcodeChannel:
qr = self.db.query(QrcodeChannel).filter(QrcodeChannel.id == qrcode_id).first()
if not qr:
raise ValueError("渠道活码不存在")
return qr
@staticmethod
def _merge_agents(agent_ids: Optional[list[int]], agent_names: Optional[list[str]]) -> list[dict]:
ids = agent_ids or []
names = agent_names or []
return [{"id": aid, "name": (names[idx] if idx < len(names) else "")} for idx, aid in enumerate(ids)]