Skip to content
Toggle navigation
Projects
Groups
Snippets
Help
ai
/
ai-workflow
This project
Loading...
Sign in
Toggle navigation
Go to a project
Project
Repository
Issues
0
Merge Requests
0
Pipelines
Wiki
Settings
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Commit 45f6b9ad
authored
Jul 17, 2026
by
sunqi02
Browse Files
Options
Browse Files
Tag
Download
Email Patches
Plain Diff
feat(customer-info): 添加客户群周报推送功能
1 parent
55832ee4
Show whitespace changes
Inline
Side-by-side
Showing
6 changed files
with
165 additions
and
2 deletions
workspace/agent-admin/backend/app/customer_info/api.py
workspace/agent-admin/backend/app/customer_info/schema.py
workspace/agent-admin/backend/app/customer_info/weekly_report_service.py
workspace/agent-admin/backend/app/jobs/log_context.py
workspace/agent-admin/backend/app/jobs/runner.py
workspace/agent-admin/backend/app/jobs/scheduler.py
workspace/agent-admin/backend/app/customer_info/api.py
View file @
45f6b9a
...
@@ -10,9 +10,11 @@ from app.customer_info.schema import (
...
@@ -10,9 +10,11 @@ from app.customer_info.schema import (
CustomerGroupPhoneResponse
,
CustomerGroupPhoneResponse
,
PhoneBindingSubmitRequest
,
PhoneBindingSubmitRequest
,
SendByPhoneRequest
,
SendByPhoneRequest
,
WeeklyReportTriggerResponse
,
)
)
from
app.customer_info.send_service
import
PhoneMessageSender
,
SendByPhoneError
from
app.customer_info.send_service
import
PhoneMessageSender
,
SendByPhoneError
from
app.customer_info.service
import
CustomerInfoService
from
app.customer_info.service
import
CustomerInfoService
from
app.customer_info.weekly_report_service
import
WeeklyReportService
router
=
APIRouter
(
prefix
=
"/api/v1/customer-info"
,
tags
=
[
"customer-info"
])
router
=
APIRouter
(
prefix
=
"/api/v1/customer-info"
,
tags
=
[
"customer-info"
])
...
@@ -21,6 +23,10 @@ def get_customer_info_service(db: Session = Depends(get_db)) -> CustomerInfoServ
...
@@ -21,6 +23,10 @@ def get_customer_info_service(db: Session = Depends(get_db)) -> CustomerInfoServ
return
CustomerInfoService
(
db
)
return
CustomerInfoService
(
db
)
def
get_weekly_report_service
(
db
:
Session
=
Depends
(
get_db
))
->
WeeklyReportService
:
return
WeeklyReportService
(
db
)
@router.post
(
"/phone"
,
response_model
=
ApiResponse
[
SuccessFlagData
])
@router.post
(
"/phone"
,
response_model
=
ApiResponse
[
SuccessFlagData
])
def
submit_phone
(
def
submit_phone
(
req
:
PhoneBindingSubmitRequest
,
req
:
PhoneBindingSubmitRequest
,
...
@@ -72,3 +78,14 @@ async def send_by_phone(
...
@@ -72,3 +78,14 @@ async def send_by_phone(
if
result
[
"success"
]:
if
result
[
"success"
]:
return
success_response_payload
(
200
,
result
)
return
success_response_payload
(
200
,
result
)
raise
HTTPException
(
status_code
=
502
,
detail
=
result
[
"message"
])
raise
HTTPException
(
status_code
=
502
,
detail
=
result
[
"message"
])
@router.post
(
"/weekly-report/trigger"
,
response_model
=
ApiResponse
[
WeeklyReportTriggerResponse
])
def
trigger_weekly_report
(
service
:
WeeklyReportService
=
Depends
(
get_weekly_report_service
),
):
"""手动触发客户群周报推送(测试用)。"""
result
=
service
.
run_and_send
()
if
not
result
[
"send_result"
][
"success"
]:
raise
HTTPException
(
status_code
=
502
,
detail
=
result
[
"send_result"
][
"message"
])
return
success_response_payload
(
200
,
result
)
workspace/agent-admin/backend/app/customer_info/schema.py
View file @
45f6b9a
...
@@ -23,6 +23,19 @@ class SendByPhoneResponse(BaseModel):
...
@@ -23,6 +23,19 @@ class SendByPhoneResponse(BaseModel):
message
:
str
message
:
str
class
WeeklyReportStats
(
BaseModel
):
total_groups
:
int
new_groups
:
int
bound_groups
:
int
pass_rate
:
float
class
WeeklyReportTriggerResponse
(
BaseModel
):
stats
:
WeeklyReportStats
content
:
str
send_result
:
dict
class
CustomerGroupPhoneResponse
(
BaseModel
):
class
CustomerGroupPhoneResponse
(
BaseModel
):
model_config
=
ConfigDict
(
from_attributes
=
True
)
model_config
=
ConfigDict
(
from_attributes
=
True
)
...
...
workspace/agent-admin/backend/app/customer_info/weekly_report_service.py
0 → 100644
View file @
45f6b9a
from
__future__
import
annotations
import
logging
from
datetime
import
timedelta
from
typing
import
Dict
,
Any
import
httpx
from
sqlalchemy
import
text
from
sqlalchemy.orm
import
Session
from
app.infrastructure.time
import
china_now
logger
=
logging
.
getLogger
(
__name__
)
WECOM_WEBHOOK_URL
=
(
"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=c1357c4b-c802-4b93-93d9-e871301a4015"
)
class
WeeklyReportService
:
"""客户群周报服务:统计 customer_group_phones 过去7天数据并推送到企业微信群机器人。"""
def
__init__
(
self
,
db
:
Session
):
self
.
db
=
db
def
build_stats
(
self
)
->
Dict
[
str
,
int
|
float
]:
"""统计过去7天相关指标。
Returns:
total_groups: 当前非 deleted 状态的总群数
new_groups: 过去7天新增的群数
bound_groups: 已绑定手机号的群数
pass_rate: 认证通过率(已绑定 / 总群数 * 100)
"""
now
=
china_now
()
seven_days_ago
=
now
-
timedelta
(
days
=
7
)
row
=
self
.
db
.
execute
(
text
(
"""
SELECT
COUNT(*) AS total_groups,
SUM(CASE WHEN create_time >= :seven_days_ago THEN 1 ELSE 0 END) AS new_groups,
SUM(CASE WHEN phone IS NOT NULL THEN 1 ELSE 0 END) AS bound_groups
FROM customer_group_phones
WHERE group_status != 'deleted'
"""
),
{
"seven_days_ago"
:
seven_days_ago
},
)
.
fetchone
()
total_groups
=
int
(
row
.
total_groups
or
0
)
new_groups
=
int
(
row
.
new_groups
or
0
)
bound_groups
=
int
(
row
.
bound_groups
or
0
)
pass_rate
=
(
bound_groups
/
total_groups
*
100
)
if
total_groups
>
0
else
0.0
return
{
"total_groups"
:
total_groups
,
"new_groups"
:
new_groups
,
"bound_groups"
:
bound_groups
,
"pass_rate"
:
round
(
pass_rate
,
2
),
}
def
build_markdown_content
(
self
,
stats
:
Dict
[
str
,
int
|
float
])
->
str
:
"""生成企业微信群机器人 markdown 消息内容。"""
today
=
china_now
()
.
strftime
(
"
%
Y-
%
m-
%
d"
)
return
(
f
"# 客户群周报({today})
\n
"
f
"> 统计周期:过去7天
\n\n
"
f
"**新增群数:** {stats['new_groups']} 个
\n
"
f
"**绑定手机号的群数:** {stats['bound_groups']} 个
\n
"
f
"**认证通过率:** {stats['pass_rate']}
%
\n
"
f
"**当前总群数:** {stats['total_groups']} 个
\n
"
)
def
send_report
(
self
,
content
:
str
)
->
Dict
[
str
,
Any
]:
"""调用企业微信群机器人 webhook 发送 markdown 消息。"""
payload
=
{
"msgtype"
:
"markdown"
,
"markdown"
:
{
"content"
:
content
},
}
try
:
resp
=
httpx
.
post
(
WECOM_WEBHOOK_URL
,
json
=
payload
,
timeout
=
10
)
resp
.
raise_for_status
()
result
=
resp
.
json
()
logger
.
info
(
"企业微信群机器人周报推送成功: response=
%
s"
,
result
)
return
{
"success"
:
True
,
"message"
:
"推送成功"
,
"detail"
:
result
}
except
httpx
.
HTTPStatusError
as
e
:
logger
.
error
(
"企业微信群机器人周报推送失败: status=
%
s body=
%
s"
,
e
.
response
.
status_code
,
e
.
response
.
text
,
)
return
{
"success"
:
False
,
"message"
:
f
"HTTP错误: {e.response.status_code}"
,
"detail"
:
e
.
response
.
text
,
}
except
httpx
.
RequestError
as
e
:
logger
.
error
(
"企业微信群机器人周报请求异常:
%
s"
,
e
)
return
{
"success"
:
False
,
"message"
:
f
"请求异常: {e}"
,
"detail"
:
str
(
e
)}
def
run_and_send
(
self
)
->
Dict
[
str
,
Any
]:
"""一键统计并发送周报。"""
stats
=
self
.
build_stats
()
content
=
self
.
build_markdown_content
(
stats
)
send_result
=
self
.
send_report
(
content
)
return
{
"stats"
:
stats
,
"content"
:
content
,
"send_result"
:
send_result
}
workspace/agent-admin/backend/app/jobs/log_context.py
View file @
45f6b9a
...
@@ -9,6 +9,7 @@ JOB_NAME_MAP = {
...
@@ -9,6 +9,7 @@ JOB_NAME_MAP = {
"dispatch_customer_group_messages"
:
"分发客户群消息到下游"
,
"dispatch_customer_group_messages"
:
"分发客户群消息到下游"
,
"sync_customer_group_phones"
:
"同步客户号码与群组关系"
,
"sync_customer_group_phones"
:
"同步客户号码与群组关系"
,
"daily_phone_push"
:
"每日手机号收集推送"
,
"daily_phone_push"
:
"每日手机号收集推送"
,
"weekly_customer_group_report"
:
"客户群每周机器人周报推送"
,
}
}
_job_key_var
:
ContextVar
[
str
|
None
]
=
ContextVar
(
"job_key"
,
default
=
None
)
_job_key_var
:
ContextVar
[
str
|
None
]
=
ContextVar
(
"job_key"
,
default
=
None
)
...
...
workspace/agent-admin/backend/app/jobs/runner.py
View file @
45f6b9a
...
@@ -20,6 +20,7 @@ from app.service.wecom_customer_group_orchestration_service import (
...
@@ -20,6 +20,7 @@ from app.service.wecom_customer_group_orchestration_service import (
)
)
from
app.service.wecom_sync_service
import
NoopWeComMessageDispatcher
,
WeComSyncService
from
app.service.wecom_sync_service
import
NoopWeComMessageDispatcher
,
WeComSyncService
from
app.customer_info.service
import
CustomerInfoService
from
app.customer_info.service
import
CustomerInfoService
from
app.customer_info.weekly_report_service
import
WeeklyReportService
logger
=
logging
.
getLogger
(
__name__
)
logger
=
logging
.
getLogger
(
__name__
)
...
@@ -43,11 +44,12 @@ def _build_services():
...
@@ -43,11 +44,12 @@ def _build_services():
batch_dispatcher
=
HttpChatCompletionsBatchDispatcher
(),
batch_dispatcher
=
HttpChatCompletionsBatchDispatcher
(),
)
)
customer_info_service
=
CustomerInfoService
(
db
)
customer_info_service
=
CustomerInfoService
(
db
)
return
db
,
sync_service
,
orchestration_service
,
customer_info_service
weekly_report_service
=
WeeklyReportService
(
db
)
return
db
,
sync_service
,
orchestration_service
,
customer_info_service
,
weekly_report_service
def
run_job
(
job_key
:
str
)
->
None
:
def
run_job
(
job_key
:
str
)
->
None
:
db
,
sync_service
,
orchestration_service
,
customer_info_service
=
_build_services
()
db
,
sync_service
,
orchestration_service
,
customer_info_service
,
weekly_report_service
=
_build_services
()
token
=
set_job_log_context
(
job_key
)
token
=
set_job_log_context
(
job_key
)
try
:
try
:
config
=
sync_service
.
ensure_job_config
(
job_key
)
config
=
sync_service
.
ensure_job_config
(
job_key
)
...
@@ -79,6 +81,8 @@ def run_job(job_key: str) -> None:
...
@@ -79,6 +81,8 @@ def run_job(job_key: str) -> None:
count
=
_run_sync_customer_group_phones
(
customer_info_service
)
count
=
_run_sync_customer_group_phones
(
customer_info_service
)
elif
job_key
==
"daily_phone_push"
:
elif
job_key
==
"daily_phone_push"
:
count
=
_run_daily_phone_push
(
customer_info_service
)
count
=
_run_daily_phone_push
(
customer_info_service
)
elif
job_key
==
"weekly_customer_group_report"
:
count
=
_run_weekly_customer_group_report
(
weekly_report_service
)
else
:
else
:
raise
ValueError
(
f
"Unsupported job_key: {job_key}"
)
raise
ValueError
(
f
"Unsupported job_key: {job_key}"
)
...
@@ -116,6 +120,16 @@ def _run_daily_phone_push(service: CustomerInfoService) -> int:
...
@@ -116,6 +120,16 @@ def _run_daily_phone_push(service: CustomerInfoService) -> int:
return
len
(
candidates
)
return
len
(
candidates
)
def
_run_weekly_customer_group_report
(
service
:
WeeklyReportService
)
->
int
:
"""执行每周一客户群机器人周报推送。"""
result
=
service
.
run_and_send
()
if
result
[
"send_result"
][
"success"
]:
logger
.
info
(
format_job_log
(
"客户群周报推送成功: stats=
%
s"
%
result
[
"stats"
]))
return
1
logger
.
error
(
format_job_log
(
"客户群周报推送失败:
%
s"
%
result
[
"send_result"
]))
return
0
def
send_im_message
(
def
send_im_message
(
bot_id
:
str
,
bot_id
:
str
,
group_id
:
str
,
group_id
:
str
,
...
...
workspace/agent-admin/backend/app/jobs/scheduler.py
View file @
45f6b9a
...
@@ -86,6 +86,18 @@ def build_scheduler() -> BlockingScheduler:
...
@@ -86,6 +86,18 @@ def build_scheduler() -> BlockingScheduler:
hour
=
9
,
hour
=
9
,
minute
=
0
,
minute
=
0
,
)
)
scheduler
.
add_job
(
run_job
,
"cron"
,
args
=
[
"weekly_customer_group_report"
],
id
=
"weekly_customer_group_report"
,
replace_existing
=
True
,
max_instances
=
1
,
coalesce
=
True
,
day_of_week
=
"mon"
,
hour
=
9
,
minute
=
0
,
)
return
scheduler
return
scheduler
...
...
Write
Preview
Markdown
is supported
Attach a file
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to post a comment