添加引导词和投递模板

This commit is contained in:
2026-08-26 16:19:15 +08:00
parent ab79dd89be
commit 8d57c5dbc3
17 changed files with 644 additions and 13 deletions
+4 -6
View File
@@ -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-26T07:13:00Z"
modules: modules:
"": "":
dir_name: Boss直聘 AI 智能投递系统(客户端-服务端) dir_name: jianli-boss
title: Boss直聘 AI 智能投递系统(客户端-服务端) title: jianli-boss
scope: scope: []
- .gitignore
- README.md
source_files: [] source_files: []
children: children:
- client - client
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -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.7 set APP_VERSION=1.8
echo [1/2] 安装打包依赖... echo [1/2] 安装打包依赖...
pip install pyinstaller PySide6 --quiet pip install pyinstaller PySide6 --quiet
+3 -1
View File
@@ -37,7 +37,7 @@ class AIClient:
# ------------------------------------------------------------------ # ------------------------------------------------------------------
# 职位匹配度评分 # 职位匹配度评分
# ------------------------------------------------------------------ # ------------------------------------------------------------------
def score_job(self, jd_text: str, resume_content: str) -> MatchResult: def score_job(self, jd_text: str, resume_content: str, prompt: str | None = None) -> MatchResult:
"""根据 JD 与主简历内容评估匹配度""" """根据 JD 与主简历内容评估匹配度"""
if not self.available(): if not self.available():
return MatchResult(50, "AI 未配置,默认放行") return MatchResult(50, "AI 未配置,默认放行")
@@ -49,6 +49,8 @@ class AIClient:
"评分标准:80-100 高度匹配;60-79 基本匹配;40-59 部分匹配;0-39 不匹配。" "评分标准:80-100 高度匹配;60-79 基本匹配;40-59 部分匹配;0-39 不匹配。"
) )
user_prompt = f"【职位描述】\n{jd_text}\n\n【候选人简历】\n{resume_content}" user_prompt = f"【职位描述】\n{jd_text}\n\n【候选人简历】\n{resume_content}"
if prompt:
user_prompt += f"\n\n【用户额外偏好/引导词】\n{prompt}"
try: try:
resp = self.client.chat.completions.create( resp = self.client.chat.completions.create(
+4 -2
View File
@@ -177,7 +177,7 @@ class Applicant:
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
@@ -185,6 +185,7 @@ class Applicant:
session = self.server.start_session( session = self.server.start_session(
keywords=",".join(keywords), city=city, 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"]
@@ -197,6 +198,7 @@ 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(
@@ -462,7 +464,7 @@ class Applicant:
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_content:
result = self.ai.score_job(card.jd_text, self.primary_resume_content) result = self.ai.score_job(card.jd_text, self.primary_resume_content, prompt=self.prompt)
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}")
+30 -1
View File
@@ -211,7 +211,8 @@ class ServerAPI:
# 投递会话 # 投递会话
# ------------------------------------------------------------------ # ------------------------------------------------------------------
def start_session(self, keywords: str, city: 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={
@@ -219,6 +220,7 @@ class ServerAPI:
"city": city, "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,
) )
@@ -279,6 +281,33 @@ 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()
+41
View File
@@ -168,6 +168,7 @@ def start_apply_shared(params: dict) -> dict:
boss_online_only=bool(params.get("boss_online_only")), boss_online_only=bool(params.get("boss_online_only")),
daily_limit=int(params.get("daily_limit") or 0), daily_limit=int(params.get("daily_limit") or 0),
allow_headhunter=bool(params.get("allow_headhunter")), allow_headhunter=bool(params.get("allow_headhunter")),
prompt=params.get("prompt"),
) )
return {"ok": True, "msg": "投递任务已启动", "session_id": applicant.session_id} return {"ok": True, "msg": "投递任务已启动", "session_id": applicant.session_id}
@@ -216,6 +217,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):
@@ -488,6 +490,45 @@ def stop_apply():
return {"ok": True, "msg": "正在停止投递任务..."} return {"ok": True, "msg": "正在停止投递任务..."}
# =======================================================
# 投递条件模板(服务端持久化)
# =======================================================
@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
+150
View File
@@ -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 => {
@@ -379,6 +380,7 @@ $('btnStartApply').addEventListener('click', async () => {
boss_online_only: $('bossOnlineOnly').checked, boss_online_only: $('bossOnlineOnly').checked,
allow_headhunter: $('allowHeadhunter').checked, allow_headhunter: $('allowHeadhunter').checked,
daily_limit: parseInt($('dailyLimit').value) || 0, daily_limit: parseInt($('dailyLimit').value) || 0,
prompt: $('prompt').value.trim() || null,
}), }),
}); });
toast('投递任务已启动'); toast('投递任务已启动');
@@ -397,6 +399,154 @@ $('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;
$('allowHeadhunter').checked = !!t.allow_headhunter;
$('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,
allow_headhunter: $('allowHeadhunter').checked,
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);
+1
View File
@@ -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 {
+47
View File
@@ -81,6 +81,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开发">
@@ -128,6 +140,10 @@
</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>
@@ -209,6 +225,37 @@
</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>
+25
View File
@@ -66,6 +66,7 @@ CREATE TABLE IF NOT EXISTS apply_sessions (
city 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,
@@ -105,6 +106,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 不再投递该公司)
-- ------------------------------------------------------------ -- ------------------------------------------------------------
+2 -1
View File
@@ -14,7 +14,7 @@ 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, rpa from .routers import register, resumes, sessions, jobs, blacklist, rpa, templates
@asynccontextmanager @asynccontextmanager
@@ -50,6 +50,7 @@ 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(rpa.router)
app.include_router(templates.router)
@app.get("/", tags=["健康检查"]) @app.get("/", tags=["健康检查"])
+38
View File
@@ -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):
@@ -91,6 +92,8 @@ class ApplySession(Base):
# 薪资范围 # 薪资范围
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)
@@ -204,3 +207,38 @@ class RpaTask(Base):
updated_at = Column(DateTime, default=utcnow, onupdate=utcnow, nullable=False) updated_at = Column(DateTime, default=utcnow, onupdate=utcnow, nullable=False)
user = relationship("User") user = relationship("User")
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")
+1
View File
@@ -37,6 +37,7 @@ def start_session(
city=req.city, 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()
+135
View File
@@ -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}
+37
View File
@@ -97,6 +97,7 @@ class SessionStartIn(BaseModel):
city: 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):
@@ -106,6 +107,7 @@ class SessionOut(BaseModel):
city: 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
@@ -156,6 +158,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
# ======================================================= # =======================================================
# 公司黑名单 # 公司黑名单
# ======================================================= # =======================================================
+124
View File
@@ -198,6 +198,17 @@
</div> </div>
<div class="bl-tip" id="rsDetail">进度:- | 更新:-</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 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> <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> <input type="text" id="rKeywords" placeholder="如:Python开发,后端工程师" value="Python开发"></div>
@@ -221,6 +232,10 @@
<button id="btnStartRemote" style="background:#1890ff;">开始投递</button> <button id="btnStartRemote" style="background:#1890ff;">开始投递</button>
<button id="btnStopRemote">结束投递</button> <button id="btnStopRemote">结束投递</button>
</div> </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 class="bl-tip">任务下发后客户端 5 秒内认领执行;同类型任务未结束前不能重复下发。</div>
<table> <table>
@@ -503,6 +518,7 @@ document.getElementById('btnStartRemote').onclick = () => {
daily_limit: parseInt(document.getElementById('rLimit').value, 10) || 0, daily_limit: parseInt(document.getElementById('rLimit').value, 10) || 0,
boss_online_only: document.getElementById('rOnlineOnly').checked, boss_online_only: document.getElementById('rOnlineOnly').checked,
allow_headhunter: document.getElementById('rHunter').checked, allow_headhunter: document.getElementById('rHunter').checked,
prompt: document.getElementById('rPrompt').value.trim() || null,
}); });
}; };
document.getElementById('btnStopRemote').onclick = () => { document.getElementById('btnStopRemote').onclick = () => {
@@ -520,6 +536,99 @@ document.getElementById('tbody').addEventListener('click', e => {
} }
}); });
// 远程模板管理
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();
// 自定义日期默认填入今天 // 自定义日期默认填入今天
@@ -528,6 +637,7 @@ 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();
@@ -538,5 +648,19 @@ setInterval(() => {
} }
}, 5000); }, 5000);
</script> </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>
</body> </body>
</html> </html>