Compare commits
10
Commits
48dd28a796
...
7cdfd76bfb
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7cdfd76bfb | ||
|
|
a9752b01a9 | ||
|
|
493287c99f | ||
|
|
692b166d9f | ||
|
|
602a137c93 | ||
|
|
80bf1d218c | ||
|
|
fae7a51cc5 | ||
|
|
8d57c5dbc3 | ||
|
|
ab79dd89be | ||
|
|
e3280623de |
@@ -3,14 +3,12 @@ schema_version: 1
|
|||||||
locale: zh-CN
|
locale: zh-CN
|
||||||
branch: master
|
branch: master
|
||||||
nodes_managed: true
|
nodes_managed: true
|
||||||
exported_at: "2026-08-25T11:06:55Z"
|
exported_at: "2026-08-31T09:16:18Z"
|
||||||
modules:
|
modules:
|
||||||
"":
|
"":
|
||||||
dir_name: Boss直聘 AI 智能投递系统(客户端-服务端)
|
dir_name: Boss 直聘 AI 投递系统(客户端-服务端协作)
|
||||||
title: Boss直聘 AI 智能投递系统(客户端-服务端)
|
title: Boss 直聘 AI 投递系统(客户端-服务端协作)
|
||||||
scope:
|
scope: []
|
||||||
- .gitignore
|
|
||||||
- README.md
|
|
||||||
source_files: []
|
source_files: []
|
||||||
children:
|
children:
|
||||||
- client
|
- client
|
||||||
@@ -18,8 +16,8 @@ modules:
|
|||||||
depends_on: []
|
depends_on: []
|
||||||
related_to: []
|
related_to: []
|
||||||
client:
|
client:
|
||||||
dir_name: 简历投递客户端(本地控制面板 + AdsPower + AI 评分)
|
dir_name: 客户端自动化控制服务(client)
|
||||||
title: 简历投递客户端(本地控制面板 + AdsPower + AI 评分)
|
title: 客户端自动化控制服务(client)
|
||||||
scope:
|
scope:
|
||||||
- client/
|
- client/
|
||||||
source_files: []
|
source_files: []
|
||||||
@@ -28,8 +26,8 @@ modules:
|
|||||||
depends_on: []
|
depends_on: []
|
||||||
related_to: []
|
related_to: []
|
||||||
client/shared_client_utils:
|
client/shared_client_utils:
|
||||||
dir_name: 客户端主程序与云端_AI 能力封装
|
dir_name: 客户端主进程与云端 API 封装
|
||||||
title: 客户端主程序与云端/AI 能力封装
|
title: 客户端主进程与云端 API 封装
|
||||||
scope:
|
scope:
|
||||||
- client/main.py
|
- client/main.py
|
||||||
- client/config.py
|
- client/config.py
|
||||||
@@ -40,17 +38,19 @@ modules:
|
|||||||
source_files: []
|
source_files: []
|
||||||
children: []
|
children: []
|
||||||
depends_on: []
|
depends_on: []
|
||||||
related_to: []
|
related_to:
|
||||||
|
- path: server
|
||||||
server:
|
server:
|
||||||
dir_name: Boss直聘投递服务端
|
dir_name: Boss 直聘投递服务(FastAPI 服务端)
|
||||||
title: Boss直聘投递服务端
|
title: Boss 直聘投递服务(FastAPI 服务端)
|
||||||
scope:
|
scope:
|
||||||
- server/
|
- server/
|
||||||
source_files: []
|
source_files: []
|
||||||
children:
|
children:
|
||||||
- server/infrastructure
|
- server/infrastructure
|
||||||
depends_on: []
|
depends_on: []
|
||||||
related_to: []
|
related_to:
|
||||||
|
- path: client/shared_client_utils
|
||||||
server/infrastructure:
|
server/infrastructure:
|
||||||
dir_name: FastAPI 服务端基础设施(应用启动、配置、数据库、ORM、认证)
|
dir_name: FastAPI 服务端基础设施(应用启动、配置、数据库、ORM、认证)
|
||||||
title: FastAPI 服务端基础设施(应用启动、配置、数据库、ORM、认证)
|
title: FastAPI 服务端基础设施(应用启动、配置、数据库、ORM、认证)
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
+1
-1
@@ -7,7 +7,7 @@ REM 每次升级改 APP_VERSION,避免与正在运行的旧版本目录冲突
|
|||||||
REM 使用:把整个文件夹拷到目标机器(或压缩成 zip 发送),
|
REM 使用:把整个文件夹拷到目标机器(或压缩成 zip 发送),
|
||||||
REM 双击文件夹里的 Boss直聘AI投递-%APP_VERSION%.exe 运行。
|
REM 双击文件夹里的 Boss直聘AI投递-%APP_VERSION%.exe 运行。
|
||||||
REM ============================================================
|
REM ============================================================
|
||||||
set APP_VERSION=1.5
|
set APP_VERSION=1.18
|
||||||
|
|
||||||
echo [1/2] 安装打包依赖...
|
echo [1/2] 安装打包依赖...
|
||||||
pip install pyinstaller PySide6 --quiet
|
pip install pyinstaller PySide6 --quiet
|
||||||
|
|||||||
+1
-4
@@ -17,9 +17,6 @@ BROWSER_MODE=chrome
|
|||||||
ADSPOWER_API_URL=http://local.adspower.net:50325
|
ADSPOWER_API_URL=http://local.adspower.net:50325
|
||||||
ADSPOWER_USER_ID=
|
ADSPOWER_USER_ID=
|
||||||
|
|
||||||
# AI 大模型(OpenAI 兼容接口,代码已内置生产配置,仅在需要覆盖时填写)
|
# AI 打分经云端服务端代理,客户端无需配置模型密钥
|
||||||
#AI_BASE_URL=https://api.siliconflow.cn/v1
|
|
||||||
#AI_MODEL=deepseek-ai/DeepSeek-V4-Flash
|
|
||||||
#AI_API_KEY=
|
|
||||||
# 低于该分数的职位自动跳过
|
# 低于该分数的职位自动跳过
|
||||||
AI_MIN_SCORE=65
|
AI_MIN_SCORE=65
|
||||||
|
|||||||
+87
-72
@@ -1,100 +1,124 @@
|
|||||||
"""
|
"""
|
||||||
客户端 AI 大模型封装(OpenAI 兼容接口)
|
客户端 AI 评分封装(经云端服务端代理)
|
||||||
|
模型配置(OpenAI 兼容 base_url/api_key/model)与密钥全部由服务端持有,
|
||||||
|
客户端只负责:发起打分任务 → 轮询结果;不再直连任何大模型。
|
||||||
功能:
|
功能:
|
||||||
1. 职位匹配度评分
|
1. 职位匹配度评分(异步任务:开始打分 + 轮询结果)
|
||||||
2. 简历内容整理
|
2. 简历内容整理(服务端同步代理)
|
||||||
"""
|
"""
|
||||||
import json
|
import time
|
||||||
import os
|
import uuid
|
||||||
from openai import OpenAI
|
|
||||||
|
import requests
|
||||||
from loguru import logger
|
from loguru import logger
|
||||||
|
|
||||||
from .config import client_settings
|
from .server_api import ServerAPI
|
||||||
|
|
||||||
|
# 轮询间隔 / 等待总预算(与服务端 5 分钟悬空判定对齐)
|
||||||
|
POLL_INTERVAL_S = 3
|
||||||
|
POLL_BUDGET_S = 300
|
||||||
|
|
||||||
|
|
||||||
|
def gen_request_key() -> str:
|
||||||
|
"""幂等键:uuid1 = 本机 MAC + 时间戳,.hex 为 32 位十六进制
|
||||||
|
(与服务端 ai_score_task.request_key VARCHAR(32) 严格对齐)"""
|
||||||
|
return uuid.uuid1().hex
|
||||||
|
|
||||||
|
|
||||||
|
def _detail_of(e: requests.HTTPError) -> str:
|
||||||
|
"""从 HTTPError 中提取服务端 detail 文案"""
|
||||||
|
try:
|
||||||
|
return str(e.response.json().get("detail") or e)
|
||||||
|
except Exception:
|
||||||
|
return str(e)
|
||||||
|
|
||||||
|
|
||||||
class MatchResult:
|
class MatchResult:
|
||||||
def __init__(self, score: int, reason: str):
|
def __init__(self, score: int, reason: str, fatal: bool = False):
|
||||||
self.score = score
|
self.score = score
|
||||||
self.reason = reason
|
self.reason = reason
|
||||||
|
# fatal = 模型级失败(调用出错/超时/未配置):客户端必须跳过该岗位;
|
||||||
|
# 非 fatal(服务端不可达等网络问题):按约定降级默认放行
|
||||||
|
self.fatal = fatal
|
||||||
|
|
||||||
def is_worth_applying(self, threshold: int = 60) -> bool:
|
def is_worth_applying(self, threshold: int = 60) -> bool:
|
||||||
return self.score >= threshold
|
return self.score >= threshold
|
||||||
|
|
||||||
|
|
||||||
class AIClient:
|
class AIClient:
|
||||||
"""OpenAI 兼容大模型客户端"""
|
"""AI 评分客户端(服务端代理模式)"""
|
||||||
|
|
||||||
def __init__(self, api_key: str | None = None, base_url: str | None = None,
|
def __init__(self, server: ServerAPI):
|
||||||
model: str | None = None):
|
self.server = server
|
||||||
self.api_key = api_key or client_settings.AI_API_KEY or os.environ.get("AI_API_KEY", "")
|
|
||||||
self.base_url = base_url or client_settings.AI_BASE_URL
|
|
||||||
self.model = model or client_settings.AI_MODEL
|
|
||||||
self.client = OpenAI(api_key=self.api_key, base_url=self.base_url)
|
|
||||||
|
|
||||||
def available(self) -> bool:
|
def available(self) -> bool:
|
||||||
return bool(self.api_key)
|
"""可用条件:已登录云端账号(打分接口需 JWT 鉴权)。
|
||||||
|
模型是否配置由服务端判定,未配置时发起打分会返回明确错误。"""
|
||||||
|
return bool(self.server.token)
|
||||||
|
|
||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
# 职位匹配度评分
|
# 职位匹配度评分(异步任务 + 轮询)
|
||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
def score_job(self, jd_text: str, resume_content: str) -> MatchResult:
|
def score_job(self, job_ref: str, jd_text: str, resume_id: int | None,
|
||||||
"""根据 JD 与主简历内容评估匹配度"""
|
conditions: dict | None = None,
|
||||||
|
prompt: str | None = None) -> MatchResult:
|
||||||
|
"""发起打分并等待结果。
|
||||||
|
- 服务端明确失败(模型未配置/简历缺失/限额/模型报错/超时)→ fatal,调用方跳岗
|
||||||
|
- 网络层不可达 → 降级默认放行(保持既有容错约定)
|
||||||
|
"""
|
||||||
if not self.available():
|
if not self.available():
|
||||||
return MatchResult(50, "AI 未配置,默认放行")
|
return MatchResult(50, "AI 未接入(未登录系统账号),默认放行")
|
||||||
|
if not resume_id:
|
||||||
|
return MatchResult(50, "无主简历,跳过 AI 评分默认放行")
|
||||||
|
|
||||||
system_prompt = (
|
conds = dict(conditions or {})
|
||||||
"你是专业招聘顾问。根据职位描述(JD)和候选人简历,输出 JSON 评估结果,"
|
if prompt:
|
||||||
"不要输出 JSON 以外的内容。\n"
|
conds["prompt"] = prompt
|
||||||
'格式:{"score": <0-100整数>, "reason": "<一句话评价>"}\n'
|
request_key = gen_request_key()
|
||||||
"评分标准:80-100 高度匹配;60-79 基本匹配;40-59 部分匹配;0-39 不匹配。"
|
|
||||||
)
|
|
||||||
user_prompt = f"【职位描述】\n{jd_text}\n\n【候选人简历】\n{resume_content}"
|
|
||||||
|
|
||||||
|
# 1) 开始打分(幂等键保证网络重试不会重复调用大模型)
|
||||||
try:
|
try:
|
||||||
resp = self.client.chat.completions.create(
|
self.server.start_ai_score({
|
||||||
model=self.model,
|
"request_key": request_key,
|
||||||
messages=[
|
"resume_id": resume_id,
|
||||||
{"role": "system", "content": system_prompt},
|
"jd_text": jd_text,
|
||||||
{"role": "user", "content": user_prompt},
|
"job_ref": job_ref,
|
||||||
],
|
"conditions": conds,
|
||||||
temperature=0.2,
|
})
|
||||||
max_tokens=256,
|
except requests.HTTPError as e:
|
||||||
)
|
return MatchResult(-1, f"AI 打分不可用:{_detail_of(e)}", fatal=True)
|
||||||
raw = resp.choices[0].message.content.strip()
|
|
||||||
if raw.startswith("```"):
|
|
||||||
raw = raw.split("```")[1]
|
|
||||||
if raw.startswith("json"):
|
|
||||||
raw = raw[4:]
|
|
||||||
data = json.loads(raw)
|
|
||||||
return MatchResult(int(data.get("score", 50)), data.get("reason", ""))
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning(f"AI 评分失败,默认放行:{e}")
|
logger.warning(f"AI 打分发起失败(服务端不可达),默认放行:{e}")
|
||||||
return MatchResult(50, f"AI 异常:{e}")
|
return MatchResult(50, "AI 服务不可达,默认放行")
|
||||||
|
|
||||||
|
# 2) 轮询结果:成功返回分数;失败带原因(调用方跳岗);处理中继续等待
|
||||||
|
deadline = time.time() + POLL_BUDGET_S
|
||||||
|
while time.time() < deadline:
|
||||||
|
time.sleep(POLL_INTERVAL_S)
|
||||||
|
try:
|
||||||
|
r = self.server.get_ai_score_result(request_key)
|
||||||
|
except Exception as e:
|
||||||
|
logger.debug(f"AI 结果轮询异常,稍后重试:{e}")
|
||||||
|
continue
|
||||||
|
status = r.get("status")
|
||||||
|
if status == "success":
|
||||||
|
return MatchResult(int(r.get("score") or 0), r.get("reason") or "")
|
||||||
|
if status == "failed":
|
||||||
|
return MatchResult(-1, f"AI 打分失败:{r.get('reason') or '未知'}",
|
||||||
|
fatal=True)
|
||||||
|
# pending / running:等待下一次轮询
|
||||||
|
logger.warning(f"AI 打分等待超时({POLL_BUDGET_S}s),跳过该岗位:{job_ref}")
|
||||||
|
return MatchResult(-1, f"AI 打分超时({POLL_BUDGET_S // 60} 分钟)", fatal=True)
|
||||||
|
|
||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
# 简历内容整理
|
# 简历内容整理(服务端同步代理,低频调用)
|
||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
def clean_resume(self, raw_text: str) -> str:
|
def clean_resume(self, raw_text: str) -> str:
|
||||||
"""用 AI 将抓取的杂乱简历文本整理为清晰的结构化文本"""
|
"""用 AI 将抓取的杂乱简历文本整理为清晰的结构化文本"""
|
||||||
if not self.available():
|
if not self.available():
|
||||||
return raw_text
|
return raw_text
|
||||||
|
|
||||||
system_prompt = (
|
|
||||||
"你是简历整理助手。将下面抓取的杂乱简历文本整理为清晰、结构化的纯文本简历,"
|
|
||||||
"保留所有关键信息(姓名可省略,联系方式可保留),去除广告和无关内容。"
|
|
||||||
"直接输出整理后的文本,不要加任何解释。"
|
|
||||||
)
|
|
||||||
try:
|
try:
|
||||||
resp = self.client.chat.completions.create(
|
return self.server.clean_resume_via_server(raw_text)
|
||||||
model=self.model,
|
|
||||||
messages=[
|
|
||||||
{"role": "system", "content": system_prompt},
|
|
||||||
{"role": "user", "content": raw_text},
|
|
||||||
],
|
|
||||||
temperature=0.3,
|
|
||||||
max_tokens=2048,
|
|
||||||
)
|
|
||||||
return resp.choices[0].message.content.strip()
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning(f"AI 整理简历失败,返回原文:{e}")
|
logger.warning(f"AI 整理简历失败,返回原文:{e}")
|
||||||
return raw_text
|
return raw_text
|
||||||
@@ -103,13 +127,4 @@ class AIClient:
|
|||||||
# 连通测试
|
# 连通测试
|
||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
def ping(self) -> bool:
|
def ping(self) -> bool:
|
||||||
try:
|
return self.server.ping()
|
||||||
resp = self.client.chat.completions.create(
|
|
||||||
model=self.model,
|
|
||||||
messages=[{"role": "user", "content": "回复1"}],
|
|
||||||
max_tokens=5,
|
|
||||||
)
|
|
||||||
return True
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"AI 接口连通失败:{e}")
|
|
||||||
return False
|
|
||||||
|
|||||||
@@ -0,0 +1,478 @@
|
|||||||
|
"""
|
||||||
|
Boss 激活自动化模块(单机功能,低痕迹 CDP 版)
|
||||||
|
目标:对"已沟通但对方未读我消息"的 Boss 补发一条自定义消息,激活会话。
|
||||||
|
真实页面结构(消息页 /web/geek/chat,已实测):
|
||||||
|
- 左侧列表:.user-list-content > ul > li,内容块 .friend-content(可信点击目标),
|
||||||
|
姓名 .name-text,缩略消息 .gray.last-msg 内含 i.message-status(class 取值:
|
||||||
|
status-read=[已读] / status-delivery=[送达])与预览文本 .last-msg-text;
|
||||||
|
- 点击联系人后右侧 .chat-conversation 渲染 .message-content,
|
||||||
|
消息条目 li.message-item(我发出的带 .item-myself),正文 .text-content;
|
||||||
|
- 输入:div#chat-input[contenteditable=true](.message-controls 内,非 textarea);
|
||||||
|
- 发送:button.btn-send。
|
||||||
|
合成 el.click() 对列表项无效,必须 Input.dispatchMouseEvent 可信点击。
|
||||||
|
"""
|
||||||
|
import difflib
|
||||||
|
import json
|
||||||
|
import random
|
||||||
|
import time
|
||||||
|
import threading
|
||||||
|
|
||||||
|
from loguru import logger
|
||||||
|
|
||||||
|
from .cdp_lite import LiteCDP, CDPSession
|
||||||
|
from .manager import BrowserManager
|
||||||
|
|
||||||
|
# 消息页
|
||||||
|
CHAT_PAGE = "https://www.zhipin.com/web/geek/chat"
|
||||||
|
|
||||||
|
# 我发出消息的已读状态(DOM class → 展示文案)
|
||||||
|
STATUS_MAP = {
|
||||||
|
"status-read": "已读",
|
||||||
|
"status-delivery": "送达",
|
||||||
|
}
|
||||||
|
# 视为"对方未读"的状态([送达]=对方还没看;页面若出现字面[未读]同样命中)
|
||||||
|
UNREAD_STATUS = {"送达", "未读"}
|
||||||
|
# 视为"已读"的状态
|
||||||
|
READ_STATUS = {"已读"}
|
||||||
|
# 消息状态过滤选项:值 → 允许通过的状态集合(None=不限)
|
||||||
|
STATUS_FILTERS = {
|
||||||
|
"unread": UNREAD_STATUS,
|
||||||
|
"read": READ_STATUS,
|
||||||
|
"all": None,
|
||||||
|
}
|
||||||
|
|
||||||
|
# 读取左侧联系人列表(实测 DOM)
|
||||||
|
_LIST_JS = """(() => [...new Set([...document.querySelectorAll('.friend-content-warp')]
|
||||||
|
.map(w => w.closest('li')).filter(Boolean))].map(li => {
|
||||||
|
const fc = li.querySelector('.friend-content');
|
||||||
|
const st = li.querySelector('.message-status');
|
||||||
|
const lm = li.querySelector('.last-msg-text');
|
||||||
|
const nm = li.querySelector('.name-text');
|
||||||
|
const co = li.querySelector('.title-box .name-box');
|
||||||
|
const r = fc ? fc.getBoundingClientRect() : null;
|
||||||
|
return {
|
||||||
|
name: nm ? nm.innerText.trim() : '',
|
||||||
|
title: co ? co.innerText.replace(/\\s+/g, ' ').trim().slice(0, 40) : '',
|
||||||
|
status: st ? String(st.className) : '',
|
||||||
|
statusText: st ? st.innerText.trim() : '',
|
||||||
|
preview: lm ? lm.innerText.trim() : '',
|
||||||
|
x: r ? Math.round(r.x + r.width / 2) : 0,
|
||||||
|
y: r ? Math.round(r.y + r.height / 2) : 0,
|
||||||
|
visible: !!r && r.height > 0,
|
||||||
|
};
|
||||||
|
}))()"""
|
||||||
|
|
||||||
|
# 右侧会话:最后一条"我发出的"消息正文(实测:.message-item.item-myself)
|
||||||
|
_LAST_MINE_JS = """(() => {
|
||||||
|
const items = [...document.querySelectorAll(
|
||||||
|
'.chat-conversation .message-item.item-myself')];
|
||||||
|
if (!items.length) return '';
|
||||||
|
const el = items[items.length - 1].querySelector('.text-content');
|
||||||
|
return el ? el.innerText.trim() : '';
|
||||||
|
})()"""
|
||||||
|
|
||||||
|
# 发送按钮坐标(实测:button.btn-send,每次实时计算不缓存)
|
||||||
|
_SEND_BTN_JS = """(() => {
|
||||||
|
const b = document.querySelector('button.btn-send');
|
||||||
|
if (!b || b.offsetHeight <= 0) return null;
|
||||||
|
const r = b.getBoundingClientRect();
|
||||||
|
return JSON.stringify({x: r.x + r.width / 2, y: r.y + r.height / 2,
|
||||||
|
disabled: !!b.disabled});
|
||||||
|
})()"""
|
||||||
|
|
||||||
|
# 输入框定位(实测:聊天页真实输入框是 contenteditable 的 div#chat-input,
|
||||||
|
# 位于 .message-controls > .chat-editor > .editor-container;
|
||||||
|
# 页面上另有 0×0 的 textarea.input 属无关隐藏元素,不作首选;坐标每次实时计算)
|
||||||
|
_INPUT_BOX_JS = """(() => {
|
||||||
|
const ta = document.querySelector('#chat-input')
|
||||||
|
|| document.querySelector('.chat-conversation [contenteditable="true"]')
|
||||||
|
|| document.querySelector('.editor-container [contenteditable="true"]')
|
||||||
|
|| [...document.querySelectorAll('[contenteditable="true"]')]
|
||||||
|
.find(e => e.offsetHeight > 0)
|
||||||
|
|| null;
|
||||||
|
if (!ta) return null;
|
||||||
|
const r = ta.getBoundingClientRect();
|
||||||
|
return JSON.stringify({x: r.x + r.width / 2, y: r.y + r.height / 2,
|
||||||
|
visible: r.width > 0 && r.height > 0,
|
||||||
|
kind: ta.tagName.toLowerCase()});
|
||||||
|
})()"""
|
||||||
|
|
||||||
|
# 输入框不可见时的 JS 聚焦兜底(可信 insertText 只认焦点,不认尺寸)
|
||||||
|
_FOCUS_INPUT_JS = """(() => {
|
||||||
|
const ta = document.querySelector('#chat-input')
|
||||||
|
|| document.querySelector('.chat-conversation [contenteditable="true"]')
|
||||||
|
|| document.querySelector('.editor-container [contenteditable="true"]')
|
||||||
|
|| [...document.querySelectorAll('[contenteditable="true"]')]
|
||||||
|
.find(e => e.offsetHeight > 0)
|
||||||
|
|| null;
|
||||||
|
if (!ta) return false;
|
||||||
|
ta.focus();
|
||||||
|
return document.activeElement === ta;
|
||||||
|
})()"""
|
||||||
|
|
||||||
|
# 左侧列表滚动(加载更多联系人)
|
||||||
|
# 步长动态计算:取滚动容器自身可视高度的 80%(不同分辨率/缩放下均不会跳过头)
|
||||||
|
_LIST_SCROLL_JS = """(() => {
|
||||||
|
const el = document.querySelector('.user-list-content')
|
||||||
|
|| document.querySelector('.user-list')
|
||||||
|
|| document.querySelector('.chat-content');
|
||||||
|
if (!el) return -1;
|
||||||
|
el.scrollTop += Math.max(240, Math.round(el.clientHeight * 0.8));
|
||||||
|
return el.scrollTop;
|
||||||
|
})()"""
|
||||||
|
|
||||||
|
# 按姓名在当前 DOM 重取联系人最新可点坐标(发送后列表会重排,快照坐标必失效;
|
||||||
|
# inView=false 表示元素在可视区外,可信点击会落空,必须先滚入视口;
|
||||||
|
# 可视范围动态取自滚动容器自身的 rect(顶部自动避开搜索栏/标签头,底部取容器高度),
|
||||||
|
# 不依赖窗口分辨率,任何屏幕/缩放比下均成立;
|
||||||
|
# 传入姓名由 Python 侧 json.dumps 拼接)
|
||||||
|
_LOCATE_ITEM_JS = """(name) => {
|
||||||
|
const lis = [...new Set([...document.querySelectorAll('.friend-content-warp')]
|
||||||
|
.map(w => w.closest('li')).filter(Boolean))];
|
||||||
|
const scroller = document.querySelector('.user-list-content')
|
||||||
|
|| document.querySelector('.user-list');
|
||||||
|
const sr = scroller ? scroller.getBoundingClientRect() : null;
|
||||||
|
const top = sr ? Math.max(0, sr.top) : 0;
|
||||||
|
const bottom = sr ? Math.min(window.innerHeight, sr.bottom) : window.innerHeight;
|
||||||
|
for (const li of lis) {
|
||||||
|
const nm = li.querySelector('.name-text');
|
||||||
|
if (!nm || nm.innerText.trim() !== name) continue;
|
||||||
|
const fc = li.querySelector('.friend-content');
|
||||||
|
const r = fc ? fc.getBoundingClientRect() : null;
|
||||||
|
if (!r || r.height <= 0) continue;
|
||||||
|
return JSON.stringify({x: r.x + r.width / 2, y: r.y + r.height / 2,
|
||||||
|
inView: r.y >= top && r.y + r.height <= bottom});
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}"""
|
||||||
|
|
||||||
|
# 把指定联系人滚入可视区(列表一次性渲染全部条目,视口外坐标点击必落空)
|
||||||
|
_BRING_INTO_VIEW_JS = """(name) => {
|
||||||
|
const lis = [...new Set([...document.querySelectorAll('.friend-content-warp')]
|
||||||
|
.map(w => w.closest('li')).filter(Boolean))];
|
||||||
|
for (const li of lis) {
|
||||||
|
const nm = li.querySelector('.name-text');
|
||||||
|
if (!nm || nm.innerText.trim() !== name) continue;
|
||||||
|
li.scrollIntoView({block: 'center'});
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}"""
|
||||||
|
|
||||||
|
# 当前会话区头部姓名(点击后校验是否切到目标会话,防发错人)
|
||||||
|
_CONV_NAME_JS = """(() => {
|
||||||
|
const el = document.querySelector('.chat-conversation .top-info-content .name-text')
|
||||||
|
|| document.querySelector('.chat-conversation .name-text');
|
||||||
|
return el ? el.innerText.trim() : '';
|
||||||
|
})()"""
|
||||||
|
|
||||||
|
|
||||||
|
def similarity(a: str, b: str) -> float:
|
||||||
|
"""两段文本的相似度(0~1,difflib 序列比对)"""
|
||||||
|
a, b = (a or "").strip(), (b or "").strip()
|
||||||
|
if not a or not b:
|
||||||
|
return 0.0
|
||||||
|
return difflib.SequenceMatcher(None, a, b).ratio()
|
||||||
|
|
||||||
|
|
||||||
|
class Activator:
|
||||||
|
"""Boss 激活执行器(可启停,单机功能不依赖云端)"""
|
||||||
|
|
||||||
|
def __init__(self, manager: BrowserManager):
|
||||||
|
self.manager = manager
|
||||||
|
self.cdp = LiteCDP()
|
||||||
|
|
||||||
|
self._stop_event = threading.Event()
|
||||||
|
self._thread: threading.Thread | None = None
|
||||||
|
self.is_running = False
|
||||||
|
|
||||||
|
self.stats = {"scanned": 0, "sent": 0, "skipped": 0, "current": ""}
|
||||||
|
|
||||||
|
self._tab: dict | None = None
|
||||||
|
self._sess: CDPSession | None = None
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# 启停控制
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def start(self, match_text: str, threshold: float, reply_message: str,
|
||||||
|
max_count: int = 20, dry_run: bool = False,
|
||||||
|
status_filter: str = "unread") -> None:
|
||||||
|
if self.is_running:
|
||||||
|
logger.warning("已有激活任务在运行")
|
||||||
|
return
|
||||||
|
self.match_text = match_text.strip()
|
||||||
|
self.threshold = max(0.0, min(1.0, threshold))
|
||||||
|
self.reply_message = reply_message.strip()
|
||||||
|
self.max_count = max_count
|
||||||
|
self.dry_run = dry_run
|
||||||
|
# 消息状态过滤(非法取值回退默认"仅未读",与原行为一致)
|
||||||
|
self.status_filter = status_filter if status_filter in STATUS_FILTERS else "unread"
|
||||||
|
|
||||||
|
self._stop_event.clear()
|
||||||
|
self.is_running = True
|
||||||
|
self.stats = {"scanned": 0, "sent": 0, "skipped": 0, "current": "初始化..."}
|
||||||
|
self._thread = threading.Thread(target=self._run, daemon=True)
|
||||||
|
self._thread.start()
|
||||||
|
logger.success(f"Boss 激活任务已启动(状态过滤={self.status_filter},"
|
||||||
|
f"阈值 {self.threshold:.0%},"
|
||||||
|
f"上限 {self.max_count},试跑={self.dry_run})")
|
||||||
|
|
||||||
|
def stop(self) -> None:
|
||||||
|
logger.info("收到停止激活请求...")
|
||||||
|
self._stop_event.set()
|
||||||
|
|
||||||
|
def _should_stop(self) -> bool:
|
||||||
|
return self._stop_event.is_set()
|
||||||
|
|
||||||
|
def _sleep(self, min_s: float, max_s: float) -> None:
|
||||||
|
total = random.uniform(min_s, max_s)
|
||||||
|
elapsed = 0.0
|
||||||
|
while elapsed < total and not self._should_stop():
|
||||||
|
time.sleep(0.5)
|
||||||
|
elapsed += 0.5
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# 主循环
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def _run(self):
|
||||||
|
processed: set[str] = set()
|
||||||
|
# 本次任务已发送过的联系人姓名(发送后列表重排、预览变化,
|
||||||
|
# 同一人会被当成“新联系人”重新出现,按姓名排除防重复发送)
|
||||||
|
self._sent_names: set[str] = set()
|
||||||
|
try:
|
||||||
|
self.manager.ensure_browser_started()
|
||||||
|
self._tab = self.cdp.open_tab(CHAT_PAGE)
|
||||||
|
time.sleep(8) # 等 SPA 挂载
|
||||||
|
self._sess = CDPSession(self._tab["webSocketDebuggerUrl"])
|
||||||
|
|
||||||
|
no_new = 0
|
||||||
|
while not self._should_stop():
|
||||||
|
if self.max_count and self.stats["sent"] >= self.max_count:
|
||||||
|
logger.info(f"已达发送上限({self.max_count}),任务结束")
|
||||||
|
break
|
||||||
|
items = self._read_list()
|
||||||
|
candidates = [it for it in items
|
||||||
|
if self._item_key(it) not in processed
|
||||||
|
and (it.get("name") or "") not in self._sent_names]
|
||||||
|
logger.debug(f"联系人列表读取:共 {len(items)} 条,待处理 {len(candidates)} 条")
|
||||||
|
if not candidates:
|
||||||
|
no_new += 1
|
||||||
|
if no_new >= 3:
|
||||||
|
logger.info("列表已扫完,没有新的联系人")
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
no_new = 0
|
||||||
|
for it in candidates:
|
||||||
|
if self._should_stop():
|
||||||
|
break
|
||||||
|
if self.max_count and self.stats["sent"] >= self.max_count:
|
||||||
|
break
|
||||||
|
processed.add(self._item_key(it))
|
||||||
|
self._handle_item(it)
|
||||||
|
# 下拉加载更多联系人
|
||||||
|
self._sess.eval_js(_LIST_SCROLL_JS)
|
||||||
|
self._sleep(1.5, 3)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"激活任务异常:{e}")
|
||||||
|
finally:
|
||||||
|
if self._sess:
|
||||||
|
self._sess.close()
|
||||||
|
if self._tab:
|
||||||
|
self.cdp.close_tab(self._tab["id"])
|
||||||
|
self.is_running = False
|
||||||
|
self.stats["current"] = "已结束"
|
||||||
|
logger.info(f"激活任务结束。扫描 {self.stats['scanned']} 个,"
|
||||||
|
f"发送 {self.stats['sent']} 条,跳过 {self.stats['skipped']} 个")
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# 列表读取与状态解析
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def _read_list(self) -> list[dict]:
|
||||||
|
raw = self._sess.eval_js(_LIST_JS)
|
||||||
|
if isinstance(raw, str):
|
||||||
|
try:
|
||||||
|
raw = json.loads(raw or "[]")
|
||||||
|
except Exception:
|
||||||
|
raw = []
|
||||||
|
return [it for it in (raw or []) if it.get("visible")]
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _item_status(it: dict) -> str:
|
||||||
|
"""缩略消息状态文案:优先 class 映射,其次元素文字,兼容字面[未读]/[已读]"""
|
||||||
|
cls = it.get("status") or ""
|
||||||
|
for k, v in STATUS_MAP.items():
|
||||||
|
if k in cls:
|
||||||
|
return v
|
||||||
|
text = (it.get("statusText") or "").strip("[] ")
|
||||||
|
return text
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _item_key(it: dict) -> str:
|
||||||
|
"""联系人去重键:姓名 + 缩略预览"""
|
||||||
|
return f"{it.get('name', '')}|{it.get('preview', '')[:20]}"
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# 实时定位与会话校验(防点错人/读旧会话)
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def _locate_fresh(self, name: str) -> dict | None:
|
||||||
|
"""按姓名在当前 DOM 重取最新可点坐标与可视状态。
|
||||||
|
列表在发送后会重排,快照坐标不可信,每次点击前必须重取。"""
|
||||||
|
expr = f"({_LOCATE_ITEM_JS})({json.dumps(name)})"
|
||||||
|
raw = self._sess.eval_js(expr)
|
||||||
|
if not raw:
|
||||||
|
return None
|
||||||
|
return json.loads(raw)
|
||||||
|
|
||||||
|
def _bring_into_view(self, name: str) -> bool:
|
||||||
|
"""把联系人滚入可视区(列表全量渲染,视口外点击必落空)"""
|
||||||
|
expr = f"({_BRING_INTO_VIEW_JS})({json.dumps(name)})"
|
||||||
|
return self._sess.eval_js(expr) is True
|
||||||
|
|
||||||
|
def _conv_name(self) -> str:
|
||||||
|
"""当前会话区头部姓名"""
|
||||||
|
return (self._sess.eval_js(_CONV_NAME_JS) or "").strip()
|
||||||
|
|
||||||
|
def _enter_conversation(self, name: str) -> bool:
|
||||||
|
"""点击进入目标会话并校验切换成功(最多 3 次)。
|
||||||
|
视口外的联系人先滚入可视区再点击;
|
||||||
|
校验不通过绝不允许后续读消息/发送,从根源上防发错人。"""
|
||||||
|
for attempt in range(3):
|
||||||
|
loc = self._locate_fresh(name)
|
||||||
|
if not loc:
|
||||||
|
logger.debug(f"当前列表找不到联系人(第{attempt + 1}次):{name}")
|
||||||
|
return False
|
||||||
|
if not loc.get("inView"):
|
||||||
|
# 视口外:滚入可视区后重取坐标(滚动会改变所有条目坐标)
|
||||||
|
self._bring_into_view(name)
|
||||||
|
time.sleep(random.uniform(0.6, 1.0))
|
||||||
|
loc = self._locate_fresh(name) or loc
|
||||||
|
self._sess.human_click(loc["x"], loc["y"])
|
||||||
|
time.sleep(random.uniform(1.8, 2.8))
|
||||||
|
cur = self._conv_name()
|
||||||
|
if cur == name:
|
||||||
|
return True
|
||||||
|
logger.warning(f"会话未切到目标(第{attempt + 1}次,当前={cur or '空'}):{name}")
|
||||||
|
time.sleep(random.uniform(0.8, 1.5))
|
||||||
|
return False
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# 单联系人处理:未读过滤 → 进入会话 → 最后一条消息 → 相似度 → 发送
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def _handle_item(self, item: dict) -> None:
|
||||||
|
name = item.get("name") or "未知联系人"
|
||||||
|
status = self._item_status(item)
|
||||||
|
self.stats["scanned"] += 1
|
||||||
|
self.stats["current"] = f"查看:{name}({status or '无状态'})"
|
||||||
|
|
||||||
|
# 条件1:最后一条消息状态须符合所选过滤(仅未读/仅已读/不限)
|
||||||
|
allowed = STATUS_FILTERS[self.status_filter]
|
||||||
|
if allowed is not None and status not in allowed:
|
||||||
|
self.stats["skipped"] += 1
|
||||||
|
logger.debug(f"状态[{status or '无'}]不符合所选过滤"
|
||||||
|
f"({self.status_filter}),跳过:{name}")
|
||||||
|
return
|
||||||
|
|
||||||
|
# 条件2:点击进入会话(实时重取坐标 + 校验会话切换,防点错人/读旧会话)
|
||||||
|
if not self._enter_conversation(name):
|
||||||
|
self.stats["skipped"] += 1
|
||||||
|
logger.warning(f"无法进入目标会话,跳过:{name}")
|
||||||
|
return
|
||||||
|
last_msg = (self._sess.eval_js(_LAST_MINE_JS) or "").strip()
|
||||||
|
if not last_msg:
|
||||||
|
# 会话里没读到我发出的消息时退回缩略预览
|
||||||
|
logger.debug(f"会话内未读到我发出的消息,退回缩略预览:{name}")
|
||||||
|
last_msg = (item.get("preview") or "").strip()
|
||||||
|
if not last_msg:
|
||||||
|
self.stats["skipped"] += 1
|
||||||
|
logger.warning(f"无法读取最后一条消息,跳过:{name}")
|
||||||
|
return
|
||||||
|
|
||||||
|
# 条件3:与用户输入文本相似度达标
|
||||||
|
ratio = similarity(last_msg, self.match_text)
|
||||||
|
logger.info(f"匹配 {ratio:.0%}(阈值 {self.threshold:.0%}):"
|
||||||
|
f"{name} | {last_msg[:50]}")
|
||||||
|
if ratio < self.threshold:
|
||||||
|
self.stats["skipped"] += 1
|
||||||
|
return
|
||||||
|
|
||||||
|
if self.dry_run:
|
||||||
|
self.stats["sent"] += 1
|
||||||
|
logger.success(f"[试跑] 命中将发送:{name}")
|
||||||
|
self._sleep(1, 2)
|
||||||
|
return
|
||||||
|
|
||||||
|
if self._send_reply(name):
|
||||||
|
self.stats["sent"] += 1
|
||||||
|
self._sent_names.add(name)
|
||||||
|
self._sleep(5, 10)
|
||||||
|
|
||||||
|
def _send_reply(self, name: str) -> bool:
|
||||||
|
"""定位输入框聚焦 → 可信输入 → 点发送按钮(坐标每次实时计算,不缓存)"""
|
||||||
|
self.stats["current"] = f"发送激活消息:{name}"
|
||||||
|
|
||||||
|
# 输入框(会话打开后异步渲染,实测可能延迟 10s+,需充分等待)
|
||||||
|
input_info = None
|
||||||
|
for _ in range(15):
|
||||||
|
if self._should_stop():
|
||||||
|
return False
|
||||||
|
input_info = self._sess.eval_js(_INPUT_BOX_JS)
|
||||||
|
if input_info:
|
||||||
|
break
|
||||||
|
time.sleep(1)
|
||||||
|
if not input_info:
|
||||||
|
logger.warning(f"未找到可用输入框,跳过:{name}")
|
||||||
|
self.stats["skipped"] += 1
|
||||||
|
return False
|
||||||
|
|
||||||
|
p = json.loads(input_info)
|
||||||
|
# 发送前二次确认:输入框可能等了十几秒才出现,期间会话若已变化,
|
||||||
|
# 此处不拦就会把消息发到错误的人(防发错人最后一道闸)
|
||||||
|
cur = self._conv_name()
|
||||||
|
if cur and cur != name:
|
||||||
|
logger.warning(f"发送前发现会话已变化(当前={cur}),放弃发送:{name}")
|
||||||
|
self.stats["skipped"] += 1
|
||||||
|
return False
|
||||||
|
if p.get("visible"):
|
||||||
|
# 可见:可信点击实时计算的坐标中心聚焦
|
||||||
|
self._sess.human_click(p["x"], p["y"])
|
||||||
|
time.sleep(random.uniform(0.4, 0.8))
|
||||||
|
else:
|
||||||
|
# 0×0 隐藏输入框(新版页面实测存在):JS 聚焦,
|
||||||
|
# 后续 Input.insertText 仍为浏览器级可信输入
|
||||||
|
focused = self._sess.eval_js(_FOCUS_INPUT_JS)
|
||||||
|
if not focused:
|
||||||
|
logger.warning(f"输入框无法聚焦,跳过:{name}")
|
||||||
|
self.stats["skipped"] += 1
|
||||||
|
return False
|
||||||
|
time.sleep(random.uniform(0.3, 0.6))
|
||||||
|
|
||||||
|
# 可信文本输入(浏览器级 input 事件,与真人键入无异)
|
||||||
|
self._sess.call("Input.insertText", {"text": self.reply_message})
|
||||||
|
time.sleep(random.uniform(0.6, 1.2))
|
||||||
|
|
||||||
|
# 点击发送按钮(输入后 disabled 会解除)
|
||||||
|
sent = False
|
||||||
|
for _ in range(3):
|
||||||
|
btn = self._sess.eval_js(_SEND_BTN_JS)
|
||||||
|
if btn:
|
||||||
|
q = json.loads(btn)
|
||||||
|
if not q.get("disabled"):
|
||||||
|
self._sess.human_click(q["x"], q["y"])
|
||||||
|
sent = True
|
||||||
|
break
|
||||||
|
time.sleep(1)
|
||||||
|
if not sent:
|
||||||
|
# 兜底:可信 Enter 键提交
|
||||||
|
logger.debug(f"发送按钮不可用,改用 Enter 提交:{name}")
|
||||||
|
self._press_enter()
|
||||||
|
time.sleep(1.5)
|
||||||
|
logger.success(f"[{self.stats['sent'] + 1}] 已发送激活消息:{name}")
|
||||||
|
return True
|
||||||
|
|
||||||
|
def _press_enter(self) -> None:
|
||||||
|
"""可信 Enter 键(提交消息兜底)"""
|
||||||
|
for evt_type in ("rawKeyDown", "keyUp"):
|
||||||
|
self._sess.call("Input.dispatchKeyEvent", {
|
||||||
|
"type": evt_type, "key": "Enter", "code": "Enter",
|
||||||
|
"windowsVirtualKeyCode": 13, "nativeVirtualKeyCode": 13})
|
||||||
|
time.sleep(0.05)
|
||||||
+30
-26
@@ -28,22 +28,6 @@ from ..server_api import ServerAPI
|
|||||||
# 职位列表页(注意是 jobs 复数)
|
# 职位列表页(注意是 jobs 复数)
|
||||||
JOBS_PAGE = "https://www.zhipin.com/web/geek/jobs"
|
JOBS_PAGE = "https://www.zhipin.com/web/geek/jobs"
|
||||||
|
|
||||||
# 常见城市编码 → 名称(用于在期望条件栏匹配目标城市)
|
|
||||||
CITY_NAMES = {
|
|
||||||
"101010100": "北京", "101020100": "上海", "101280100": "广州",
|
|
||||||
"101280600": "深圳", "101190100": "杭州", "101030100": "天津",
|
|
||||||
"101200100": "武汉", "101110100": "西安", "101270100": "成都",
|
|
||||||
"101040100": "重庆", "101190400": "苏州", "101200200": "南京",
|
|
||||||
"101210100": "合肥", "101180100": "郑州", "101230100": "福州",
|
|
||||||
"101240100": "南昌", "101250100": "济南", "101260100": "贵阳",
|
|
||||||
"101290100": "昆明", "101300100": "兰州", "101050100": "哈尔滨",
|
|
||||||
"101060100": "长春", "101070100": "沈阳", "101080100": "呼和浩特",
|
|
||||||
"101090100": "石家庄", "101100100": "太原", "101120100": "青岛",
|
|
||||||
"101190500": "宁波", "101280300": "佛山", "101280200": "珠海",
|
|
||||||
"101120200": "大连", "101210200": "厦门", "101180200": "开封",
|
|
||||||
"101200300": "无锡", "101190200": "温州", "101270200": "绵阳",
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class JobCard:
|
class JobCard:
|
||||||
@@ -174,7 +158,9 @@ class Applicant:
|
|||||||
self.is_running = False
|
self.is_running = False
|
||||||
|
|
||||||
self.session_id: int | None = None
|
self.session_id: int | None = None
|
||||||
self.primary_resume_content: str = ""
|
self.primary_resume_id: int | None = None
|
||||||
|
# 本次投递所用条件快照(随每次打分请求上送服务端)
|
||||||
|
self._score_conditions: dict = {}
|
||||||
self.stats = {"applied": 0, "skipped": 0, "current": ""}
|
self.stats = {"applied": 0, "skipped": 0, "current": ""}
|
||||||
|
|
||||||
# 列表页会话(整个任务期间保持一个标签页)
|
# 列表页会话(整个任务期间保持一个标签页)
|
||||||
@@ -189,23 +175,24 @@ class Applicant:
|
|||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
# 启停控制
|
# 启停控制
|
||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
def start(self, keywords: list[str], city_code: str,
|
def start(self, keywords: list[str], city: str,
|
||||||
salary_min: int | None, salary_max: int | None,
|
salary_min: int | None, salary_max: int | None,
|
||||||
min_score: int, delay_range: tuple[int, int],
|
min_score: int, delay_range: tuple[int, int],
|
||||||
boss_online_only: bool = False, daily_limit: int = 0,
|
boss_online_only: bool = False, daily_limit: int = 0,
|
||||||
allow_headhunter: bool = False) -> None:
|
allow_headhunter: bool = False, prompt: str | None = None) -> None:
|
||||||
if self.is_running:
|
if self.is_running:
|
||||||
logger.warning("已有投递任务在运行")
|
logger.warning("已有投递任务在运行")
|
||||||
return
|
return
|
||||||
|
|
||||||
session = self.server.start_session(
|
session = self.server.start_session(
|
||||||
keywords=",".join(keywords), city_code=city_code,
|
keywords=",".join(keywords), city=city,
|
||||||
salary_min=salary_min, salary_max=salary_max,
|
salary_min=salary_min, salary_max=salary_max,
|
||||||
|
prompt=prompt,
|
||||||
)
|
)
|
||||||
self.session_id = session["id"]
|
self.session_id = session["id"]
|
||||||
|
|
||||||
primary = self.server.get_primary_resume()
|
primary = self.server.get_primary_resume()
|
||||||
self.primary_resume_content = primary["content"] if primary else ""
|
self.primary_resume_id = primary["id"] if primary else None
|
||||||
|
|
||||||
self._stop_event.clear()
|
self._stop_event.clear()
|
||||||
self.is_running = True
|
self.is_running = True
|
||||||
@@ -213,11 +200,12 @@ class Applicant:
|
|||||||
self.boss_online_only = boss_online_only
|
self.boss_online_only = boss_online_only
|
||||||
self.daily_limit = daily_limit
|
self.daily_limit = daily_limit
|
||||||
self.allow_headhunter = allow_headhunter
|
self.allow_headhunter = allow_headhunter
|
||||||
|
self.prompt = prompt
|
||||||
self._daily_base = 0
|
self._daily_base = 0
|
||||||
|
|
||||||
self._thread = threading.Thread(
|
self._thread = threading.Thread(
|
||||||
target=self._run,
|
target=self._run,
|
||||||
args=(keywords, city_code, salary_min, salary_max,
|
args=(keywords, city, salary_min, salary_max,
|
||||||
min_score, delay_range),
|
min_score, delay_range),
|
||||||
daemon=True,
|
daemon=True,
|
||||||
)
|
)
|
||||||
@@ -252,9 +240,16 @@ class Applicant:
|
|||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
# 主循环
|
# 主循环
|
||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
def _run(self, keywords, city_code, salary_min, salary_max,
|
def _run(self, keywords, city, salary_min, salary_max,
|
||||||
min_score, delay_range):
|
min_score, delay_range):
|
||||||
try:
|
try:
|
||||||
|
# 投递条件快照:随每次 AI 打分请求上送服务端(简历内容由服务端按 id 自取)
|
||||||
|
self._score_conditions = {
|
||||||
|
"keywords": ",".join(keywords),
|
||||||
|
"city": city,
|
||||||
|
"salary_min": salary_min,
|
||||||
|
"salary_max": salary_max,
|
||||||
|
}
|
||||||
self.manager.ensure_browser_started()
|
self.manager.ensure_browser_started()
|
||||||
# 整个任务只开一个列表标签页,模拟真人持续浏览
|
# 整个任务只开一个列表标签页,模拟真人持续浏览
|
||||||
self._tab = self.cdp.open_tab(JOBS_PAGE)
|
self._tab = self.cdp.open_tab(JOBS_PAGE)
|
||||||
@@ -283,7 +278,7 @@ class Applicant:
|
|||||||
logger.warning(f"获取公司黑名单失败,黑名单过滤跳过:{e}")
|
logger.warning(f"获取公司黑名单失败,黑名单过滤跳过:{e}")
|
||||||
self._blacklist = set()
|
self._blacklist = set()
|
||||||
|
|
||||||
city_name = CITY_NAMES.get(str(city_code), "")
|
city_name = str(city or "").strip()
|
||||||
for keyword in keywords:
|
for keyword in keywords:
|
||||||
if self._should_stop():
|
if self._should_stop():
|
||||||
break
|
break
|
||||||
@@ -477,8 +472,17 @@ class Applicant:
|
|||||||
card.jd_text = self._fetch_jd(card)
|
card.jd_text = self._fetch_jd(card)
|
||||||
|
|
||||||
ai_score, ai_reason = -1, ""
|
ai_score, ai_reason = -1, ""
|
||||||
if self.ai and self.ai.available() and self.primary_resume_content:
|
if self.ai and self.ai.available() and self.primary_resume_id:
|
||||||
result = self.ai.score_job(card.jd_text, self.primary_resume_content)
|
result = self.ai.score_job(card.job_id, card.jd_text,
|
||||||
|
self.primary_resume_id,
|
||||||
|
conditions=self._score_conditions,
|
||||||
|
prompt=self.prompt)
|
||||||
|
if result.fatal:
|
||||||
|
# 模型级失败(报错/超时/未配置):跳过该岗位,避免盲投
|
||||||
|
logger.warning(f"AI 打分失败,跳过岗位:{card.company} - {card.title}"
|
||||||
|
f" | {result.reason}")
|
||||||
|
self._report_skip(card, result.reason[:255])
|
||||||
|
return 0
|
||||||
ai_score, ai_reason = result.score, result.reason
|
ai_score, ai_reason = result.score, result.reason
|
||||||
logger.info(f"AI 评分 {ai_score}(及格线 {min_score}):"
|
logger.info(f"AI 评分 {ai_score}(及格线 {min_score}):"
|
||||||
f"{card.company} - {card.title} | {ai_reason}")
|
f"{card.company} - {card.title} | {ai_reason}")
|
||||||
|
|||||||
+2
-4
@@ -34,11 +34,9 @@ class ClientSettings(BaseSettings):
|
|||||||
ADSPOWER_USER_ID: str = ""
|
ADSPOWER_USER_ID: str = ""
|
||||||
|
|
||||||
# -------------------------------------------------------
|
# -------------------------------------------------------
|
||||||
# AI 大模型(OpenAI 兼容接口,默认内置生产配置,.env 可覆盖)
|
# AI 打分(模型配置与密钥由云端服务端持有并代理调用,
|
||||||
|
# 客户端只保留本地投递过滤线)
|
||||||
# -------------------------------------------------------
|
# -------------------------------------------------------
|
||||||
AI_BASE_URL: str = "https://api.siliconflow.cn/v1"
|
|
||||||
AI_MODEL: str = "deepseek-ai/DeepSeek-V4-Flash"
|
|
||||||
AI_API_KEY: str = "sk-wptdswlffnkdorhomdgfifhxxbrsuklsloardmclwxjjehpa"
|
|
||||||
AI_MIN_SCORE: int = 65
|
AI_MIN_SCORE: int = 65
|
||||||
|
|
||||||
# -------------------------------------------------------
|
# -------------------------------------------------------
|
||||||
|
|||||||
@@ -0,0 +1,61 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""
|
||||||
|
端到端试跑验证 Activator(dry_run=True 只识别、绝不发送):
|
||||||
|
扫描左侧列表 → 状态过滤(送达/未读)→ 可信点击进入会话 →
|
||||||
|
读取我发出的最后一条消息 → 相似度比对 → 命中仅记录日志。
|
||||||
|
用法:python -m client.debug_activate_dry
|
||||||
|
日志:client/data/debug/activate_dry.log + 控制台
|
||||||
|
"""
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from loguru import logger
|
||||||
|
|
||||||
|
from client.browser.manager import BrowserManager
|
||||||
|
from client.browser.activator import Activator, similarity
|
||||||
|
|
||||||
|
OUT = Path(__file__).resolve().parent / "data" / "debug" / "activate_dry.log"
|
||||||
|
|
||||||
|
# 实测账号中真实的打招呼语(用于匹配条件)
|
||||||
|
MATCH_TEXT = ("您好 我对这份工作很感兴趣也很有信心完成相关工作,"
|
||||||
|
"想跟您沟通一下细节,请问您方便聊聊吗。")
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
OUT.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
if OUT.exists():
|
||||||
|
OUT.unlink()
|
||||||
|
logger.add(str(OUT), encoding="utf-8", level="DEBUG")
|
||||||
|
|
||||||
|
# 相似度函数单元自检(纯函数,无浏览器依赖)
|
||||||
|
cases = [
|
||||||
|
(MATCH_TEXT, MATCH_TEXT, 1.0),
|
||||||
|
(MATCH_TEXT, MATCH_TEXT[:-3], None), # 少几个字,应明显低于 1
|
||||||
|
("好的", MATCH_TEXT, None), # 完全不相关,应远低于阈值
|
||||||
|
("", MATCH_TEXT, 0.0),
|
||||||
|
]
|
||||||
|
for a, b, expect in cases:
|
||||||
|
r = similarity(a, b)
|
||||||
|
line = f"[自检] similarity={r:.3f} | a={a[:20]!r} b={b[:20]!r}"
|
||||||
|
if expect is not None:
|
||||||
|
line += f" expect={expect}"
|
||||||
|
print(line.encode("utf-8", "replace").decode("utf-8"), flush=True)
|
||||||
|
|
||||||
|
manager = BrowserManager()
|
||||||
|
act = Activator(manager)
|
||||||
|
act.start(match_text=MATCH_TEXT, threshold=0.8,
|
||||||
|
reply_message="[试跑] 本消息不会真的发送",
|
||||||
|
max_count=3, dry_run=True)
|
||||||
|
|
||||||
|
# 等任务跑完(最长 3 分钟)
|
||||||
|
for _ in range(180):
|
||||||
|
if not act.is_running:
|
||||||
|
break
|
||||||
|
time.sleep(1)
|
||||||
|
|
||||||
|
print(f"[结果] stats={act.stats}", flush=True)
|
||||||
|
print(f"[完成] 详细日志见 {OUT}", flush=True)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""
|
||||||
|
实测探测消息页(/web/geek/chat)左侧联系人列表真实 DOM:
|
||||||
|
1. 原生开标签页到消息页,等 SPA 渲染;
|
||||||
|
2. 统计各候选选择器命中数;
|
||||||
|
3. 导出前若干条列表项的 class / innerText / 外层 HTML;
|
||||||
|
4. 顺带探测输入框与发送按钮候选。
|
||||||
|
用法:python -m client.debug_chat_probe
|
||||||
|
产物:client/data/debug/chat_list_probe.txt
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import requests
|
||||||
|
import websocket
|
||||||
|
|
||||||
|
CDP = "http://127.0.0.1:9222"
|
||||||
|
CHAT_URL = "https://www.zhipin.com/web/geek/chat"
|
||||||
|
OUT = Path(__file__).resolve().parent / "data" / "debug" / "chat_list_probe5.txt"
|
||||||
|
|
||||||
|
_msg_id = 0
|
||||||
|
|
||||||
|
|
||||||
|
def send(ws, method, params=None):
|
||||||
|
global _msg_id
|
||||||
|
_msg_id += 1
|
||||||
|
ws.send(json.dumps({"id": _msg_id, "method": method, "params": params or {}}))
|
||||||
|
while True:
|
||||||
|
msg = json.loads(ws.recv())
|
||||||
|
if msg.get("id") == _msg_id:
|
||||||
|
return msg.get("result") or {}
|
||||||
|
|
||||||
|
|
||||||
|
def evaluate(ws, expression):
|
||||||
|
return send(ws, "Runtime.evaluate",
|
||||||
|
{"expression": expression, "returnByValue": True}) \
|
||||||
|
.get("result", {}).get("value")
|
||||||
|
|
||||||
|
|
||||||
|
PROBE_JS = """(() => {
|
||||||
|
const fs = [];
|
||||||
|
// 1. message-status 全部 class 取值
|
||||||
|
const statusSet = {};
|
||||||
|
for (const el of document.querySelectorAll('.message-status')) {
|
||||||
|
const k = String(el.className).trim();
|
||||||
|
statusSet[k] = (statusSet[k] || 0) + 1;
|
||||||
|
}
|
||||||
|
fs.push('== message-status 取值 ==');
|
||||||
|
Object.entries(statusSet).forEach(([k, n]) => fs.push(' ' + k + ' -> ' + n));
|
||||||
|
|
||||||
|
// 2. 点击第 1 条列表项(只读验证,不发消息)
|
||||||
|
const wraps = [...document.querySelectorAll('.friend-content-warp')];
|
||||||
|
const lis = [...new Set(wraps.map(w => w.closest('li')).filter(Boolean))];
|
||||||
|
fs.push('== li 总数:' + lis.length + ' ==');
|
||||||
|
if (!lis.length) return fs.join('\\n');
|
||||||
|
const target = lis[0];
|
||||||
|
const nameEl = target.querySelector('.name-text');
|
||||||
|
fs.push('点击目标:' + (nameEl ? nameEl.innerText.trim() : '未知'));
|
||||||
|
target.click();
|
||||||
|
return fs.join('\\n');
|
||||||
|
})()"""
|
||||||
|
|
||||||
|
# 点击后轮询右侧会话区结构(消息气泡/输入框/发送按钮)
|
||||||
|
CONV_JS = """(() => {
|
||||||
|
const fs = [];
|
||||||
|
const conv = document.querySelector('.chat-conversation');
|
||||||
|
if (!conv) { fs.push('无 .chat-conversation'); return fs.join('\\n'); }
|
||||||
|
fs.push('== conversation children ==');
|
||||||
|
[...conv.children].forEach(c => fs.push(' <' + c.tagName + ' class=' + String(c.className).slice(0, 80) + '>'));
|
||||||
|
// 消息气泡候选 class 统计
|
||||||
|
const clsCount = {};
|
||||||
|
for (const el of conv.querySelectorAll('[class]')) {
|
||||||
|
for (const c of String(el.className).split(/\\s+/)) {
|
||||||
|
if (/msg|item|message|bubble|text|self|other/i.test(c)) clsCount[c] = (clsCount[c] || 0) + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fs.push('== 会话区高频 class ==');
|
||||||
|
Object.entries(clsCount).sort((a, b) => b[1] - a[1]).slice(0, 25)
|
||||||
|
.forEach(([k, n]) => fs.push(' .' + k + ' -> ' + n));
|
||||||
|
// 最后一条消息候选样本(取出现次数多的容器类下的最后 2 个)
|
||||||
|
const items = [...conv.querySelectorAll('.chat-message .item, [class*="msg-item"], [class*="message-item"], .item-myself, .item-other')];
|
||||||
|
fs.push('== 消息条目候选数:' + items.length + ' ==');
|
||||||
|
items.slice(-2).forEach((el, i) => {
|
||||||
|
fs.push('--- msg ' + i + ' class=' + String(el.className).slice(0, 100));
|
||||||
|
fs.push(' text: ' + (el.innerText || '').replace(/\\s+/g, ' ').trim().slice(0, 120));
|
||||||
|
fs.push(' html: ' + el.outerHTML.replace(/\\s+/g, ' ').slice(0, 1200));
|
||||||
|
});
|
||||||
|
// 输入框与发送按钮(会话打开后才渲染)
|
||||||
|
const ta = conv.querySelector('textarea') || document.querySelector('.chat-conversation textarea');
|
||||||
|
fs.push('== 输入框:' + (ta ? 'textarea.input=' + ta.className : '无') + ' ==');
|
||||||
|
const sends = [...document.querySelectorAll('a,button,div,span')]
|
||||||
|
.filter(e => (e.innerText || '').trim() === '发送' && e.offsetHeight > 0);
|
||||||
|
fs.push('== 发送按钮候选:' + sends.length + ' ==');
|
||||||
|
sends.slice(0, 3).forEach(e => fs.push(' <' + e.tagName + ' class=' + String(e.className).slice(0, 80) + '>'));
|
||||||
|
return fs.join('\\n');
|
||||||
|
})()"""
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
OUT.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
lines = []
|
||||||
|
|
||||||
|
def log(*a):
|
||||||
|
s = " ".join(str(x) for x in a)
|
||||||
|
lines.append(s)
|
||||||
|
OUT.write_text("\n".join(lines), encoding="utf-8")
|
||||||
|
try:
|
||||||
|
print(f"[probe] line {len(lines)} written", flush=True)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# 已有聊天页标签则复用,否则新开
|
||||||
|
tab = None
|
||||||
|
for t in requests.get(f"{CDP}/json", timeout=5).json():
|
||||||
|
if "/web/geek/chat" in (t.get("url") or "") and t.get("webSocketDebuggerUrl"):
|
||||||
|
tab = t
|
||||||
|
break
|
||||||
|
if not tab:
|
||||||
|
r = requests.put(f"{CDP}/json/new?{CHAT_URL}", timeout=10)
|
||||||
|
if r.status_code == 405:
|
||||||
|
r = requests.get(f"{CDP}/json/new?{CHAT_URL}", timeout=10)
|
||||||
|
tab = r.json()
|
||||||
|
time.sleep(10) # 等 SPA 挂载
|
||||||
|
|
||||||
|
log("== URL ==", tab.get("url"))
|
||||||
|
ws = websocket.create_connection(tab["webSocketDebuggerUrl"], timeout=30)
|
||||||
|
try:
|
||||||
|
for attempt in range(3):
|
||||||
|
val = evaluate(ws, PROBE_JS)
|
||||||
|
if val:
|
||||||
|
log(val)
|
||||||
|
break
|
||||||
|
time.sleep(3)
|
||||||
|
# 点击后等会话区渲染,再读结构(最多等 10s)
|
||||||
|
for i in range(5):
|
||||||
|
time.sleep(2)
|
||||||
|
conv_val = evaluate(ws, CONV_JS)
|
||||||
|
if conv_val and '消息条目候选数:0' not in conv_val:
|
||||||
|
break
|
||||||
|
log(conv_val or '会话区探测为空')
|
||||||
|
finally:
|
||||||
|
ws.close()
|
||||||
|
log("== DONE ==")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""
|
||||||
|
第二轮实测:用浏览器级可信点击(Input.dispatchMouseEvent)打开左侧第一条会话,
|
||||||
|
探测右侧消息区真实结构(消息条目 / 最后一条消息 / 输入框 / 发送按钮)。
|
||||||
|
只读验证:点击联系人、读取 DOM,绝不输入与发送。
|
||||||
|
用法:python -m client.debug_chat_probe2
|
||||||
|
产物:client/data/debug/chat_conv_probe.txt
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import requests
|
||||||
|
import websocket
|
||||||
|
|
||||||
|
CDP = "http://127.0.0.1:9222"
|
||||||
|
OUT = Path(__file__).resolve().parent / "data" / "debug" / "chat_conv_probe2.txt"
|
||||||
|
|
||||||
|
_msg_id = 0
|
||||||
|
|
||||||
|
|
||||||
|
def send(ws, method, params=None):
|
||||||
|
global _msg_id
|
||||||
|
_msg_id += 1
|
||||||
|
ws.send(json.dumps({"id": _msg_id, "method": method, "params": params or {}}))
|
||||||
|
while True:
|
||||||
|
msg = json.loads(ws.recv())
|
||||||
|
if msg.get("id") == _msg_id:
|
||||||
|
return msg.get("result") or {}
|
||||||
|
|
||||||
|
|
||||||
|
def evaluate(ws, expression):
|
||||||
|
return send(ws, "Runtime.evaluate",
|
||||||
|
{"expression": expression, "returnByValue": True}) \
|
||||||
|
.get("result", {}).get("value")
|
||||||
|
|
||||||
|
|
||||||
|
# 会话已打开,只定位输入框与发送按钮(不再点击)
|
||||||
|
POS_JS = """(() => {
|
||||||
|
const fs = [];
|
||||||
|
const tas = [...document.querySelectorAll('textarea')];
|
||||||
|
fs.push('== textarea 总数:' + tas.length + ' ==');
|
||||||
|
tas.forEach((ta, i) => {
|
||||||
|
const r = ta.getBoundingClientRect();
|
||||||
|
fs.push('--- ta' + i + ' class=' + ta.className + ' placeholder=' + (ta.placeholder || '').slice(0, 40));
|
||||||
|
fs.push(' 可见=' + (ta.offsetHeight > 0) + ' rect=(' + Math.round(r.x) + ',' + Math.round(r.y) + ',' + Math.round(r.width) + 'x' + Math.round(r.height) + ')');
|
||||||
|
fs.push(' 祖先链:' + (() => {
|
||||||
|
const chain = []; let cur = ta.parentElement;
|
||||||
|
for (let j = 0; j < 6 && cur; j++) { chain.push(String(cur.className).slice(0, 60)); cur = cur.parentElement; }
|
||||||
|
return chain.join(' < '); })());
|
||||||
|
});
|
||||||
|
const sends = [...document.querySelectorAll('a,button,div,span')]
|
||||||
|
.filter(e => (e.innerText || '').trim() === '发送' && e.offsetHeight > 0);
|
||||||
|
fs.push('== 发送按钮:' + sends.length + ' ==');
|
||||||
|
sends.forEach(e => {
|
||||||
|
const r = e.getBoundingClientRect();
|
||||||
|
fs.push(' <' + e.tagName + ' class=' + String(e.className).slice(0, 100) + '> disabled=' + e.disabled + ' rect=(' + Math.round(r.x + r.width / 2) + ',' + Math.round(r.y + r.height / 2) + ')');
|
||||||
|
});
|
||||||
|
return fs.join('\\n');
|
||||||
|
})()"""
|
||||||
|
|
||||||
|
# 会话区结构探测(同上一轮)
|
||||||
|
CONV_JS = """(() => {
|
||||||
|
const fs = [];
|
||||||
|
const conv = document.querySelector('.chat-conversation');
|
||||||
|
if (!conv) { fs.push('无 .chat-conversation'); return fs.join('\\n'); }
|
||||||
|
fs.push('== conversation children ==');
|
||||||
|
[...conv.children].forEach(c => fs.push(' <' + c.tagName + ' class=' + String(c.className).slice(0, 80) + '>'));
|
||||||
|
const clsCount = {};
|
||||||
|
for (const el of conv.querySelectorAll('[class]')) {
|
||||||
|
for (const c of String(el.className).split(/\\s+/)) {
|
||||||
|
if (/msg|item|message|bubble|text|self|other|my/i.test(c)) clsCount[c] = (clsCount[c] || 0) + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fs.push('== 会话区高频 class(前30) ==');
|
||||||
|
Object.entries(clsCount).sort((a, b) => b[1] - a[1]).slice(0, 30)
|
||||||
|
.forEach(([k, n]) => fs.push(' .' + k + ' -> ' + n));
|
||||||
|
const items = [...conv.querySelectorAll('.chat-message .item, [class*="msg-item"], [class*="message-item"], .item-myself, .item-other')];
|
||||||
|
fs.push('== 消息条目候选数:' + items.length + ' ==');
|
||||||
|
items.slice(-3).forEach((el, i) => {
|
||||||
|
fs.push('--- msg ' + i + ' class=' + String(el.className).slice(0, 100));
|
||||||
|
fs.push(' text: ' + (el.innerText || '').replace(/\\s+/g, ' ').trim().slice(0, 150));
|
||||||
|
fs.push(' html: ' + el.outerHTML.replace(/\\s+/g, ' ').slice(0, 1500));
|
||||||
|
});
|
||||||
|
const ta = conv.querySelector('textarea') || document.querySelector('.chat-conversation textarea');
|
||||||
|
fs.push('== 输入框:' + (ta ? 'class=' + ta.className : '无') + ' ==');
|
||||||
|
if (ta) {
|
||||||
|
const wrap = ta.closest('[class*="input"]') || ta.parentElement;
|
||||||
|
fs.push('输入框外层:' + (wrap ? wrap.outerHTML.replace(/\\s+/g, ' ').slice(0, 1500) : 'null'));
|
||||||
|
}
|
||||||
|
const sends = [...document.querySelectorAll('a,button,div,span')]
|
||||||
|
.filter(e => (e.innerText || '').trim() === '发送' && e.offsetHeight > 0);
|
||||||
|
fs.push('== 发送按钮候选:' + sends.length + ' ==');
|
||||||
|
sends.slice(0, 3).forEach(e => fs.push(' <' + e.tagName + ' class=' + String(e.className).slice(0, 80) + '>'));
|
||||||
|
return fs.join('\\n');
|
||||||
|
})()"""
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
OUT.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
lines = []
|
||||||
|
|
||||||
|
def log(*a):
|
||||||
|
s = " ".join(str(x) for x in a)
|
||||||
|
lines.append(s)
|
||||||
|
OUT.write_text("\n".join(lines), encoding="utf-8")
|
||||||
|
|
||||||
|
tab = None
|
||||||
|
for t in requests.get(f"{CDP}/json", timeout=5).json():
|
||||||
|
if "/web/geek/chat" in (t.get("url") or "") and t.get("webSocketDebuggerUrl"):
|
||||||
|
tab = t
|
||||||
|
break
|
||||||
|
if not tab:
|
||||||
|
log("== 没有聊天页标签,请先开聊天页 ==")
|
||||||
|
return
|
||||||
|
|
||||||
|
# 可信点击要求标签页在前台
|
||||||
|
requests.get(f"{CDP}/json/activate/{tab['id']}", timeout=5)
|
||||||
|
time.sleep(1)
|
||||||
|
ws = websocket.create_connection(tab["webSocketDebuggerUrl"], timeout=30)
|
||||||
|
try:
|
||||||
|
# 会话已在上一轮点开,直接定位输入框/发送按钮(不再点击,避免切会话)
|
||||||
|
log(evaluate(ws, POS_JS) or "探测为空")
|
||||||
|
finally:
|
||||||
|
ws.close()
|
||||||
|
log("== DONE ==")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""
|
||||||
|
第三轮实测:以可见的 button.btn-send 为锚点,探测输入区真实结构。
|
||||||
|
只读 DOM,绝不输入与发送。
|
||||||
|
前提:浏览器已开聊天页(/web/geek/chat)且左侧已点开任意一个会话。
|
||||||
|
用法:python -m client.debug_chat_probe3
|
||||||
|
产物:client/data/debug/chat_conv_probe3.txt
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import requests
|
||||||
|
import websocket
|
||||||
|
|
||||||
|
CDP = "http://127.0.0.1:9222"
|
||||||
|
OUT = Path(__file__).resolve().parent / "data" / "debug" / "chat_conv_probe3.txt"
|
||||||
|
|
||||||
|
_msg_id = 0
|
||||||
|
|
||||||
|
|
||||||
|
def send(ws, method, params=None):
|
||||||
|
global _msg_id
|
||||||
|
_msg_id += 1
|
||||||
|
ws.send(json.dumps({"id": _msg_id, "method": method, "params": params or {}}))
|
||||||
|
while True:
|
||||||
|
msg = json.loads(ws.recv())
|
||||||
|
if msg.get("id") == _msg_id:
|
||||||
|
return msg.get("result") or {}
|
||||||
|
|
||||||
|
|
||||||
|
def evaluate(ws, expression):
|
||||||
|
return send(ws, "Runtime.evaluate",
|
||||||
|
{"expression": expression, "returnByValue": True}) \
|
||||||
|
.get("result", {}).get("value")
|
||||||
|
|
||||||
|
|
||||||
|
PROBE_JS = """(() => {
|
||||||
|
const fs = [];
|
||||||
|
// 1) 以发送按钮为锚点
|
||||||
|
const btn = document.querySelector('button.btn-send');
|
||||||
|
if (!btn) { fs.push('无 button.btn-send'); }
|
||||||
|
else {
|
||||||
|
const r = btn.getBoundingClientRect();
|
||||||
|
fs.push('== btn-send 可见=' + (btn.offsetHeight > 0)
|
||||||
|
+ ' rect=(' + Math.round(r.x) + ',' + Math.round(r.y) + ','
|
||||||
|
+ Math.round(r.width) + 'x' + Math.round(r.height) + ') disabled=' + btn.disabled);
|
||||||
|
// 向上找容器并 dump 结构
|
||||||
|
let wrap = btn.parentElement;
|
||||||
|
for (let i = 0; i < 3 && wrap; i++) wrap = wrap.parentElement;
|
||||||
|
fs.push('== btn 上溯3层容器 class=' + (wrap ? String(wrap.className).slice(0, 120) : 'null'));
|
||||||
|
if (wrap) fs.push('HTML: ' + wrap.outerHTML.replace(/\\s+/g, ' ').slice(0, 3000));
|
||||||
|
}
|
||||||
|
// 2) 全页可编辑元素
|
||||||
|
const ces = [...document.querySelectorAll('[contenteditable=""],[contenteditable="true"]')]
|
||||||
|
.filter(e => e.offsetHeight > 0);
|
||||||
|
fs.push('== 可见 contenteditable:' + ces.length + ' ==');
|
||||||
|
ces.forEach((e, i) => {
|
||||||
|
const r = e.getBoundingClientRect();
|
||||||
|
fs.push('--- ce' + i + ' <' + e.tagName + ' class=' + String(e.className).slice(0, 80)
|
||||||
|
+ '> rect=(' + Math.round(r.x) + ',' + Math.round(r.y) + ','
|
||||||
|
+ Math.round(r.width) + 'x' + Math.round(r.height) + ')'
|
||||||
|
+ ' text=' + (e.innerText || '').slice(0, 40).replace(/\\n/g, ' '));
|
||||||
|
});
|
||||||
|
// 3) 全页 input/textarea(含隐藏,附 display/visibility 样式)
|
||||||
|
const eds = [...document.querySelectorAll('textarea,input')];
|
||||||
|
fs.push('== input/textarea 总数:' + eds.length + ' ==');
|
||||||
|
eds.forEach((e, i) => {
|
||||||
|
const cs = getComputedStyle(e);
|
||||||
|
const r = e.getBoundingClientRect();
|
||||||
|
fs.push('--- ed' + i + ' <' + e.tagName + ' class=' + String(e.className).slice(0, 60)
|
||||||
|
+ ' ph=' + (e.placeholder || '').slice(0, 30)
|
||||||
|
+ '> display=' + cs.display + ' visibility=' + cs.visibility
|
||||||
|
+ ' rect=(' + Math.round(r.x) + ',' + Math.round(r.y) + ','
|
||||||
|
+ Math.round(r.width) + 'x' + Math.round(r.height) + ')');
|
||||||
|
});
|
||||||
|
// 4) iframe 里是否藏着输入框
|
||||||
|
const ifs = [...document.querySelectorAll('iframe')];
|
||||||
|
fs.push('== iframe:' + ifs.length + ' ==');
|
||||||
|
ifs.forEach((f, i) => fs.push('--- if' + i + ' src=' + (f.src || '').slice(0, 80)));
|
||||||
|
return fs.join('\\n');
|
||||||
|
})()"""
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
OUT.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
lines = []
|
||||||
|
|
||||||
|
def log(*a):
|
||||||
|
s = " ".join(str(x) for x in a)
|
||||||
|
lines.append(s)
|
||||||
|
OUT.write_text("\n".join(lines), encoding="utf-8")
|
||||||
|
|
||||||
|
tab = None
|
||||||
|
for t in requests.get(f"{CDP}/json", timeout=5).json():
|
||||||
|
if "/web/geek/chat" in (t.get("url") or "") and t.get("webSocketDebuggerUrl"):
|
||||||
|
tab = t
|
||||||
|
break
|
||||||
|
if not tab:
|
||||||
|
log("== 没有聊天页标签,请先开聊天页 ==")
|
||||||
|
return
|
||||||
|
|
||||||
|
requests.get(f"{CDP}/json/activate/{tab['id']}", timeout=5)
|
||||||
|
time.sleep(1)
|
||||||
|
ws = websocket.create_connection(tab["webSocketDebuggerUrl"], timeout=30)
|
||||||
|
try:
|
||||||
|
log(evaluate(ws, PROBE_JS) or "探测为空")
|
||||||
|
finally:
|
||||||
|
ws.close()
|
||||||
|
log("== DONE ==")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""只读实测:在真实聊天页执行 activator.py 内的 _INPUT_BOX_JS / _FOCUS_INPUT_JS / _SEND_BTN_JS
|
||||||
|
(聚焦只验证可达性,绝不输入、绝不点击、绝不发送)"""
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import requests
|
||||||
|
import websocket
|
||||||
|
|
||||||
|
CDP = "http://127.0.0.1:9222"
|
||||||
|
src = Path(__file__).resolve().parent / "browser" / "activator.py"
|
||||||
|
text = src.read_text(encoding="utf-8")
|
||||||
|
|
||||||
|
def extract(name):
|
||||||
|
return re.search(rf'{name} = """(.*?)"""', text, re.S).group(1)
|
||||||
|
|
||||||
|
INPUT_JS = extract("_INPUT_BOX_JS")
|
||||||
|
SEND_JS = extract("_SEND_BTN_JS")
|
||||||
|
# 聚焦验证:聚焦后记录并还原(只读会话内容不变,聚焦无副作用)
|
||||||
|
FOCUS_CHECK_JS = extract("_FOCUS_INPUT_JS")
|
||||||
|
|
||||||
|
_msg_id = 0
|
||||||
|
|
||||||
|
def call(ws, method, params=None):
|
||||||
|
global _msg_id
|
||||||
|
_msg_id += 1
|
||||||
|
ws.send(json.dumps({"id": _msg_id, "method": method, "params": params or {}}))
|
||||||
|
while True:
|
||||||
|
m = json.loads(ws.recv())
|
||||||
|
if m.get("id") == _msg_id:
|
||||||
|
return m.get("result") or {}
|
||||||
|
|
||||||
|
def ev(ws, expr):
|
||||||
|
return call(ws, "Runtime.evaluate",
|
||||||
|
{"expression": expr, "returnByValue": True}) \
|
||||||
|
.get("result", {}).get("value")
|
||||||
|
|
||||||
|
def main():
|
||||||
|
tab = None
|
||||||
|
for t in requests.get(f"{CDP}/json", timeout=5).json():
|
||||||
|
if "/web/geek/chat" in (t.get("url") or "") and t.get("webSocketDebuggerUrl"):
|
||||||
|
tab = t
|
||||||
|
break
|
||||||
|
if not tab:
|
||||||
|
print("FAIL 未找到聊天页标签")
|
||||||
|
return
|
||||||
|
ws = websocket.create_connection(tab["webSocketDebuggerUrl"], timeout=30)
|
||||||
|
try:
|
||||||
|
r1 = ev(ws, INPUT_JS)
|
||||||
|
print("输入框定位:", r1)
|
||||||
|
ok1 = False
|
||||||
|
if r1:
|
||||||
|
p = json.loads(r1)
|
||||||
|
# 命中真实输入框:可见的 contenteditable div,坐标为正(坐标每次实时计算)
|
||||||
|
ok1 = (p.get("visible") is True and p.get("kind") == "div"
|
||||||
|
and p["x"] > 0 and p["y"] > 0)
|
||||||
|
print("PASS" if ok1 else "FAIL", "真实页面输入框可定位且可见")
|
||||||
|
|
||||||
|
r2 = ev(ws, SEND_JS)
|
||||||
|
print("发送按钮:", r2)
|
||||||
|
ok2 = bool(r2)
|
||||||
|
print("PASS" if ok2 else "FAIL", "真实页面发送按钮可定位")
|
||||||
|
|
||||||
|
r3 = ev(ws, FOCUS_CHECK_JS)
|
||||||
|
print("聚焦检查:", r3)
|
||||||
|
print("PASS" if r3 is True else "FAIL", "输入框可聚焦")
|
||||||
|
finally:
|
||||||
|
ws.close()
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""只读实测:验证 _LIST_JS / _LOCATE_ITEM_JS / _CONV_NAME_JS 在真实页面的行为
|
||||||
|
绝不点击、绝不输入、绝不发送"""
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import requests
|
||||||
|
import websocket
|
||||||
|
|
||||||
|
CDP = "http://127.0.0.1:9222"
|
||||||
|
src = (Path(__file__).resolve().parent / "browser" / "activator.py").read_text(encoding="utf-8")
|
||||||
|
|
||||||
|
def extract(name):
|
||||||
|
return re.search(rf'{name} = """(.*?)"""', src, re.S).group(1)
|
||||||
|
|
||||||
|
LIST_JS = extract("_LIST_JS")
|
||||||
|
LOCATE_JS = extract("_LOCATE_ITEM_JS")
|
||||||
|
CONV_JS = extract("_CONV_NAME_JS")
|
||||||
|
|
||||||
|
_msg_id = 0
|
||||||
|
|
||||||
|
def call(ws, method, params=None):
|
||||||
|
global _msg_id
|
||||||
|
_msg_id += 1
|
||||||
|
ws.send(json.dumps({"id": _msg_id, "method": method, "params": params or {}}))
|
||||||
|
while True:
|
||||||
|
m = json.loads(ws.recv())
|
||||||
|
if m.get("id") == _msg_id:
|
||||||
|
return m.get("result") or {}
|
||||||
|
|
||||||
|
def ev(ws, expr):
|
||||||
|
return call(ws, "Runtime.evaluate",
|
||||||
|
{"expression": expr, "returnByValue": True}) \
|
||||||
|
.get("result", {}).get("value")
|
||||||
|
|
||||||
|
def main():
|
||||||
|
tab = next((t for t in requests.get(f"{CDP}/json", timeout=5).json()
|
||||||
|
if "/web/geek/chat" in (t.get("url") or "")
|
||||||
|
and t.get("webSocketDebuggerUrl")), None)
|
||||||
|
if not tab:
|
||||||
|
print("FAIL 未找到聊天页标签")
|
||||||
|
return
|
||||||
|
ws = websocket.create_connection(tab["webSocketDebuggerUrl"], timeout=30)
|
||||||
|
fails = []
|
||||||
|
try:
|
||||||
|
# 1) 列表可读(returnByValue 时可能直接是 list)
|
||||||
|
raw_list = ev(ws, LIST_JS)
|
||||||
|
items = raw_list if isinstance(raw_list, list) else json.loads(raw_list or "[]")
|
||||||
|
visible = [it for it in items if it.get("visible")]
|
||||||
|
names = [it.get("name") for it in visible if it.get("name")]
|
||||||
|
print(f"列表可见联系人 {len(visible)} 个:{names[:8]}")
|
||||||
|
if not names:
|
||||||
|
fails.append("列表为空")
|
||||||
|
|
||||||
|
# 2) 当前会话头部姓名可读
|
||||||
|
cur = ev(ws, CONV_JS)
|
||||||
|
print(f"当前会话头部姓名:{cur!r}")
|
||||||
|
if not cur:
|
||||||
|
fails.append("会话头部姓名为空(选择器可能失配!)")
|
||||||
|
|
||||||
|
# 3) 按真实存在的姓名重定位 → 必须返回坐标
|
||||||
|
target = cur if cur in names else (names[0] if names else None)
|
||||||
|
if target:
|
||||||
|
raw = ev(ws, f"({LOCATE_JS})({json.dumps(target)})")
|
||||||
|
print(f"重定位[{target}]:{raw}")
|
||||||
|
if not raw:
|
||||||
|
# 当前会话的人可能不在可见列表(被过滤等),用列表第一人再试
|
||||||
|
raw2 = ev(ws, f"({LOCATE_JS})({json.dumps(names[0])})")
|
||||||
|
print(f"重定位[{names[0]}]:{raw2}")
|
||||||
|
if not raw2:
|
||||||
|
fails.append("重定位失败")
|
||||||
|
else:
|
||||||
|
p = json.loads(raw)
|
||||||
|
if not (p["x"] > 0 and p["y"] > 0):
|
||||||
|
fails.append("重定位坐标非正")
|
||||||
|
|
||||||
|
# 4) 不存在的姓名 → 必须返回 null(防点错人的前提)
|
||||||
|
raw3 = ev(ws, f"({LOCATE_JS})({json.dumps('不存在的人Zz9')})")
|
||||||
|
print(f"重定位[不存在的人]:{raw3}")
|
||||||
|
if raw3 not in (None, "", "null"):
|
||||||
|
fails.append("幽灵姓名竟返回了坐标!")
|
||||||
|
finally:
|
||||||
|
ws.close()
|
||||||
|
print()
|
||||||
|
print("全部通过" if not fails else f"失败:{fails}")
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""实测:视口外联系人 定位→滚入视口→重定位 全流程
|
||||||
|
唯一副作用:会滚动左侧列表位置(无点击、无输入、无发送)"""
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import requests
|
||||||
|
import websocket
|
||||||
|
|
||||||
|
CDP = "http://127.0.0.1:9222"
|
||||||
|
src = (Path(__file__).resolve().parent / "browser" / "activator.py").read_text(encoding="utf-8")
|
||||||
|
|
||||||
|
def extract(name):
|
||||||
|
return re.search(rf'{name} = """(.*?)"""', src, re.S).group(1)
|
||||||
|
|
||||||
|
LIST_JS = extract("_LIST_JS")
|
||||||
|
LOCATE_JS = extract("_LOCATE_ITEM_JS")
|
||||||
|
BRING_JS = extract("_BRING_INTO_VIEW_JS")
|
||||||
|
|
||||||
|
_msg_id = 0
|
||||||
|
|
||||||
|
def call(ws, method, params=None):
|
||||||
|
global _msg_id
|
||||||
|
_msg_id += 1
|
||||||
|
ws.send(json.dumps({"id": _msg_id, "method": method, "params": params or {}}))
|
||||||
|
while True:
|
||||||
|
m = json.loads(ws.recv())
|
||||||
|
if m.get("id") == _msg_id:
|
||||||
|
return m.get("result") or {}
|
||||||
|
|
||||||
|
def ev(ws, expr):
|
||||||
|
return call(ws, "Runtime.evaluate",
|
||||||
|
{"expression": expr, "returnByValue": True}) \
|
||||||
|
.get("result", {}).get("value")
|
||||||
|
|
||||||
|
VIEWPORT_JS = "(() => window.innerHeight)()"
|
||||||
|
SCROLL_INFO_JS = """(() => {
|
||||||
|
const el = document.querySelector('.user-list-content')
|
||||||
|
|| document.querySelector('.user-list');
|
||||||
|
if (!el) return null;
|
||||||
|
return {clientHeight: el.clientHeight, scrollTop: el.scrollTop,
|
||||||
|
scrollHeight: el.scrollHeight};
|
||||||
|
})()"""
|
||||||
|
|
||||||
|
def main():
|
||||||
|
tab = next((t for t in requests.get(f"{CDP}/json", timeout=5).json()
|
||||||
|
if "/web/geek/chat" in (t.get("url") or "")
|
||||||
|
and t.get("webSocketDebuggerUrl")), None)
|
||||||
|
if not tab:
|
||||||
|
print("FAIL 未找到聊天页标签")
|
||||||
|
return
|
||||||
|
ws = websocket.create_connection(tab["webSocketDebuggerUrl"], timeout=30)
|
||||||
|
fails = []
|
||||||
|
try:
|
||||||
|
viewport = ev(ws, VIEWPORT_JS)
|
||||||
|
print(f"当前视口高度(动态):{viewport}")
|
||||||
|
sc = ev(ws, SCROLL_INFO_JS)
|
||||||
|
print(f"滚动容器:{sc}")
|
||||||
|
# 滚动步长动态性验证:新步长 = max(240, clientHeight*0.8),不再固定 480
|
||||||
|
if sc:
|
||||||
|
expected = max(240, round(sc["clientHeight"] * 0.8))
|
||||||
|
print(f"预期翻页步长(动态计算):{expected}")
|
||||||
|
raw = ev(ws, LIST_JS)
|
||||||
|
items = raw if isinstance(raw, list) else json.loads(raw or "[]")
|
||||||
|
names = [it.get("name") for it in items
|
||||||
|
if it.get("visible") and it.get("name")]
|
||||||
|
first, last = names[0], names[-1]
|
||||||
|
print(f"列表 {len(names)} 人,首位={first},末位={last}")
|
||||||
|
|
||||||
|
# 1) 首位联系人:应在视口内
|
||||||
|
loc1 = json.loads(ev(ws, f"({LOCATE_JS})({json.dumps(first)})"))
|
||||||
|
print(f"定位[{first}]:{loc1}")
|
||||||
|
if not (loc1 and loc1.get("inView") is True):
|
||||||
|
fails.append("首位应在视口内")
|
||||||
|
|
||||||
|
# 2) 末位联系人:应判为视口外(探针实测 y=3209 > 视口 825)
|
||||||
|
loc2 = json.loads(ev(ws, f"({LOCATE_JS})({json.dumps(last)})"))
|
||||||
|
print(f"定位[{last}]:{loc2}")
|
||||||
|
if not loc2:
|
||||||
|
fails.append("末位定位失败")
|
||||||
|
elif loc2.get("inView") is True:
|
||||||
|
print("(末位恰在视口内,跳过滚动验证)")
|
||||||
|
else:
|
||||||
|
# 3) 滚入视口 → 重定位应变 inView=true 且 y 在视口内
|
||||||
|
ok = ev(ws, f"({BRING_JS})({json.dumps(last)})")
|
||||||
|
print(f"滚入视口[{last}]:{ok}")
|
||||||
|
if ok is not True:
|
||||||
|
fails.append("scrollIntoView 返回非 true")
|
||||||
|
import time
|
||||||
|
time.sleep(0.8)
|
||||||
|
loc3 = json.loads(ev(ws, f"({LOCATE_JS})({json.dumps(last)})"))
|
||||||
|
print(f"滚动后重定位[{last}]:{loc3}")
|
||||||
|
if not (loc3 and loc3.get("inView") is True
|
||||||
|
and 0 < loc3["y"] < viewport):
|
||||||
|
fails.append("滚入视口后仍未进入可视区")
|
||||||
|
# 还原:滚回首位,避免影响用户当前浏览位置
|
||||||
|
ev(ws, f"({BRING_JS})({json.dumps(first)})")
|
||||||
|
|
||||||
|
# 4) 幽灵姓名
|
||||||
|
if ev(ws, f"({BRING_JS})({json.dumps('不存在的人Zz9')})") is not False:
|
||||||
|
fails.append("幽灵姓名滚入视口竟返回 true")
|
||||||
|
finally:
|
||||||
|
ws.close()
|
||||||
|
print()
|
||||||
|
print("全部通过" if not fails else f"失败:{fails}")
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""只读实测:找出左侧联系人列表的真正滚动容器
|
||||||
|
原则:不修改任何 scrollTop,只读取结构信息"""
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import requests
|
||||||
|
import websocket
|
||||||
|
|
||||||
|
CDP = "http://127.0.0.1:9222"
|
||||||
|
OUT = Path(__file__).resolve().parent / "data" / "debug" / "chat_scroll_probe.txt"
|
||||||
|
|
||||||
|
PROBE_JS = """(() => {
|
||||||
|
const fs = [];
|
||||||
|
// 1) 从首个联系人向上找所有"可滚动"祖先(overflow 允许滚动且可滚高度>0)
|
||||||
|
const li = document.querySelector('.friend-content-warp');
|
||||||
|
if (!li) { fs.push('无列表项'); return fs.join('\\n'); }
|
||||||
|
let cur = li.parentElement;
|
||||||
|
fs.push('== 自列表项向上的祖先链(含滚动能力) ==');
|
||||||
|
let depth = 0;
|
||||||
|
while (cur && depth < 10) {
|
||||||
|
const cs = getComputedStyle(cur);
|
||||||
|
const canScroll = /(auto|scroll|overlay)/.test(cs.overflowY)
|
||||||
|
&& cur.scrollHeight > cur.clientHeight;
|
||||||
|
fs.push(' d' + depth + ' <' + cur.tagName + ' class=' + String(cur.className).slice(0, 70)
|
||||||
|
+ '> overflowY=' + cs.overflowY
|
||||||
|
+ ' scrollH=' + cur.scrollHeight + ' clientH=' + cur.clientHeight
|
||||||
|
+ ' scrollTop=' + Math.round(cur.scrollTop)
|
||||||
|
+ (canScroll ? ' ← 可滚动' : ''));
|
||||||
|
cur = cur.parentElement;
|
||||||
|
depth++;
|
||||||
|
}
|
||||||
|
// 2) 现有 _LIST_SCROLL_JS 三个候选元素的状态对比
|
||||||
|
fs.push('== 现有滚动候选元素现状 ==');
|
||||||
|
['.user-list-content', '.user-list', '.chat-content'].forEach(sel => {
|
||||||
|
const el = document.querySelector(sel);
|
||||||
|
if (!el) { fs.push(' ' + sel + ' 不存在'); return; }
|
||||||
|
const cs = getComputedStyle(el);
|
||||||
|
fs.push(' ' + sel + ' overflowY=' + cs.overflowY
|
||||||
|
+ ' scrollH=' + el.scrollHeight + ' clientH=' + el.clientHeight
|
||||||
|
+ ' children=' + el.children.length);
|
||||||
|
});
|
||||||
|
// 3) li 总数与 ul 容器
|
||||||
|
const lis = [...document.querySelectorAll('.friend-content-warp')]
|
||||||
|
.map(w => w.closest('li')).filter(Boolean);
|
||||||
|
fs.push('== li 总数:' + new Set(lis).size + ' ==');
|
||||||
|
const ul = lis[0] ? lis[0].parentElement : null;
|
||||||
|
fs.push('ul 容器:' + (ul ? '<' + ul.tagName + ' class=' + String(ul.className).slice(0, 60) + '>' : 'null'));
|
||||||
|
// 4) 最后一个 li 的视口位置(判断是否在可视区外)
|
||||||
|
const last = lis[lis.length - 1];
|
||||||
|
if (last) {
|
||||||
|
const r = last.getBoundingClientRect();
|
||||||
|
fs.push('最后li rect: y=' + Math.round(r.y) + ' h=' + Math.round(r.height)
|
||||||
|
+ ' viewportH=' + window.innerHeight);
|
||||||
|
}
|
||||||
|
return fs.join('\\n');
|
||||||
|
})()"""
|
||||||
|
|
||||||
|
_msg_id = 0
|
||||||
|
|
||||||
|
def call(ws, method, params=None):
|
||||||
|
global _msg_id
|
||||||
|
_msg_id += 1
|
||||||
|
ws.send(json.dumps({"id": _msg_id, "method": method, "params": params or {}}))
|
||||||
|
while True:
|
||||||
|
m = json.loads(ws.recv())
|
||||||
|
if m.get("id") == _msg_id:
|
||||||
|
return m.get("result") or {}
|
||||||
|
|
||||||
|
def main():
|
||||||
|
OUT.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
tab = next((t for t in requests.get(f"{CDP}/json", timeout=5).json()
|
||||||
|
if "/web/geek/chat" in (t.get("url") or "")
|
||||||
|
and t.get("webSocketDebuggerUrl")), None)
|
||||||
|
out = []
|
||||||
|
if not tab:
|
||||||
|
out.append("== 没有聊天页标签 ==")
|
||||||
|
else:
|
||||||
|
ws = websocket.create_connection(tab["webSocketDebuggerUrl"], timeout=30)
|
||||||
|
try:
|
||||||
|
v = call(ws, "Runtime.evaluate",
|
||||||
|
{"expression": PROBE_JS, "returnByValue": True}) \
|
||||||
|
.get("result", {}).get("value")
|
||||||
|
out.append(v or "探测为空")
|
||||||
|
finally:
|
||||||
|
ws.close()
|
||||||
|
out.append("== DONE ==")
|
||||||
|
text = "\n".join(out)
|
||||||
|
OUT.write_text(text, encoding="utf-8")
|
||||||
|
print(text)
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
+1
-2
@@ -88,8 +88,7 @@ def main() -> None:
|
|||||||
logger.warning("浏览器模式:chrome,但未检测到 Chrome/Edge,请安装或在 .env 配置 BROWSER_PATH")
|
logger.warning("浏览器模式:chrome,但未检测到 Chrome/Edge,请安装或在 .env 配置 BROWSER_PATH")
|
||||||
elif not client_settings.ADSPOWER_USER_ID:
|
elif not client_settings.ADSPOWER_USER_ID:
|
||||||
logger.warning("浏览器模式:adspower,尚未配置 Profile ID(ADSPOWER_USER_ID)")
|
logger.warning("浏览器模式:adspower,尚未配置 Profile ID(ADSPOWER_USER_ID)")
|
||||||
if not client_settings.AI_API_KEY:
|
# AI 打分经云端服务端代理(模型配置在服务端 /view 维护),客户端无需本地密钥
|
||||||
logger.warning("尚未配置 AI_API_KEY,AI 评分功能将不可用")
|
|
||||||
|
|
||||||
host = client_settings.WEB_HOST
|
host = client_settings.WEB_HOST
|
||||||
port = client_settings.WEB_PORT
|
port = client_settings.WEB_PORT
|
||||||
|
|||||||
+98
-11
@@ -50,17 +50,18 @@ class ServerAPI:
|
|||||||
def _headers(self) -> dict:
|
def _headers(self) -> dict:
|
||||||
return {"Authorization": f"Bearer {self.token}"} if self.token else {}
|
return {"Authorization": f"Bearer {self.token}"} if self.token else {}
|
||||||
|
|
||||||
def _req(self, method: str, url: str, **kwargs) -> requests.Response:
|
def _req(self, method: str, url: str, retries: int = 5, **kwargs) -> requests.Response:
|
||||||
"""云端请求统一入口:网络层异常重试 5 次、每次间隔 1 秒,仍失败才抛出。
|
"""云端请求统一入口:网络层异常重试(默认 5 次、每次间隔 1 秒),仍失败才抛出。
|
||||||
仅重试连接类异常(RequestException 发生在请求阶段);
|
仅重试连接类异常(RequestException 发生在请求阶段);
|
||||||
HTTP 状态码错误由调用方 raise_for_status 抛出,不重试。"""
|
HTTP 状态码错误由调用方 raise_for_status 抛出,不重试。
|
||||||
|
AI 代理类长调用可传小 retries,避免重试放大等待。"""
|
||||||
last: Exception | None = None
|
last: Exception | None = None
|
||||||
for i in range(5):
|
for i in range(retries):
|
||||||
try:
|
try:
|
||||||
return requests.request(method, url, **kwargs)
|
return requests.request(method, url, **kwargs)
|
||||||
except requests.RequestException as e:
|
except requests.RequestException as e:
|
||||||
last = e
|
last = e
|
||||||
logger.warning(f"云端请求失败({i + 1}/5),1 秒后重试:"
|
logger.warning(f"云端请求失败({i + 1}/{retries}),1 秒后重试:"
|
||||||
f"{method.upper()} {url}:{e}")
|
f"{method.upper()} {url}:{e}")
|
||||||
time.sleep(1)
|
time.sleep(1)
|
||||||
raise last
|
raise last
|
||||||
@@ -117,13 +118,14 @@ class ServerAPI:
|
|||||||
resp.raise_for_status()
|
resp.raise_for_status()
|
||||||
return resp.json()
|
return resp.json()
|
||||||
|
|
||||||
def heartbeat(self) -> bool:
|
def heartbeat(self, payload: dict | None = None) -> bool:
|
||||||
"""发送心跳,刷新服务端 last_seen_at;失败返回 False(不抛异常)"""
|
"""发送心跳并携带 RPA 全量状态;失败返回 False(不抛异常)"""
|
||||||
if not self.token:
|
if not self.token:
|
||||||
return False
|
return False
|
||||||
try:
|
try:
|
||||||
resp = self._req("post",
|
resp = self._req("post",
|
||||||
f"{self.base_url}/api/auth/heartbeat",
|
f"{self.base_url}/api/auth/heartbeat",
|
||||||
|
json=payload or {},
|
||||||
headers=self._headers(), timeout=10,
|
headers=self._headers(), timeout=10,
|
||||||
)
|
)
|
||||||
return resp.status_code == 200
|
return resp.status_code == 200
|
||||||
@@ -131,6 +133,21 @@ class ServerAPI:
|
|||||||
logger.debug(f"心跳发送失败:{e}")
|
logger.debug(f"心跳发送失败:{e}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
def fetch_pending_task(self) -> dict | None:
|
||||||
|
"""轮询拉取待执行的远程控制任务(服务端已标记 running)"""
|
||||||
|
resp = self._req("get", f"{self.base_url}/api/rpa/tasks/pending",
|
||||||
|
headers=self._headers(), timeout=10)
|
||||||
|
resp.raise_for_status()
|
||||||
|
return resp.json().get("task")
|
||||||
|
|
||||||
|
def finish_task(self, task_id: int, status: str, result: str = "") -> None:
|
||||||
|
"""远程任务执行完回调:更新终态与结果"""
|
||||||
|
resp = self._req("post",
|
||||||
|
f"{self.base_url}/api/rpa/tasks/{task_id}/finish",
|
||||||
|
json={"status": status, "result": result[:500]},
|
||||||
|
headers=self._headers(), timeout=10)
|
||||||
|
resp.raise_for_status()
|
||||||
|
|
||||||
def update_login_status(self, status: str, boss_account: str | None = None) -> dict:
|
def update_login_status(self, status: str, boss_account: str | None = None) -> dict:
|
||||||
payload = {"login_status": status}
|
payload = {"login_status": status}
|
||||||
if boss_account:
|
if boss_account:
|
||||||
@@ -194,15 +211,17 @@ class ServerAPI:
|
|||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
# 投递会话
|
# 投递会话
|
||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
def start_session(self, keywords: str, city_code: str,
|
def start_session(self, keywords: str, city: str,
|
||||||
salary_min: int | None, salary_max: int | None) -> dict:
|
salary_min: int | None, salary_max: int | None,
|
||||||
|
prompt: str | None = None) -> dict:
|
||||||
resp = self._req("post",
|
resp = self._req("post",
|
||||||
f"{self.base_url}/api/sessions/start",
|
f"{self.base_url}/api/sessions/start",
|
||||||
json={
|
json={
|
||||||
"keywords": keywords,
|
"keywords": keywords,
|
||||||
"city_code": city_code,
|
"city": city,
|
||||||
"salary_min": salary_min,
|
"salary_min": salary_min,
|
||||||
"salary_max": salary_max,
|
"salary_max": salary_max,
|
||||||
|
"prompt": prompt,
|
||||||
},
|
},
|
||||||
headers=self._headers(), timeout=15,
|
headers=self._headers(), timeout=15,
|
||||||
)
|
)
|
||||||
@@ -229,11 +248,25 @@ class ServerAPI:
|
|||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
# 投递记录
|
# 投递记录
|
||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
|
# 上报字段长度上限(与服务端列长对齐);jd_text 需传完整全文供服务端按上限分流:
|
||||||
|
# 短文本入库,超长由服务端落盘归档到文件——这里 300000 仅是防病理值的安全上限,
|
||||||
|
# 不做业务截断,避免丢失归档所需的全文
|
||||||
|
_REPORT_TEXT_LIMITS = {
|
||||||
|
"job_title": 128, "company": 128, "salary": 32, "location": 64,
|
||||||
|
"ai_reason": 255, "skip_reason": 255, "greeting": 500,
|
||||||
|
"jd_text": 300000,
|
||||||
|
}
|
||||||
|
|
||||||
def report_application(self, session_id: int | None, data: dict) -> dict:
|
def report_application(self, session_id: int | None, data: dict) -> dict:
|
||||||
params = {"session_id": session_id} if session_id else {}
|
params = {"session_id": session_id} if session_id else {}
|
||||||
|
payload = dict(data)
|
||||||
|
for key, limit in self._REPORT_TEXT_LIMITS.items():
|
||||||
|
val = payload.get(key)
|
||||||
|
if isinstance(val, str) and len(val) > limit:
|
||||||
|
payload[key] = val[:limit]
|
||||||
resp = self._req("post",
|
resp = self._req("post",
|
||||||
f"{self.base_url}/api/jobs/report",
|
f"{self.base_url}/api/jobs/report",
|
||||||
json=data, params=params, headers=self._headers(), timeout=15,
|
json=payload, params=params, headers=self._headers(), timeout=15,
|
||||||
)
|
)
|
||||||
resp.raise_for_status()
|
resp.raise_for_status()
|
||||||
return resp.json()
|
return resp.json()
|
||||||
@@ -263,11 +296,65 @@ class ServerAPI:
|
|||||||
page += 1
|
page += 1
|
||||||
return companies
|
return companies
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# 投递条件模板
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def list_templates(self) -> list[dict]:
|
||||||
|
resp = self._req("get", f"{self.base_url}/api/templates",
|
||||||
|
headers=self._headers(), timeout=15)
|
||||||
|
resp.raise_for_status()
|
||||||
|
return resp.json()
|
||||||
|
|
||||||
|
def create_template(self, data: dict) -> dict:
|
||||||
|
resp = self._req("post", f"{self.base_url}/api/templates",
|
||||||
|
json=data, headers=self._headers(), timeout=15)
|
||||||
|
resp.raise_for_status()
|
||||||
|
return resp.json()
|
||||||
|
|
||||||
|
def update_template(self, template_id: int, data: dict) -> dict:
|
||||||
|
resp = self._req("put", f"{self.base_url}/api/templates/{template_id}",
|
||||||
|
json=data, headers=self._headers(), timeout=15)
|
||||||
|
resp.raise_for_status()
|
||||||
|
return resp.json()
|
||||||
|
|
||||||
|
def delete_template(self, template_id: int) -> dict:
|
||||||
|
resp = self._req("delete", f"{self.base_url}/api/templates/{template_id}",
|
||||||
|
headers=self._headers(), timeout=15)
|
||||||
|
resp.raise_for_status()
|
||||||
|
return resp.json()
|
||||||
|
|
||||||
def get_stats(self) -> dict:
|
def get_stats(self) -> dict:
|
||||||
resp = self._req("get", f"{self.base_url}/api/jobs/stats", headers=self._headers(), timeout=15)
|
resp = self._req("get", f"{self.base_url}/api/jobs/stats", headers=self._headers(), timeout=15)
|
||||||
resp.raise_for_status()
|
resp.raise_for_status()
|
||||||
return resp.json()
|
return resp.json()
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# AI 代理(模型配置在服务端,客户端不持有任何密钥)
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def start_ai_score(self, payload: dict) -> dict:
|
||||||
|
"""开始打分任务(异步)。payload 含 request_key 幂等键,
|
||||||
|
网络重试不会导致服务端重复调用大模型"""
|
||||||
|
resp = self._req("post", f"{self.base_url}/api/ai/score/start",
|
||||||
|
json=payload, headers=self._headers(),
|
||||||
|
timeout=30, retries=2)
|
||||||
|
resp.raise_for_status()
|
||||||
|
return resp.json()
|
||||||
|
|
||||||
|
def get_ai_score_result(self, request_key: str) -> dict:
|
||||||
|
"""轮询打分结果:{status: pending/running/success/failed, score, reason}"""
|
||||||
|
resp = self._req("get", f"{self.base_url}/api/ai/score/result/{request_key}",
|
||||||
|
headers=self._headers(), timeout=15, retries=2)
|
||||||
|
resp.raise_for_status()
|
||||||
|
return resp.json()
|
||||||
|
|
||||||
|
def clean_resume_via_server(self, raw_text: str) -> str:
|
||||||
|
"""经服务端 AI 代理整理简历内容(低频同步,超时对齐服务端 5 分钟阶梯)"""
|
||||||
|
resp = self._req("post", f"{self.base_url}/api/ai/clean-resume",
|
||||||
|
json={"raw_text": raw_text}, headers=self._headers(),
|
||||||
|
timeout=330, retries=1)
|
||||||
|
resp.raise_for_status()
|
||||||
|
return resp.json().get("content") or raw_text
|
||||||
|
|
||||||
def today_applied_count(self) -> int:
|
def today_applied_count(self) -> int:
|
||||||
"""当天(北京时间)实际投递数量"""
|
"""当天(北京时间)实际投递数量"""
|
||||||
resp = self._req("get", f"{self.base_url}/api/jobs/today-count", headers=self._headers(), timeout=15)
|
resp = self._req("get", f"{self.base_url}/api/jobs/today-count", headers=self._headers(), timeout=15)
|
||||||
|
|||||||
+258
-46
@@ -21,6 +21,7 @@ from ..fingerprint import get_machine_summary
|
|||||||
from ..browser.manager import BrowserManager
|
from ..browser.manager import BrowserManager
|
||||||
from ..browser.resume_scraper import ResumeScraper
|
from ..browser.resume_scraper import ResumeScraper
|
||||||
from ..browser.applicant import Applicant
|
from ..browser.applicant import Applicant
|
||||||
|
from ..browser.activator import Activator
|
||||||
|
|
||||||
WEB_DIR = Path(__file__).parent
|
WEB_DIR = Path(__file__).parent
|
||||||
|
|
||||||
@@ -36,46 +37,162 @@ class AppState:
|
|||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.server_api = ServerAPI()
|
self.server_api = ServerAPI()
|
||||||
self.browser = BrowserManager()
|
self.browser = BrowserManager()
|
||||||
self.ai = AIClient()
|
self.ai = AIClient(self.server_api)
|
||||||
self.applicant: Applicant | None = None
|
self.applicant: Applicant | None = None
|
||||||
|
self.activator: Activator | None = None
|
||||||
self.connected = False # 是否已注册/登录云端
|
self.connected = False # 是否已注册/登录云端
|
||||||
self.login_polling = False
|
self.login_polling = False
|
||||||
self._heartbeat_started = False
|
self._control_started = False
|
||||||
|
self._boss_login = "unknown" # Boss 登录状态缓存(控制线程周期刷新)
|
||||||
|
|
||||||
def ensure_applicant(self) -> Applicant:
|
def ensure_applicant(self) -> Applicant:
|
||||||
if self.applicant is None:
|
if self.applicant is None:
|
||||||
self.applicant = Applicant(self.browser, self.server_api, self.ai)
|
self.applicant = Applicant(self.browser, self.server_api, self.ai)
|
||||||
return self.applicant
|
return self.applicant
|
||||||
|
|
||||||
# ------------------------------------------------------------------
|
def ensure_activator(self) -> Activator:
|
||||||
# 心跳:登录成功后启动后台线程,周期性向服务端上报存活
|
if self.activator is None:
|
||||||
# ------------------------------------------------------------------
|
self.activator = Activator(self.browser)
|
||||||
def ensure_heartbeat(self) -> None:
|
return self.activator
|
||||||
if self._heartbeat_started or not self.server_api.token:
|
|
||||||
return
|
|
||||||
self._heartbeat_started = True
|
|
||||||
threading.Thread(target=self._heartbeat_loop, daemon=True).start()
|
|
||||||
logger.info(f"心跳线程已启动,间隔 {client_settings.HEARTBEAT_INTERVAL}s")
|
|
||||||
|
|
||||||
def _heartbeat_loop(self) -> None:
|
# ------------------------------------------------------------------
|
||||||
|
# 控制线程:登录成功后启动,5s 一轮 = 心跳带全量状态 + outbox 补发 + 远程任务轮询
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def ensure_control(self) -> None:
|
||||||
|
if self._control_started or not self.server_api.token:
|
||||||
|
return
|
||||||
|
self._control_started = True
|
||||||
|
threading.Thread(target=self._control_loop, daemon=True).start()
|
||||||
|
logger.info("控制线程已启动(状态上报/outbox 补发/远程任务轮询,间隔 5s)")
|
||||||
|
|
||||||
|
def _control_loop(self) -> None:
|
||||||
|
rounds = 0
|
||||||
while True:
|
while True:
|
||||||
if not self.server_api.token:
|
if not self.server_api.token:
|
||||||
# 已退出登录,停止心跳
|
# 已退出登录,停止控制线程
|
||||||
self._heartbeat_started = False
|
self._control_started = False
|
||||||
logger.info("已退出登录,心跳停止")
|
logger.info("已退出登录,控制线程停止")
|
||||||
break
|
break
|
||||||
self.server_api.heartbeat()
|
try:
|
||||||
# 心跳每轮顺便补发 outbox(网络恢复后自动补齐丢失记录)
|
self.server_api.heartbeat(self._collect_status(rounds))
|
||||||
|
except Exception as e:
|
||||||
|
logger.debug(f"状态上报失败:{e}")
|
||||||
try:
|
try:
|
||||||
outbox.flush(self.server_api)
|
outbox.flush(self.server_api)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.debug(f"outbox 补发轮异常:{e}")
|
logger.debug(f"outbox 补发轮异常:{e}")
|
||||||
time.sleep(client_settings.HEARTBEAT_INTERVAL)
|
try:
|
||||||
|
self._poll_remote_task()
|
||||||
|
except Exception as e:
|
||||||
|
logger.debug(f"远程任务轮询异常:{e}")
|
||||||
|
rounds += 1
|
||||||
|
time.sleep(5)
|
||||||
|
|
||||||
|
def _collect_status(self, rounds: int) -> dict:
|
||||||
|
"""采集 RPA 全量状态,随心跳上报(每用户单设备,服务端一行快照)"""
|
||||||
|
# 每 6 轮(约 30s)活体刷新 Boss 登录状态,其余轮次用缓存
|
||||||
|
if rounds % 6 == 0:
|
||||||
|
try:
|
||||||
|
if self.browser.is_browser_running():
|
||||||
|
new = "logged_in" if self.browser.check_boss_login() else "not_login"
|
||||||
|
else:
|
||||||
|
new = "not_login"
|
||||||
|
if new != self._boss_login:
|
||||||
|
self._boss_login = new
|
||||||
|
# 与云端 User.login_status 保持一致
|
||||||
|
try:
|
||||||
|
if new == "logged_in":
|
||||||
|
self.server_api.update_login_status("logged_in",
|
||||||
|
self.browser.get_boss_account_name())
|
||||||
|
else:
|
||||||
|
self.server_api.update_login_status("not_login")
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
except Exception as e:
|
||||||
|
logger.debug(f"Boss 登录状态刷新失败:{e}")
|
||||||
|
applying = bool(self.applicant and self.applicant.is_running)
|
||||||
|
stats = self.applicant.stats if self.applicant else {}
|
||||||
|
return {
|
||||||
|
"boss_login": self._boss_login,
|
||||||
|
"browser": "running" if self.browser.is_browser_running() else "stopped",
|
||||||
|
"apply_status": "running" if applying else "idle",
|
||||||
|
"current": (stats.get("current") or "") if applying else "",
|
||||||
|
"applied": stats.get("applied", 0),
|
||||||
|
"skipped": stats.get("skipped", 0),
|
||||||
|
}
|
||||||
|
|
||||||
|
def _poll_remote_task(self) -> None:
|
||||||
|
"""拉取并执行云端下发的远程控制任务,执行完回调终态"""
|
||||||
|
task = self.server_api.fetch_pending_task()
|
||||||
|
if not task:
|
||||||
|
return
|
||||||
|
tid, ttype = task["id"], task["task_type"]
|
||||||
|
logger.info(f"收到远程任务 #{tid}:{ttype}")
|
||||||
|
try:
|
||||||
|
if ttype == "start_apply":
|
||||||
|
res = start_apply_shared(task.get("params") or {})
|
||||||
|
status, result = ("done", res["msg"]) if res["ok"] else ("failed", res["msg"])
|
||||||
|
elif ttype == "stop_apply":
|
||||||
|
applicant = self.ensure_applicant()
|
||||||
|
if applicant.is_running:
|
||||||
|
applicant.stop()
|
||||||
|
status, result = "done", "停止指令已下达"
|
||||||
|
else:
|
||||||
|
status, result = "done", "当前没有运行中的投递任务"
|
||||||
|
elif ttype == "start_activate":
|
||||||
|
# 定时调度器下发的 Boss 激活任务(与面板 /api/start-activate 同一入口)
|
||||||
|
res = start_activate_shared(task.get("params") or {})
|
||||||
|
status, result = ("done", res["msg"]) if res["ok"] else ("failed", res["msg"])
|
||||||
|
elif ttype == "stop_activate":
|
||||||
|
activator = self.ensure_activator()
|
||||||
|
if activator.is_running:
|
||||||
|
activator.stop()
|
||||||
|
status, result = "done", "停止指令已下达"
|
||||||
|
else:
|
||||||
|
status, result = "done", "当前没有运行中的激活任务"
|
||||||
|
else:
|
||||||
|
status, result = "failed", f"未知任务类型:{ttype}"
|
||||||
|
except Exception as e:
|
||||||
|
status, result = "failed", f"执行异常:{e}"
|
||||||
|
logger.info(f"远程任务 #{tid} 执行结果:{status} - {result}")
|
||||||
|
try:
|
||||||
|
self.server_api.finish_task(tid, status, result)
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"远程任务回调失败 #{tid}:{e}")
|
||||||
|
|
||||||
|
|
||||||
state = AppState()
|
state = AppState()
|
||||||
|
|
||||||
|
|
||||||
|
def start_apply_shared(params: dict) -> dict:
|
||||||
|
"""面板 / 远程任务共用的启动入口(返回 ok+msg,不抛业务异常)"""
|
||||||
|
if state.activator and state.activator.is_running:
|
||||||
|
return {"ok": False, "msg": "Boss 激活任务运行中,请先停止"}
|
||||||
|
if not state.server_api.get_primary_resume():
|
||||||
|
return {"ok": False, "msg": "请先设置主简历"}
|
||||||
|
try:
|
||||||
|
# 浏览器可能被用户手动关闭,投递前确保已拉起(复用登录态 profile)
|
||||||
|
state.browser.ensure_browser_started()
|
||||||
|
except RuntimeError as e:
|
||||||
|
return {"ok": False, "msg": str(e)}
|
||||||
|
applicant = state.ensure_applicant()
|
||||||
|
if applicant.is_running:
|
||||||
|
return {"ok": False, "msg": "已有投递任务在运行"}
|
||||||
|
applicant.start(
|
||||||
|
keywords=list(params.get("keywords") or []),
|
||||||
|
city=str(params.get("city") or ""),
|
||||||
|
salary_min=params.get("salary_min"),
|
||||||
|
salary_max=params.get("salary_max"),
|
||||||
|
min_score=int(params.get("min_score") or 65),
|
||||||
|
delay_range=(int(params.get("delay_min") or 3), int(params.get("delay_max") or 8)),
|
||||||
|
boss_online_only=bool(params.get("boss_online_only")),
|
||||||
|
daily_limit=int(params.get("daily_limit") or 0),
|
||||||
|
allow_headhunter=bool(params.get("allow_headhunter")),
|
||||||
|
prompt=params.get("prompt"),
|
||||||
|
)
|
||||||
|
return {"ok": True, "msg": "投递任务已启动", "session_id": applicant.session_id}
|
||||||
|
|
||||||
|
|
||||||
# =======================================================
|
# =======================================================
|
||||||
# 前置校验(收敛:所有需要已登录云端的路由统一走这里)
|
# 前置校验(收敛:所有需要已登录云端的路由统一走这里)
|
||||||
# =======================================================
|
# =======================================================
|
||||||
@@ -111,7 +228,7 @@ class AuthReq(BaseModel):
|
|||||||
|
|
||||||
class StartApplyReq(BaseModel):
|
class StartApplyReq(BaseModel):
|
||||||
keywords: list[str]
|
keywords: list[str]
|
||||||
city_code: str
|
city: str
|
||||||
salary_min: int | None = None
|
salary_min: int | None = None
|
||||||
salary_max: int | None = None
|
salary_max: int | None = None
|
||||||
min_score: int = 65
|
min_score: int = 65
|
||||||
@@ -120,6 +237,7 @@ class StartApplyReq(BaseModel):
|
|||||||
boss_online_only: bool = False
|
boss_online_only: bool = False
|
||||||
daily_limit: int = 0
|
daily_limit: int = 0
|
||||||
allow_headhunter: bool = False
|
allow_headhunter: bool = False
|
||||||
|
prompt: str | None = None
|
||||||
|
|
||||||
|
|
||||||
class ResumeUpdateReq(BaseModel):
|
class ResumeUpdateReq(BaseModel):
|
||||||
@@ -128,6 +246,15 @@ class ResumeUpdateReq(BaseModel):
|
|||||||
content: str | None = None
|
content: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class StartActivateReq(BaseModel):
|
||||||
|
match_text: str # 匹配条件文本(最后一条消息与之比对)
|
||||||
|
status_filter: str = "unread" # 消息状态过滤:unread=仅未读 / read=仅已读 / all=不限
|
||||||
|
threshold: int = 80 # 相似度阈值(0-100)
|
||||||
|
reply_message: str # 命中后发送的自定义消息
|
||||||
|
max_count: int = 20 # 单次任务发送上限(0=不限)
|
||||||
|
dry_run: bool = False # 试跑:只识别命中,不真正发送
|
||||||
|
|
||||||
|
|
||||||
# =======================================================
|
# =======================================================
|
||||||
# 页面
|
# 页面
|
||||||
# =======================================================
|
# =======================================================
|
||||||
@@ -148,7 +275,7 @@ def get_status():
|
|||||||
try:
|
try:
|
||||||
me = state.server_api.get_me()
|
me = state.server_api.get_me()
|
||||||
state.connected = True
|
state.connected = True
|
||||||
state.ensure_heartbeat() # token 有效时确保心跳线程在跑
|
state.ensure_control() # token 有效时确保控制线程在跑
|
||||||
except Exception:
|
except Exception:
|
||||||
state.connected = False
|
state.connected = False
|
||||||
state.server_api.logout() # token 失效,清除本地缓存
|
state.server_api.logout() # token 失效,清除本地缓存
|
||||||
@@ -200,7 +327,7 @@ def register(req: AuthReq):
|
|||||||
try:
|
try:
|
||||||
data = state.server_api.register(req.username, req.password, req.nickname)
|
data = state.server_api.register(req.username, req.password, req.nickname)
|
||||||
state.connected = True
|
state.connected = True
|
||||||
state.ensure_heartbeat()
|
state.ensure_control()
|
||||||
return {"ok": True, "user_id": data["user_id"], "username": data["username"]}
|
return {"ok": True, "user_id": data["user_id"], "username": data["username"]}
|
||||||
except requests.HTTPError as e:
|
except requests.HTTPError as e:
|
||||||
raise HTTPException(status_code=e.response.status_code, detail=_extract_error(e))
|
raise HTTPException(status_code=e.response.status_code, detail=_extract_error(e))
|
||||||
@@ -214,7 +341,7 @@ def login(req: AuthReq):
|
|||||||
try:
|
try:
|
||||||
data = state.server_api.login(req.username, req.password)
|
data = state.server_api.login(req.username, req.password)
|
||||||
state.connected = True
|
state.connected = True
|
||||||
state.ensure_heartbeat()
|
state.ensure_control()
|
||||||
return {"ok": True, "user_id": data["user_id"], "username": data["username"]}
|
return {"ok": True, "user_id": data["user_id"], "username": data["username"]}
|
||||||
except requests.HTTPError as e:
|
except requests.HTTPError as e:
|
||||||
raise HTTPException(status_code=e.response.status_code, detail=_extract_error(e))
|
raise HTTPException(status_code=e.response.status_code, detail=_extract_error(e))
|
||||||
@@ -377,30 +504,10 @@ def delete_resume(resume_id: int):
|
|||||||
def start_apply(req: StartApplyReq):
|
def start_apply(req: StartApplyReq):
|
||||||
_require_auth()
|
_require_auth()
|
||||||
_require_rpa_online() # 在线预检:与服务端 require_online_user 前置校验呼应
|
_require_rpa_online() # 在线预检:与服务端 require_online_user 前置校验呼应
|
||||||
if not state.server_api.get_primary_resume():
|
res = start_apply_shared(req.model_dump())
|
||||||
raise HTTPException(status_code=400, detail="请先设置主简历")
|
if not res["ok"]:
|
||||||
try:
|
raise HTTPException(status_code=400, detail=res["msg"])
|
||||||
# 浏览器可能被用户手动关闭,投递前确保已拉起(复用登录态 profile)
|
return {"ok": True, "session_id": res.get("session_id")}
|
||||||
state.browser.ensure_browser_started()
|
|
||||||
except RuntimeError as e:
|
|
||||||
raise HTTPException(status_code=400, detail=str(e))
|
|
||||||
|
|
||||||
applicant = state.ensure_applicant()
|
|
||||||
if applicant.is_running:
|
|
||||||
raise HTTPException(status_code=400, detail="已有投递任务在运行")
|
|
||||||
|
|
||||||
applicant.start(
|
|
||||||
keywords=req.keywords,
|
|
||||||
city_code=req.city_code,
|
|
||||||
salary_min=req.salary_min,
|
|
||||||
salary_max=req.salary_max,
|
|
||||||
min_score=req.min_score,
|
|
||||||
delay_range=(req.delay_min, req.delay_max),
|
|
||||||
boss_online_only=req.boss_online_only,
|
|
||||||
daily_limit=req.daily_limit,
|
|
||||||
allow_headhunter=req.allow_headhunter,
|
|
||||||
)
|
|
||||||
return {"ok": True, "session_id": applicant.session_id}
|
|
||||||
|
|
||||||
|
|
||||||
@app.post("/api/stop-apply")
|
@app.post("/api/stop-apply")
|
||||||
@@ -412,6 +519,111 @@ def stop_apply():
|
|||||||
return {"ok": True, "msg": "正在停止投递任务..."}
|
return {"ok": True, "msg": "正在停止投递任务..."}
|
||||||
|
|
||||||
|
|
||||||
|
# =======================================================
|
||||||
|
# Boss 激活(单机功能,不依赖云端账号;也支持定时调度器远程下发)
|
||||||
|
# =======================================================
|
||||||
|
def start_activate_shared(params: dict) -> dict:
|
||||||
|
"""面板 / 远程定时任务共用的激活启动入口(返回 ok+msg,不抛业务异常)"""
|
||||||
|
match_text = (params.get("match_text") or "").strip()
|
||||||
|
if not match_text:
|
||||||
|
return {"ok": False, "msg": "缺少匹配条件文本 match_text"}
|
||||||
|
reply_message = (params.get("reply_message") or "").strip()
|
||||||
|
if not reply_message:
|
||||||
|
return {"ok": False, "msg": "缺少激活消息 reply_message"}
|
||||||
|
status_filter = params.get("status_filter") or "unread"
|
||||||
|
if status_filter not in ("unread", "read", "all"):
|
||||||
|
return {"ok": False, "msg": f"消息状态过滤取值非法:{status_filter}"}
|
||||||
|
try:
|
||||||
|
threshold = max(0, min(100, int(params.get("threshold") or 80)))
|
||||||
|
max_count = max(0, int(params.get("max_count") or 0))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return {"ok": False, "msg": "threshold / max_count 参数非法"}
|
||||||
|
if state.applicant and state.applicant.is_running:
|
||||||
|
return {"ok": False, "msg": "投递任务运行中,请先停止"}
|
||||||
|
activator = state.ensure_activator()
|
||||||
|
if activator.is_running:
|
||||||
|
return {"ok": False, "msg": "已有激活任务在运行"}
|
||||||
|
try:
|
||||||
|
# 复用登录态 profile,浏览器被手动关闭时自动拉起
|
||||||
|
state.browser.ensure_browser_started()
|
||||||
|
except RuntimeError as e:
|
||||||
|
return {"ok": False, "msg": str(e)}
|
||||||
|
activator.start(
|
||||||
|
match_text=match_text,
|
||||||
|
status_filter=status_filter,
|
||||||
|
threshold=threshold / 100.0,
|
||||||
|
reply_message=reply_message,
|
||||||
|
max_count=max_count,
|
||||||
|
dry_run=bool(params.get("dry_run")),
|
||||||
|
)
|
||||||
|
return {"ok": True, "msg": "Boss 激活任务已启动"}
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/start-activate")
|
||||||
|
def start_activate(req: StartActivateReq):
|
||||||
|
# Pydantic 已校验字段类型,业务校验统一在 shared 入口(与远程定时任务同源)
|
||||||
|
res = start_activate_shared(req.model_dump())
|
||||||
|
if not res["ok"]:
|
||||||
|
raise HTTPException(status_code=400, detail=res["msg"])
|
||||||
|
return {"ok": True, "msg": res["msg"]}
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/stop-activate")
|
||||||
|
def stop_activate():
|
||||||
|
activator = state.ensure_activator()
|
||||||
|
if not activator.is_running:
|
||||||
|
return {"ok": False, "msg": "当前没有运行中的激活任务"}
|
||||||
|
activator.stop()
|
||||||
|
return {"ok": True, "msg": "正在停止激活任务..."}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/activate-status")
|
||||||
|
def activate_status():
|
||||||
|
activator = state.activator
|
||||||
|
if activator is None:
|
||||||
|
return {"running": False, "stats": None}
|
||||||
|
return {"running": activator.is_running, "stats": activator.stats}
|
||||||
|
|
||||||
|
|
||||||
|
# =======================================================
|
||||||
|
# 投递条件模板(服务端持久化)
|
||||||
|
# =======================================================
|
||||||
|
@app.get("/api/templates")
|
||||||
|
def list_templates():
|
||||||
|
_require_auth()
|
||||||
|
try:
|
||||||
|
return state.server_api.list_templates()
|
||||||
|
except requests.HTTPError as e:
|
||||||
|
raise HTTPException(status_code=e.response.status_code, detail=_extract_error(e))
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/templates")
|
||||||
|
def create_template(req: dict):
|
||||||
|
_require_auth()
|
||||||
|
try:
|
||||||
|
return state.server_api.create_template(req)
|
||||||
|
except requests.HTTPError as e:
|
||||||
|
raise HTTPException(status_code=e.response.status_code, detail=_extract_error(e))
|
||||||
|
|
||||||
|
|
||||||
|
@app.put("/api/templates/{template_id}")
|
||||||
|
def update_template(template_id: int, req: dict):
|
||||||
|
_require_auth()
|
||||||
|
try:
|
||||||
|
return state.server_api.update_template(template_id, req)
|
||||||
|
except requests.HTTPError as e:
|
||||||
|
raise HTTPException(status_code=e.response.status_code, detail=_extract_error(e))
|
||||||
|
|
||||||
|
|
||||||
|
@app.delete("/api/templates/{template_id}")
|
||||||
|
def delete_template(template_id: int):
|
||||||
|
_require_auth()
|
||||||
|
try:
|
||||||
|
return state.server_api.delete_template(template_id)
|
||||||
|
except requests.HTTPError as e:
|
||||||
|
raise HTTPException(status_code=e.response.status_code, detail=_extract_error(e))
|
||||||
|
|
||||||
|
|
||||||
@app.get("/api/apply-status")
|
@app.get("/api/apply-status")
|
||||||
def apply_status():
|
def apply_status():
|
||||||
applicant = state.applicant
|
applicant = state.applicant
|
||||||
|
|||||||
@@ -0,0 +1,79 @@
|
|||||||
|
// ==========================================================
|
||||||
|
// Boss 激活(单机功能):顶层菜单切换 + 激活任务控制与进度轮询
|
||||||
|
// ==========================================================
|
||||||
|
(function () {
|
||||||
|
const items = document.querySelectorAll("#modeMenu .mode-item");
|
||||||
|
const applyMode = $("applyMode");
|
||||||
|
const activateMode = $("activateMode");
|
||||||
|
|
||||||
|
// 顶层菜单切换
|
||||||
|
items.forEach(it => it.addEventListener("click", () => {
|
||||||
|
items.forEach(x => x.classList.toggle("active", x === it));
|
||||||
|
const mode = it.dataset.mode;
|
||||||
|
applyMode.classList.toggle("hidden", mode !== "apply");
|
||||||
|
activateMode.classList.toggle("hidden", mode !== "activate");
|
||||||
|
}));
|
||||||
|
|
||||||
|
// ------------------------------------------------------------
|
||||||
|
// 激活任务
|
||||||
|
// ------------------------------------------------------------
|
||||||
|
let actTimer = null;
|
||||||
|
|
||||||
|
async function pollActivate() {
|
||||||
|
try {
|
||||||
|
const r = await api("/api/activate-status");
|
||||||
|
setActivateUI(r.running, r.stats);
|
||||||
|
} catch (e) { /* 轮询失败忽略 */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
function setActivateUI(running, stats) {
|
||||||
|
$("btnStartActivate").classList.toggle("hidden", running);
|
||||||
|
$("btnStopActivate").classList.toggle("hidden", !running);
|
||||||
|
$("actProgressBox").classList.toggle("hidden", !running && !stats);
|
||||||
|
if (stats) {
|
||||||
|
$("actProgressCurrent").textContent = stats.current || "";
|
||||||
|
$("actStatScanned").textContent = stats.scanned || 0;
|
||||||
|
$("actStatSent").textContent = stats.sent || 0;
|
||||||
|
$("actStatSkipped").textContent = stats.skipped || 0;
|
||||||
|
}
|
||||||
|
if (running && !actTimer) {
|
||||||
|
actTimer = setInterval(pollActivate, 2000);
|
||||||
|
} else if (!running && actTimer) {
|
||||||
|
clearInterval(actTimer);
|
||||||
|
actTimer = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$("btnStartActivate").addEventListener("click", async () => {
|
||||||
|
const match_text = $("actMatchText").value.trim();
|
||||||
|
const reply_message = $("actReplyMessage").value.trim();
|
||||||
|
if (!match_text) return toast("请填写匹配条件文本");
|
||||||
|
if (!reply_message) return toast("请填写激活消息");
|
||||||
|
try {
|
||||||
|
const r = await api("/api/start-activate", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({
|
||||||
|
match_text,
|
||||||
|
status_filter: $("actStatusFilter").value,
|
||||||
|
threshold: parseInt($("actThreshold").value, 10) || 80,
|
||||||
|
reply_message,
|
||||||
|
max_count: parseInt($("actMaxCount").value, 10) || 0,
|
||||||
|
dry_run: $("actDryRun").checked,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
toast(r.msg || "激活任务已启动");
|
||||||
|
setActivateUI(true, null);
|
||||||
|
pollActivate();
|
||||||
|
} catch (e) { toast("启动失败:" + e.message); }
|
||||||
|
});
|
||||||
|
|
||||||
|
$("btnStopActivate").addEventListener("click", async () => {
|
||||||
|
try {
|
||||||
|
const r = await api("/api/stop-activate", { method: "POST" });
|
||||||
|
toast(r.msg);
|
||||||
|
} catch (e) { toast("停止失败:" + e.message); }
|
||||||
|
});
|
||||||
|
|
||||||
|
// 初始状态轮询(页面加载时若任务运行中则恢复进度条)
|
||||||
|
pollActivate();
|
||||||
|
})();
|
||||||
+154
-2
@@ -26,6 +26,7 @@ function goToStep(step) {
|
|||||||
}
|
}
|
||||||
if (step === 2) detectBossLogin(); // 进入 Boss登录 步骤自动活体检测
|
if (step === 2) detectBossLogin(); // 进入 Boss登录 步骤自动活体检测
|
||||||
if (step === 3) loadResumes();
|
if (step === 3) loadResumes();
|
||||||
|
if (step === 4) loadTemplates();
|
||||||
if (step === 5) loadHistory();
|
if (step === 5) loadHistory();
|
||||||
}
|
}
|
||||||
document.querySelectorAll('.step').forEach(el => {
|
document.querySelectorAll('.step').forEach(el => {
|
||||||
@@ -372,13 +373,14 @@ $('btnStartApply').addEventListener('click', async () => {
|
|||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
keywords,
|
keywords,
|
||||||
city_code: $('cityCode').value,
|
city: $('city').value,
|
||||||
salary_min: parseInt($('salaryMin').value) || null,
|
salary_min: parseInt($('salaryMin').value) || null,
|
||||||
salary_max: parseInt($('salaryMax').value) || null,
|
salary_max: parseInt($('salaryMax').value) || null,
|
||||||
min_score: parseInt($('minScore').value) || 65,
|
min_score: parseInt($('minScore').value) || 65,
|
||||||
boss_online_only: $('bossOnlineOnly').checked,
|
boss_online_only: $('bossOnlineOnly').checked,
|
||||||
allow_headhunter: $('allowHeadhunter').checked,
|
allow_headhunter: false, // TODO: 猎头功能暂时隐藏(工作流有问题),恢复时改回 $('allowHeadhunter').checked
|
||||||
daily_limit: parseInt($('dailyLimit').value) || 0,
|
daily_limit: parseInt($('dailyLimit').value) || 0,
|
||||||
|
prompt: $('prompt').value.trim() || null,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
toast('投递任务已启动');
|
toast('投递任务已启动');
|
||||||
@@ -397,6 +399,156 @@ $('btnStopApply').addEventListener('click', async () => {
|
|||||||
} catch (e) { toast('停止失败:' + e.message); }
|
} catch (e) { toast('停止失败:' + e.message); }
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ==========================================================
|
||||||
|
// 投递模板管理
|
||||||
|
// ==========================================================
|
||||||
|
let templatesCache = [];
|
||||||
|
let editingTemplateId = null;
|
||||||
|
|
||||||
|
async function loadTemplates() {
|
||||||
|
try {
|
||||||
|
templatesCache = await api('/api/templates') || [];
|
||||||
|
const select = $('templateSelect');
|
||||||
|
select.innerHTML = '<option value="">-- 不使用模板 --</option>';
|
||||||
|
templatesCache.forEach(t => {
|
||||||
|
const opt = document.createElement('option');
|
||||||
|
opt.value = t.id;
|
||||||
|
opt.textContent = t.name;
|
||||||
|
select.appendChild(opt);
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
console.error('加载模板失败', e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function fillApplyForm(t) {
|
||||||
|
$('keywords').value = (t.keywords || '').replace(/,/g, ', ');
|
||||||
|
$('city').value = t.city || '北京';
|
||||||
|
$('salaryMin').value = t.salary_min || '';
|
||||||
|
$('salaryMax').value = t.salary_max || '';
|
||||||
|
$('minScore').value = t.min_score || 65;
|
||||||
|
$('dailyLimit').value = t.daily_limit || 30;
|
||||||
|
$('bossOnlineOnly').checked = !!t.boss_online_only;
|
||||||
|
// TODO: 猎头功能隐藏期间强制置为未勾选(忽略模板里的旧值)
|
||||||
|
$('allowHeadhunter').checked = false;
|
||||||
|
$('prompt').value = t.prompt || '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function collectTemplateFromForm() {
|
||||||
|
return {
|
||||||
|
keywords: $('keywords').value.split(',').map(k => k.trim()).filter(Boolean).join(','),
|
||||||
|
city: $('city').value,
|
||||||
|
salary_min: parseInt($('salaryMin').value) || null,
|
||||||
|
salary_max: parseInt($('salaryMax').value) || null,
|
||||||
|
min_score: parseInt($('minScore').value) || 65,
|
||||||
|
daily_limit: parseInt($('dailyLimit').value) || 0,
|
||||||
|
boss_online_only: $('bossOnlineOnly').checked,
|
||||||
|
// TODO: 猎头功能隐藏期间保存模板时强制 false(恢复时改回 $('allowHeadhunter').checked)
|
||||||
|
allow_headhunter: false,
|
||||||
|
prompt: $('prompt').value.trim() || null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
$('templateSelect').addEventListener('change', () => {
|
||||||
|
const id = $('templateSelect').value;
|
||||||
|
if (!id) return;
|
||||||
|
const t = templatesCache.find(x => String(x.id) === id);
|
||||||
|
if (t) fillApplyForm(t);
|
||||||
|
});
|
||||||
|
|
||||||
|
$('btnSaveTemplate').addEventListener('click', () => {
|
||||||
|
editingTemplateId = null;
|
||||||
|
$('templateName').value = '';
|
||||||
|
$('saveTemplateModal').classList.remove('hidden');
|
||||||
|
});
|
||||||
|
|
||||||
|
$('btnCancelSaveTemplate').addEventListener('click', () => {
|
||||||
|
$('saveTemplateModal').classList.add('hidden');
|
||||||
|
});
|
||||||
|
|
||||||
|
$('btnConfirmSaveTemplate').addEventListener('click', async () => {
|
||||||
|
const name = $('templateName').value.trim();
|
||||||
|
if (!name) { toast('请输入模板名称'); return; }
|
||||||
|
const data = { name, ...collectTemplateFromForm() };
|
||||||
|
try {
|
||||||
|
if (editingTemplateId) {
|
||||||
|
await api(`/api/templates/${editingTemplateId}`, { method: 'PUT', body: JSON.stringify(data) });
|
||||||
|
toast('模板已更新');
|
||||||
|
} else {
|
||||||
|
await api('/api/templates', { method: 'POST', body: JSON.stringify(data) });
|
||||||
|
toast('模板已保存');
|
||||||
|
}
|
||||||
|
$('saveTemplateModal').classList.add('hidden');
|
||||||
|
await loadTemplates();
|
||||||
|
} catch (e) {
|
||||||
|
toast('保存失败:' + e.message, 5000);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
$('btnManageTemplates').addEventListener('click', async () => {
|
||||||
|
await renderTemplatesList();
|
||||||
|
$('manageTemplatesModal').classList.remove('hidden');
|
||||||
|
});
|
||||||
|
|
||||||
|
$('btnCloseManageTemplates').addEventListener('click', () => {
|
||||||
|
$('manageTemplatesModal').classList.add('hidden');
|
||||||
|
});
|
||||||
|
|
||||||
|
async function renderTemplatesList() {
|
||||||
|
await loadTemplates();
|
||||||
|
const tbody = $('templatesBody');
|
||||||
|
if (!templatesCache.length) {
|
||||||
|
tbody.innerHTML = '<tr><td colspan="4" style="text-align:center;color:#999">暂无模板</td></tr>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
tbody.innerHTML = templatesCache.map(t => `
|
||||||
|
<tr>
|
||||||
|
<td>${escapeHtml(t.name)}</td>
|
||||||
|
<td>${escapeHtml(t.keywords || '-')}</td>
|
||||||
|
<td>${escapeHtml(t.city || '-')}</td>
|
||||||
|
<td>
|
||||||
|
<button class="btn btn-sm" data-tid="${t.id}" data-action="apply">套用</button>
|
||||||
|
<button class="btn btn-sm" data-tid="${t.id}" data-action="edit">编辑</button>
|
||||||
|
<button class="btn btn-sm btn-danger" data-tid="${t.id}" data-action="delete">删除</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
`).join('');
|
||||||
|
tbody.querySelectorAll('button').forEach(b => {
|
||||||
|
b.addEventListener('click', handleTemplateAction);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleTemplateAction(e) {
|
||||||
|
const tid = parseInt(e.target.dataset.tid);
|
||||||
|
const action = e.target.dataset.action;
|
||||||
|
if (action === 'apply') {
|
||||||
|
const t = templatesCache.find(x => x.id === tid);
|
||||||
|
if (t) {
|
||||||
|
fillApplyForm(t);
|
||||||
|
$('templateSelect').value = tid;
|
||||||
|
$('manageTemplatesModal').classList.add('hidden');
|
||||||
|
toast('已套用模板:' + t.name);
|
||||||
|
}
|
||||||
|
} else if (action === 'edit') {
|
||||||
|
const t = templatesCache.find(x => x.id === tid);
|
||||||
|
if (!t) return;
|
||||||
|
editingTemplateId = tid;
|
||||||
|
$('templateName').value = t.name;
|
||||||
|
fillApplyForm(t);
|
||||||
|
$('manageTemplatesModal').classList.add('hidden');
|
||||||
|
$('saveTemplateModal').classList.remove('hidden');
|
||||||
|
} else if (action === 'delete') {
|
||||||
|
if (!confirm('确定删除该模板吗?')) return;
|
||||||
|
try {
|
||||||
|
await api(`/api/templates/${tid}`, { method: 'DELETE' });
|
||||||
|
toast('模板已删除');
|
||||||
|
await renderTemplatesList();
|
||||||
|
} catch (e) {
|
||||||
|
toast('删除失败:' + e.message, 5000);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function toggleApplyUI(running) {
|
function toggleApplyUI(running) {
|
||||||
$('btnStartApply').classList.toggle('hidden', running);
|
$('btnStartApply').classList.toggle('hidden', running);
|
||||||
$('btnStopApply').classList.toggle('hidden', !running);
|
$('btnStopApply').classList.toggle('hidden', !running);
|
||||||
|
|||||||
@@ -180,6 +180,7 @@ body {
|
|||||||
.action-buttons { display: flex; gap: 12px; margin-top: 10px; }
|
.action-buttons { display: flex; gap: 12px; margin-top: 10px; }
|
||||||
.btn-outline { background: #fff; border: 1px solid var(--primary); color: var(--primary); }
|
.btn-outline { background: #fff; border: 1px solid var(--primary); color: var(--primary); }
|
||||||
.btn-outline:hover { filter: brightness(.96); }
|
.btn-outline:hover { filter: brightness(.96); }
|
||||||
|
.btn-sm { padding: 3px 8px; font-size: 12px; }
|
||||||
|
|
||||||
/* 登录/注册模式切换引导链接 */
|
/* 登录/注册模式切换引导链接 */
|
||||||
.switch-link {
|
.switch-link {
|
||||||
@@ -349,3 +350,29 @@ body {
|
|||||||
max-width: 80%;
|
max-width: 80%;
|
||||||
}
|
}
|
||||||
.toast.show { transform: translateX(-50%) translateY(0); opacity: 1; }
|
.toast.show { transform: translateX(-50%) translateY(0); opacity: 1; }
|
||||||
|
|
||||||
|
/* ===== 顶层功能菜单(AI投递 / Boss激活) ===== */
|
||||||
|
.mode-menu {
|
||||||
|
display: flex;
|
||||||
|
gap: 8px;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
.mode-item {
|
||||||
|
flex: 1;
|
||||||
|
text-align: center;
|
||||||
|
padding: 12px 8px;
|
||||||
|
background: var(--card);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 8px;
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 15px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--text-light);
|
||||||
|
transition: all .2s;
|
||||||
|
}
|
||||||
|
.mode-item:hover { border-color: var(--primary); }
|
||||||
|
.mode-item.active {
|
||||||
|
background: var(--primary);
|
||||||
|
color: #fff;
|
||||||
|
border-color: var(--primary);
|
||||||
|
}
|
||||||
|
|||||||
+125
-14
@@ -4,7 +4,7 @@
|
|||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
<title>Boss直聘 AI 智能投递</title>
|
<title>Boss直聘 AI 智能投递</title>
|
||||||
<link rel="stylesheet" href="/static/style.css?v=3">
|
<link rel="stylesheet" href="/static/style.css?v=4">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div class="container">
|
<div class="container">
|
||||||
@@ -17,9 +17,16 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="status-badges" id="statusBadges"></div>
|
<div class="status-badges" id="statusBadges"></div>
|
||||||
</header>
|
</header>
|
||||||
|
<!-- 顶层功能菜单 -->
|
||||||
|
<nav class="mode-menu" id="modeMenu">
|
||||||
|
<div class="mode-item active" data-mode="apply">AI 智能投递</div>
|
||||||
|
<div class="mode-item" data-mode="activate">Boss 激活(单机)</div>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
|
||||||
<!-- 步骤导航 -->
|
<!-- 步骤导航 -->
|
||||||
<nav class="steps">
|
<div id="applyMode">
|
||||||
|
<nav class="steps">
|
||||||
<div class="step active" data-step="1"><span class="step-num">1</span> 账号</div>
|
<div class="step active" data-step="1"><span class="step-num">1</span> 账号</div>
|
||||||
<div class="step" data-step="2"><span class="step-num">2</span> Boss登录</div>
|
<div class="step" data-step="2"><span class="step-num">2</span> Boss登录</div>
|
||||||
<div class="step" data-step="3"><span class="step-num">3</span> 简历</div>
|
<div class="step" data-step="3"><span class="step-num">3</span> 简历</div>
|
||||||
@@ -81,6 +88,18 @@
|
|||||||
<!-- Step 4: 配置投递 -->
|
<!-- Step 4: 配置投递 -->
|
||||||
<section class="panel hidden" id="panel-4">
|
<section class="panel hidden" id="panel-4">
|
||||||
<h2>配置并开始投递</h2>
|
<h2>配置并开始投递</h2>
|
||||||
|
<div class="form-row">
|
||||||
|
<div class="form-group" style="flex:3;">
|
||||||
|
<label>选择模板</label>
|
||||||
|
<select id="templateSelect">
|
||||||
|
<option value="">-- 不使用模板 --</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="form-group" style="display:flex;align-items:flex-end;gap:8px;padding-bottom:6px;">
|
||||||
|
<button class="btn btn-outline" id="btnManageTemplates" type="button">管理模板</button>
|
||||||
|
<button class="btn btn-outline" id="btnSaveTemplate" type="button">保存为模板</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label>搜索关键词(多个用逗号分隔)</label>
|
<label>搜索关键词(多个用逗号分隔)</label>
|
||||||
<input type="text" id="keywords" placeholder="如:Python开发,后端工程师" value="Python开发">
|
<input type="text" id="keywords" placeholder="如:Python开发,后端工程师" value="Python开发">
|
||||||
@@ -88,15 +107,15 @@
|
|||||||
<div class="form-row">
|
<div class="form-row">
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label>城市</label>
|
<label>城市</label>
|
||||||
<select id="cityCode">
|
<select id="city">
|
||||||
<option value="101010100">北京</option>
|
<option value="北京">北京</option>
|
||||||
<option value="101020100">上海</option>
|
<option value="上海">上海</option>
|
||||||
<option value="101280100">广州</option>
|
<option value="广州">广州</option>
|
||||||
<option value="101280600">深圳</option>
|
<option value="深圳">深圳</option>
|
||||||
<option value="101210100">杭州</option>
|
<option value="杭州">杭州</option>
|
||||||
<option value="101190100">成都</option>
|
<option value="成都">成都</option>
|
||||||
<option value="101110100">西安</option>
|
<option value="西安">西安</option>
|
||||||
<option value="101120100">济南</option>
|
<option value="济南">济南</option>
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
@@ -123,11 +142,18 @@
|
|||||||
<label style="display:flex;align-items:center;gap:6px;margin:0;cursor:pointer;">
|
<label style="display:flex;align-items:center;gap:6px;margin:0;cursor:pointer;">
|
||||||
<input type="checkbox" id="bossOnlineOnly" style="width:auto;"> 只投递 Boss 在线的
|
<input type="checkbox" id="bossOnlineOnly" style="width:auto;"> 只投递 Boss 在线的
|
||||||
</label>
|
</label>
|
||||||
<label style="display:flex; align-items:center; gap:6px; margin-top:8px;">
|
<!-- TODO: 猎头功能暂时隐藏——当前工作流有问题(猎头职位的识别/筛选流程未跑通),
|
||||||
|
待工作流修复后再恢复展示。隐藏期间 allow_headhunter 在 app.js 中强制为 false,
|
||||||
|
恢复时同步去掉此处 display:none 与 app.js 的三处强制值 -->
|
||||||
|
<label style="display:none; align-items:center; gap:6px; margin-top:8px;">
|
||||||
<input type="checkbox" id="allowHeadhunter" style="width:auto;"> 考虑猎头职位
|
<input type="checkbox" id="allowHeadhunter" style="width:auto;"> 考虑猎头职位
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>AI 引导词(可选,会作为 AI 评分时的额外偏好)</label>
|
||||||
|
<textarea id="prompt" rows="4" placeholder="例如:优先投递 Java 后端岗位,接受 10-15K,有 AI 项目经验优先"></textarea>
|
||||||
|
</div>
|
||||||
<div class="action-buttons">
|
<div class="action-buttons">
|
||||||
<button class="btn btn-success" id="btnStartApply">▶ 开始投递</button>
|
<button class="btn btn-success" id="btnStartApply">▶ 开始投递</button>
|
||||||
<button class="btn btn-danger hidden" id="btnStopApply">■ 结束投递</button>
|
<button class="btn btn-danger hidden" id="btnStopApply">■ 结束投递</button>
|
||||||
@@ -153,7 +179,7 @@
|
|||||||
<span class="chip" data-hrange="month">本月</span>
|
<span class="chip" data-hrange="month">本月</span>
|
||||||
<span class="chip" data-hrange="custom">自定义</span>
|
<span class="chip" data-hrange="custom">自定义</span>
|
||||||
<span id="histCustomRange" class="hidden">
|
<span id="histCustomRange" class="hidden">
|
||||||
<input type="date" id="histDateStart"> ~ <input type="date" id="histDateEnd">
|
<input type="date" id="histDateStart"> 至 <input type="date" id="histDateEnd">
|
||||||
<button class="btn-query" id="btnHistQuery">查询</button>
|
<button class="btn-query" id="btnHistQuery">查询</button>
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
@@ -188,6 +214,58 @@
|
|||||||
<button id="btnHistNext">下一页</button>
|
<button id="btnHistNext">下一页</button>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Boss 激活(单机功能) -->
|
||||||
|
<div id="activateMode" class="hidden">
|
||||||
|
<section class="panel">
|
||||||
|
<h2>Boss 激活</h2>
|
||||||
|
<p class="hint">扫描消息页联系人:最后一条消息符合所选状态、且内容达到下方匹配条件时,自动发送一条激活消息。单机功能,无需登录系统账号。</p>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>匹配条件文本</label>
|
||||||
|
<textarea id="actMatchText" rows="3" placeholder="输入要匹配的消息内容(与对方最后一条消息比对)"></textarea>
|
||||||
|
</div>
|
||||||
|
<div class="form-row">
|
||||||
|
<div class="form-group">
|
||||||
|
<label>消息状态过滤</label>
|
||||||
|
<select id="actStatusFilter">
|
||||||
|
<option value="unread" selected>仅未读([送达]/[未读])</option>
|
||||||
|
<option value="read">仅已读([已读])</option>
|
||||||
|
<option value="all">不限(已读+未读)</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>相似度阈值(%)</label>
|
||||||
|
<input type="number" id="actThreshold" value="80" min="0" max="100">
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>单次发送上限(0=不限)</label>
|
||||||
|
<input type="number" id="actMaxCount" value="20" min="0">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>激活消息(命中后发送)</label>
|
||||||
|
<textarea id="actReplyMessage" rows="4" placeholder="如:您好,请问该岗位还在招聘吗?方便沟通一下吗"></textarea>
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label style="display:flex;align-items:center;gap:6px;margin:0;cursor:pointer;">
|
||||||
|
<input type="checkbox" id="actDryRun" style="width:auto;" checked> 试跑模式(只识别命中,不真正发送)
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div class="action-buttons">
|
||||||
|
<button class="btn btn-success" id="btnStartActivate">开始激活</button>
|
||||||
|
<button class="btn btn-danger hidden" id="btnStopActivate">停止激活</button>
|
||||||
|
</div>
|
||||||
|
<div class="progress-box hidden" id="actProgressBox">
|
||||||
|
<div class="progress-current" id="actProgressCurrent">准备中...</div>
|
||||||
|
<div class="progress-stats">
|
||||||
|
<span>已扫描:<strong id="actStatScanned">0</strong></span>
|
||||||
|
<span>已发送:<strong id="actStatSent">0</strong></span>
|
||||||
|
<span>已跳过:<strong id="actStatSkipped">0</strong></span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- 简历编辑弹窗 -->
|
<!-- 简历编辑弹窗 -->
|
||||||
@@ -209,9 +287,42 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- 保存模板弹窗 -->
|
||||||
|
<div class="modal-mask hidden" id="saveTemplateModal">
|
||||||
|
<div class="modal-box">
|
||||||
|
<h3>保存为模板</h3>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>模板名称</label>
|
||||||
|
<input type="text" id="templateName" placeholder="如:Java 北京 10-15K">
|
||||||
|
</div>
|
||||||
|
<div class="action-buttons">
|
||||||
|
<button class="btn btn-primary" id="btnConfirmSaveTemplate">保 存</button>
|
||||||
|
<button class="btn btn-outline" id="btnCancelSaveTemplate">取 消</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 模板管理弹窗 -->
|
||||||
|
<div class="modal-mask hidden" id="manageTemplatesModal">
|
||||||
|
<div class="modal-box" style="min-width: 680px; max-width: 90vw;">
|
||||||
|
<h3>管理投递模板</h3>
|
||||||
|
<table class="history-table">
|
||||||
|
<thead>
|
||||||
|
<tr><th>名称</th><th>关键词</th><th>城市</th><th>操作</th></tr>
|
||||||
|
</thead>
|
||||||
|
<tbody id="templatesBody"></tbody>
|
||||||
|
</table>
|
||||||
|
<div class="action-buttons">
|
||||||
|
<button class="btn btn-outline" id="btnCloseManageTemplates">关 闭</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<!-- Toast 提示 -->
|
<!-- Toast 提示 -->
|
||||||
<div class="toast" id="toast"></div>
|
<div class="toast" id="toast"></div>
|
||||||
|
|
||||||
<script src="/static/app.js?v=3"></script>
|
<script src="/static/app.js?v=6"></script>
|
||||||
|
<script src="/static/activate.js?v=6"></script>
|
||||||
|
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+6
-1
@@ -11,11 +11,13 @@ services:
|
|||||||
MYSQL_ROOT_PASSWORD: ${DB_PASSWORD:-root123456}
|
MYSQL_ROOT_PASSWORD: ${DB_PASSWORD:-root123456}
|
||||||
MYSQL_DATABASE: ${DB_NAME:-jianli_boss}
|
MYSQL_DATABASE: ${DB_NAME:-jianli_boss}
|
||||||
TZ: Asia/Shanghai
|
TZ: Asia/Shanghai
|
||||||
# 统一 utf8mb4,避免中文乱码
|
# 统一 utf8mb4,避免中文乱码;显式放大 max_allowed_packet(JD 全文归档入库,
|
||||||
|
# 防止大包触发 1153 'Got a packet bigger than max_allowed_packet')
|
||||||
command:
|
command:
|
||||||
- --character-set-server=utf8mb4
|
- --character-set-server=utf8mb4
|
||||||
- --collation-server=utf8mb4_unicode_ci
|
- --collation-server=utf8mb4_unicode_ci
|
||||||
- --default-authentication-plugin=mysql_native_password
|
- --default-authentication-plugin=mysql_native_password
|
||||||
|
- --max-allowed-packet=64M
|
||||||
ports:
|
ports:
|
||||||
- "3306:3306"
|
- "3306:3306"
|
||||||
volumes:
|
volumes:
|
||||||
@@ -53,6 +55,9 @@ services:
|
|||||||
DEBUG: ${DEBUG:-false}
|
DEBUG: ${DEBUG:-false}
|
||||||
ports:
|
ports:
|
||||||
- "8000:8000"
|
- "8000:8000"
|
||||||
|
volumes:
|
||||||
|
# 超长 JD 归档目录持久化(服务端写入 /app/jd_archive/,重建容器不丢文件)
|
||||||
|
- ./jd_archive:/app/jd_archive
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
|
|||||||
+172
-15
@@ -63,9 +63,10 @@ CREATE TABLE IF NOT EXISTS apply_sessions (
|
|||||||
user_id INT NOT NULL,
|
user_id INT NOT NULL,
|
||||||
status VARCHAR(20) NOT NULL DEFAULT 'running' COMMENT '会话状态:running/stopped/finished',
|
status VARCHAR(20) NOT NULL DEFAULT 'running' COMMENT '会话状态:running/stopped/finished',
|
||||||
keywords VARCHAR(512) NULL COMMENT '搜索关键词(逗号分隔)',
|
keywords VARCHAR(512) NULL COMMENT '搜索关键词(逗号分隔)',
|
||||||
city_code VARCHAR(20) NULL COMMENT '城市代码',
|
city VARCHAR(20) NULL COMMENT '城市名称',
|
||||||
salary_min INT NULL COMMENT '最低薪资(K)',
|
salary_min INT NULL COMMENT '最低薪资(K)',
|
||||||
salary_max INT NULL COMMENT '最高薪资(K)',
|
salary_max INT NULL COMMENT '最高薪资(K)',
|
||||||
|
prompt TEXT NULL COMMENT 'AI评分引导词',
|
||||||
applied_count INT NOT NULL DEFAULT 0 COMMENT '本次会话投递数',
|
applied_count INT NOT NULL DEFAULT 0 COMMENT '本次会话投递数',
|
||||||
skipped_count INT NOT NULL DEFAULT 0 COMMENT '本次会话跳过数',
|
skipped_count INT NOT NULL DEFAULT 0 COMMENT '本次会话跳过数',
|
||||||
started_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
started_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
@@ -92,7 +93,8 @@ CREATE TABLE IF NOT EXISTS job_applications (
|
|||||||
ai_score INT NOT NULL DEFAULT -1 COMMENT 'AI匹配评分(-1=未评分)',
|
ai_score INT NOT NULL DEFAULT -1 COMMENT 'AI匹配评分(-1=未评分)',
|
||||||
ai_reason VARCHAR(255) NULL COMMENT 'AI评分理由',
|
ai_reason VARCHAR(255) NULL COMMENT 'AI评分理由',
|
||||||
skip_reason VARCHAR(255) NULL COMMENT '跳过原因',
|
skip_reason VARCHAR(255) NULL COMMENT '跳过原因',
|
||||||
jd_text TEXT NULL COMMENT '职位JD全文(投递/跳过时归档,供复盘与面试准备)',
|
jd_text TEXT NULL COMMENT '职位JD全文(投递/跳过时归档;超长时本列留空、落盘到 jd_archive/,改存 jd_file 路径)',
|
||||||
|
jd_file VARCHAR(255) NULL COMMENT '超长JD归档文件路径(相对项目根目录,如 jd_archive/1_xxx.txt)',
|
||||||
greeting VARCHAR(500) NULL COMMENT '实际发送的打招呼语(仅chat方式有值)',
|
greeting VARCHAR(500) NULL COMMENT '实际发送的打招呼语(仅chat方式有值)',
|
||||||
applied_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '投递时间',
|
applied_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '投递时间',
|
||||||
UNIQUE KEY uq_user_job (user_id, job_id) COMMENT '同一用户不重复投递同一职位',
|
UNIQUE KEY uq_user_job (user_id, job_id) COMMENT '同一用户不重复投递同一职位',
|
||||||
@@ -105,6 +107,30 @@ CREATE TABLE IF NOT EXISTS job_applications (
|
|||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
|
||||||
COMMENT='投递记录';
|
COMMENT='投递记录';
|
||||||
|
|
||||||
|
-- ------------------------------------------------------------
|
||||||
|
-- 5. 投递条件模板(本地面板 + 远程控制共用)
|
||||||
|
-- ------------------------------------------------------------
|
||||||
|
CREATE TABLE IF NOT EXISTS apply_templates (
|
||||||
|
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
user_id INT NOT NULL,
|
||||||
|
name VARCHAR(128) NOT NULL COMMENT '模板名称',
|
||||||
|
keywords VARCHAR(512) NULL COMMENT '搜索关键词(逗号分隔)',
|
||||||
|
city VARCHAR(20) NULL COMMENT '城市名称',
|
||||||
|
salary_min INT NULL COMMENT '最低薪资(K)',
|
||||||
|
salary_max INT NULL COMMENT '最高薪资(K)',
|
||||||
|
min_score INT NOT NULL DEFAULT 65 COMMENT 'AI最低匹配分',
|
||||||
|
daily_limit INT NOT NULL DEFAULT 0 COMMENT '每日投递上限(0=不限)',
|
||||||
|
boss_online_only TINYINT(1) NOT NULL DEFAULT 0 COMMENT '只投递Boss在线的职位',
|
||||||
|
allow_headhunter TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否考虑猎头职位',
|
||||||
|
prompt TEXT NULL COMMENT 'AI评分引导词',
|
||||||
|
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at DATETIME NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
|
KEY ix_apply_templates_user_id (user_id),
|
||||||
|
CONSTRAINT fk_apply_templates_user FOREIGN KEY (user_id)
|
||||||
|
REFERENCES users (id) ON DELETE CASCADE
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
|
||||||
|
COMMENT='投递条件模板';
|
||||||
|
|
||||||
-- ------------------------------------------------------------
|
-- ------------------------------------------------------------
|
||||||
-- 5. 公司黑名单(拉黑后 RPA 不再投递该公司)
|
-- 5. 公司黑名单(拉黑后 RPA 不再投递该公司)
|
||||||
-- ------------------------------------------------------------
|
-- ------------------------------------------------------------
|
||||||
@@ -120,21 +146,152 @@ CREATE TABLE IF NOT EXISTS company_blacklist (
|
|||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
|
||||||
COMMENT='公司黑名单';
|
COMMENT='公司黑名单';
|
||||||
|
|
||||||
-- ============================================================
|
-- ------------------------------------------------------------
|
||||||
-- 附:老库升级脚本(已建过表、缺少新增字段时执行)
|
-- 6. RPA 状态快照(每用户一行,心跳携带全量状态上报)
|
||||||
-- ============================================================
|
-- ------------------------------------------------------------
|
||||||
ALTER TABLE job_applications
|
CREATE TABLE IF NOT EXISTS rpa_status (
|
||||||
ADD COLUMN jd_text TEXT NULL COMMENT '职位JD全文',
|
user_id INT PRIMARY KEY,
|
||||||
ADD COLUMN greeting VARCHAR(500) NULL COMMENT '实际发送的打招呼语';
|
boss_login VARCHAR(20) NOT NULL DEFAULT 'unknown' COMMENT 'Boss登录状态',
|
||||||
|
browser VARCHAR(20) NOT NULL DEFAULT 'unknown' COMMENT '浏览器状态',
|
||||||
|
apply_status VARCHAR(20) NOT NULL DEFAULT 'idle' COMMENT '投递状态 idle/running',
|
||||||
|
current VARCHAR(200) NULL COMMENT '当前进度文本',
|
||||||
|
applied INT NOT NULL DEFAULT 0 COMMENT '本次投递数',
|
||||||
|
skipped INT NOT NULL DEFAULT 0 COMMENT '本次跳过数',
|
||||||
|
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
|
CONSTRAINT fk_rpa_status_user FOREIGN KEY (user_id)
|
||||||
|
REFERENCES users (id) ON DELETE CASCADE
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
|
||||||
|
COMMENT='RPA 状态快照';
|
||||||
|
|
||||||
老库新增公司黑名单表:
|
-- ------------------------------------------------------------
|
||||||
CREATE TABLE IF NOT EXISTS company_blacklist (
|
-- 7. 远程控制任务(云端下发 → 客户端轮询执行 → 回调更新)
|
||||||
|
-- ------------------------------------------------------------
|
||||||
|
CREATE TABLE IF NOT EXISTS rpa_task (
|
||||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||||
user_id INT NOT NULL,
|
user_id INT NOT NULL,
|
||||||
company VARCHAR(128) NOT NULL,
|
task_type VARCHAR(20) NOT NULL COMMENT 'start_apply/stop_apply',
|
||||||
|
params TEXT NULL COMMENT '任务参数 JSON',
|
||||||
|
status VARCHAR(20) NOT NULL DEFAULT 'pending' COMMENT 'pending/running/done/failed/expired',
|
||||||
|
result VARCHAR(500) NULL COMMENT '执行结果',
|
||||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
UNIQUE KEY uq_user_company (user_id, company),
|
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
KEY ix_blacklist_user_id (user_id),
|
KEY ix_rpa_task_user (user_id),
|
||||||
CONSTRAINT fk_blacklist_user FOREIGN KEY (user_id)
|
KEY ix_rpa_task_user_status (user_id, status),
|
||||||
|
CONSTRAINT fk_rpa_task_user FOREIGN KEY (user_id)
|
||||||
REFERENCES users (id) ON DELETE CASCADE
|
REFERENCES users (id) ON DELETE CASCADE
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
|
||||||
|
COMMENT='远程控制任务';
|
||||||
|
|
||||||
|
-- ------------------------------------------------------------
|
||||||
|
-- 7b. 定时任务排程(远程控制页创建,服务端调度器每日到点自动下发 rpa_task)
|
||||||
|
-- ------------------------------------------------------------
|
||||||
|
CREATE TABLE IF NOT EXISTS rpa_schedule (
|
||||||
|
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
user_id INT NOT NULL,
|
||||||
|
kind VARCHAR(20) NOT NULL COMMENT 'apply=自动投递/activate=Boss激活',
|
||||||
|
params TEXT NULL COMMENT '任务参数 JSON(投递条件/激活参数)',
|
||||||
|
start_time VARCHAR(5) NOT NULL COMMENT '每日开始时间 HH:MM(北京时间)',
|
||||||
|
end_time VARCHAR(5) NOT NULL COMMENT '每日结束时间 HH:MM(北京时间)',
|
||||||
|
enabled TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否启用',
|
||||||
|
last_start_date VARCHAR(10) NULL COMMENT '最近开始下发日期(北京 YYYY-MM-DD,防当日重复)',
|
||||||
|
last_stop_date VARCHAR(10) NULL COMMENT '最近结束下发日期(北京 YYYY-MM-DD,防当日重复)',
|
||||||
|
last_result VARCHAR(255) NULL COMMENT '最近一次调度结果说明',
|
||||||
|
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
KEY ix_rpa_schedule_user (user_id),
|
||||||
|
CONSTRAINT fk_rpa_schedule_user FOREIGN KEY (user_id)
|
||||||
|
REFERENCES users (id) ON DELETE CASCADE
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
|
||||||
|
COMMENT='定时任务排程';
|
||||||
|
|
||||||
|
-- ------------------------------------------------------------
|
||||||
|
-- 8. AI 模型配置(全局单行,id=1,/view 管理页在线维护)
|
||||||
|
-- ------------------------------------------------------------
|
||||||
|
CREATE TABLE IF NOT EXISTS ai_config (
|
||||||
|
id INT NOT NULL DEFAULT 1 PRIMARY KEY,
|
||||||
|
base_url VARCHAR(255) NULL COMMENT 'OpenAI兼容接口地址,如 https://api.siliconflow.cn/v1',
|
||||||
|
api_key VARCHAR(255) NULL COMMENT '模型 API Key',
|
||||||
|
model VARCHAR(128) NULL COMMENT '模型名,如 deepseek-ai/DeepSeek-V3',
|
||||||
|
timeout_s INT NOT NULL DEFAULT 300 COMMENT '服务端调用大模型超时(秒)',
|
||||||
|
enabled TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否启用AI代理',
|
||||||
|
updated_at DATETIME NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
|
||||||
|
COMMENT='AI模型配置(全局单行)';
|
||||||
|
|
||||||
|
-- ------------------------------------------------------------
|
||||||
|
-- 9. AI 打分任务(客户端异步评分:开始打分 + 轮询结果)
|
||||||
|
-- request_key 为客户端 uuid1().hex(MAC+时间戳,32 位),故 VARCHAR(32)
|
||||||
|
-- ------------------------------------------------------------
|
||||||
|
CREATE TABLE IF NOT EXISTS ai_score_task (
|
||||||
|
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
user_id INT NOT NULL,
|
||||||
|
request_key VARCHAR(32) NOT NULL COMMENT '幂等键:客户端uuid1().hex(MAC+时间戳,32位)',
|
||||||
|
resume_id INT NULL COMMENT '主简历ID(服务端从库中取内容)',
|
||||||
|
job_ref VARCHAR(64) NULL COMMENT 'Boss职位ID(审计追踪用)',
|
||||||
|
jd_text TEXT NOT NULL COMMENT '职位JD全文(评分输入)',
|
||||||
|
conditions TEXT NULL COMMENT '投递条件JSON:keywords/city/salary_min/salary_max/prompt',
|
||||||
|
status VARCHAR(20) NOT NULL DEFAULT 'pending' COMMENT 'pending/running/success/failed',
|
||||||
|
score INT NULL COMMENT '成功时的匹配分(0-100)',
|
||||||
|
reason VARCHAR(512) NULL COMMENT '成功时一句话评价;失败时失败原因',
|
||||||
|
error TEXT NULL COMMENT '详细错误信息(调试用)',
|
||||||
|
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
finished_at DATETIME NULL,
|
||||||
|
UNIQUE KEY uq_user_request_key (user_id, request_key),
|
||||||
|
KEY idx_user_created (user_id, created_at),
|
||||||
|
CONSTRAINT fk_ai_score_task_user FOREIGN KEY (user_id)
|
||||||
|
REFERENCES users (id) ON DELETE CASCADE,
|
||||||
|
CONSTRAINT fk_ai_score_task_resume FOREIGN KEY (resume_id)
|
||||||
|
REFERENCES resumes (id) ON DELETE SET NULL
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
|
||||||
|
COMMENT='AI打分任务(客户端异步评分)';
|
||||||
|
|
||||||
|
-- -- ============================================================
|
||||||
|
-- -- 附:老库升级脚本(已建过表、缺少新增字段时执行)
|
||||||
|
-- -- ============================================================
|
||||||
|
-- ALTER TABLE job_applications
|
||||||
|
-- ADD COLUMN jd_text TEXT NULL COMMENT '职位JD全文',
|
||||||
|
-- ADD COLUMN greeting VARCHAR(500) NULL COMMENT '实际发送的打招呼语';
|
||||||
|
--
|
||||||
|
-- 老库新增公司黑名单表:
|
||||||
|
-- CREATE TABLE IF NOT EXISTS company_blacklist (
|
||||||
|
-- id INT AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
-- user_id INT NOT NULL,
|
||||||
|
-- company VARCHAR(128) NOT NULL,
|
||||||
|
-- created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
-- UNIQUE KEY uq_user_company (user_id, company),
|
||||||
|
-- KEY ix_blacklist_user_id (user_id),
|
||||||
|
-- CONSTRAINT fk_blacklist_user FOREIGN KEY (user_id)
|
||||||
|
-- REFERENCES users (id) ON DELETE CASCADE
|
||||||
|
-- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- v1.11 老库升级(AI 服务端代理:ai_config + ai_score_task 两表),
|
||||||
|
-- 完整可重复执行版本见 docs/upgrade_1.11.sql。
|
||||||
|
|
||||||
|
-- v1.18 老库升级(job_applications 新增 jd_file:超长 JD 落盘归档路径),
|
||||||
|
-- 完整可重复执行版本见 docs/upgrade_jd_file.sql。
|
||||||
|
|
||||||
|
-- 老库城市字段改名(城市代码 → 城市名称):
|
||||||
|
ALTER TABLE apply_sessions
|
||||||
|
CHANGE COLUMN city_code city VARCHAR(20) NULL COMMENT '城市名称';
|
||||||
|
|
||||||
|
-- v1.8 老库升级(引导词 + 投递模板),完整可重复执行版本见 docs/upgrade_1.8.sql:
|
||||||
|
-- ALTER TABLE apply_sessions
|
||||||
|
-- ADD COLUMN prompt TEXT NULL COMMENT 'AI评分引导词' AFTER salary_max;
|
||||||
|
-- CREATE TABLE IF NOT EXISTS apply_templates (
|
||||||
|
-- id INT AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
-- user_id INT NOT NULL,
|
||||||
|
-- name VARCHAR(128) NOT NULL COMMENT '模板名称',
|
||||||
|
-- keywords VARCHAR(512) NULL,
|
||||||
|
-- city VARCHAR(20) NULL,
|
||||||
|
-- salary_min INT NULL,
|
||||||
|
-- salary_max INT NULL,
|
||||||
|
-- min_score INT NOT NULL DEFAULT 65,
|
||||||
|
-- daily_limit INT NOT NULL DEFAULT 0,
|
||||||
|
-- boss_online_only TINYINT(1) NOT NULL DEFAULT 0,
|
||||||
|
-- allow_headhunter TINYINT(1) NOT NULL DEFAULT 0,
|
||||||
|
-- prompt TEXT NULL,
|
||||||
|
-- created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
-- updated_at DATETIME NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
|
-- KEY ix_apply_templates_user_id (user_id),
|
||||||
|
-- CONSTRAINT fk_apply_templates_user FOREIGN KEY (user_id)
|
||||||
|
-- REFERENCES users (id) ON DELETE CASCADE
|
||||||
|
-- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
-- ============================================================
|
||||||
|
-- Boss直聘 AI 投递系统 - 老库升级脚本(v1.11)
|
||||||
|
-- 适用场景:数据库已存在旧表,需要补充本次新增的表
|
||||||
|
--
|
||||||
|
-- 本次变更(AI 服务端代理):
|
||||||
|
-- 1. 新增 ai_config 表(模型配置,OpenAI 兼容,/view 管理页在线维护)
|
||||||
|
-- 2. 新增 ai_score_task 表(异步打分任务,客户端发起→服务端调模型→落表→客户端轮询)
|
||||||
|
-- request_key 为客户端 uuid1().hex(MAC+时间戳,32 位),故 VARCHAR(32)
|
||||||
|
--
|
||||||
|
-- 执行方式(Docker MySQL):
|
||||||
|
-- docker exec -i jianli-boss-mysql mysql -uroot -p<密码> jianli_boss < docs/upgrade_1.11.sql
|
||||||
|
--
|
||||||
|
-- 注意:脚本可重复执行安全(CREATE TABLE 使用 IF NOT EXISTS)
|
||||||
|
-- ============================================================
|
||||||
|
|
||||||
|
USE jianli_boss;
|
||||||
|
|
||||||
|
-- ------------------------------------------------------------
|
||||||
|
-- 1. AI 模型配置(全局单行,id=1)
|
||||||
|
-- ------------------------------------------------------------
|
||||||
|
CREATE TABLE IF NOT EXISTS ai_config (
|
||||||
|
id INT NOT NULL DEFAULT 1 PRIMARY KEY,
|
||||||
|
base_url VARCHAR(255) NULL COMMENT 'OpenAI兼容接口地址,如 https://api.siliconflow.cn/v1',
|
||||||
|
api_key VARCHAR(255) NULL COMMENT '模型 API Key',
|
||||||
|
model VARCHAR(128) NULL COMMENT '模型名,如 deepseek-ai/DeepSeek-V3',
|
||||||
|
timeout_s INT NOT NULL DEFAULT 300 COMMENT '服务端调用大模型超时(秒)',
|
||||||
|
enabled TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否启用AI代理',
|
||||||
|
updated_at DATETIME NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
|
||||||
|
COMMENT='AI模型配置(全局单行)';
|
||||||
|
|
||||||
|
-- ------------------------------------------------------------
|
||||||
|
-- 2. AI 打分任务(异步:开始打分 + 轮询结果)
|
||||||
|
-- ------------------------------------------------------------
|
||||||
|
CREATE TABLE IF NOT EXISTS ai_score_task (
|
||||||
|
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
user_id INT NOT NULL,
|
||||||
|
request_key VARCHAR(32) NOT NULL COMMENT '幂等键:客户端uuid1().hex(MAC+时间戳,32位)',
|
||||||
|
resume_id INT NULL COMMENT '主简历ID(服务端从库中取内容)',
|
||||||
|
job_ref VARCHAR(64) NULL COMMENT 'Boss职位ID(审计追踪用)',
|
||||||
|
jd_text TEXT NOT NULL COMMENT '职位JD全文(评分输入)',
|
||||||
|
conditions TEXT NULL COMMENT '投递条件JSON:keywords/city/salary_min/salary_max/prompt',
|
||||||
|
status VARCHAR(20) NOT NULL DEFAULT 'pending' COMMENT 'pending/running/success/failed',
|
||||||
|
score INT NULL COMMENT '成功时的匹配分(0-100)',
|
||||||
|
reason VARCHAR(512) NULL COMMENT '成功时一句话评价;失败时失败原因',
|
||||||
|
error TEXT NULL COMMENT '详细错误信息(调试用)',
|
||||||
|
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
finished_at DATETIME NULL,
|
||||||
|
UNIQUE KEY uq_user_request_key (user_id, request_key),
|
||||||
|
KEY idx_user_created (user_id, created_at),
|
||||||
|
CONSTRAINT fk_ai_score_task_user FOREIGN KEY (user_id)
|
||||||
|
REFERENCES users (id) ON DELETE CASCADE,
|
||||||
|
CONSTRAINT fk_ai_score_task_resume FOREIGN KEY (resume_id)
|
||||||
|
REFERENCES resumes (id) ON DELETE SET NULL
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
|
||||||
|
COMMENT='AI打分任务(客户端异步评分)';
|
||||||
|
|
||||||
|
-- ------------------------------------------------------------
|
||||||
|
-- 3. 验证(执行后应能看到两张新表)
|
||||||
|
-- ------------------------------------------------------------
|
||||||
|
SHOW TABLES LIKE 'ai_config';
|
||||||
|
SHOW TABLES LIKE 'ai_score_task';
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
-- ============================================================
|
||||||
|
-- Boss直聘 AI 投递系统 - 老库升级脚本(v1.8)
|
||||||
|
-- 适用场景:数据库已存在旧表,需要补充本次新增的字段/表
|
||||||
|
--
|
||||||
|
-- 本次变更:
|
||||||
|
-- 1. apply_sessions 新增 prompt 字段(AI评分引导词)
|
||||||
|
-- 2. 新增 apply_templates 表(投递条件模板)
|
||||||
|
--
|
||||||
|
-- 执行方式(Docker MySQL):
|
||||||
|
-- docker exec -i jianli-boss-mysql mysql -uroot -p<密码> jianli_boss < docs/upgrade_1.8.sql
|
||||||
|
--
|
||||||
|
-- 注意:脚本可重复执行安全处理
|
||||||
|
-- · ALTER 用存储过程判断列不存在才添加
|
||||||
|
-- · CREATE TABLE 使用 IF NOT EXISTS
|
||||||
|
-- ============================================================
|
||||||
|
|
||||||
|
USE jianli_boss;
|
||||||
|
|
||||||
|
-- ------------------------------------------------------------
|
||||||
|
-- 1. apply_sessions 新增 prompt 列(列已存在时自动跳过)
|
||||||
|
-- ------------------------------------------------------------
|
||||||
|
DROP PROCEDURE IF EXISTS sp_add_session_prompt;
|
||||||
|
DELIMITER $$
|
||||||
|
CREATE PROCEDURE sp_add_session_prompt()
|
||||||
|
BEGIN
|
||||||
|
IF NOT EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.COLUMNS
|
||||||
|
WHERE TABLE_SCHEMA = 'jianli_boss'
|
||||||
|
AND TABLE_NAME = 'apply_sessions'
|
||||||
|
AND COLUMN_NAME = 'prompt'
|
||||||
|
) THEN
|
||||||
|
ALTER TABLE apply_sessions
|
||||||
|
ADD COLUMN prompt TEXT NULL COMMENT 'AI评分引导词' AFTER salary_max;
|
||||||
|
END IF;
|
||||||
|
END$$
|
||||||
|
DELIMITER ;
|
||||||
|
CALL sp_add_session_prompt();
|
||||||
|
DROP PROCEDURE IF EXISTS sp_add_session_prompt;
|
||||||
|
|
||||||
|
-- ------------------------------------------------------------
|
||||||
|
-- 2. 新增投递条件模板表
|
||||||
|
-- ------------------------------------------------------------
|
||||||
|
CREATE TABLE IF NOT EXISTS apply_templates (
|
||||||
|
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
user_id INT NOT NULL,
|
||||||
|
name VARCHAR(128) NOT NULL COMMENT '模板名称',
|
||||||
|
keywords VARCHAR(512) NULL COMMENT '搜索关键词(逗号分隔)',
|
||||||
|
city VARCHAR(20) NULL COMMENT '城市名称',
|
||||||
|
salary_min INT NULL COMMENT '最低薪资(K)',
|
||||||
|
salary_max INT NULL COMMENT '最高薪资(K)',
|
||||||
|
min_score INT NOT NULL DEFAULT 65 COMMENT 'AI最低匹配分',
|
||||||
|
daily_limit INT NOT NULL DEFAULT 0 COMMENT '每日投递上限(0=不限)',
|
||||||
|
boss_online_only TINYINT(1) NOT NULL DEFAULT 0 COMMENT '只投递Boss在线的职位',
|
||||||
|
allow_headhunter TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否考虑猎头职位',
|
||||||
|
prompt TEXT NULL COMMENT 'AI评分引导词',
|
||||||
|
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at DATETIME NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
|
KEY ix_apply_templates_user_id (user_id),
|
||||||
|
CONSTRAINT fk_apply_templates_user FOREIGN KEY (user_id)
|
||||||
|
REFERENCES users (id) ON DELETE CASCADE
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
|
||||||
|
COMMENT='投递条件模板';
|
||||||
|
|
||||||
|
-- ------------------------------------------------------------
|
||||||
|
-- 3. 验证(执行后应能看到 prompt 列与 apply_templates 表)
|
||||||
|
-- ------------------------------------------------------------
|
||||||
|
SHOW COLUMNS FROM apply_sessions LIKE 'prompt';
|
||||||
|
SHOW TABLES LIKE 'apply_templates';
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
-- ============================================================
|
||||||
|
-- v1.18 老库升级:job_applications 新增 jd_file 列
|
||||||
|
-- 背景:超长 JD(> 20000 字符)不再入库,落盘到项目根目录
|
||||||
|
-- jd_archive/ 文件,库内仅存相对路径,避免触发
|
||||||
|
-- MySQL max_allowed_packet(1153)。
|
||||||
|
-- 幂等:可重复执行(已存在该列时跳过)。
|
||||||
|
-- 执行:docker exec -i jianli-boss-mysql mysql -uroot -p<密码> <数据库名> < docs/upgrade_jd_file.sql
|
||||||
|
-- ============================================================
|
||||||
|
|
||||||
|
SET @col_exists := (
|
||||||
|
SELECT COUNT(*) FROM information_schema.COLUMNS
|
||||||
|
WHERE TABLE_SCHEMA = DATABASE()
|
||||||
|
AND TABLE_NAME = 'job_applications'
|
||||||
|
AND COLUMN_NAME = 'jd_file'
|
||||||
|
);
|
||||||
|
SET @ddl := IF(@col_exists = 0,
|
||||||
|
'ALTER TABLE job_applications ADD COLUMN jd_file VARCHAR(255) NULL COMMENT ''超长JD归档文件路径(相对项目根目录,如 jd_archive/1_xxx.txt)'' AFTER jd_text',
|
||||||
|
'SELECT ''jd_file 列已存在,跳过'' AS msg');
|
||||||
|
PREPARE stmt FROM @ddl;
|
||||||
|
EXECUTE stmt;
|
||||||
|
DEALLOCATE PREPARE stmt;
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
-- ============================================================
|
||||||
|
-- v1.19 老库升级:新增 rpa_schedule 定时任务排程表
|
||||||
|
-- 背景:网页端「远程控制」新增定时任务——每日到点由服务端调度器
|
||||||
|
-- 自动下发 rpa_task(apply=自动投递 / activate=Boss激活),
|
||||||
|
-- 结束时间到点自动下发对应 stop 任务。
|
||||||
|
-- 幂等:可重复执行(CREATE TABLE IF NOT EXISTS)。
|
||||||
|
-- 执行:docker exec -i jianli-boss-mysql mysql -uroot -p<密码> <数据库名> < docs/upgrade_rpa_schedule.sql
|
||||||
|
-- ============================================================
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS rpa_schedule (
|
||||||
|
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
user_id INT NOT NULL,
|
||||||
|
kind VARCHAR(20) NOT NULL COMMENT 'apply=自动投递/activate=Boss激活',
|
||||||
|
params TEXT NULL COMMENT '任务参数 JSON(投递条件/激活参数)',
|
||||||
|
start_time VARCHAR(5) NOT NULL COMMENT '每日开始时间 HH:MM(北京时间)',
|
||||||
|
end_time VARCHAR(5) NOT NULL COMMENT '每日结束时间 HH:MM(北京时间)',
|
||||||
|
enabled TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否启用',
|
||||||
|
last_start_date VARCHAR(10) NULL COMMENT '最近开始下发日期(北京 YYYY-MM-DD,防当日重复)',
|
||||||
|
last_stop_date VARCHAR(10) NULL COMMENT '最近结束下发日期(北京 YYYY-MM-DD,防当日重复)',
|
||||||
|
last_result VARCHAR(255) NULL COMMENT '最近一次调度结果说明',
|
||||||
|
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
KEY ix_rpa_schedule_user (user_id),
|
||||||
|
CONSTRAINT fk_rpa_schedule_user FOREIGN KEY (user_id)
|
||||||
|
REFERENCES users (id) ON DELETE CASCADE
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
|
||||||
|
COMMENT='定时任务排程';
|
||||||
+8
-1
@@ -14,7 +14,8 @@ from loguru import logger
|
|||||||
|
|
||||||
from .config import settings
|
from .config import settings
|
||||||
from .database import engine
|
from .database import engine
|
||||||
from .routers import register, resumes, sessions, jobs, blacklist
|
from .scheduler import start_scheduler, stop_scheduler
|
||||||
|
from .routers import register, resumes, sessions, jobs, blacklist, rpa, templates, ai
|
||||||
|
|
||||||
|
|
||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
@@ -25,7 +26,10 @@ async def lifespan(app: FastAPI):
|
|||||||
logger.success("数据库连接成功")
|
logger.success("数据库连接成功")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"数据库连接失败,请检查配置及数据库是否已初始化:{e}")
|
logger.error(f"数据库连接失败,请检查配置及数据库是否已初始化:{e}")
|
||||||
|
# 定时任务调度器:后台循环扫描 rpa_schedule,到点自动下发 RpaTask
|
||||||
|
sched_task = start_scheduler()
|
||||||
yield
|
yield
|
||||||
|
await stop_scheduler(sched_task)
|
||||||
|
|
||||||
|
|
||||||
app = FastAPI(
|
app = FastAPI(
|
||||||
@@ -49,6 +53,9 @@ app.include_router(resumes.router)
|
|||||||
app.include_router(sessions.router)
|
app.include_router(sessions.router)
|
||||||
app.include_router(jobs.router)
|
app.include_router(jobs.router)
|
||||||
app.include_router(blacklist.router)
|
app.include_router(blacklist.router)
|
||||||
|
app.include_router(rpa.router)
|
||||||
|
app.include_router(templates.router)
|
||||||
|
app.include_router(ai.router)
|
||||||
|
|
||||||
|
|
||||||
@app.get("/", tags=["健康检查"])
|
@app.get("/", tags=["健康检查"])
|
||||||
|
|||||||
+175
-3
@@ -46,6 +46,7 @@ class User(Base):
|
|||||||
applications = relationship("JobApplication", back_populates="user", cascade="all, delete-orphan")
|
applications = relationship("JobApplication", back_populates="user", cascade="all, delete-orphan")
|
||||||
sessions = relationship("ApplySession", back_populates="user", cascade="all, delete-orphan")
|
sessions = relationship("ApplySession", back_populates="user", cascade="all, delete-orphan")
|
||||||
blacklist = relationship("CompanyBlacklist", back_populates="user", cascade="all, delete-orphan")
|
blacklist = relationship("CompanyBlacklist", back_populates="user", cascade="all, delete-orphan")
|
||||||
|
templates = relationship("ApplyTemplate", back_populates="user", cascade="all, delete-orphan")
|
||||||
|
|
||||||
|
|
||||||
class Resume(Base):
|
class Resume(Base):
|
||||||
@@ -86,11 +87,13 @@ class ApplySession(Base):
|
|||||||
status = Column(String(20), default="running", nullable=False)
|
status = Column(String(20), default="running", nullable=False)
|
||||||
# 搜索关键词(逗号分隔)
|
# 搜索关键词(逗号分隔)
|
||||||
keywords = Column(String(512), nullable=True)
|
keywords = Column(String(512), nullable=True)
|
||||||
# 城市代码
|
# 城市
|
||||||
city_code = Column(String(20), nullable=True)
|
city = Column(String(20), nullable=True)
|
||||||
# 薪资范围
|
# 薪资范围
|
||||||
salary_min = Column(Integer, nullable=True)
|
salary_min = Column(Integer, nullable=True)
|
||||||
salary_max = Column(Integer, nullable=True)
|
salary_max = Column(Integer, nullable=True)
|
||||||
|
# AI 评分引导词(用户自定义补充偏好)
|
||||||
|
prompt = Column(Text, nullable=True)
|
||||||
# 本次会话投递数量统计
|
# 本次会话投递数量统计
|
||||||
applied_count = Column(Integer, default=0)
|
applied_count = Column(Integer, default=0)
|
||||||
skipped_count = Column(Integer, default=0)
|
skipped_count = Column(Integer, default=0)
|
||||||
@@ -128,8 +131,11 @@ class JobApplication(Base):
|
|||||||
ai_reason = Column(String(255), nullable=True)
|
ai_reason = Column(String(255), nullable=True)
|
||||||
# 跳过原因
|
# 跳过原因
|
||||||
skip_reason = Column(String(255), nullable=True)
|
skip_reason = Column(String(255), nullable=True)
|
||||||
# 职位 JD 全文(投递/跳过时归档,供复盘与面试准备)
|
# 职位 JD 全文(投递/跳过时归档,供复盘与面试准备);
|
||||||
|
# 超过 JD_TEXT_LIMIT 的超长 JD 不入本列,落盘到项目根目录 jd_archive/,本列留空、改存 jd_file 路径
|
||||||
jd_text = Column(Text, nullable=True)
|
jd_text = Column(Text, nullable=True)
|
||||||
|
# 超长 JD 归档文件路径(相对项目根目录,如 jd_archive/1_0daaa9fd.txt)
|
||||||
|
jd_file = Column(String(255), nullable=True)
|
||||||
# 实际发送的打招呼语(仅 chat 方式有值)
|
# 实际发送的打招呼语(仅 chat 方式有值)
|
||||||
greeting = Column(String(500), nullable=True)
|
greeting = Column(String(500), nullable=True)
|
||||||
applied_at = Column(DateTime, default=utcnow, nullable=False)
|
applied_at = Column(DateTime, default=utcnow, nullable=False)
|
||||||
@@ -156,3 +162,169 @@ class CompanyBlacklist(Base):
|
|||||||
created_at = Column(DateTime, default=utcnow, nullable=False)
|
created_at = Column(DateTime, default=utcnow, nullable=False)
|
||||||
|
|
||||||
user = relationship("User", back_populates="blacklist")
|
user = relationship("User", back_populates="blacklist")
|
||||||
|
|
||||||
|
|
||||||
|
class RpaStatus(Base):
|
||||||
|
"""
|
||||||
|
客户端 RPA 状态快照(每用户一行,单设备不做设备区分)。
|
||||||
|
心跳每次携带全量状态上报:Boss 登录 / 浏览器 / 投递状态。
|
||||||
|
"""
|
||||||
|
__tablename__ = "rpa_status"
|
||||||
|
|
||||||
|
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"),
|
||||||
|
primary_key=True)
|
||||||
|
# Boss 直聘登录状态:not_login / logging_in / logged_in / unknown
|
||||||
|
boss_login = Column(String(20), default="unknown", nullable=False)
|
||||||
|
# 指纹浏览器状态:running / stopped / unknown
|
||||||
|
browser = Column(String(20), default="unknown", nullable=False)
|
||||||
|
# 投递状态:idle / running
|
||||||
|
apply_status = Column(String(20), default="idle", nullable=False)
|
||||||
|
# 当前进度文本(如“评估:xx公司 - xx职位”)
|
||||||
|
current = Column(String(200), nullable=True)
|
||||||
|
applied = Column(Integer, default=0, nullable=False)
|
||||||
|
skipped = Column(Integer, default=0, nullable=False)
|
||||||
|
updated_at = Column(DateTime, default=utcnow, onupdate=utcnow, nullable=False)
|
||||||
|
|
||||||
|
user = relationship("User")
|
||||||
|
|
||||||
|
|
||||||
|
class RpaTask(Base):
|
||||||
|
"""
|
||||||
|
远程控制任务(云端下发 → 客户端轮询执行 → 回调更新状态)。
|
||||||
|
状态机:pending → running → done/failed;pending 超时 → expired。
|
||||||
|
去重:同类型任务未达终态(done/failed/expired)时拒绝重复下发。
|
||||||
|
"""
|
||||||
|
__tablename__ = "rpa_task"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||||
|
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"),
|
||||||
|
nullable=False, index=True)
|
||||||
|
# start_apply / stop_apply
|
||||||
|
task_type = Column(String(20), nullable=False)
|
||||||
|
# 任务参数 JSON(start_apply 的投递参数)
|
||||||
|
params = Column(Text, nullable=True)
|
||||||
|
# pending / running / done / failed / expired
|
||||||
|
status = Column(String(20), default="pending", nullable=False)
|
||||||
|
result = Column(String(500), nullable=True)
|
||||||
|
created_at = Column(DateTime, default=utcnow, nullable=False)
|
||||||
|
updated_at = Column(DateTime, default=utcnow, onupdate=utcnow, nullable=False)
|
||||||
|
|
||||||
|
user = relationship("User")
|
||||||
|
|
||||||
|
|
||||||
|
class RpaSchedule(Base):
|
||||||
|
"""
|
||||||
|
定时任务排程(远程控制页创建,服务端调度器每日到点自动下发 RpaTask)。
|
||||||
|
kind:apply=自动投递 / activate=Boss 激活;时间均为北京时间 HH:MM。
|
||||||
|
防重复:last_start_date / last_stop_date 记录当日已下发日期,每类动作每天只触发一次。
|
||||||
|
"""
|
||||||
|
__tablename__ = "rpa_schedule"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||||
|
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"),
|
||||||
|
nullable=False, index=True)
|
||||||
|
# apply / activate
|
||||||
|
kind = Column(String(20), nullable=False)
|
||||||
|
# 任务参数 JSON:apply=投递条件;activate=激活参数(match_text/status_filter/threshold/reply_message/max_count/dry_run)
|
||||||
|
params = Column(Text, nullable=True)
|
||||||
|
# 每日开始/结束时间 HH:MM(北京时间),结束时间到点自动下发对应 stop 任务
|
||||||
|
start_time = Column(String(5), nullable=False)
|
||||||
|
end_time = Column(String(5), nullable=False)
|
||||||
|
enabled = Column(Boolean, default=True, nullable=False)
|
||||||
|
# 最近一次开始/结束下发日期(北京日期 YYYY-MM-DD,防当日重复触发)
|
||||||
|
last_start_date = Column(String(10), nullable=True)
|
||||||
|
last_stop_date = Column(String(10), nullable=True)
|
||||||
|
# 最近一次调度结果说明(已下发任务#ID / 跳过原因)
|
||||||
|
last_result = Column(String(255), nullable=True)
|
||||||
|
created_at = Column(DateTime, default=utcnow, nullable=False)
|
||||||
|
|
||||||
|
|
||||||
|
class ApplyTemplate(Base):
|
||||||
|
"""
|
||||||
|
投递条件模板
|
||||||
|
用户保存常用投递配置,支持在本地面板和远程控制面板套用。
|
||||||
|
"""
|
||||||
|
__tablename__ = "apply_templates"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||||
|
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"),
|
||||||
|
nullable=False, index=True)
|
||||||
|
# 模板名称(用户自定义)
|
||||||
|
name = Column(String(128), nullable=False)
|
||||||
|
# 搜索关键词(逗号分隔)
|
||||||
|
keywords = Column(String(512), nullable=True)
|
||||||
|
# 城市
|
||||||
|
city = Column(String(20), nullable=True)
|
||||||
|
# 薪资范围
|
||||||
|
salary_min = Column(Integer, nullable=True)
|
||||||
|
salary_max = Column(Integer, nullable=True)
|
||||||
|
# AI 最低匹配分
|
||||||
|
min_score = Column(Integer, default=65)
|
||||||
|
# 每日投递上限(0=不限)
|
||||||
|
daily_limit = Column(Integer, default=0)
|
||||||
|
# 是否只投递 Boss 在线的职位
|
||||||
|
boss_online_only = Column(Boolean, default=False, nullable=False)
|
||||||
|
# 是否考虑猎头职位
|
||||||
|
allow_headhunter = Column(Boolean, default=False, nullable=False)
|
||||||
|
# AI 评分引导词
|
||||||
|
prompt = Column(Text, nullable=True)
|
||||||
|
created_at = Column(DateTime, default=utcnow, nullable=False)
|
||||||
|
updated_at = Column(DateTime, default=utcnow, onupdate=utcnow, nullable=False)
|
||||||
|
|
||||||
|
user = relationship("User", back_populates="templates")
|
||||||
|
|
||||||
|
|
||||||
|
class AIConfig(Base):
|
||||||
|
"""
|
||||||
|
AI 模型配置(全局单行,id=1)
|
||||||
|
OpenAI 兼容接口,由管理页面(/view)在线维护,
|
||||||
|
客户端不再持有任何模型密钥。
|
||||||
|
"""
|
||||||
|
__tablename__ = "ai_config"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, default=1)
|
||||||
|
# OpenAI 兼容接口地址,如 https://api.siliconflow.cn/v1
|
||||||
|
base_url = Column(String(255), nullable=True)
|
||||||
|
api_key = Column(String(255), nullable=True)
|
||||||
|
model = Column(String(128), nullable=True)
|
||||||
|
# 服务端调用大模型的超时(秒)
|
||||||
|
timeout_s = Column(Integer, default=300, nullable=False)
|
||||||
|
# 是否启用 AI 代理(关闭后客户端评分请求直接返回未配置)
|
||||||
|
enabled = Column(Boolean, default=True, nullable=False)
|
||||||
|
updated_at = Column(DateTime, default=utcnow, onupdate=utcnow)
|
||||||
|
|
||||||
|
|
||||||
|
class AIScoreTask(Base):
|
||||||
|
"""
|
||||||
|
AI 打分任务(客户端异步评分)
|
||||||
|
客户端发起打分 → 服务端后台调用大模型 → 结果落表 → 客户端轮询取结果。
|
||||||
|
request_key 为客户端生成的幂等键(uuid1 hex,MAC+时间戳,32 位),
|
||||||
|
重复提交同键直接返回已有任务,不会重复调用大模型。
|
||||||
|
"""
|
||||||
|
__tablename__ = "ai_score_task"
|
||||||
|
__table_args__ = (
|
||||||
|
# 同一用户内幂等键唯一(防重复调用大模型)
|
||||||
|
UniqueConstraint("user_id", "request_key", name="uq_user_request_key"),
|
||||||
|
Index("idx_user_created", "user_id", "created_at"),
|
||||||
|
)
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||||
|
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
|
||||||
|
# 幂等键:客户端 uuid1().hex,32 位十六进制字符串,故 VARCHAR(32)
|
||||||
|
request_key = Column(String(32), nullable=False)
|
||||||
|
resume_id = Column(Integer, ForeignKey("resumes.id", ondelete="SET NULL"), nullable=True)
|
||||||
|
# 客户端职位标识(Boss job_id,仅审计追踪用)
|
||||||
|
job_ref = Column(String(64), nullable=True)
|
||||||
|
# 职位 JD 全文(评分输入)
|
||||||
|
jd_text = Column(Text, nullable=False)
|
||||||
|
# 投递条件 JSON:keywords/city/salary_min/salary_max/prompt
|
||||||
|
conditions = Column(Text, nullable=True)
|
||||||
|
# pending / running / success / failed
|
||||||
|
status = Column(String(20), default="pending", nullable=False)
|
||||||
|
score = Column(Integer, nullable=True)
|
||||||
|
# 成功时一句话评价;失败时失败原因(客户端据此跳岗)
|
||||||
|
reason = Column(String(512), nullable=True)
|
||||||
|
# 详细错误信息(调试用)
|
||||||
|
error = Column(Text, nullable=True)
|
||||||
|
created_at = Column(DateTime, default=utcnow, nullable=False)
|
||||||
|
finished_at = Column(DateTime, nullable=True)
|
||||||
|
|||||||
@@ -8,3 +8,4 @@ pydantic>=2.7.0
|
|||||||
pydantic-settings>=2.3.0
|
pydantic-settings>=2.3.0
|
||||||
python-jose[cryptography]>=3.3.0
|
python-jose[cryptography]>=3.3.0
|
||||||
loguru>=0.7.2
|
loguru>=0.7.2
|
||||||
|
requests>=2.31.0
|
||||||
|
|||||||
@@ -0,0 +1,332 @@
|
|||||||
|
"""
|
||||||
|
AI 代理路由:模型配置管理 + 异步打分任务 + 简历整理
|
||||||
|
- 客户端发起打分(POST /api/ai/score/start)→ 服务端后台线程调用大模型 → 结果落表
|
||||||
|
- 客户端轮询结果(GET /api/ai/score/result/{request_key}):
|
||||||
|
成功返回 score+reason;失败返回 reason(客户端跳过该岗位);处理中则继续等待
|
||||||
|
- request_key 为客户端生成的幂等键(本机 MAC+时间戳的 uuid1 hex,32 位),
|
||||||
|
重复提交同键直接返回已有任务,绝不重复调用大模型
|
||||||
|
- 模型配置(OpenAI 兼容)由 /view 管理页在线维护,客户端不持有任何密钥
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import threading
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
|
||||||
|
import requests
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
from loguru import logger
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from ..auth import get_current_user
|
||||||
|
from ..database import get_db, SessionLocal
|
||||||
|
from ..models import AIConfig, AIScoreTask, Resume, User, utcnow
|
||||||
|
from ..schemas import AIConfigIn, CleanResumeIn, ScoreStartIn
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/ai", tags=["AI代理"])
|
||||||
|
|
||||||
|
# 简易限额:每用户每日允许发起的打分次数(内存计数,重启清零)
|
||||||
|
DAILY_QUOTA = 2000
|
||||||
|
# 处理中任务超过该时长仍无结果 → 判定失败(防悬空等待,5 分钟)
|
||||||
|
TASK_TIMEOUT_S = 300
|
||||||
|
|
||||||
|
_quota_lock = threading.Lock()
|
||||||
|
_quota: dict = {} # {(user_id, 北京日期): 已用次数}
|
||||||
|
|
||||||
|
_SCORE_SYSTEM_PROMPT = (
|
||||||
|
"你是专业招聘顾问。根据职位描述(JD)和候选人简历,输出 JSON 评估结果,"
|
||||||
|
"不要输出 JSON 以外的内容。\n"
|
||||||
|
'格式:{"score": <0-100整数>, "reason": "<一句话评价>"}\n'
|
||||||
|
"评分标准:80-100 高度匹配;60-79 基本匹配;40-59 部分匹配;0-39 不匹配。"
|
||||||
|
)
|
||||||
|
_CLEAN_SYSTEM_PROMPT = (
|
||||||
|
"你是简历整理助手。将下面抓取的杂乱简历文本整理为清晰、结构化的纯文本简历,"
|
||||||
|
"保留所有关键信息(姓名可省略,联系方式可保留),去除广告和无关内容。"
|
||||||
|
"直接输出整理后的文本,不要加任何解释。"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# 工具函数
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def _today_bj() -> str:
|
||||||
|
"""北京日期(限额按天清零)"""
|
||||||
|
return datetime.now(timezone(timedelta(hours=8))).strftime("%Y-%m-%d")
|
||||||
|
|
||||||
|
|
||||||
|
def _quota_ok(user_id: int) -> bool:
|
||||||
|
with _quota_lock:
|
||||||
|
return _quota.get((user_id, _today_bj()), 0) < DAILY_QUOTA
|
||||||
|
|
||||||
|
|
||||||
|
def _quota_inc(user_id: int) -> None:
|
||||||
|
with _quota_lock:
|
||||||
|
key = (user_id, _today_bj())
|
||||||
|
_quota[key] = _quota.get(key, 0) + 1
|
||||||
|
|
||||||
|
|
||||||
|
def _get_config(db: Session) -> AIConfig | None:
|
||||||
|
return db.query(AIConfig).filter(AIConfig.id == 1).first()
|
||||||
|
|
||||||
|
|
||||||
|
def _llm_chat(cfg: AIConfig, system: str, user_text: str,
|
||||||
|
max_tokens: int, temperature: float) -> str:
|
||||||
|
"""直接 HTTP 调用 OpenAI 兼容 chat/completions(服务端不引入 openai SDK)"""
|
||||||
|
url = (cfg.base_url or "").rstrip("/") + "/chat/completions"
|
||||||
|
messages = []
|
||||||
|
if system:
|
||||||
|
messages.append({"role": "system", "content": system})
|
||||||
|
messages.append({"role": "user", "content": user_text})
|
||||||
|
resp = requests.post(
|
||||||
|
url,
|
||||||
|
headers={"Authorization": f"Bearer {cfg.api_key}"},
|
||||||
|
json={"model": cfg.model, "messages": messages,
|
||||||
|
"temperature": temperature, "max_tokens": max_tokens},
|
||||||
|
timeout=cfg.timeout_s or 300,
|
||||||
|
)
|
||||||
|
resp.raise_for_status()
|
||||||
|
data = resp.json()
|
||||||
|
return (data["choices"][0]["message"]["content"] or "").strip()
|
||||||
|
|
||||||
|
|
||||||
|
def parse_score(raw: str) -> tuple[int, str]:
|
||||||
|
"""解析模型返回的评分 JSON(纯函数,便于单测)"""
|
||||||
|
raw = (raw or "").strip()
|
||||||
|
if raw.startswith("```"):
|
||||||
|
raw = raw.split("```")[1]
|
||||||
|
if raw.startswith("json"):
|
||||||
|
raw = raw[4:]
|
||||||
|
data = json.loads(raw)
|
||||||
|
return int(data.get("score", 50)), str(data.get("reason", ""))[:500]
|
||||||
|
|
||||||
|
|
||||||
|
def build_score_user_prompt(jd_text: str, resume_content: str,
|
||||||
|
conditions: dict | None) -> str:
|
||||||
|
"""拼装评分用户提示词(纯函数,便于单测)"""
|
||||||
|
user_prompt = f"【职位描述】\n{jd_text}\n\n【候选人简历】\n{resume_content}"
|
||||||
|
conds = []
|
||||||
|
if conditions:
|
||||||
|
if conditions.get("keywords"):
|
||||||
|
conds.append(f"搜索关键词:{conditions['keywords']}")
|
||||||
|
if conditions.get("city"):
|
||||||
|
conds.append(f"目标城市:{conditions['city']}")
|
||||||
|
if conditions.get("salary_min") or conditions.get("salary_max"):
|
||||||
|
conds.append(f"期望薪资:{conditions.get('salary_min') or '?'}"
|
||||||
|
f"-{conditions.get('salary_max') or '?'}K")
|
||||||
|
if conds:
|
||||||
|
user_prompt += "\n\n【本次投递条件】\n" + "\n".join(conds)
|
||||||
|
if conditions and conditions.get("prompt"):
|
||||||
|
user_prompt += f"\n\n【用户额外偏好/引导词】\n{conditions['prompt']}"
|
||||||
|
return user_prompt
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# 异步打分:开始 + 查询结果
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
@router.post("/score/start")
|
||||||
|
def score_start(
|
||||||
|
req: ScoreStartIn,
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""开始打分任务(幂等:同 request_key 重复提交直接返回已有任务)"""
|
||||||
|
task = db.query(AIScoreTask).filter(
|
||||||
|
AIScoreTask.user_id == current_user.id,
|
||||||
|
AIScoreTask.request_key == req.request_key,
|
||||||
|
).first()
|
||||||
|
if task:
|
||||||
|
logger.debug(f"幂等命中,直接返回已有打分任务:{req.request_key}")
|
||||||
|
return {"request_key": task.request_key, "status": task.status}
|
||||||
|
|
||||||
|
cfg = _get_config(db)
|
||||||
|
if not cfg or not cfg.enabled or not cfg.api_key:
|
||||||
|
raise HTTPException(status_code=400, detail="服务端未配置 AI 模型,请联系管理员")
|
||||||
|
resume = db.query(Resume).filter(
|
||||||
|
Resume.id == req.resume_id,
|
||||||
|
Resume.user_id == current_user.id,
|
||||||
|
).first()
|
||||||
|
if not resume or not (resume.content or "").strip():
|
||||||
|
raise HTTPException(status_code=404, detail="简历不存在或内容为空")
|
||||||
|
if not _quota_ok(current_user.id):
|
||||||
|
raise HTTPException(status_code=429, detail="今日 AI 打分次数已用完")
|
||||||
|
|
||||||
|
_quota_inc(current_user.id)
|
||||||
|
conditions = req.conditions.model_dump() if req.conditions else {}
|
||||||
|
task = AIScoreTask(
|
||||||
|
user_id=current_user.id,
|
||||||
|
request_key=req.request_key,
|
||||||
|
resume_id=resume.id,
|
||||||
|
job_ref=req.job_ref,
|
||||||
|
jd_text=req.jd_text,
|
||||||
|
conditions=json.dumps(conditions, ensure_ascii=False),
|
||||||
|
status="pending",
|
||||||
|
)
|
||||||
|
db.add(task)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(task)
|
||||||
|
|
||||||
|
threading.Thread(target=_run_score_task, args=(task.id,), daemon=True).start()
|
||||||
|
logger.info(f"AI 打分任务已受理:task={task.id} user={current_user.id} "
|
||||||
|
f"job_ref={req.job_ref}")
|
||||||
|
return {"request_key": task.request_key, "status": task.status}
|
||||||
|
|
||||||
|
|
||||||
|
def _run_score_task(task_id: int) -> None:
|
||||||
|
"""后台执行打分:独立 DB 会话,成功/失败结果一律落表"""
|
||||||
|
db = SessionLocal()
|
||||||
|
try:
|
||||||
|
task = db.query(AIScoreTask).filter(AIScoreTask.id == task_id).first()
|
||||||
|
if not task:
|
||||||
|
return
|
||||||
|
task.status = "running"
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
cfg = _get_config(db)
|
||||||
|
if not cfg or not cfg.api_key:
|
||||||
|
raise RuntimeError("AI 模型配置缺失或已停用")
|
||||||
|
resume = (db.query(Resume).filter(Resume.id == task.resume_id).first()
|
||||||
|
if task.resume_id else None)
|
||||||
|
resume_content = ((resume.content if resume else "") or "")
|
||||||
|
|
||||||
|
try:
|
||||||
|
conditions = json.loads(task.conditions or "{}")
|
||||||
|
except Exception:
|
||||||
|
conditions = {}
|
||||||
|
|
||||||
|
user_prompt = build_score_user_prompt(task.jd_text, resume_content, conditions)
|
||||||
|
raw = _llm_chat(cfg, _SCORE_SYSTEM_PROMPT, user_prompt,
|
||||||
|
max_tokens=256, temperature=0.2)
|
||||||
|
score, reason = parse_score(raw)
|
||||||
|
|
||||||
|
task.status = "success"
|
||||||
|
task.score = score
|
||||||
|
task.reason = reason
|
||||||
|
task.finished_at = utcnow()
|
||||||
|
db.commit()
|
||||||
|
logger.success(f"AI 打分完成:task={task_id} score={score}")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"AI 打分任务失败 task={task_id}:{e}")
|
||||||
|
try:
|
||||||
|
db.rollback()
|
||||||
|
task = db.query(AIScoreTask).filter(AIScoreTask.id == task_id).first()
|
||||||
|
if task and task.status in ("pending", "running"):
|
||||||
|
task.status = "failed"
|
||||||
|
task.reason = f"模型调用失败:{str(e)[:200]}"
|
||||||
|
task.error = str(e)[:2000]
|
||||||
|
task.finished_at = utcnow()
|
||||||
|
db.commit()
|
||||||
|
except Exception:
|
||||||
|
db.rollback()
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/score/result/{request_key}")
|
||||||
|
def score_result(
|
||||||
|
request_key: str,
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""查询打分结果(客户端轮询)
|
||||||
|
status:pending/running=处理中(客户端继续等待下一次轮询);
|
||||||
|
success=返回 score+reason;failed=返回 reason(客户端跳过该岗位)。
|
||||||
|
处理中的任务若超 5 分钟仍无结果,判定为失败(防悬空)。
|
||||||
|
"""
|
||||||
|
task = db.query(AIScoreTask).filter(
|
||||||
|
AIScoreTask.user_id == current_user.id,
|
||||||
|
AIScoreTask.request_key == request_key,
|
||||||
|
).first()
|
||||||
|
if not task:
|
||||||
|
raise HTTPException(status_code=404, detail="打分任务不存在")
|
||||||
|
if task.status in ("pending", "running") and \
|
||||||
|
(utcnow() - task.created_at).total_seconds() > TASK_TIMEOUT_S:
|
||||||
|
task.status = "failed"
|
||||||
|
task.reason = "打分超时(超过 5 分钟无结果)"
|
||||||
|
task.finished_at = utcnow()
|
||||||
|
db.commit()
|
||||||
|
return {"status": task.status, "score": task.score, "reason": task.reason}
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# 简历整理(低频同步调用,简历抓取时用)
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
@router.post("/clean-resume")
|
||||||
|
def clean_resume(
|
||||||
|
req: CleanResumeIn,
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
cfg = _get_config(db)
|
||||||
|
if not cfg or not cfg.enabled or not cfg.api_key:
|
||||||
|
raise HTTPException(status_code=400, detail="服务端未配置 AI 模型")
|
||||||
|
try:
|
||||||
|
text = _llm_chat(cfg, _CLEAN_SYSTEM_PROMPT, req.raw_text,
|
||||||
|
max_tokens=2048, temperature=0.3)
|
||||||
|
except Exception as e:
|
||||||
|
raise HTTPException(status_code=502, detail=f"AI 整理失败:{str(e)[:200]}")
|
||||||
|
return {"content": text}
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# 模型配置(管理页面在线维护)
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def _config_out(cfg: AIConfig, with_key: bool) -> dict:
|
||||||
|
return {
|
||||||
|
"base_url": cfg.base_url or "",
|
||||||
|
"api_key": cfg.api_key if with_key else "",
|
||||||
|
"model": cfg.model or "",
|
||||||
|
"timeout_s": cfg.timeout_s,
|
||||||
|
"enabled": cfg.enabled,
|
||||||
|
"updated_at": cfg.updated_at,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/config")
|
||||||
|
def get_ai_config(
|
||||||
|
with_key: bool = False,
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""获取模型配置(默认不回显密钥;编辑时带 with_key=true 回显)"""
|
||||||
|
cfg = _get_config(db)
|
||||||
|
if not cfg:
|
||||||
|
return {"base_url": "", "api_key": "", "model": "",
|
||||||
|
"timeout_s": 300, "enabled": False, "updated_at": None}
|
||||||
|
return _config_out(cfg, with_key=with_key)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/config")
|
||||||
|
def save_ai_config(
|
||||||
|
req: AIConfigIn,
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""保存模型配置(OpenAI 兼容接口)"""
|
||||||
|
cfg = _get_config(db)
|
||||||
|
if not cfg:
|
||||||
|
cfg = AIConfig(id=1)
|
||||||
|
db.add(cfg)
|
||||||
|
cfg.base_url = (req.base_url or "").strip()
|
||||||
|
cfg.api_key = (req.api_key or "").strip()
|
||||||
|
cfg.model = (req.model or "").strip()
|
||||||
|
cfg.timeout_s = req.timeout_s
|
||||||
|
cfg.enabled = req.enabled
|
||||||
|
db.commit()
|
||||||
|
db.refresh(cfg)
|
||||||
|
logger.info(f"AI 模型配置已更新(by user {current_user.id}):"
|
||||||
|
f"{cfg.base_url} / {cfg.model} / enabled={cfg.enabled}")
|
||||||
|
return _config_out(cfg, with_key=False)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/config/test")
|
||||||
|
def test_ai_config(
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""连通测试:用当前已保存配置发起一次最小请求"""
|
||||||
|
cfg = _get_config(db)
|
||||||
|
if not cfg or not cfg.api_key:
|
||||||
|
return {"ok": False, "detail": "尚未配置 API Key"}
|
||||||
|
try:
|
||||||
|
_llm_chat(cfg, "", "回复1", max_tokens=5, temperature=0)
|
||||||
|
return {"ok": True, "detail": "连通正常"}
|
||||||
|
except Exception as e:
|
||||||
|
return {"ok": False, "detail": str(e)[:300]}
|
||||||
+86
-4
@@ -1,11 +1,14 @@
|
|||||||
"""
|
"""
|
||||||
投递记录路由:上报投递结果、查询历史、统计
|
投递记录路由:上报投递结果、查询历史、统计
|
||||||
"""
|
"""
|
||||||
|
import re
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
from typing import Optional
|
from pathlib import Path
|
||||||
|
from typing import Optional, Tuple
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
from sqlalchemy import func
|
from sqlalchemy import func
|
||||||
|
from loguru import logger
|
||||||
|
|
||||||
from ..auth import get_current_user
|
from ..auth import get_current_user
|
||||||
from ..database import get_db
|
from ..database import get_db
|
||||||
@@ -15,6 +18,52 @@ from ..schemas import ApplicationIn, ApplicationOut, Message, StatsOut
|
|||||||
|
|
||||||
router = APIRouter(prefix="/api/jobs", tags=["投递记录"])
|
router = APIRouter(prefix="/api/jobs", tags=["投递记录"])
|
||||||
|
|
||||||
|
# jd_text 入库上限(字符):超过则落盘为文件(库内只存路径),
|
||||||
|
# 控制写入包体积,避免触发 MySQL max_allowed_packet(1153)
|
||||||
|
JD_TEXT_LIMIT = 20000
|
||||||
|
|
||||||
|
# 归档目录:项目根目录下的 jd_archive/(本文件位于 server/routers/,上溯两级即项目根)
|
||||||
|
PROJECT_ROOT = Path(__file__).resolve().parents[2]
|
||||||
|
JD_DIR_NAME = "jd_archive"
|
||||||
|
|
||||||
|
|
||||||
|
def _archive_jd(user_id: int, job_id: str, jd_text: Optional[str]) -> Tuple[Optional[str], Optional[str]]:
|
||||||
|
"""JD 存储分流:≤ 上限直接入库;超限写入 jd_archive/ 文件。
|
||||||
|
返回 (jd_text, jd_file):两者必有一空。文件名按 用户_职位 去重,重复上报覆盖"""
|
||||||
|
if not jd_text or len(jd_text) <= JD_TEXT_LIMIT:
|
||||||
|
return jd_text, None
|
||||||
|
safe_job = re.sub(r"[^\w\-]", "_", job_id or "")[:48] or "unknown"
|
||||||
|
rel = f"{JD_DIR_NAME}/{user_id}_{safe_job}.txt"
|
||||||
|
try:
|
||||||
|
target = PROJECT_ROOT / rel
|
||||||
|
target.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
target.write_text(jd_text, encoding="utf-8")
|
||||||
|
logger.info(f"超长 JD 已归档到文件({len(jd_text)} 字符):{rel}")
|
||||||
|
return None, rel
|
||||||
|
except OSError as e:
|
||||||
|
# 落盘失败也不能把巨包塞进数据库:截断到上限入库,保底不丢全部信息且不炸库
|
||||||
|
logger.error(f"JD 归档落盘失败,截断入库:{e}")
|
||||||
|
return jd_text[:JD_TEXT_LIMIT], None
|
||||||
|
|
||||||
|
|
||||||
|
def _clip(value: Optional[str], limit: int) -> Optional[str]:
|
||||||
|
"""按列长度截断文本,防止超长写入导致 1153 / Data too long"""
|
||||||
|
return value[:limit] if value else value
|
||||||
|
|
||||||
|
|
||||||
|
def _sanitize(req: ApplicationIn) -> ApplicationIn:
|
||||||
|
"""上报字段统一裁剪(与 models.py 列长度保持一致);
|
||||||
|
jd_text 不在此截断——由 _archive_jd 按上限分流到数据库/文件"""
|
||||||
|
req.job_title = _clip(req.job_title, 128)
|
||||||
|
req.company = _clip(req.company, 128)
|
||||||
|
req.salary = _clip(req.salary, 32)
|
||||||
|
req.location = _clip(req.location, 64)
|
||||||
|
req.apply_type = _clip(req.apply_type, 20) or "skipped"
|
||||||
|
req.ai_reason = _clip(req.ai_reason, 255)
|
||||||
|
req.skip_reason = _clip(req.skip_reason, 255)
|
||||||
|
req.greeting = _clip(req.greeting, 500)
|
||||||
|
return req
|
||||||
|
|
||||||
|
|
||||||
@router.post("/report", response_model=ApplicationOut)
|
@router.post("/report", response_model=ApplicationOut)
|
||||||
def report_application(
|
def report_application(
|
||||||
@@ -27,6 +76,9 @@ def report_application(
|
|||||||
客户端上报一条投递/跳过记录(前置校验:RPA 必须在线)。
|
客户端上报一条投递/跳过记录(前置校验:RPA 必须在线)。
|
||||||
同一用户 + 同一职位 ID 去重,已存在则更新。
|
同一用户 + 同一职位 ID 去重,已存在则更新。
|
||||||
"""
|
"""
|
||||||
|
req = _sanitize(req)
|
||||||
|
# JD 分流:短文本入库,超长落盘为文件(库存路径)
|
||||||
|
jd_text, jd_file = _archive_jd(current_user.id, req.job_id, req.jd_text)
|
||||||
existing = db.query(JobApplication).filter(
|
existing = db.query(JobApplication).filter(
|
||||||
JobApplication.user_id == current_user.id,
|
JobApplication.user_id == current_user.id,
|
||||||
JobApplication.job_id == req.job_id,
|
JobApplication.job_id == req.job_id,
|
||||||
@@ -41,7 +93,9 @@ def report_application(
|
|||||||
# 否则记录停留在首次上报时间,看起来像“漏报”
|
# 否则记录停留在首次上报时间,看起来像“漏报”
|
||||||
existing.applied_at = datetime.utcnow()
|
existing.applied_at = datetime.utcnow()
|
||||||
if req.jd_text:
|
if req.jd_text:
|
||||||
existing.jd_text = req.jd_text
|
# 新 JD 覆盖旧值;文本与归档文件二者只留其一,避免读到陈旧数据
|
||||||
|
existing.jd_text = jd_text
|
||||||
|
existing.jd_file = jd_file
|
||||||
if req.greeting:
|
if req.greeting:
|
||||||
existing.greeting = req.greeting
|
existing.greeting = req.greeting
|
||||||
if session_id:
|
if session_id:
|
||||||
@@ -60,7 +114,8 @@ def report_application(
|
|||||||
ai_score=req.ai_score,
|
ai_score=req.ai_score,
|
||||||
ai_reason=req.ai_reason,
|
ai_reason=req.ai_reason,
|
||||||
skip_reason=req.skip_reason,
|
skip_reason=req.skip_reason,
|
||||||
jd_text=req.jd_text,
|
jd_text=jd_text,
|
||||||
|
jd_file=jd_file,
|
||||||
greeting=req.greeting,
|
greeting=req.greeting,
|
||||||
)
|
)
|
||||||
db.add(record)
|
db.add(record)
|
||||||
@@ -184,6 +239,7 @@ def page_applications(
|
|||||||
rows = query.order_by(JobApplication.applied_at.desc()) \
|
rows = query.order_by(JobApplication.applied_at.desc()) \
|
||||||
.offset((page - 1) * page_size).limit(page_size).all()
|
.offset((page - 1) * page_size).limit(page_size).all()
|
||||||
items = [{
|
items = [{
|
||||||
|
"id": r.id,
|
||||||
"job_title": r.job_title,
|
"job_title": r.job_title,
|
||||||
"company": r.company,
|
"company": r.company,
|
||||||
"salary": r.salary,
|
"salary": r.salary,
|
||||||
@@ -193,8 +249,10 @@ def page_applications(
|
|||||||
"ai_reason": r.ai_reason,
|
"ai_reason": r.ai_reason,
|
||||||
"skip_reason": r.skip_reason,
|
"skip_reason": r.skip_reason,
|
||||||
"greeting": r.greeting,
|
"greeting": r.greeting,
|
||||||
# JD 全文截断,供客户端悬停摘要展示,控制分页响应体积
|
# JD 全文截断,供客户端悬停摘要展示,控制分页响应体积;
|
||||||
|
# 完整内容(含归档文件)通过 /{app_id}/jd 接口按需获取,has_jd 标记有无 JD 可看
|
||||||
"jd_text": (r.jd_text or "")[:500],
|
"jd_text": (r.jd_text or "")[:500],
|
||||||
|
"has_jd": bool(r.jd_text or r.jd_file),
|
||||||
"applied_at": (r.applied_at + timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S"),
|
"applied_at": (r.applied_at + timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S"),
|
||||||
} for r in rows]
|
} for r in rows]
|
||||||
return {
|
return {
|
||||||
@@ -232,3 +290,27 @@ def get_stats(
|
|||||||
total_skipped=count(apply_type="skipped"),
|
total_skipped=count(apply_type="skipped"),
|
||||||
today_applied=today_applied,
|
today_applied=today_applied,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{app_id}/jd", response_model=dict)
|
||||||
|
def get_application_jd(
|
||||||
|
app_id: int,
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""查看单条投递记录的完整 JD:先取 jd_text 字段,为空则读 jd_file 归档文件"""
|
||||||
|
record = db.query(JobApplication).filter(
|
||||||
|
JobApplication.id == app_id,
|
||||||
|
JobApplication.user_id == current_user.id,
|
||||||
|
).first()
|
||||||
|
if not record:
|
||||||
|
raise HTTPException(status_code=404, detail="投递记录不存在")
|
||||||
|
if record.jd_text:
|
||||||
|
return {"id": app_id, "source": "db", "jd_text": record.jd_text}
|
||||||
|
if record.jd_file:
|
||||||
|
target = (PROJECT_ROOT / record.jd_file).resolve()
|
||||||
|
# 防路径穿越:归档文件必须位于项目根目录内,防止库内路径被篡改后读到任意文件
|
||||||
|
if target.is_file() and str(target).startswith(str(PROJECT_ROOT)):
|
||||||
|
return {"id": app_id, "source": "file", "jd_text": target.read_text(encoding="utf-8")}
|
||||||
|
raise HTTPException(status_code=410, detail="JD 归档文件不存在或已丢失")
|
||||||
|
raise HTTPException(status_code=404, detail="该记录未包含 JD")
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
账号注册 / 登录 / 用户状态路由
|
账号注册 / 登录 / 用户状态路由
|
||||||
"""
|
"""
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
from typing import Optional
|
||||||
from fastapi import APIRouter, Depends, HTTPException
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
@@ -9,11 +10,11 @@ from ..auth import (
|
|||||||
create_access_token, get_current_user, hash_password, verify_password,
|
create_access_token, get_current_user, hash_password, verify_password,
|
||||||
)
|
)
|
||||||
from ..database import get_db
|
from ..database import get_db
|
||||||
from ..models import User
|
from ..models import User, RpaStatus
|
||||||
from ..online import is_online, touch, require_online_user
|
from ..online import is_online, touch, require_online_user
|
||||||
from ..schemas import (
|
from ..schemas import (
|
||||||
RegisterRequest, LoginRequest, AuthResponse,
|
RegisterRequest, LoginRequest, AuthResponse,
|
||||||
UserInfo, LoginStatusUpdate, Message,
|
UserInfo, LoginStatusUpdate, Message, HeartbeatIn,
|
||||||
)
|
)
|
||||||
|
|
||||||
router = APIRouter(prefix="/api/auth", tags=["认证与用户"])
|
router = APIRouter(prefix="/api/auth", tags=["认证与用户"])
|
||||||
@@ -60,11 +61,27 @@ def login(req: LoginRequest, db: Session = Depends(get_db)):
|
|||||||
|
|
||||||
@router.post("/heartbeat", response_model=Message)
|
@router.post("/heartbeat", response_model=Message)
|
||||||
def heartbeat(
|
def heartbeat(
|
||||||
|
req: Optional[HeartbeatIn] = None,
|
||||||
current_user: User = Depends(get_current_user),
|
current_user: User = Depends(get_current_user),
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
):
|
):
|
||||||
"""客户端心跳:刷新 last_seen_at,用于在线判定(统一走 online.touch)"""
|
"""客户端心跳:刷新 last_seen_at(在线判定),同时携带 RPA 全量状态写入 rpa_status"""
|
||||||
touch(current_user, db)
|
touch(current_user, db)
|
||||||
|
st = db.query(RpaStatus).filter(RpaStatus.user_id == current_user.id).first()
|
||||||
|
if st is None:
|
||||||
|
st = RpaStatus(user_id=current_user.id)
|
||||||
|
db.add(st)
|
||||||
|
if req:
|
||||||
|
if req.boss_login:
|
||||||
|
st.boss_login = req.boss_login
|
||||||
|
if req.browser:
|
||||||
|
st.browser = req.browser
|
||||||
|
if req.apply_status:
|
||||||
|
st.apply_status = req.apply_status
|
||||||
|
st.current = (req.current or "")[:200] or None
|
||||||
|
st.applied = req.applied
|
||||||
|
st.skipped = req.skipped
|
||||||
|
db.commit()
|
||||||
return Message(msg="ok")
|
return Message(msg="ok")
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,279 @@
|
|||||||
|
"""
|
||||||
|
远程控制路由:云端下发开始/结束任务,客户端轮询执行并回调。
|
||||||
|
|
||||||
|
- 状态快照 rpa_status:心跳携带全量状态上报,每用户一行(单设备)
|
||||||
|
- 任务 rpa_task:pending → running → done/failed,pending 超时 → expired
|
||||||
|
(start_apply / stop_apply 可由控制端手动下发;start_activate / stop_activate
|
||||||
|
仅由定时调度器下发)
|
||||||
|
- 去重(服务端权威拦截):同类型任务未达终态时拒绝重复下发
|
||||||
|
- 定时排程 rpa_schedule:每日到点由 scheduler 自动下发对应任务
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from ..auth import get_current_user
|
||||||
|
from ..database import get_db
|
||||||
|
from ..models import User, RpaStatus, RpaTask, RpaSchedule
|
||||||
|
from ..online import is_online
|
||||||
|
from ..scheduler import KIND_TASK_TYPES, PENDING_EXPIRE_MINUTES
|
||||||
|
from ..schemas import RpaTaskIn, RpaTaskFinishIn, RpaScheduleIn, Message
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/rpa", tags=["远程控制"])
|
||||||
|
|
||||||
|
# 任务终态:达到终态后同类型任务才允许再次下发
|
||||||
|
TERMINAL_STATUS = ("done", "failed", "expired")
|
||||||
|
# 定时排程时间格式:HH:MM(零填充 24 小时制)
|
||||||
|
_TIME_RE = re.compile(r"^([01]\d|2[0-3]):[0-5]\d$")
|
||||||
|
|
||||||
|
|
||||||
|
def _task_dict(t: RpaTask) -> dict:
|
||||||
|
return {
|
||||||
|
"id": t.id,
|
||||||
|
"task_type": t.task_type,
|
||||||
|
"params": json.loads(t.params) if t.params else None,
|
||||||
|
"status": t.status,
|
||||||
|
"result": t.result,
|
||||||
|
"created_at": (t.created_at + timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S"),
|
||||||
|
"updated_at": (t.updated_at + timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/status", response_model=dict)
|
||||||
|
def get_rpa_status(
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""RPA 状态快照(控制端展示):在线 + Boss登录 + 浏览器 + 投递状态"""
|
||||||
|
st = db.query(RpaStatus).filter(RpaStatus.user_id == current_user.id).first()
|
||||||
|
return {
|
||||||
|
"online": is_online(current_user),
|
||||||
|
"boss_login": st.boss_login if st else "unknown",
|
||||||
|
"browser": st.browser if st else "unknown",
|
||||||
|
"apply_status": st.apply_status if st else "idle",
|
||||||
|
"current": st.current if st else None,
|
||||||
|
"applied": st.applied if st else 0,
|
||||||
|
"skipped": st.skipped if st else 0,
|
||||||
|
"updated_at": (st.updated_at + timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S") if st else None,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/tasks", response_model=dict)
|
||||||
|
def create_task(
|
||||||
|
req: RpaTaskIn,
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""控制端下发任务。服务端权威去重:同类型非终态任务存在时拒绝"""
|
||||||
|
if req.task_type not in ("start_apply", "stop_apply"):
|
||||||
|
raise HTTPException(status_code=422, detail="未知任务类型")
|
||||||
|
|
||||||
|
if not is_online(current_user):
|
||||||
|
raise HTTPException(status_code=409, detail="RPA 客户端离线,无法下发任务")
|
||||||
|
|
||||||
|
# 去重拦截:同类型任务未达终态,禁止重复下发
|
||||||
|
dup = db.query(RpaTask).filter(
|
||||||
|
RpaTask.user_id == current_user.id,
|
||||||
|
RpaTask.task_type == req.task_type,
|
||||||
|
RpaTask.status.in_(("pending", "running")),
|
||||||
|
).first()
|
||||||
|
if dup:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=409,
|
||||||
|
detail=f"已有同类型任务未结束(#{dup.id} 状态={dup.status}),请勿重复下发")
|
||||||
|
|
||||||
|
# 基于状态快照的业务预检,避免下发必然失败的任务
|
||||||
|
st = db.query(RpaStatus).filter(RpaStatus.user_id == current_user.id).first()
|
||||||
|
if req.task_type == "start_apply" and st and st.apply_status == "running":
|
||||||
|
raise HTTPException(status_code=409, detail="投递任务已在运行中")
|
||||||
|
if req.task_type == "stop_apply" and st and st.apply_status != "running":
|
||||||
|
raise HTTPException(status_code=409, detail="当前没有运行中的投递任务")
|
||||||
|
|
||||||
|
if req.task_type == "start_apply":
|
||||||
|
params = req.params or {}
|
||||||
|
if not params.get("keywords") or not params.get("city"):
|
||||||
|
raise HTTPException(status_code=422, detail="开始投递必须提供 keywords 与 city")
|
||||||
|
|
||||||
|
task = RpaTask(
|
||||||
|
user_id=current_user.id,
|
||||||
|
task_type=req.task_type,
|
||||||
|
params=json.dumps(req.params or {}, ensure_ascii=False),
|
||||||
|
)
|
||||||
|
db.add(task)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(task)
|
||||||
|
return _task_dict(task)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/tasks", response_model=dict)
|
||||||
|
def list_tasks(
|
||||||
|
limit: int = Query(20, ge=1, le=100),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""控制端任务历史(倒序)"""
|
||||||
|
rows = db.query(RpaTask).filter(RpaTask.user_id == current_user.id) \
|
||||||
|
.order_by(RpaTask.id.desc()).limit(limit).all()
|
||||||
|
return {"items": [_task_dict(t) for t in rows]}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/tasks/pending", response_model=dict)
|
||||||
|
def fetch_pending_task(
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""客户端轮询:取走最早一条 pending 并标记 running(认领即占位,防重复拉取)"""
|
||||||
|
# 顺带过期清理:pending 超时未认领 → expired
|
||||||
|
cutoff = datetime.utcnow() - timedelta(minutes=PENDING_EXPIRE_MINUTES)
|
||||||
|
stale = db.query(RpaTask).filter(
|
||||||
|
RpaTask.user_id == current_user.id,
|
||||||
|
RpaTask.status == "pending",
|
||||||
|
RpaTask.created_at < cutoff,
|
||||||
|
).all()
|
||||||
|
for t in stale:
|
||||||
|
t.status = "expired"
|
||||||
|
t.result = f"超过 {PENDING_EXPIRE_MINUTES} 分钟未执行,自动过期"
|
||||||
|
|
||||||
|
task = db.query(RpaTask).filter(
|
||||||
|
RpaTask.user_id == current_user.id,
|
||||||
|
RpaTask.status == "pending",
|
||||||
|
).order_by(RpaTask.id.asc()).first()
|
||||||
|
if not task:
|
||||||
|
db.commit()
|
||||||
|
return {"task": None}
|
||||||
|
task.status = "running"
|
||||||
|
db.commit()
|
||||||
|
db.refresh(task)
|
||||||
|
return {"task": _task_dict(task)}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/tasks/{task_id}/finish", response_model=Message)
|
||||||
|
def finish_task(
|
||||||
|
task_id: int,
|
||||||
|
req: RpaTaskFinishIn,
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""客户端执行完回调:更新任务终态与结果"""
|
||||||
|
if req.status not in ("done", "failed"):
|
||||||
|
raise HTTPException(status_code=422, detail="回调状态只能为 done/failed")
|
||||||
|
task = db.query(RpaTask).filter(
|
||||||
|
RpaTask.id == task_id,
|
||||||
|
RpaTask.user_id == current_user.id,
|
||||||
|
).first()
|
||||||
|
if not task:
|
||||||
|
raise HTTPException(status_code=404, detail="任务不存在")
|
||||||
|
task.status = req.status
|
||||||
|
task.result = (req.result or "")[:500]
|
||||||
|
db.commit()
|
||||||
|
return Message(msg="ok")
|
||||||
|
|
||||||
|
|
||||||
|
# =======================================================
|
||||||
|
# 定时任务排程(每日到点由调度器自动下发 RpaTask)
|
||||||
|
# =======================================================
|
||||||
|
def _schedule_dict(s: RpaSchedule) -> dict:
|
||||||
|
return {
|
||||||
|
"id": s.id,
|
||||||
|
"kind": s.kind,
|
||||||
|
"params": json.loads(s.params) if s.params else None,
|
||||||
|
"start_time": s.start_time,
|
||||||
|
"end_time": s.end_time,
|
||||||
|
"enabled": bool(s.enabled),
|
||||||
|
"last_start_date": s.last_start_date,
|
||||||
|
"last_stop_date": s.last_stop_date,
|
||||||
|
"last_result": s.last_result,
|
||||||
|
"created_at": (s.created_at + timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/schedules", response_model=dict)
|
||||||
|
def list_schedules(
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""当前用户的定时排程列表(倒序)"""
|
||||||
|
rows = db.query(RpaSchedule).filter(RpaSchedule.user_id == current_user.id) \
|
||||||
|
.order_by(RpaSchedule.id.desc()).all()
|
||||||
|
return {"items": [_schedule_dict(s) for s in rows]}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/schedules", response_model=dict)
|
||||||
|
def create_schedule(
|
||||||
|
req: RpaScheduleIn,
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""创建定时排程。不做客户端在线预检(定时本就是为无人值守场景,
|
||||||
|
下发时若离线由 pending 过期机制兑底)"""
|
||||||
|
if req.kind not in KIND_TASK_TYPES:
|
||||||
|
raise HTTPException(status_code=422, detail="任务类型只能为 apply(自动投递)或 activate(Boss激活)")
|
||||||
|
if not _TIME_RE.match(req.start_time or "") or not _TIME_RE.match(req.end_time or ""):
|
||||||
|
raise HTTPException(status_code=422, detail="时间格式应为 HH:MM(24 小时制)")
|
||||||
|
if req.end_time <= req.start_time:
|
||||||
|
raise HTTPException(status_code=422, detail="结束时间必须晚于开始时间")
|
||||||
|
|
||||||
|
params = req.params or {}
|
||||||
|
if req.kind == "apply":
|
||||||
|
if not params.get("keywords") or not params.get("city"):
|
||||||
|
raise HTTPException(status_code=422, detail="定时投递必须提供 keywords 与 city")
|
||||||
|
else: # activate
|
||||||
|
if not (params.get("match_text") or "").strip():
|
||||||
|
raise HTTPException(status_code=422, detail="定时激活必须提供匹配条件文本 match_text")
|
||||||
|
if not (params.get("reply_message") or "").strip():
|
||||||
|
raise HTTPException(status_code=422, detail="定时激活必须提供激活消息 reply_message")
|
||||||
|
if params.get("status_filter") not in (None, "unread", "read", "all"):
|
||||||
|
raise HTTPException(status_code=422, detail="消息状态过滤取值非法")
|
||||||
|
|
||||||
|
sched = RpaSchedule(
|
||||||
|
user_id=current_user.id,
|
||||||
|
kind=req.kind,
|
||||||
|
params=json.dumps(params, ensure_ascii=False),
|
||||||
|
start_time=req.start_time,
|
||||||
|
end_time=req.end_time,
|
||||||
|
enabled=True,
|
||||||
|
)
|
||||||
|
db.add(sched)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(sched)
|
||||||
|
return _schedule_dict(sched)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/schedules/{schedule_id}", response_model=dict)
|
||||||
|
def toggle_schedule(
|
||||||
|
schedule_id: int,
|
||||||
|
enabled: bool = Query(..., description="启用/停用"),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""启用/停用定时排程"""
|
||||||
|
sched = db.query(RpaSchedule).filter(
|
||||||
|
RpaSchedule.id == schedule_id,
|
||||||
|
RpaSchedule.user_id == current_user.id,
|
||||||
|
).first()
|
||||||
|
if not sched:
|
||||||
|
raise HTTPException(status_code=404, detail="排程不存在")
|
||||||
|
sched.enabled = enabled
|
||||||
|
db.commit()
|
||||||
|
return _schedule_dict(sched)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/schedules/{schedule_id}", response_model=Message)
|
||||||
|
def delete_schedule(
|
||||||
|
schedule_id: int,
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""删除定时排程(仅停止后续调度,不影响已下发的任务)"""
|
||||||
|
sched = db.query(RpaSchedule).filter(
|
||||||
|
RpaSchedule.id == schedule_id,
|
||||||
|
RpaSchedule.user_id == current_user.id,
|
||||||
|
).first()
|
||||||
|
if not sched:
|
||||||
|
raise HTTPException(status_code=404, detail="排程不存在")
|
||||||
|
db.delete(sched)
|
||||||
|
db.commit()
|
||||||
|
return Message(msg="已删除")
|
||||||
@@ -34,9 +34,10 @@ def start_session(
|
|||||||
user_id=current_user.id,
|
user_id=current_user.id,
|
||||||
status="running",
|
status="running",
|
||||||
keywords=req.keywords,
|
keywords=req.keywords,
|
||||||
city_code=req.city_code,
|
city=req.city,
|
||||||
salary_min=req.salary_min,
|
salary_min=req.salary_min,
|
||||||
salary_max=req.salary_max,
|
salary_max=req.salary_max,
|
||||||
|
prompt=req.prompt,
|
||||||
)
|
)
|
||||||
db.add(session)
|
db.add(session)
|
||||||
db.commit()
|
db.commit()
|
||||||
|
|||||||
@@ -0,0 +1,135 @@
|
|||||||
|
"""
|
||||||
|
投递条件模板路由:增删改查 + 套用
|
||||||
|
"""
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from ..auth import get_current_user
|
||||||
|
from ..database import get_db
|
||||||
|
from ..models import ApplyTemplate, User
|
||||||
|
from ..schemas import TemplateIn, TemplateOut
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/templates", tags=["投递模板"])
|
||||||
|
|
||||||
|
|
||||||
|
def _template_out(t: ApplyTemplate) -> dict:
|
||||||
|
return {
|
||||||
|
"id": t.id,
|
||||||
|
"name": t.name,
|
||||||
|
"keywords": t.keywords,
|
||||||
|
"city": t.city,
|
||||||
|
"salary_min": t.salary_min,
|
||||||
|
"salary_max": t.salary_max,
|
||||||
|
"min_score": t.min_score,
|
||||||
|
"daily_limit": t.daily_limit,
|
||||||
|
"boss_online_only": t.boss_online_only,
|
||||||
|
"allow_headhunter": t.allow_headhunter,
|
||||||
|
"prompt": t.prompt,
|
||||||
|
"created_at": t.created_at,
|
||||||
|
"updated_at": t.updated_at,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("", response_model=list[TemplateOut])
|
||||||
|
def list_templates(
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""获取当前用户的所有投递模板(按更新时间倒序)"""
|
||||||
|
rows = db.query(ApplyTemplate).filter(
|
||||||
|
ApplyTemplate.user_id == current_user.id
|
||||||
|
).order_by(ApplyTemplate.updated_at.desc()).all()
|
||||||
|
return rows
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("", response_model=TemplateOut)
|
||||||
|
def create_template(
|
||||||
|
req: TemplateIn,
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""创建投递模板"""
|
||||||
|
t = ApplyTemplate(
|
||||||
|
user_id=current_user.id,
|
||||||
|
name=req.name,
|
||||||
|
keywords=req.keywords,
|
||||||
|
city=req.city,
|
||||||
|
salary_min=req.salary_min,
|
||||||
|
salary_max=req.salary_max,
|
||||||
|
min_score=req.min_score,
|
||||||
|
daily_limit=req.daily_limit,
|
||||||
|
boss_online_only=req.boss_online_only,
|
||||||
|
allow_headhunter=req.allow_headhunter,
|
||||||
|
prompt=req.prompt,
|
||||||
|
)
|
||||||
|
db.add(t)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(t)
|
||||||
|
return t
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{template_id}", response_model=TemplateOut)
|
||||||
|
def get_template(
|
||||||
|
template_id: int,
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""获取单个模板详情"""
|
||||||
|
t = db.query(ApplyTemplate).filter(
|
||||||
|
ApplyTemplate.id == template_id,
|
||||||
|
ApplyTemplate.user_id == current_user.id,
|
||||||
|
).first()
|
||||||
|
if not t:
|
||||||
|
raise HTTPException(status_code=404, detail="模板不存在")
|
||||||
|
return t
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{template_id}", response_model=TemplateOut)
|
||||||
|
def update_template(
|
||||||
|
template_id: int,
|
||||||
|
req: TemplateIn,
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""更新投递模板"""
|
||||||
|
t = db.query(ApplyTemplate).filter(
|
||||||
|
ApplyTemplate.id == template_id,
|
||||||
|
ApplyTemplate.user_id == current_user.id,
|
||||||
|
).first()
|
||||||
|
if not t:
|
||||||
|
raise HTTPException(status_code=404, detail="模板不存在")
|
||||||
|
|
||||||
|
t.name = req.name
|
||||||
|
t.keywords = req.keywords
|
||||||
|
t.city = req.city
|
||||||
|
t.salary_min = req.salary_min
|
||||||
|
t.salary_max = req.salary_max
|
||||||
|
t.min_score = req.min_score
|
||||||
|
t.daily_limit = req.daily_limit
|
||||||
|
t.boss_online_only = req.boss_online_only
|
||||||
|
t.allow_headhunter = req.allow_headhunter
|
||||||
|
t.prompt = req.prompt
|
||||||
|
|
||||||
|
db.commit()
|
||||||
|
db.refresh(t)
|
||||||
|
return t
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{template_id}")
|
||||||
|
def delete_template(
|
||||||
|
template_id: int,
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""删除投递模板"""
|
||||||
|
t = db.query(ApplyTemplate).filter(
|
||||||
|
ApplyTemplate.id == template_id,
|
||||||
|
ApplyTemplate.user_id == current_user.id,
|
||||||
|
).first()
|
||||||
|
if not t:
|
||||||
|
raise HTTPException(status_code=404, detail="模板不存在")
|
||||||
|
db.delete(t)
|
||||||
|
db.commit()
|
||||||
|
return {"ok": True}
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
"""
|
||||||
|
定时任务调度器:后台循环扫描 rpa_schedule 表,每日到点自动下发 RpaTask,
|
||||||
|
客户端通过现有 /api/rpa/tasks/pending 轮询认领执行(认领机制零改动)。
|
||||||
|
|
||||||
|
- 每 SCAN_INTERVAL 秒扫描一轮;排程时间均为北京时间 HH:MM
|
||||||
|
- 每个排程每天只下发一次开始动作、一次结束动作
|
||||||
|
(last_start_date / last_stop_date 记录北京日期防重复)
|
||||||
|
- 下发前复用 RpaTask 去重规则:同类型任务未达终态则跳过本轮,
|
||||||
|
不消耗当日次数,下轮重试
|
||||||
|
- 客户端离线时照常下发:任务 pending 超过 10 分钟无人认领,
|
||||||
|
由 fetch_pending_task 的现有过期机制自动 expired
|
||||||
|
"""
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
|
from loguru import logger
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from .database import SessionLocal
|
||||||
|
from .models import RpaSchedule, RpaTask
|
||||||
|
|
||||||
|
SCAN_INTERVAL = 30 # 秒
|
||||||
|
# pending 超过该时长未客户端认领则过期(与 routers/rpa.py 共用同一常量)
|
||||||
|
PENDING_EXPIRE_MINUTES = 10
|
||||||
|
|
||||||
|
# kind → (开始任务类型, 结束任务类型)
|
||||||
|
KIND_TASK_TYPES = {
|
||||||
|
"apply": ("start_apply", "stop_apply"),
|
||||||
|
"activate": ("start_activate", "stop_activate"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _beijing_now() -> datetime:
|
||||||
|
return datetime.utcnow() + timedelta(hours=8)
|
||||||
|
|
||||||
|
|
||||||
|
def _due(last_date: str | None, hhmm: str, now_cn: datetime) -> bool:
|
||||||
|
"""到点判断:当日未触发过 且 当前 HH:MM 已到(零填充字符串可按字典序比较)"""
|
||||||
|
return last_date != now_cn.strftime("%Y-%m-%d") and now_cn.strftime("%H:%M") >= hhmm
|
||||||
|
|
||||||
|
|
||||||
|
def _dispatch(db: Session, sched: RpaSchedule, start: bool, now_cn: datetime) -> None:
|
||||||
|
"""下发一次开始/结束任务,并更新防重复日期"""
|
||||||
|
task_type = KIND_TASK_TYPES[sched.kind][0 if start else 1]
|
||||||
|
action = "开始" if start else "结束"
|
||||||
|
dup = db.query(RpaTask).filter(
|
||||||
|
RpaTask.user_id == sched.user_id,
|
||||||
|
RpaTask.task_type == task_type,
|
||||||
|
RpaTask.status.in_(("pending", "running")),
|
||||||
|
).first()
|
||||||
|
if dup:
|
||||||
|
# 同类型任务未终态:不消耗当日次数,下一轮重试
|
||||||
|
sched.last_result = f"定时{action}跳过:同类型任务 #{dup.id} 未结束"
|
||||||
|
db.commit()
|
||||||
|
return
|
||||||
|
|
||||||
|
task = RpaTask(
|
||||||
|
user_id=sched.user_id,
|
||||||
|
task_type=task_type,
|
||||||
|
# 只有开始任务携带参数;stop 任务无需 params
|
||||||
|
params=json.dumps(json.loads(sched.params) if sched.params else {},
|
||||||
|
ensure_ascii=False) if start else None,
|
||||||
|
)
|
||||||
|
db.add(task)
|
||||||
|
db.flush() # 先取 task.id 再写排程状态
|
||||||
|
|
||||||
|
today = now_cn.strftime("%Y-%m-%d")
|
||||||
|
if start:
|
||||||
|
sched.last_start_date = today
|
||||||
|
else:
|
||||||
|
sched.last_stop_date = today
|
||||||
|
sched.last_result = f"定时{action}已下发:任务 #{task.id}({task_type})"
|
||||||
|
db.commit()
|
||||||
|
logger.info(f"定时任务排程 #{sched.id}({sched.kind}) {action}已下发 -> RpaTask #{task.id} {task_type}")
|
||||||
|
|
||||||
|
|
||||||
|
def _expire_stale(db: Session) -> None:
|
||||||
|
"""pending 过期清理兜底:客户端长期离线不轮询时,fetch_pending_task 的清理
|
||||||
|
永远不会被触发,残留 pending 会永久阻塞后续调度——由调度器每轮代做"""
|
||||||
|
cutoff = datetime.utcnow() - timedelta(minutes=PENDING_EXPIRE_MINUTES)
|
||||||
|
stale = db.query(RpaTask).filter(
|
||||||
|
RpaTask.status == "pending",
|
||||||
|
RpaTask.created_at < cutoff,
|
||||||
|
).all()
|
||||||
|
for t in stale:
|
||||||
|
t.status = "expired"
|
||||||
|
t.result = f"超过 {PENDING_EXPIRE_MINUTES} 分钟未执行,自动过期"
|
||||||
|
if stale:
|
||||||
|
db.commit()
|
||||||
|
logger.info(f"调度器清理超时未认领任务 {len(stale)} 条")
|
||||||
|
|
||||||
|
|
||||||
|
def tick(db: Session | None = None) -> None:
|
||||||
|
"""单轮扫描。db 可注入(测试用),缺省自建会话;异常只记日志不中断循环"""
|
||||||
|
own = db is None
|
||||||
|
if own:
|
||||||
|
db = SessionLocal()
|
||||||
|
try:
|
||||||
|
_expire_stale(db)
|
||||||
|
now_cn = _beijing_now()
|
||||||
|
rows = db.query(RpaSchedule).filter(RpaSchedule.enabled.is_(True)).all()
|
||||||
|
for s in rows:
|
||||||
|
if s.kind not in KIND_TASK_TYPES:
|
||||||
|
logger.warning(f"定时任务排程 #{s.id} 类型未知({s.kind}),跳过")
|
||||||
|
continue
|
||||||
|
if _due(s.last_start_date, s.start_time, now_cn):
|
||||||
|
_dispatch(db, s, start=True, now_cn=now_cn)
|
||||||
|
if _due(s.last_stop_date, s.end_time, now_cn):
|
||||||
|
_dispatch(db, s, start=False, now_cn=now_cn)
|
||||||
|
except Exception as e:
|
||||||
|
db.rollback()
|
||||||
|
logger.error(f"定时任务扫描异常:{e}")
|
||||||
|
finally:
|
||||||
|
if own:
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
|
||||||
|
async def _loop() -> None:
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
# 同步 DB 操作丢线程池,避免阻塞事件循环
|
||||||
|
await asyncio.to_thread(tick)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"定时任务调度循环异常:{e}")
|
||||||
|
await asyncio.sleep(SCAN_INTERVAL)
|
||||||
|
|
||||||
|
|
||||||
|
def start_scheduler() -> asyncio.Task:
|
||||||
|
"""lifespan 内启动后台调度循环,返回 Task 供关闭时取消"""
|
||||||
|
logger.info(f"定时任务调度器已启动(每 {SCAN_INTERVAL} 秒扫描)")
|
||||||
|
return asyncio.create_task(_loop())
|
||||||
|
|
||||||
|
|
||||||
|
async def stop_scheduler(task: asyncio.Task | None) -> None:
|
||||||
|
if task is None:
|
||||||
|
return
|
||||||
|
task.cancel()
|
||||||
|
try:
|
||||||
|
await task
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
pass
|
||||||
+109
-2
@@ -94,18 +94,20 @@ class ResumeUpdateIn(BaseModel):
|
|||||||
# =======================================================
|
# =======================================================
|
||||||
class SessionStartIn(BaseModel):
|
class SessionStartIn(BaseModel):
|
||||||
keywords: str
|
keywords: str
|
||||||
city_code: str
|
city: str
|
||||||
salary_min: Optional[int] = None
|
salary_min: Optional[int] = None
|
||||||
salary_max: Optional[int] = None
|
salary_max: Optional[int] = None
|
||||||
|
prompt: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
class SessionOut(BaseModel):
|
class SessionOut(BaseModel):
|
||||||
id: int
|
id: int
|
||||||
status: str
|
status: str
|
||||||
keywords: Optional[str]
|
keywords: Optional[str]
|
||||||
city_code: Optional[str]
|
city: Optional[str]
|
||||||
salary_min: Optional[int]
|
salary_min: Optional[int]
|
||||||
salary_max: Optional[int]
|
salary_max: Optional[int]
|
||||||
|
prompt: Optional[str]
|
||||||
applied_count: int
|
applied_count: int
|
||||||
skipped_count: int
|
skipped_count: int
|
||||||
started_at: datetime
|
started_at: datetime
|
||||||
@@ -149,6 +151,8 @@ class ApplicationOut(BaseModel):
|
|||||||
ai_reason: Optional[str]
|
ai_reason: Optional[str]
|
||||||
skip_reason: Optional[str]
|
skip_reason: Optional[str]
|
||||||
jd_text: Optional[str]
|
jd_text: Optional[str]
|
||||||
|
# 超长 JD 归档文件路径(相对项目根目录);与 jd_text 二者只有一非空
|
||||||
|
jd_file: Optional[str] = None
|
||||||
greeting: Optional[str]
|
greeting: Optional[str]
|
||||||
applied_at: datetime
|
applied_at: datetime
|
||||||
|
|
||||||
@@ -156,6 +160,41 @@ class ApplicationOut(BaseModel):
|
|||||||
from_attributes = True
|
from_attributes = True
|
||||||
|
|
||||||
|
|
||||||
|
# =======================================================
|
||||||
|
# 投递条件模板
|
||||||
|
# =======================================================
|
||||||
|
class TemplateIn(BaseModel):
|
||||||
|
name: str = Field(..., min_length=1, max_length=128, description="模板名称")
|
||||||
|
keywords: Optional[str] = Field(None, max_length=512, description="搜索关键词(逗号分隔)")
|
||||||
|
city: Optional[str] = Field(None, max_length=20, description="城市")
|
||||||
|
salary_min: Optional[int] = None
|
||||||
|
salary_max: Optional[int] = None
|
||||||
|
min_score: int = Field(65, ge=0, le=100, description="AI 最低匹配分")
|
||||||
|
daily_limit: int = Field(0, ge=0, description="每日投递上限(0=不限)")
|
||||||
|
boss_online_only: bool = False
|
||||||
|
allow_headhunter: bool = False
|
||||||
|
prompt: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class TemplateOut(BaseModel):
|
||||||
|
id: int
|
||||||
|
name: str
|
||||||
|
keywords: Optional[str]
|
||||||
|
city: Optional[str]
|
||||||
|
salary_min: Optional[int]
|
||||||
|
salary_max: Optional[int]
|
||||||
|
min_score: int
|
||||||
|
daily_limit: int
|
||||||
|
boss_online_only: bool
|
||||||
|
allow_headhunter: bool
|
||||||
|
prompt: Optional[str]
|
||||||
|
created_at: datetime
|
||||||
|
updated_at: datetime
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
from_attributes = True
|
||||||
|
|
||||||
|
|
||||||
# =======================================================
|
# =======================================================
|
||||||
# 公司黑名单
|
# 公司黑名单
|
||||||
# =======================================================
|
# =======================================================
|
||||||
@@ -172,6 +211,37 @@ class BlacklistOut(BaseModel):
|
|||||||
from_attributes = True
|
from_attributes = True
|
||||||
|
|
||||||
|
|
||||||
|
# =======================================================
|
||||||
|
# 远程控制(RPA 状态上报 + 任务下发)
|
||||||
|
# =======================================================
|
||||||
|
class HeartbeatIn(BaseModel):
|
||||||
|
"""心跳携带的 RPA 全量状态(可选,老客户端不带体也兼容)"""
|
||||||
|
boss_login: Optional[str] = None
|
||||||
|
browser: Optional[str] = None
|
||||||
|
apply_status: Optional[str] = None
|
||||||
|
current: Optional[str] = None
|
||||||
|
applied: int = 0
|
||||||
|
skipped: int = 0
|
||||||
|
|
||||||
|
|
||||||
|
class RpaTaskIn(BaseModel):
|
||||||
|
task_type: str = Field(..., description="start_apply / stop_apply")
|
||||||
|
params: Optional[dict] = None
|
||||||
|
|
||||||
|
|
||||||
|
class RpaScheduleIn(BaseModel):
|
||||||
|
"""定时任务排程:每日 start_time 下发开始任务、end_time 下发结束任务(北京时间)"""
|
||||||
|
kind: str = Field(..., description="apply=自动投递 / activate=Boss激活")
|
||||||
|
start_time: str = Field(..., description="每日开始时间 HH:MM")
|
||||||
|
end_time: str = Field(..., description="每日结束时间 HH:MM")
|
||||||
|
params: Optional[dict] = None
|
||||||
|
|
||||||
|
|
||||||
|
class RpaTaskFinishIn(BaseModel):
|
||||||
|
status: str = Field(..., description="done / failed")
|
||||||
|
result: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
# =======================================================
|
# =======================================================
|
||||||
# 通用
|
# 通用
|
||||||
# =======================================================
|
# =======================================================
|
||||||
@@ -179,6 +249,43 @@ class Message(BaseModel):
|
|||||||
msg: str
|
msg: str
|
||||||
|
|
||||||
|
|
||||||
|
# =======================================================
|
||||||
|
# AI 代理(异步打分 + 模型配置)
|
||||||
|
# =======================================================
|
||||||
|
class ScoreConditions(BaseModel):
|
||||||
|
"""本次投递所用条件(客户端每次随打分请求上送)"""
|
||||||
|
keywords: Optional[str] = None
|
||||||
|
city: Optional[str] = None
|
||||||
|
salary_min: Optional[int] = None
|
||||||
|
salary_max: Optional[int] = None
|
||||||
|
# AI 评分引导词(用户自定义额外偏好)
|
||||||
|
prompt: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class ScoreStartIn(BaseModel):
|
||||||
|
# 幂等键:客户端用本机 MAC+时间戳生成的 uuid1 hex(32 位十六进制)
|
||||||
|
request_key: str = Field(..., min_length=32, max_length=32,
|
||||||
|
pattern=r"^[0-9a-fA-F]{32}$",
|
||||||
|
description="uuid1().hex,32 位十六进制")
|
||||||
|
resume_id: int = Field(..., description="主简历 ID,服务端从库中取内容")
|
||||||
|
jd_text: str = Field(..., min_length=1, description="职位 JD 全文")
|
||||||
|
job_ref: Optional[str] = Field(None, max_length=64, description="Boss 职位 ID(审计用)")
|
||||||
|
conditions: Optional[ScoreConditions] = None
|
||||||
|
|
||||||
|
|
||||||
|
class CleanResumeIn(BaseModel):
|
||||||
|
raw_text: str = Field(..., min_length=1, description="抓取到的原始简历文本")
|
||||||
|
|
||||||
|
|
||||||
|
class AIConfigIn(BaseModel):
|
||||||
|
"""模型配置(OpenAI 兼容接口,/view 管理页维护)"""
|
||||||
|
base_url: str = Field("", max_length=255, description="如 https://api.siliconflow.cn/v1")
|
||||||
|
api_key: str = Field("", max_length=255)
|
||||||
|
model: str = Field("", max_length=128)
|
||||||
|
timeout_s: int = Field(300, ge=10, le=600, description="服务端调用大模型超时(秒)")
|
||||||
|
enabled: bool = True
|
||||||
|
|
||||||
|
|
||||||
class StatsOut(BaseModel):
|
class StatsOut(BaseModel):
|
||||||
total_applied: int
|
total_applied: int
|
||||||
total_chat: int
|
total_chat: int
|
||||||
|
|||||||
+463
-6
@@ -72,6 +72,10 @@
|
|||||||
.bl-btn { border: 1px solid #ffd6d6; background: #fff; color: #e64340; border-radius: 4px; font-size: 12px; padding: 1px 8px; cursor: pointer; margin-left: 6px; }
|
.bl-btn { border: 1px solid #ffd6d6; background: #fff; color: #e64340; border-radius: 4px; font-size: 12px; padding: 1px 8px; cursor: pointer; margin-left: 6px; }
|
||||||
.bl-btn:hover { background: #fff1f0; }
|
.bl-btn:hover { background: #fff1f0; }
|
||||||
|
|
||||||
|
/* JD 查看按钮 */
|
||||||
|
.jd-btn { border: 1px solid #91d5ff; background: #fff; color: #1890ff; border-radius: 4px; font-size: 12px; padding: 1px 8px; cursor: pointer; }
|
||||||
|
.jd-btn:hover { background: #e6f7ff; }
|
||||||
|
|
||||||
/* 黑名单页 */
|
/* 黑名单页 */
|
||||||
.bl-add { display: flex; gap: 10px; background: #fff; border-radius: 10px; padding: 16px 18px; box-shadow: 0 2px 8px rgba(0,0,0,.05); margin-bottom: 16px; }
|
.bl-add { display: flex; gap: 10px; background: #fff; border-radius: 10px; padding: 16px 18px; box-shadow: 0 2px 8px rgba(0,0,0,.05); margin-bottom: 16px; }
|
||||||
.bl-add input { flex: 1; padding: 9px 12px; border: 1px solid #d9d9d9; border-radius: 6px; font-size: 14px; }
|
.bl-add input { flex: 1; padding: 9px 12px; border: 1px solid #d9d9d9; border-radius: 6px; font-size: 14px; }
|
||||||
@@ -111,6 +115,8 @@
|
|||||||
<aside>
|
<aside>
|
||||||
<div class="menu-item active" data-page="data">投递数据</div>
|
<div class="menu-item active" data-page="data">投递数据</div>
|
||||||
<div class="menu-item" data-page="blacklist">公司黑名单</div>
|
<div class="menu-item" data-page="blacklist">公司黑名单</div>
|
||||||
|
<div class="menu-item" data-page="remote">远程控制</div>
|
||||||
|
<div class="menu-item" data-page="aiConfig">模型配置</div>
|
||||||
</aside>
|
</aside>
|
||||||
|
|
||||||
<!-- 右侧内容 -->
|
<!-- 右侧内容 -->
|
||||||
@@ -154,7 +160,7 @@
|
|||||||
|
|
||||||
<table>
|
<table>
|
||||||
<thead><tr>
|
<thead><tr>
|
||||||
<th>时间</th><th>职位</th><th>公司</th><th>薪资</th><th>结果</th><th>AI评分</th><th>备注</th>
|
<th>时间</th><th>职位</th><th>公司</th><th>薪资</th><th>结果</th><th>AI评分</th><th>备注</th><th style="width:60px">JD</th>
|
||||||
</tr></thead>
|
</tr></thead>
|
||||||
<tbody id="tbody"></tbody>
|
<tbody id="tbody"></tbody>
|
||||||
</table>
|
</table>
|
||||||
@@ -186,6 +192,121 @@
|
|||||||
<button id="blNext">下一页</button>
|
<button id="blNext">下一页</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- 远程控制 -->
|
||||||
|
<div id="pageRemote" class="hidden">
|
||||||
|
<div class="stats" id="remoteStatus">
|
||||||
|
<div class="stat-card"><div class="num" id="rsOnline">-</div><div class="label">客户端在线</div></div>
|
||||||
|
<div class="stat-card"><div class="num" id="rsBoss">-</div><div class="label">Boss 登录</div></div>
|
||||||
|
<div class="stat-card"><div class="num" id="rsBrowser">-</div><div class="label">浏览器</div></div>
|
||||||
|
<div class="stat-card"><div class="num" id="rsApply">-</div><div class="label">投递状态</div></div>
|
||||||
|
</div>
|
||||||
|
<div class="bl-tip" id="rsDetail">进度:- | 更新:-</div>
|
||||||
|
|
||||||
|
<div class="bl-add" style="flex-wrap:wrap;align-items:flex-end;">
|
||||||
|
<div style="flex:2;min-width:220px;"><label style="font-size:12px;color:#666;">选择模板</label>
|
||||||
|
<select id="rTemplate" style="width:100%;padding:9px 10px;border:1px solid #d9d9d9;border-radius:6px;">
|
||||||
|
<option value="">-- 不使用模板 --</option>
|
||||||
|
</select></div>
|
||||||
|
<div style="display:flex;align-items:flex-end;gap:8px;padding-bottom:10px;">
|
||||||
|
<button id="btnRefreshTemplates" type="button">刷新模板</button>
|
||||||
|
<button id="btnSaveTemplateRemote" type="button">保存为模板</button>
|
||||||
|
<button id="btnManageTemplatesRemote" type="button">管理模板</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="bl-add" style="flex-wrap:wrap;align-items:flex-end;">
|
||||||
|
<div style="flex:2;min-width:220px;"><label style="font-size:12px;color:#666;">搜索关键词(多个用逗号分隔)</label>
|
||||||
|
<input type="text" id="rKeywords" placeholder="如:Python开发,后端工程师" value="Python开发"></div>
|
||||||
|
<div style="min-width:110px;"><label style="font-size:12px;color:#666;">城市</label>
|
||||||
|
<select id="rCity" style="width:100%;padding:9px 10px;border:1px solid #d9d9d9;border-radius:6px;">
|
||||||
|
<option value="北京">北京</option><option value="上海">上海</option>
|
||||||
|
<option value="广州">广州</option><option value="深圳">深圳</option>
|
||||||
|
<option value="杭州">杭州</option><option value="成都">成都</option>
|
||||||
|
<option value="西安">西安</option><option value="济南">济南</option>
|
||||||
|
</select></div>
|
||||||
|
<div style="width:110px;"><label style="font-size:12px;color:#666;">AI 最低匹配分</label>
|
||||||
|
<input type="number" id="rScore" value="65" min="0" max="100"></div>
|
||||||
|
<div style="width:100px;"><label style="font-size:12px;color:#666;">最低薪资 (K)</label>
|
||||||
|
<input type="number" id="rSalaryMin" value="15" min="0"></div>
|
||||||
|
<div style="width:100px;"><label style="font-size:12px;color:#666;">最高薪资 (K)</label>
|
||||||
|
<input type="number" id="rSalaryMax" value="40" min="0"></div>
|
||||||
|
<div style="width:140px;"><label style="font-size:12px;color:#666;">每日投递上限(0=不限)</label>
|
||||||
|
<input type="number" id="rLimit" value="30" min="0"></div>
|
||||||
|
<label style="display:flex;align-items:center;gap:4px;font-size:13px;padding-bottom:10px;"><input type="checkbox" id="rOnlineOnly"> 只投递 Boss 在线的</label>
|
||||||
|
<label style="display:flex;align-items:center;gap:4px;font-size:13px;padding-bottom:10px;"><input type="checkbox" id="rHunter"> 考虑猎头职位</label>
|
||||||
|
<button id="btnStartRemote" style="background:#1890ff;">开始投递</button>
|
||||||
|
<button id="btnStopRemote">结束投递</button>
|
||||||
|
</div>
|
||||||
|
<div class="bl-add" style="flex-wrap:wrap;align-items:flex-end;">
|
||||||
|
<div style="flex:1;min-width:300px;"><label style="font-size:12px;color:#666;">AI 引导词(可选)</label>
|
||||||
|
<textarea id="rPrompt" rows="3" style="width:100%;padding:9px 10px;border:1px solid #d9d9d9;border-radius:6px;resize:vertical;" placeholder="例如:优先投递 Java 后端岗位,接受 10-15K,有 AI 项目经验优先"></textarea></div>
|
||||||
|
</div>
|
||||||
|
<div class="bl-tip">任务下发后客户端 5 秒内认领执行;同类型任务未结束前不能重复下发。</div>
|
||||||
|
|
||||||
|
<!-- 定时任务(每日自动:到点下发开始,到结束时间自动停止) -->
|
||||||
|
<div style="font-size:14px;font-weight:600;color:#1890ff;margin:18px 4px 10px;">定时任务(每日自动)</div>
|
||||||
|
<div class="bl-add" style="flex-wrap:wrap;align-items:flex-end;">
|
||||||
|
<div style="min-width:130px;"><label style="font-size:12px;color:#666;">任务类型</label>
|
||||||
|
<select id="schKind" style="width:100%;padding:9px 10px;border:1px solid #d9d9d9;border-radius:6px;">
|
||||||
|
<option value="apply">自动投递</option>
|
||||||
|
<option value="activate">Boss 激活</option>
|
||||||
|
</select></div>
|
||||||
|
<div style="min-width:120px;"><label style="font-size:12px;color:#666;">每日开始时间</label>
|
||||||
|
<input type="time" id="schStart" value="09:00" style="width:100%;padding:8px 10px;border:1px solid #d9d9d9;border-radius:6px;"></div>
|
||||||
|
<div style="min-width:120px;"><label style="font-size:12px;color:#666;">每日结束时间</label>
|
||||||
|
<input type="time" id="schEnd" value="18:00" style="width:100%;padding:8px 10px;border:1px solid #d9d9d9;border-radius:6px;"></div>
|
||||||
|
<button id="btnSchAdd" style="background:#1890ff;">添加排程</button>
|
||||||
|
</div>
|
||||||
|
<!-- Boss 激活专属参数(任务类型=激活时显示;自动投递使用上方投递表单的条件) -->
|
||||||
|
<div class="bl-add hidden" id="schActParams" style="flex-wrap:wrap;align-items:flex-end;">
|
||||||
|
<div style="flex:2;min-width:220px;"><label style="font-size:12px;color:#666;">匹配条件文本</label>
|
||||||
|
<input type="text" id="schMatch" placeholder="与对方最后一条消息比对,如:Python开发" style="width:100%;padding:9px 10px;border:1px solid #d9d9d9;border-radius:6px;"></div>
|
||||||
|
<div style="min-width:110px;"><label style="font-size:12px;color:#666;">消息状态</label>
|
||||||
|
<select id="schStatus" style="width:100%;padding:9px 10px;border:1px solid #d9d9d9;border-radius:6px;">
|
||||||
|
<option value="unread" selected>仅未读</option>
|
||||||
|
<option value="read">仅已读</option>
|
||||||
|
<option value="all">不限</option>
|
||||||
|
</select></div>
|
||||||
|
<div style="width:100px;"><label style="font-size:12px;color:#666;">匹配阈值</label>
|
||||||
|
<input type="number" id="schThreshold" value="80" min="0" max="100" style="width:100%;padding:9px 10px;border:1px solid #d9d9d9;border-radius:6px;"></div>
|
||||||
|
<div style="flex:2;min-width:220px;"><label style="font-size:12px;color:#666;">激活消息</label>
|
||||||
|
<input type="text" id="schReply" placeholder="命中后发送的消息内容" style="width:100%;padding:9px 10px;border:1px solid #d9d9d9;border-radius:6px;"></div>
|
||||||
|
<div style="width:130px;"><label style="font-size:12px;color:#666;">发送上限(0=不限)</label>
|
||||||
|
<input type="number" id="schMax" value="20" min="0" style="width:100%;padding:9px 10px;border:1px solid #d9d9d9;border-radius:6px;"></div>
|
||||||
|
<label style="display:flex;align-items:center;gap:4px;font-size:13px;padding-bottom:10px;"><input type="checkbox" id="schDry"> 试跑(只识别不发送)</label>
|
||||||
|
</div>
|
||||||
|
<div class="bl-tip">自动投递使用上方投递表单的条件;结束时间到点自动下发停止任务;客户端离线时任务 10 分钟未认领自动过期;每条排程每天各触发一次开始/结束。</div>
|
||||||
|
<table>
|
||||||
|
<thead><tr><th style="width:50px">#</th><th style="width:90px">类型</th><th style="width:90px">每日开始</th><th style="width:90px">每日结束</th><th style="width:70px">状态</th><th>最近调度</th><th style="width:130px">操作</th></tr></thead>
|
||||||
|
<tbody id="schTbody"></tbody>
|
||||||
|
</table>
|
||||||
|
<div class="empty hidden" id="schEmpty">暂无定时任务</div>
|
||||||
|
|
||||||
|
<table style="margin-top:18px;">
|
||||||
|
<thead><tr><th style="width:150px">时间</th><th style="width:100px">类型</th><th style="width:90px">状态</th><th>结果</th></tr></thead>
|
||||||
|
<tbody id="taskTbody"></tbody>
|
||||||
|
</table>
|
||||||
|
<div class="empty hidden" id="taskEmpty">暂无远程任务</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 模型配置(AI 代理:客户端评分统一经服务端转发) -->
|
||||||
|
<div id="pageAiConfig" class="hidden">
|
||||||
|
<div class="bl-tip">客户端的 AI 评分/简历整理统一由服务端代理调用大模型(OpenAI 兼容接口),客户端不再保存任何模型密钥。</div>
|
||||||
|
<div class="bl-add" style="flex-wrap:wrap;align-items:flex-end;">
|
||||||
|
<div style="flex:2;min-width:260px;"><label style="font-size:12px;color:#666;">Base URL(OpenAI 兼容)</label>
|
||||||
|
<input type="text" id="aiBaseUrl" placeholder="如:https://api.siliconflow.cn/v1" style="width:100%;padding:9px 10px;border:1px solid #d9d9d9;border-radius:6px;"></div>
|
||||||
|
<div style="flex:2;min-width:260px;"><label style="font-size:12px;color:#666;">API Key</label>
|
||||||
|
<input type="text" id="aiApiKey" placeholder="sk-..." style="width:100%;padding:9px 10px;border:1px solid #d9d9d9;border-radius:6px;"></div>
|
||||||
|
<div style="min-width:220px;"><label style="font-size:12px;color:#666;">模型名</label>
|
||||||
|
<input type="text" id="aiModel" placeholder="如:deepseek-ai/DeepSeek-V3" style="width:100%;padding:9px 10px;border:1px solid #d9d9d9;border-radius:6px;"></div>
|
||||||
|
<div style="width:150px;"><label style="font-size:12px;color:#666;">调用超时(秒,10-600)</label>
|
||||||
|
<input type="number" id="aiTimeout" value="300" min="10" max="600" style="width:100%;padding:9px 10px;border:1px solid #d9d9d9;border-radius:6px;"></div>
|
||||||
|
<label style="display:flex;align-items:center;gap:4px;font-size:13px;padding-bottom:10px;"><input type="checkbox" id="aiEnabled" checked> 启用 AI 代理</label>
|
||||||
|
<button id="btnAiSave" style="background:#1890ff;">保存配置</button>
|
||||||
|
<button id="btnAiTest">连通测试</button>
|
||||||
|
</div>
|
||||||
|
<div class="bl-tip" id="aiConfigTip">更新时间:-</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -293,9 +414,12 @@ async function load() {
|
|||||||
const company = r.company || '';
|
const company = r.company || '';
|
||||||
const blBtn = (company && !blSet.has(company))
|
const blBtn = (company && !blSet.has(company))
|
||||||
? '<button class="bl-btn" data-company="' + esc(company) + '">拉黑</button>' : '';
|
? '<button class="bl-btn" data-company="' + esc(company) + '">拉黑</button>' : '';
|
||||||
|
// JD 列:有 JD(库内字段或归档文件)才可点开查看全文,走 /api/jobs/{id}/jd 按需拉取
|
||||||
|
const jdBtn = r.has_jd
|
||||||
|
? '<button class="jd-btn" data-id="' + r.id + '">查看</button>' : '<span style="color:#ccc;">-</span>';
|
||||||
return '<tr><td>' + esc(r.applied_at) + '</td><td>' + esc(r.job_title) + '</td><td>' + esc(company) + blBtn +
|
return '<tr><td>' + esc(r.applied_at) + '</td><td>' + esc(r.job_title) + '</td><td>' + esc(company) + blBtn +
|
||||||
'</td><td>' + esc(r.salary) + '</td><td>' + type + '</td><td>' + score +
|
'</td><td>' + esc(r.salary) + '</td><td>' + type + '</td><td>' + score +
|
||||||
'</td><td class="remark" title="' + esc(remark) + '">' + esc(remark) + '</td></tr>';
|
'</td><td class="remark" title="' + esc(remark) + '">' + esc(remark) + '</td><td>' + jdBtn + '</td></tr>';
|
||||||
}).join('');
|
}).join('');
|
||||||
document.getElementById('empty').classList.toggle('hidden', (d.items || []).length > 0);
|
document.getElementById('empty').classList.toggle('hidden', (d.items || []).length > 0);
|
||||||
|
|
||||||
@@ -348,13 +472,172 @@ async function removeBlacklist(id) {
|
|||||||
} catch (e) { alert('移除失败:' + (e.message || '')); }
|
} catch (e) { alert('移除失败:' + (e.message || '')); }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ---------- 远程控制 ---------- */
|
||||||
|
const TASK_TXT = { start_apply: '开始投递', stop_apply: '结束投递', start_activate: '开始激活', stop_activate: '停止激活' };
|
||||||
|
const TASK_STATUS_TXT = { pending: '待认领', running: '执行中', done: '已完成', failed: '失败', expired: '已过期' };
|
||||||
|
|
||||||
|
async function loadRemote() {
|
||||||
|
try {
|
||||||
|
const st = await api('/api/rpa/status');
|
||||||
|
const put = (id, txt, cls) => {
|
||||||
|
const el = document.getElementById(id);
|
||||||
|
el.textContent = txt;
|
||||||
|
el.className = 'num ' + (cls || '');
|
||||||
|
};
|
||||||
|
put('rsOnline', st.online ? '在线' : '离线', st.online ? 'green' : 'orange');
|
||||||
|
put('rsBoss', st.boss_login === 'logged_in' ? '已登录' : (st.boss_login === 'logging_in' ? '登录中' : '未登录'),
|
||||||
|
st.boss_login === 'logged_in' ? 'green' : 'orange');
|
||||||
|
put('rsBrowser', st.browser === 'running' ? '运行中' : '已停止', st.browser === 'running' ? 'green' : 'orange');
|
||||||
|
put('rsApply', st.apply_status === 'running' ? '运行中' : '空闲', st.apply_status === 'running' ? 'blue' : 'green');
|
||||||
|
document.getElementById('rsDetail').textContent =
|
||||||
|
'进度:' + (st.apply_status === 'running' ? (st.current || '-') + ' 投' + st.applied + '/跳' + st.skipped : '-') +
|
||||||
|
' | 状态更新:' + (st.updated_at || '-');
|
||||||
|
} catch (e) { /* 401 已在 api 内处理 */ }
|
||||||
|
try {
|
||||||
|
const d = await api('/api/rpa/tasks?limit=15');
|
||||||
|
const items = d.items || [];
|
||||||
|
document.getElementById('taskTbody').innerHTML = items.map(t =>
|
||||||
|
'<tr><td>' + esc(t.created_at) + '</td><td>' + (TASK_TXT[t.task_type] || t.task_type) + '</td><td>' +
|
||||||
|
(TASK_STATUS_TXT[t.status] || t.status) + '</td><td>' + esc(t.result || '-') + '</td></tr>'
|
||||||
|
).join('');
|
||||||
|
document.getElementById('taskEmpty').classList.toggle('hidden', items.length > 0);
|
||||||
|
} catch (e) { /* ignore */ }
|
||||||
|
loadSchedules();
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- 定时任务排程 ---------- */
|
||||||
|
const SCH_KIND_TXT = { apply: '自动投递', activate: 'Boss 激活' };
|
||||||
|
|
||||||
|
async function loadSchedules() {
|
||||||
|
try {
|
||||||
|
const d = await api('/api/rpa/schedules');
|
||||||
|
const items = d.items || [];
|
||||||
|
document.getElementById('schTbody').innerHTML = items.map(s =>
|
||||||
|
'<tr><td>' + s.id + '</td><td>' + (SCH_KIND_TXT[s.kind] || esc(s.kind)) + '</td><td>' + esc(s.start_time) +
|
||||||
|
'</td><td>' + esc(s.end_time) + '</td><td>' +
|
||||||
|
(s.enabled ? '<span style="color:#52c41a;">启用</span>' : '<span style="color:#999;">停用</span>') +
|
||||||
|
'</td><td class="remark" title="' + esc(s.last_result || '') + '">' + esc(s.last_result || '-') +
|
||||||
|
'</td><td><button class="bl-remove sch-toggle" data-id="' + s.id + '" data-enabled="' + (s.enabled ? 0 : 1) + '">' +
|
||||||
|
(s.enabled ? '停用' : '启用') + '</button> <button class="bl-remove sch-del" data-id="' + s.id + '" style="color:#e64340;">删除</button></td></tr>'
|
||||||
|
).join('');
|
||||||
|
document.getElementById('schEmpty').classList.toggle('hidden', items.length > 0);
|
||||||
|
} catch (e) { /* 401 已在 api 内处理 */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function addSchedule() {
|
||||||
|
const kind = document.getElementById('schKind').value;
|
||||||
|
const startTime = document.getElementById('schStart').value;
|
||||||
|
const endTime = document.getElementById('schEnd').value;
|
||||||
|
if (!startTime || !endTime) { alert('请选择开始/结束时间'); return; }
|
||||||
|
let params;
|
||||||
|
if (kind === 'apply') {
|
||||||
|
// 复用页面上方投递表单的条件(与手动开始投递同一套参数)
|
||||||
|
const keywords = (document.getElementById('rKeywords').value || '').split(/[,,\s]+/).filter(Boolean);
|
||||||
|
if (!keywords.length) { alert('自动投递需先在上方表单填写搜索关键词'); return; }
|
||||||
|
params = {
|
||||||
|
keywords,
|
||||||
|
city: document.getElementById('rCity').value,
|
||||||
|
min_score: parseInt(document.getElementById('rScore').value, 10) || 65,
|
||||||
|
salary_min: parseInt(document.getElementById('rSalaryMin').value, 10) || 0,
|
||||||
|
salary_max: parseInt(document.getElementById('rSalaryMax').value, 10) || 0,
|
||||||
|
daily_limit: parseInt(document.getElementById('rLimit').value, 10) || 0,
|
||||||
|
boss_online_only: document.getElementById('rOnlineOnly').checked,
|
||||||
|
allow_headhunter: document.getElementById('rHunter').checked,
|
||||||
|
prompt: document.getElementById('rPrompt').value.trim() || null,
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
params = {
|
||||||
|
match_text: document.getElementById('schMatch').value.trim(),
|
||||||
|
status_filter: document.getElementById('schStatus').value,
|
||||||
|
threshold: parseInt(document.getElementById('schThreshold').value, 10) || 80,
|
||||||
|
reply_message: document.getElementById('schReply').value.trim(),
|
||||||
|
max_count: parseInt(document.getElementById('schMax').value, 10) || 0,
|
||||||
|
dry_run: document.getElementById('schDry').checked,
|
||||||
|
};
|
||||||
|
if (!params.match_text) { alert('Boss 激活需填写匹配条件文本'); return; }
|
||||||
|
if (!params.reply_message) { alert('Boss 激活需填写激活消息'); return; }
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await api('/api/rpa/schedules', { method: 'POST', body: JSON.stringify({
|
||||||
|
kind, start_time: startTime, end_time: endTime, params,
|
||||||
|
})});
|
||||||
|
await loadSchedules();
|
||||||
|
} catch (e) { alert('添加失败:' + (e.message || '')); }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function sendTask(taskType, params) {
|
||||||
|
try {
|
||||||
|
await api('/api/rpa/tasks', { method: 'POST', body: JSON.stringify({ task_type: taskType, params }) });
|
||||||
|
await loadRemote();
|
||||||
|
} catch (e) { alert('下发失败:' + (e.message || '')); }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- 模型配置(AI 代理) ---------- */
|
||||||
|
async function loadAiConfig() {
|
||||||
|
try {
|
||||||
|
const d = await api('/api/ai/config?with_key=true');
|
||||||
|
document.getElementById('aiBaseUrl').value = d.base_url || '';
|
||||||
|
document.getElementById('aiApiKey').value = d.api_key || '';
|
||||||
|
document.getElementById('aiModel').value = d.model || '';
|
||||||
|
document.getElementById('aiTimeout').value = d.timeout_s || 300;
|
||||||
|
document.getElementById('aiEnabled').checked = !!d.enabled;
|
||||||
|
document.getElementById('aiConfigTip').textContent = '更新时间:' + (d.updated_at || '-');
|
||||||
|
} catch (e) { /* 401 已在 api 内处理 */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveAiConfig() {
|
||||||
|
try {
|
||||||
|
await api('/api/ai/config', { method: 'PUT', body: JSON.stringify({
|
||||||
|
base_url: document.getElementById('aiBaseUrl').value.trim(),
|
||||||
|
api_key: document.getElementById('aiApiKey').value.trim(),
|
||||||
|
model: document.getElementById('aiModel').value.trim(),
|
||||||
|
timeout_s: parseInt(document.getElementById('aiTimeout').value, 10) || 300,
|
||||||
|
enabled: document.getElementById('aiEnabled').checked,
|
||||||
|
})});
|
||||||
|
alert('模型配置已保存');
|
||||||
|
await loadAiConfig();
|
||||||
|
} catch (e) { alert('保存失败:' + (e.message || '')); }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function testAiConfig() {
|
||||||
|
try {
|
||||||
|
const d = await api('/api/ai/config/test', { method: 'POST' });
|
||||||
|
alert(d.ok ? '连通测试通过' : '连通失败:' + d.detail);
|
||||||
|
} catch (e) { alert('测试失败:' + (e.message || '')); }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- 岗位 JD 查看(先取库内字段,为空由服务端读归档文件) ---------- */
|
||||||
|
async function showJd(appId) {
|
||||||
|
const body = document.getElementById('jdBody');
|
||||||
|
const tip = document.getElementById('jdTip');
|
||||||
|
document.getElementById('jdModal').classList.remove('hidden');
|
||||||
|
tip.textContent = '加载中…';
|
||||||
|
body.textContent = '';
|
||||||
|
try {
|
||||||
|
const d = await api('/api/jobs/' + appId + '/jd');
|
||||||
|
tip.textContent = '来源:' + (d.source === 'file' ? '归档文件' : '数据库字段') +
|
||||||
|
' · ' + (d.jd_text || '').length + ' 字';
|
||||||
|
body.textContent = d.jd_text || '';
|
||||||
|
} catch (e) {
|
||||||
|
tip.textContent = '加载失败';
|
||||||
|
body.textContent = e.message || '无 JD 数据';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeJd() {
|
||||||
|
document.getElementById('jdModal').classList.add('hidden');
|
||||||
|
}
|
||||||
|
|
||||||
/* ---------- 页面切换 ---------- */
|
/* ---------- 页面切换 ---------- */
|
||||||
function switchPage(page) {
|
function switchPage(page) {
|
||||||
document.querySelectorAll('aside .menu-item').forEach(el =>
|
document.querySelectorAll('aside .menu-item').forEach(el =>
|
||||||
el.classList.toggle('active', el.dataset.page === page));
|
el.classList.toggle('active', el.dataset.page === page));
|
||||||
document.getElementById('pageData').classList.toggle('hidden', page !== 'data');
|
document.getElementById('pageData').classList.toggle('hidden', page !== 'data');
|
||||||
document.getElementById('pageBlacklist').classList.toggle('hidden', page !== 'blacklist');
|
document.getElementById('pageBlacklist').classList.toggle('hidden', page !== 'blacklist');
|
||||||
if (page === 'data') load(); else loadBlacklist();
|
document.getElementById('pageRemote').classList.toggle('hidden', page !== 'remote');
|
||||||
|
document.getElementById('pageAiConfig').classList.toggle('hidden', page !== 'aiConfig');
|
||||||
|
if (page === 'data') load(); else if (page === 'blacklist') loadBlacklist();
|
||||||
|
else if (page === 'aiConfig') loadAiConfig(); else loadRemote();
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ---------- 事件绑定 ---------- */
|
/* ---------- 事件绑定 ---------- */
|
||||||
@@ -405,17 +688,159 @@ document.getElementById('blCompany').addEventListener('keydown', e => {
|
|||||||
});
|
});
|
||||||
document.getElementById('blPrev').onclick = () => { if (blState.page > 1) { blState.page--; loadBlacklist(); } };
|
document.getElementById('blPrev').onclick = () => { if (blState.page > 1) { blState.page--; loadBlacklist(); } };
|
||||||
document.getElementById('blNext').onclick = () => { blState.page++; loadBlacklist(); };
|
document.getElementById('blNext').onclick = () => { blState.page++; loadBlacklist(); };
|
||||||
|
|
||||||
|
// 远程控制
|
||||||
|
document.getElementById('btnStartRemote').onclick = () => {
|
||||||
|
const keywords = (document.getElementById('rKeywords').value || '').split(/[,,\s]+/).filter(Boolean);
|
||||||
|
if (!keywords.length) { alert('请填写搜索关键词'); return; }
|
||||||
|
if (!confirm('确认远程启动投递任务?')) return;
|
||||||
|
sendTask('start_apply', {
|
||||||
|
keywords,
|
||||||
|
city: document.getElementById('rCity').value,
|
||||||
|
min_score: parseInt(document.getElementById('rScore').value, 10) || 65,
|
||||||
|
salary_min: parseInt(document.getElementById('rSalaryMin').value, 10) || 0,
|
||||||
|
salary_max: parseInt(document.getElementById('rSalaryMax').value, 10) || 0,
|
||||||
|
daily_limit: parseInt(document.getElementById('rLimit').value, 10) || 0,
|
||||||
|
boss_online_only: document.getElementById('rOnlineOnly').checked,
|
||||||
|
allow_headhunter: document.getElementById('rHunter').checked,
|
||||||
|
prompt: document.getElementById('rPrompt').value.trim() || null,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
document.getElementById('btnStopRemote').onclick = () => {
|
||||||
|
if (!confirm('确认远程结束投递任务?')) return;
|
||||||
|
sendTask('stop_apply', null);
|
||||||
|
};
|
||||||
|
document.getElementById('btnAiSave').onclick = saveAiConfig;
|
||||||
|
document.getElementById('btnAiTest').onclick = testAiConfig;
|
||||||
|
// 定时任务:类型切换显隐激活参数区 + 添加/启停/删除
|
||||||
|
document.getElementById('schKind').addEventListener('change', () => {
|
||||||
|
document.getElementById('schActParams').classList.toggle('hidden',
|
||||||
|
document.getElementById('schKind').value !== 'activate');
|
||||||
|
});
|
||||||
|
document.getElementById('btnSchAdd').onclick = addSchedule;
|
||||||
|
document.getElementById('schTbody').addEventListener('click', async e => {
|
||||||
|
const tog = e.target.closest('.sch-toggle');
|
||||||
|
if (tog) {
|
||||||
|
try {
|
||||||
|
await api('/api/rpa/schedules/' + tog.dataset.id + '?enabled=' + tog.dataset.enabled, { method: 'PUT' });
|
||||||
|
await loadSchedules();
|
||||||
|
} catch (err) { alert('操作失败:' + (err.message || '')); }
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const del = e.target.closest('.sch-del');
|
||||||
|
if (del && confirm('确定删除该定时任务?删除后不再自动调度。')) {
|
||||||
|
try {
|
||||||
|
await api('/api/rpa/schedules/' + del.dataset.id, { method: 'DELETE' });
|
||||||
|
await loadSchedules();
|
||||||
|
} catch (err) { alert('删除失败:' + (err.message || '')); }
|
||||||
|
}
|
||||||
|
});
|
||||||
document.getElementById('blTbody').addEventListener('click', e => {
|
document.getElementById('blTbody').addEventListener('click', e => {
|
||||||
const btn = e.target.closest('.bl-remove');
|
const btn = e.target.closest('.bl-remove');
|
||||||
if (btn) removeBlacklist(btn.dataset.id);
|
if (btn) removeBlacklist(btn.dataset.id);
|
||||||
});
|
});
|
||||||
document.getElementById('tbody').addEventListener('click', e => {
|
document.getElementById('tbody').addEventListener('click', e => {
|
||||||
|
const jdBtn = e.target.closest('.jd-btn');
|
||||||
|
if (jdBtn) { showJd(jdBtn.dataset.id); return; }
|
||||||
const btn = e.target.closest('.bl-btn');
|
const btn = e.target.closest('.bl-btn');
|
||||||
if (btn && confirm('确认拉黑公司「' + btn.dataset.company + '」?拉黑后将不再投递该公司。')) {
|
if (btn && confirm('确认拉黑公司「' + btn.dataset.company + '」?拉黑后将不再投递该公司。')) {
|
||||||
addBlacklist(btn.dataset.company);
|
addBlacklist(btn.dataset.company);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// 远程模板管理
|
||||||
|
let remoteTemplates = [];
|
||||||
|
|
||||||
|
async function loadRemoteTemplates() {
|
||||||
|
try {
|
||||||
|
remoteTemplates = await api('/api/templates') || [];
|
||||||
|
const select = document.getElementById('rTemplate');
|
||||||
|
select.innerHTML = '<option value="">-- 不使用模板 --</option>';
|
||||||
|
remoteTemplates.forEach(t => {
|
||||||
|
const opt = document.createElement('option');
|
||||||
|
opt.value = t.id;
|
||||||
|
opt.textContent = t.name;
|
||||||
|
select.appendChild(opt);
|
||||||
|
});
|
||||||
|
} catch (e) { console.error('加载模板失败', e); }
|
||||||
|
}
|
||||||
|
|
||||||
|
function fillRemoteForm(t) {
|
||||||
|
document.getElementById('rKeywords').value = (t.keywords || '').replace(/,/g, ', ');
|
||||||
|
document.getElementById('rCity').value = t.city || '北京';
|
||||||
|
document.getElementById('rScore').value = t.min_score || 65;
|
||||||
|
document.getElementById('rSalaryMin').value = t.salary_min || 0;
|
||||||
|
document.getElementById('rSalaryMax').value = t.salary_max || 0;
|
||||||
|
document.getElementById('rLimit').value = t.daily_limit || 0;
|
||||||
|
document.getElementById('rOnlineOnly').checked = !!t.boss_online_only;
|
||||||
|
document.getElementById('rHunter').checked = !!t.allow_headhunter;
|
||||||
|
document.getElementById('rPrompt').value = t.prompt || '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function collectRemoteTemplate() {
|
||||||
|
return {
|
||||||
|
keywords: document.getElementById('rKeywords').value.split(/[,,\s]+/).filter(Boolean).join(','),
|
||||||
|
city: document.getElementById('rCity').value,
|
||||||
|
salary_min: parseInt(document.getElementById('rSalaryMin').value, 10) || null,
|
||||||
|
salary_max: parseInt(document.getElementById('rSalaryMax').value, 10) || null,
|
||||||
|
min_score: parseInt(document.getElementById('rScore').value, 10) || 65,
|
||||||
|
daily_limit: parseInt(document.getElementById('rLimit').value, 10) || 0,
|
||||||
|
boss_online_only: document.getElementById('rOnlineOnly').checked,
|
||||||
|
allow_headhunter: document.getElementById('rHunter').checked,
|
||||||
|
prompt: document.getElementById('rPrompt').value.trim() || null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
document.getElementById('rTemplate').addEventListener('change', () => {
|
||||||
|
const id = document.getElementById('rTemplate').value;
|
||||||
|
if (!id) return;
|
||||||
|
const t = remoteTemplates.find(x => String(x.id) === id);
|
||||||
|
if (t) fillRemoteForm(t);
|
||||||
|
});
|
||||||
|
|
||||||
|
document.getElementById('btnRefreshTemplates').onclick = loadRemoteTemplates;
|
||||||
|
|
||||||
|
document.getElementById('btnSaveTemplateRemote').onclick = async () => {
|
||||||
|
const name = prompt('请输入模板名称:');
|
||||||
|
if (!name || !name.trim()) return;
|
||||||
|
try {
|
||||||
|
await api('/api/templates', { method: 'POST', body: JSON.stringify({ name: name.trim(), ...collectRemoteTemplate() }) });
|
||||||
|
alert('模板已保存');
|
||||||
|
await loadRemoteTemplates();
|
||||||
|
} catch (e) { alert('保存失败:' + (e.message || '')); }
|
||||||
|
};
|
||||||
|
|
||||||
|
async function renderRemoteTemplates() {
|
||||||
|
await loadRemoteTemplates();
|
||||||
|
const tbody = document.getElementById('tmplTbody');
|
||||||
|
if (!remoteTemplates.length) {
|
||||||
|
tbody.innerHTML = '<tr><td colspan="4" style="text-align:center;color:#999;padding:12px;">暂无模板</td></tr>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
tbody.innerHTML = remoteTemplates.map(t => '<tr><td style="padding:8px;border-bottom:1px solid #f0f0f0;">' + esc(t.name) + '</td><td style="padding:8px;border-bottom:1px solid #f0f0f0;">' + esc(t.keywords || '-') + '</td><td style="padding:8px;border-bottom:1px solid #f0f0f0;">' + esc(t.city || '-') + '</td><td style="padding:8px;border-bottom:1px solid #f0f0f0;"><button data-tid="' + t.id + '" class="tmpl-apply" style="margin-right:6px;">套用</button><button data-tid="' + t.id + '" class="tmpl-del" style="color:#d00;">删除</button></td></tr>').join('');
|
||||||
|
}
|
||||||
|
|
||||||
|
document.getElementById('btnManageTemplatesRemote').onclick = () => {
|
||||||
|
document.getElementById('tmplModal').classList.remove('hidden');
|
||||||
|
renderRemoteTemplates();
|
||||||
|
};
|
||||||
|
|
||||||
|
document.getElementById('tmplClose').onclick = () => {
|
||||||
|
document.getElementById('tmplModal').classList.add('hidden');
|
||||||
|
};
|
||||||
|
|
||||||
|
document.getElementById('tmplTbody').addEventListener('click', async e => {
|
||||||
|
const tid = parseInt(e.target.dataset.tid);
|
||||||
|
if (e.target.classList.contains('tmpl-apply')) {
|
||||||
|
const t = remoteTemplates.find(x => x.id === tid);
|
||||||
|
if (t) { fillRemoteForm(t); document.getElementById('rTemplate').value = tid; document.getElementById('tmplModal').classList.add('hidden'); }
|
||||||
|
} else if (e.target.classList.contains('tmpl-del')) {
|
||||||
|
if (!confirm('确定删除该模板?')) return;
|
||||||
|
try { await api('/api/templates/' + tid, { method: 'DELETE' }); alert('已删除'); await renderRemoteTemplates(); }
|
||||||
|
catch (e) { alert('删除失败:' + (e.message || '')); }
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
async function enter() {
|
async function enter() {
|
||||||
showData();
|
showData();
|
||||||
// 自定义日期默认填入今天
|
// 自定义日期默认填入今天
|
||||||
@@ -424,13 +849,45 @@ async function enter() {
|
|||||||
document.getElementById('dateEnd').value = today;
|
document.getElementById('dateEnd').value = today;
|
||||||
await loadBlacklist();
|
await loadBlacklist();
|
||||||
await load();
|
await load();
|
||||||
|
await loadRemoteTemplates();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (token()) enter(); else showLogin();
|
if (token()) enter(); else showLogin();
|
||||||
setInterval(() => {
|
setInterval(() => {
|
||||||
if (token() && !document.getElementById('dataView').classList.contains('hidden')
|
if (token() && !document.getElementById('dataView').classList.contains('hidden')) {
|
||||||
&& !document.getElementById('pageData').classList.contains('hidden')) load();
|
if (!document.getElementById('pageData').classList.contains('hidden')) load();
|
||||||
}, 30000);
|
if (!document.getElementById('pageRemote').classList.contains('hidden')) loadRemote();
|
||||||
|
}
|
||||||
|
}, 5000);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<!-- 模板管理弹窗 -->
|
||||||
|
<div id="tmplModal" class="hidden" style="position:fixed;inset:0;background:rgba(0,0,0,0.45);z-index:2000;display:flex;align-items:center;justify-content:center;">
|
||||||
|
<div style="background:#fff;border-radius:8px;padding:24px;width:760px;max-width:95vw;max-height:85vh;overflow:auto;">
|
||||||
|
<h3 style="margin:0 0 16px;">管理投递模板</h3>
|
||||||
|
<table style="width:100%;border-collapse:collapse;">
|
||||||
|
<thead><tr><th style="text-align:left;border-bottom:1px solid #eee;padding:8px;">名称</th><th style="text-align:left;border-bottom:1px solid #eee;padding:8px;">关键词</th><th style="text-align:left;border-bottom:1px solid #eee;padding:8px;">城市</th><th style="text-align:left;border-bottom:1px solid #eee;padding:8px;">操作</th></tr></thead>
|
||||||
|
<tbody id="tmplTbody"></tbody>
|
||||||
|
</table>
|
||||||
|
<div style="margin-top:16px;text-align:right;">
|
||||||
|
<button id="tmplClose" style="padding:6px 14px;border-radius:4px;border:1px solid #d9d9d9;background:#fff;cursor:pointer;">关闭</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<!-- 岗位 JD 查看弹窗 -->
|
||||||
|
<div id="jdModal" class="hidden" style="position:fixed;inset:0;background:rgba(0,0,0,0.45);z-index:2000;display:flex;align-items:center;justify-content:center;">
|
||||||
|
<div style="background:#fff;border-radius:8px;padding:24px;width:760px;max-width:95vw;max-height:85vh;display:flex;flex-direction:column;">
|
||||||
|
<h3 style="margin:0 0 8px;">岗位 JD 全文</h3>
|
||||||
|
<div id="jdTip" style="font-size:12px;color:#999;margin-bottom:10px;"></div>
|
||||||
|
<pre id="jdBody" style="flex:1;min-height:0;overflow:auto;white-space:pre-wrap;word-break:break-all;background:#fafafa;border:1px solid #f0f0f0;border-radius:6px;padding:14px;font-size:13px;line-height:1.7;"></pre>
|
||||||
|
<div style="margin-top:16px;text-align:right;">
|
||||||
|
<button id="jdClose" style="padding:6px 14px;border-radius:4px;border:1px solid #d9d9d9;background:#fff;cursor:pointer;">关闭</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<script>
|
||||||
|
document.getElementById('jdClose').onclick = closeJd;
|
||||||
|
document.getElementById('jdModal').addEventListener('click', e => { if (e.target.id === 'jdModal') closeJd(); });
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
Reference in New Issue
Block a user