新增招聘公告同步与Word和Markdown导出

This commit is contained in:
2026-12-04 14:06:47 +08:00
parent 2085b637bb
commit bf9f8dc089
7 changed files with 395 additions and 2 deletions
+21 -1
View File
@@ -18,6 +18,7 @@
<a href="#" data-view="mine">我的记录</a>
<a href="#" data-view="center">赋能中心一楼</a>
<a href="#timetables" data-view="timetables">课表收取</a>
<a href="#" data-view="recruit">招聘公告</a>
<a href="#" data-view="members">成员</a>
<a href="#" data-view="profile">设置</a>
</nav>
@@ -306,6 +307,25 @@
</div>
</main>
<!-- 招聘公告 -->
<main id="recruit-view" class="view hidden">
<div class="container">
<div class="page-head">
<div><h2>招聘公告</h2><p class="muted">同步就业平台公告,在线阅读并导出 Word 或 Markdown。</p></div>
<button class="btn primary" id="recruit-sync" type="button">同步公告</button>
</div>
<div class="filters">
<input id="recruit-q" type="search" placeholder="搜索标题 / 单位" aria-label="搜索公告" />
<button class="btn" id="recruit-refresh" type="button">刷新</button>
<button class="btn" id="recruit-export-docx" type="button">导出搜索结果 Word</button>
<button class="btn" id="recruit-export-md" type="button">导出 Markdown</button>
</div>
<p class="muted" id="recruit-status" role="status">数据来自山东管理学院就业平台,首次使用请先同步。</p>
<div id="recruit-list" class="card-list"></div>
<div id="recruit-empty" class="empty hidden">还没有公告,点「同步公告」获取最新内容。</div>
</div>
</main>
<!-- 设置 -->
<main id="profile-view" class="view hidden">
<div class="container narrow">
@@ -367,7 +387,7 @@
<div id="toast" class="toast hidden" role="status" aria-live="polite"></div>
<script src="/js/app.js?v=52"></script>
<script src="/js/app.js?v=53"></script>
</div>
</body>
</html>
+82 -1
View File
@@ -135,7 +135,7 @@
};
// ------------------------------------------------------------- 视图切换
const VIEWS = ["auth", "feed", "mine", "members", "user", "profile", "center", "timetables"];
const VIEWS = ["auth", "feed", "mine", "members", "user", "profile", "center", "timetables", "recruit"];
function show(view) {
state.view = view;
VIEWS.forEach((v) => $(`#${v}-view`).classList.toggle("hidden", v !== view));
@@ -155,6 +155,7 @@
if (view === "center") loadCenter();
if (view === 'timetables') { history.replaceState(null, '', '#timetables'); loadTimetables(); }
else if (view !== 'auth' && location.hash === '#timetables') history.replaceState(null, '', location.pathname + location.search);
if (view === 'recruit') loadRecruit();
if (view === 'auth') {
$('#timetable-mine').replaceChildren(); $('#timetable-members').replaceChildren();
timetableData = null; timetableRequest++;
@@ -1524,6 +1525,86 @@
const link = document.createElement('a');link.href=url;link.download=filename;document.body.append(link);link.click();link.remove();
setTimeout(() => URL.revokeObjectURL(url),30000);
}
let recruitItems = [];
const recruitSelection = new Set();
function recruitCard(item) {
const checked = recruitSelection.has(item.gonggao_id) ? ' checked' : '';
return `<article class="card activity-card"><div class="activity-head"><label><input type="checkbox" data-recruit-id="${item.gonggao_id}"${checked} /> ${esc(item.title)}</label></div>
<p class="muted">${esc(item.companyname || '未提供单位')} · 审核:${esc(item.check_time || '未知')} · 截止:${esc(item.valid_time || '未知')}</p>
<div class="activity-actions"><button class="btn sm" data-recruit-open="${item.gonggao_id}" type="button">阅读内容</button>
<button class="btn sm" data-recruit-export="${item.gonggao_id}" type="button">导出 Word</button>
<button class="btn sm" data-recruit-export-md="${item.gonggao_id}" type="button">导出 Markdown</button>
<a class="btn ghost sm" href="${esc(item.detail_url)}" target="_blank" rel="noopener noreferrer">原网页</a></div></article>`;
}
async function loadRecruit() {
$('#recruit-status').textContent = '正在加载公告…';
try {
const q = $('#recruit-q').value.trim();
const data = await api('/recruit/announcements' + (q ? `?q=${encodeURIComponent(q)}` : ''));
recruitItems = data.items || [];
recruitSelection.forEach(id => { if (!recruitItems.some(item => item.gonggao_id === id)) recruitSelection.delete(id); });
$('#recruit-list').innerHTML = recruitItems.map(recruitCard).join('');
$('#recruit-empty').classList.toggle('hidden', !!recruitItems.length);
$('#recruit-status').textContent = `共 ${data.total} 条${q ? `,搜索到 ${recruitItems.length} 条(最多显示 500 条)` : ''};已选 ${recruitSelection.size} 条。`;
} catch (error) { $('#recruit-status').textContent = error.message; }
}
async function openRecruit(id) {
try {
const item = await api(`/recruit/announcements/${id}`);
modal(`<div class="modal-head"><h3>${esc(item.title)}</h3><button class="icon-btn" id="modal-close">×</button></div>
<p class="modal-sub muted">${esc(item.companyname || '未提供单位')} · ${esc(item.check_time)} · 截止 ${esc(item.valid_time)}</p>
<div id="recruit-article" class="modal-body"></div>
<div class="form-actions"><button class="btn" data-recruit-export="${id}" type="button">导出 Word</button><button class="btn" data-recruit-export-md="${id}" type="button">导出 Markdown</button></div>`);
$('#recruit-article').innerHTML = item.content_html || '<p class="muted">没有正文内容。</p>';
$('#modal-close')?.addEventListener('click', closeModal);
} catch (error) { toast(error.message, true); }
}
async function exportRecruit(ids, format) {
const params = new URLSearchParams({ format: format === 'md' ? 'markdown' : 'docx' });
if (ids) params.set('ids', ids.join(',')); else params.set('all', 'true');
await downloadCenterFile('/api/recruit/export?' + params.toString(), format === 'md' ? 'recruit.md' : 'recruit.docx');
}
$('#recruit-sync').addEventListener('click', async event => {
const button = event.currentTarget; button.disabled = true;
$('#recruit-status').textContent = '正在同步,最多 62 条左右,请稍候…';
try { const result = await api('/recruit/sync', { method: 'POST' }); toast(`同步完成:新增 ${result.added},更新 ${result.updated}`); await loadRecruit(); }
catch (error) { $('#recruit-status').textContent = error.message; }
finally { button.disabled = false; }
});
$('#recruit-refresh').addEventListener('click', loadRecruit);
$('#recruit-q').addEventListener('keydown', event => { if (event.key === 'Enter') loadRecruit(); });
$('#recruit-export-docx').addEventListener('click', async event => {
event.currentTarget.disabled = true;
try { await exportRecruit(recruitSelection.size ? [...recruitSelection] : null, 'docx'); $('#recruit-status').textContent = 'Word 已下载。'; }
catch (error) { toast(error.message, true); }
finally { event.currentTarget.disabled = false; }
});
$('#recruit-export-md').addEventListener('click', async event => {
event.currentTarget.disabled = true;
try { await exportRecruit(recruitSelection.size ? [...recruitSelection] : null, 'md'); $('#recruit-status').textContent = 'Markdown 已下载。'; }
catch (error) { toast(error.message, true); }
finally { event.currentTarget.disabled = false; }
});
$('#recruit-list').addEventListener('click', async event => {
const checkbox = event.target.closest('[data-recruit-id]');
if (checkbox) {
const id = Number(checkbox.dataset.recruitId);
if (checkbox.checked) recruitSelection.add(id); else recruitSelection.delete(id);
$('#recruit-status').textContent = `已选 ${recruitSelection.size} 条公告。`;
return;
}
const open = event.target.closest('[data-recruit-open]');
if (open) { openRecruit(Number(open.dataset.recruitOpen)); return; }
const word = event.target.closest('[data-recruit-export]');
const markdown = event.target.closest('[data-recruit-export-md]');
if (word || markdown) {
const button = word || markdown; button.disabled = true;
try { await exportRecruit([Number(button.dataset.recruitExport || button.dataset.recruitExportMd)], word ? 'docx' : 'md'); }
catch (error) { toast(error.message, true); }
finally { button.disabled = false; }
}
});
document.addEventListener('click', async event => {
const button = event.target.closest('[data-material]');
if (!button || button.disabled) return;
+1
View File
@@ -10,3 +10,4 @@ rapidocr>=3.10,<3.11
onnxruntime>=1.20,<2
# 仅测试时需要
httpx>=0.27,<1
python-docx>=1.1,<2
+2
View File
@@ -44,6 +44,7 @@ from . import duty_receipts
from . import center
from . import center_duty
from . import center_export
from . import recruit
from . import timetables as timetable_routes
from .models import center_activity_meta, center_items, center_loans
import json
@@ -770,6 +771,7 @@ app = FastAPI(title="WorkLog 活动记录", version="2.0.0", lifespan=lifespan)
center.install(app, get_db, current_user, lambda: _db_path.parent / 'uploads', visible_clause)
center_duty.install(app, get_db, current_user)
center_export.install(app, get_db, current_user, visible_clause, lambda: _db_path.parent / 'uploads')
recruit.install(app, get_db, current_user)
def timetable_collectors():
values = os.getenv('WORKLOG_TIMETABLE_COLLECTORS')
+16
View File
@@ -187,8 +187,24 @@ timetables = Table('timetables', metadata,
Column('created_at', Integer, nullable=False), Column('updated_at', Integer, nullable=False),
Column('confirmed_at', Integer, nullable=True))
recruit_announcements = Table('recruit_announcements', metadata,
Column('gonggao_id', Integer, primary_key=True),
Column('title', String(255), nullable=False),
Column('companyname', String(255), nullable=False, default=''),
Column('content_html', Text, nullable=False, default=''),
Column('create_time', String(30), nullable=False, default=''),
Column('check_time', String(30), nullable=False, default=''),
Column('valid_time', String(30), nullable=False, default=''),
Column('info_from', String(255), nullable=False, default=''),
Column('iswailian', Integer, nullable=False, default=0),
Column('wailian', String(500), nullable=False, default=''),
Column('url', String(500), nullable=False, default=''),
Column('synced_at', Integer, nullable=False))
Index('ix_recruit_announcements_check_time', recruit_announcements.c.check_time.desc())
TABLES = (
users, sessions, email_verifications, activities, participations, join_links,
center_photos, center_materials, center_activity_materials, center_activity_meta,
center_items, center_loans, center_checks, center_duty_leaves, center_tutorials, timetables,
recruit_announcements,
)
+221
View File
@@ -0,0 +1,221 @@
"""招聘公告同步、浏览和 Word / Markdown 导出。"""
from __future__ import annotations
import asyncio
import io
from datetime import datetime
from html.parser import HTMLParser
from typing import Literal
import httpx
from docx import Document
from docx.shared import Pt
from fastapi import Depends, HTTPException, Query
from fastapi.responses import Response
from sqlalchemy import func, insert, select
from .duty import BEIJING
from .models import recruit_announcements
SOURCE = "https://school.gxjy.sdei.edu.cn"
LIST_ENDPOINT = SOURCE + "/sdmu/front/indexZpggList"
DETAIL_ENDPOINT = SOURCE + "/sdmu/jiuye/zhaopingg/detail"
class HTMLTextParser(HTMLParser):
blocks = {"p", "div", "section", "br", "tr", "li", "table"}
def __init__(self):
super().__init__(convert_charrefs=True)
self.parts = []
self.current = []
def handle_starttag(self, tag, attrs):
if tag in self.blocks:
text = "".join(self.current).strip()
if text:
self.parts.append(text)
self.current = []
def handle_endtag(self, tag):
if tag in self.blocks:
text = "".join(self.current).strip()
if text:
self.parts.append(text)
self.current = []
def handle_data(self, data):
self.current.append(data)
def text(self):
text = "".join(self.current).strip()
if text:
self.parts.append(text)
return "\n".join(part for part in self.parts if part)
def html_to_text(content: str) -> str:
parser = HTMLTextParser()
parser.feed(content or "")
parser.close()
return parser.text()
def public_row(row) -> dict:
data = dict(row)
data["detail_url"] = data["wailian"] if data["iswailian"] and data["wailian"] else f"{DETAIL_ENDPOINT}/{data['gonggao_id']}"
return data
async def fetch_page(client: httpx.AsyncClient, page: int, page_size: int = 50):
response = await client.get(LIST_ENDPOINT, params={"pageNum": page, "pageSize": page_size, "keyword": "", "timeRange": ""})
response.raise_for_status()
payload = response.json()
if payload.get("code") != 0:
raise RuntimeError(payload.get("msg") or "招聘公告接口返回异常")
return payload
async def sync_all(db, client: httpx.AsyncClient | None = None) -> dict:
owns_client = client is None
if owns_client:
client = httpx.AsyncClient(timeout=20)
added = updated = 0
try:
first = await fetch_page(client, 1)
pages = int(first.get("extra", {}).get("pages") or 1)
rows = list(first.get("rows") or [])
for page in range(2, pages + 1):
await asyncio.sleep(0.15)
rows.extend((await fetch_page(client, page)).get("rows") or [])
finally:
if owns_client:
await client.aclose()
now = int(datetime.now(BEIJING).timestamp() * 1000)
for raw in rows:
try:
gonggao_id = int(raw["gonggaoId"])
except (KeyError, TypeError, ValueError):
continue
values = {
"gonggao_id": gonggao_id,
"title": str(raw.get("gonggaoTitle") or "未命名公告"),
"companyname": str(raw.get("companyname") or ""),
"content_html": str(raw.get("gonggaoContent") or ""),
"create_time": str(raw.get("createTime") or ""),
"check_time": str(raw.get("checkTime") or ""),
"valid_time": str(raw.get("validTime") or ""),
"info_from": str(raw.get("infoFrom") or ""),
"iswailian": int(raw.get("iswailian") or 0),
"wailian": str(raw.get("wailian") or ""),
"url": str(raw.get("url") or ""),
"synced_at": now,
}
existing = (await db.execute(select(recruit_announcements.c.gonggao_id).where(recruit_announcements.c.gonggao_id == gonggao_id))).scalar()
if existing is None:
await db.execute(insert(recruit_announcements).values(**values))
added += 1
else:
await db.execute(recruit_announcements.update().where(recruit_announcements.c.gonggao_id == gonggao_id).values(**values))
updated += 1
await db.commit()
return {"fetched": len(rows), "added": added, "updated": updated}
def docx_bytes(rows) -> bytes:
document = Document()
style = document.styles["Normal"]
style.font.name = "Microsoft YaHei"
style.font.size = Pt(11)
for index, row in enumerate(rows, 1):
document.add_heading(row["title"], level=1)
meta = " · ".join(value for value in (row["companyname"], row["check_time"][:10], f"截止:{row['valid_time'][:10]}" if row["valid_time"] else "") if value)
if meta:
document.add_paragraph(meta)
for line in html_to_text(row["content_html"]).splitlines():
document.add_paragraph(line)
if index < len(rows):
document.add_page_break()
output = io.BytesIO()
document.save(output)
return output.getvalue()
def markdown_bytes(rows) -> bytes:
sections = []
for row in rows:
lines = [f"# {row['title']}"]
meta = [value for value in (row["companyname"], row["check_time"], row["valid_time"]) if value]
if meta:
lines.append(f"- {' / '.join(meta)}")
body = html_to_text(row["content_html"])
if body:
lines.extend([body, ""])
link = row["wailian"] if row["iswailian"] and row["wailian"] else f"{DETAIL_ENDPOINT}/{row['gonggao_id']}"
lines.append(f"原文链接:{link}")
sections.append("\n".join(lines))
return ("\n\n---\n\n".join(sections) + "\n").encode("utf-8")
def install(app, get_db, current_user):
@app.post("/api/recruit/sync")
async def sync(viewer=Depends(current_user)):
async for db in get_db():
return await sync_all(db)
@app.get("/api/recruit/announcements")
async def announcements(q: str = Query("", max_length=100), db=Depends(get_db), viewer=Depends(current_user)):
statement = select(recruit_announcements)
if q.strip():
keyword = f"%{q.strip()}%"
statement = statement.where(recruit_announcements.c.title.like(keyword) | recruit_announcements.c.companyname.like(keyword))
total = (await db.execute(select(func.count()).select_from(statement.subquery()))).scalar()
statement = statement.order_by(recruit_announcements.c.check_time.desc(), recruit_announcements.c.gonggao_id.desc()).limit(500)
rows = [public_row(row) for row in (await db.execute(statement)).mappings()]
return {"items": rows, "total": total}
@app.get("/api/recruit/announcements/{gonggao_id}")
async def announcement(gonggao_id: int, db=Depends(get_db), viewer=Depends(current_user)):
row = (await db.execute(select(recruit_announcements).where(recruit_announcements.c.gonggao_id == gonggao_id))).mappings().first()
if row is None:
raise HTTPException(404, "公告不存在,请先同步")
return public_row(row)
@app.get("/api/recruit/export")
async def export(
ids: str = Query("", max_length=5000),
all_items: bool = Query(False, alias="all"),
format: Literal["docx", "markdown"] = "docx",
q: str = Query("", max_length=100),
db=Depends(get_db),
viewer=Depends(current_user),
):
selected = []
if ids.strip():
try:
selected = [int(value.strip()) for value in ids.split(",") if value.strip()]
except ValueError:
raise HTTPException(422, "公告编号格式不正确")
if not selected and not all_items:
raise HTTPException(422, "请选择要导出的公告,或选择全部导出")
statement = select(recruit_announcements)
if selected:
statement = statement.where(recruit_announcements.c.gonggao_id.in_(selected))
elif q.strip():
keyword = f"%{q.strip()}%"
statement = statement.where(recruit_announcements.c.title.like(keyword) | recruit_announcements.c.companyname.like(keyword))
statement = statement.order_by(recruit_announcements.c.check_time.desc(), recruit_announcements.c.gonggao_id.desc())
rows = [dict(row) for row in (await db.execute(statement)).mappings()]
if not rows:
raise HTTPException(404, "没有匹配的公告")
stamp = datetime.now(BEIJING).strftime("%Y%m%d-%H%M%S")
if format == "docx":
body, extension, media_type = docx_bytes(rows), "docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
else:
body, extension, media_type = markdown_bytes(rows), "md", "text/markdown; charset=utf-8"
scope = "recruit" if len(rows) > 1 else f"recruit-{rows[0]['gonggao_id']}"
filename = f"{scope}-{stamp}.{extension}"
return Response(body, media_type=media_type, headers={
"Content-Disposition": f'attachment; filename="{filename}"',
"X-Recruit-Export-Count": str(len(rows)),
})
+52
View File
@@ -0,0 +1,52 @@
from __future__ import annotations
import unittest
from unittest.mock import patch
from unittest.mock import AsyncMock
from docx import Document
from io import BytesIO
from test_api import ApiTestCase, auth, register
from server import recruit
RAW = {
"gonggaoId": 1,
"gonggaoTitle": "测试公告",
"gonggaoContent": "<p>第一段</p><div>第二段</div>",
"companyname": "测试单位",
"createTime": "2026-11-01 10:00:00",
"checkTime": "2026-11-02 10:00:00",
"validTime": "2027-01-01 00:00:00",
"infoFrom": "测试来源",
"iswailian": 0,
"wailian": "",
"url": "",
}
class RecruitTests(ApiTestCase):
async def test_sync_list_detail_and_exports(self):
self.assertEqual((await self.client.get('/api/recruit/announcements', headers=auth('x'))).status_code, 401)
owner = await register(self.client, 'recruiter')
payload = {"code": 0, "rows": [RAW], "extra": {"pages": 1}}
fetch = AsyncMock(return_value=payload)
with patch.object(recruit, 'fetch_page', new=fetch):
data = (await self.client.post('/api/recruit/sync', headers=auth(owner['token']))).json()
self.assertEqual(data, {'fetched': 1, 'added': 1, 'updated': 0})
rows = (await self.client.get('/api/recruit/announcements', headers=auth(owner['token']))).json()
self.assertEqual(rows['total'], 1)
self.assertEqual(rows['items'][0]['gonggao_id'], 1)
self.assertTrue(rows['items'][0]['detail_url'].endswith('/1'))
detail = (await self.client.get('/api/recruit/announcements/1', headers=auth(owner['token']))).json()
self.assertEqual(detail['title'], '测试公告')
response = await self.client.get('/api/recruit/export', params={'ids': '1', 'format': 'docx'}, headers=auth(owner['token']))
self.assertEqual(response.status_code, 200)
document = Document(BytesIO(response.content))
self.assertIn('第一段', '\n'.join(p.text for p in document.paragraphs))
response = await self.client.get('/api/recruit/export', params={'ids': '1', 'format': 'markdown'}, headers=auth(owner['token']))
self.assertIn('第一段', response.text)
self.assertIn('原文链接', response.text)
response = await self.client.get('/api/recruit/export', headers=auth(owner['token']))
self.assertEqual(response.status_code, 422)