Compare commits

..
17 Commits
Author SHA1 Message Date
azzz 5ad49852b3 招聘公告按原网页顺序展示导出 2026-12-04 15:11:09 +08:00
azzz ccb05fd17e 修复招聘公告空正文与漏同步 2026-12-04 14:51:15 +08:00
azzz 656607516e 修复就业平台空参数导致同步失败 2026-12-04 14:37:25 +08:00
azzz 27a154a410 同步失败返回具体网络原因 2026-12-04 14:34:43 +08:00
azzz 634c9634f6 招聘公告同步绕过系统代理并重试 2026-12-04 14:31:46 +08:00
azzz 5246626e91 修复招聘公告导出500并增加图片缓存压缩 2026-12-04 14:26:45 +08:00
azzz eb50660a1b 招聘公告导出携带正文图片 2026-12-04 14:21:47 +08:00
azzz bf9f8dc089 新增招聘公告同步与Word和Markdown导出 2026-12-04 14:06:47 +08:00
azzz 2085b637bb 优化一楼活动Word导出顺序和日期 2026-12-03 13:52:50 +08:00
azzz 3489b5f8fa feat: export center activities with photos to Word 2026-12-02 15:32:35 +08:00
azzz 626a683876 同步赋能中心一楼值班表 2026-11-29 16:40:36 +08:00
azzz 2ba29e7d79 允许同源播放教程视频 2026-11-25 09:22:30 +08:00
azzz 219cdc7dd0 改用流式鉴权播放设备教程视频 2026-11-25 09:20:10 +08:00
azzz c611186cfc 修复设备教程视频在线预览鉴权问题 2026-11-25 09:09:11 +08:00
azzz 533c401175 新增赋能中心一楼设备教程:上传、搜索与在线播放 2026-11-23 11:13:58 +08:00
azzz ad6ab63c8e 修复赋能中心一楼记录表单:隐藏记录类型选项,保留照片与ZIP附件上传 2026-11-23 09:54:08 +08:00
azzz cf97de9423 回滚到 982f0df:重构共享逻辑并修复值班提醒回执去重 2026-11-22 23:17:01 +08:00
17 changed files with 1358 additions and 336 deletions
+1 -7
View File
@@ -1,12 +1,6 @@
# 赋能中心一楼
导航中的“赋能中心一楼”整合活动记录、独立值班、物品清点与借出登记、展厅使用登记和设备使用教程。原有活动、账号和招生就业服务队值班功能保留。
## 设备使用教程
“设备使用教程”标签页提供视频上传、按教室号或设备名搜索、在线播放和本人删除。登录成员均可上传或观看,上传时需填写教室号和设备名,支持 MP4、WebM、MOV、M4V,单个文件不超过 500MB。
视频保存在业务数据库同目录的 `uploads/tutorials/`,不会出现在静态 `/uploads` 公开目录中;上传、列表、播放均需要登录,仅上传者可删除。浏览器通过登录请求取得视频,关闭播放弹层后释放临时视频资源。新增教程记录由启动时的表结构检查自动创建,不修改已有业务数据。部署备份继续保留整个 data 目录,包括教程视频。
导航中的“赋能中心一楼”整合活动记录、独立值班、物品清点与借出登记。原有活动、账号和招生就业服务队值班功能保留。
## 赋能中心一楼值班
+17 -26
View File
@@ -19,8 +19,7 @@
--shadow: 0 2px 5px rgba(35, 64, 48, .025);
}
* { box-sizing: border-box; -webkit-text-size-adjust: 100%; text-size-adjust: 100%; }
.btn, button { font: inherit; }
* { box-sizing: border-box; }
html, body {
margin: 0;
@@ -99,7 +98,6 @@ textarea { width: 100%; resize: vertical; }
.topbar-user { display: flex; align-items: center; gap: 10px; white-space: nowrap; }
#topbar-name { font-weight: 600; font-size: 14px; }
.menu-toggle { display: none; background: none; border: none; font-size: 20px; }
.new-activity-short { display: none; }
/* ---------- 布局 ---------- */
.container { max-width: 1160px; margin: 0 auto; padding: 40px 28px 72px; }
@@ -398,8 +396,6 @@ form input, form select, form textarea, .form-card input, .form-card select { wi
/* ---------- 响应式 ---------- */
@media (max-width: 760px) {
:root { font-size: 14px; }
body { font-size: 14px; }
#nav {
display: none;
position: absolute;
@@ -517,12 +513,10 @@ button:focus-visible, a:focus-visible, [tabindex]:focus-visible { outline: 3px s
.brand-mark { width: 26px; height: 28px; }
.topbar-user { margin-left: auto; }
.menu-toggle { display: grid; place-items: center; width: 42px; height: 42px; margin-left: 0; color: var(--ink); border-radius: 8px; }
#nav { padding: 4px 10px 8px; z-index: 1; }
#nav a { padding: 10px; font-size: 14px; }
#nav a:last-child { border-top: 1px solid var(--line); margin-top: 4px; }
#new-activity-btn { flex: none; font-size: 13px; padding: 9px 12px; white-space: nowrap; }
.new-activity-label { display: none; }
.new-activity-short { display: inline; }
#nav { padding: 12px 16px; box-shadow: 0 8px 12px #263c3508; }
#nav a { padding: 12px; }
#logout-btn { min-height: 42px; }
#new-activity-btn { font-size: 13px; padding: 9px 10px; }
.container { padding: 28px 16px 56px; }
.page-head { align-items: stretch; gap: 20px; }
.page-head > div:first-child { width: 100%; }
@@ -536,18 +530,9 @@ button:focus-visible, a:focus-visible, [tabindex]:focus-visible { outline: 3px s
.stat:nth-child(even), .stat:last-child { border-right: 0; }
.stat b { font-size: 25px; }
.acard { padding: 20px; }
.acard-actions .btn { min-height: 40px; }
.photo-preview-summary { min-height: 40px; padding: 6px 10px; }
.photo-preview-summary [data-photo-preview] { min-height: 34px; padding-block: 2px; }
.acard-meta { gap: 8px 10px; margin-top: 12px; }
.acard-meta .tag.cat { display: none; }
.meta-item { max-width: 100%; }
.acard h3 { font-size: 17px; line-height: 1.4; }
.acard-desc { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; overflow: hidden; line-height: 1.6; }
.acard-actions .btn:not(.primary) { padding-inline: 10px; }
.acard-actions .btn { min-height: 42px; }
.acard-actions { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 6px; }
.acard-actions .btn { justify-content: center; padding-inline: 6px; white-space: nowrap; }
.member-grid { grid-template-columns: repeat(auto-fill, minmax(min(230px, 100%), 1fr)); }
#members-table { table-layout: fixed; }
#members-table th, #members-table td { padding: 12px 8px; font-size: 13px; overflow-wrap: anywhere; }
@@ -556,8 +541,6 @@ button:focus-visible, a:focus-visible, [tabindex]:focus-visible { outline: 3px s
.form-card { padding: 22px; }
.modal-mask { padding: 16px 10px; }
.modal { padding: 22px 18px; }
.center-tabs { gap: 4px; }
.center-tabs .tab { flex: 0 0 auto; padding-inline: 10px; font-size: 13px; white-space: nowrap; }
.p-list li { flex-wrap: wrap; }
.add-member-row input { min-width: 0; }
}
@@ -628,7 +611,7 @@ button:focus-visible, a:focus-visible, [tabindex]:focus-visible { outline: 3px s
.center-shortcuts p { margin:5px 0 0; color:var(--muted); font-size:13px; }
.center-shortcut-actions { display:flex; flex-wrap:wrap; gap:10px; }
.center-shortcut-actions a { text-decoration:none; display:inline-flex; align-items:center; }
.center-tabs { max-width:none; margin-bottom:24px; }
.center-tabs { max-width:500px; margin-bottom:24px; }
.center-check-status { padding:18px 20px; background:var(--primary-soft); border:1px solid #d5e5da; border-radius:12px; margin-bottom:20px; }
.center-subhead { margin-top:32px; }
.center-duty-head { display:flex; align-items:flex-end; justify-content:space-between; flex-wrap:wrap; gap:18px; margin-bottom:18px; }
@@ -735,7 +718,15 @@ button:focus-visible, a:focus-visible, [tabindex]:focus-visible { outline: 3px s
.center-history { margin-top:28px; }
.center-history summary { cursor:pointer; padding:12px 0; }
.center-history .acard { margin-top:12px; }
.tutorial-video { display:block; width:100%; max-height:70vh; margin-top:18px; background:#151b17; border-radius:10px; }
.tutorial-actions { display:flex; align-items:center; gap:10px; margin-top:14px; }
.tutorial-upload-status { min-height:24px; }
/* ---------- 设备使用教程 ---------- */
.tutorial-grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(280px,1fr)); gap:16px; align-items:start; }
.tutorial-card { display:flex; flex-direction:column; gap:10px; padding:14px; background:var(--card); border:1px solid var(--line); border-radius:var(--radius); box-shadow:var(--shadow); }
.tutorial-head { display:flex; align-items:center; gap:8px; flex-wrap:wrap; min-width:0; }
.tutorial-head b { font-size:15px; font-weight:600; overflow-wrap:anywhere; }
.tutorial-head .tag { max-width:100%; overflow-wrap:anywhere; white-space:normal; }
.tutorial-video { display:block; width:100%; aspect-ratio:16/9; background:#101613; border-radius:10px; }
.tutorial-note { margin:0; font-size:13px; line-height:1.65; white-space:pre-wrap; overflow-wrap:anywhere; }
.tutorial-meta { display:flex; align-items:center; justify-content:space-between; gap:10px; flex-wrap:wrap; margin-top:auto; }
.tutorial-meta .muted { min-width:0; overflow-wrap:anywhere; }
@media (max-width:760px) { .tutorial-grid { grid-template-columns:1fr; } }
@media (min-width:761px) and (max-width:1000px) { .topbar-inner { flex-wrap:wrap; } #nav { order:3; flex-basis:100%; } }
+37 -13
View File
@@ -16,8 +16,9 @@
<nav id="nav" aria-label="主导航">
<a href="#" data-view="feed">活动墙</a>
<a href="#" data-view="mine">我的记录</a>
<a href="#center-records" data-view="center">赋能中心一楼</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>
@@ -25,7 +26,7 @@
<span id="topbar-name"></span>
<button class="btn ghost sm" id="logout-btn">退出</button>
</div>
<button class="btn primary" id="new-activity-btn" aria-label="+ 记录工作"><span class="new-activity-label">+ 记录工作</span><span class="new-activity-short" aria-hidden="true">+记录</span></button>
<button class="btn primary" id="new-activity-btn">+ 记录工作</button>
<button class="menu-toggle" id="menu-toggle" aria-label="展开导航" aria-controls="nav" aria-expanded="false">☰</button>
</div>
</header>
@@ -132,7 +133,7 @@
</div>
<section class="center-shortcuts" aria-label="赋能中心一楼快捷入口">
<div><strong>赋能中心一楼</strong><p>上传活动照片,完成每日清点,申请物品借用</p></div>
<div class="center-shortcut-actions"><a class="btn primary" href="#center-records">一楼活动记录</a><a class="btn" href="#center-duty">一楼值班</a><a class="btn" href="#center-assets">物品清点与借出</a><a class="btn" href="#timetables">课表收取</a></div>
<div class="center-shortcut-actions"><a class="btn primary" href="#center-records">一楼活动记录</a><a class="btn" href="#center-tutorials">设备教程</a><a class="btn" href="#center-duty">一楼值班</a><a class="btn" href="#center-assets">物品清点与借出</a><a class="btn" href="#timetables">课表收取</a></div>
</section>
<div class="filters">
<input id="feed-q" aria-label="搜索活动或地点" placeholder="搜索活动 / 地点" type="search" />
@@ -163,23 +164,32 @@
<div class="container">
<div class="page-head"><div><h2>赋能中心一楼</h2><p class="muted">查看单独的一楼值班表,记录活动,管理物品流转并完成每日清点</p></div></div>
<details class="center-export"><summary>AI读取与数据导出</summary>
<p class="muted">导出当前账号可见的数据,隐藏联系方式。照片与材料包以引用形式提供,全部CSV打包为ZIP。</p>
<p class="muted">导出当前账号可见的数据,隐藏联系方式。JSON 和 CSV 提供照片与材料包引用,全部 CSV 打包为 ZIP。</p>
<div class="filters center-toolbar">
<label>数据范围<select id="center-export-dataset"><option value="all">全部一楼数据</option><option value="activities">一楼活动记录</option><option value="items">物品库存</option><option value="loans">借用记录</option><option value="checks">每日清点</option><option value="duty_leaves">值班请假</option></select></label>
<label>格式<select id="center-export-format"><option value="json">JSON(适合AI)</option><option value="csv">CSV(全部时为ZIP)</option></select></label>
<label>格式<select id="center-export-format"><option value="json">JSON(适合AI)</option><option value="csv">CSV(全部时为ZIP)</option><option value="word_activities">Word(活动名、日期和照片)</option></select></label>
<label id="center-export-order-field" class="hidden">活动顺序<select id="center-export-order"><option value="desc">举办日期从新到旧</option><option value="asc">举办日期从旧到新</option></select></label>
<label>关键词<input id="center-export-q" type="search" placeholder="主题、物品、申请理由" /></label>
<label>从<input id="center-export-from" type="date" /></label><label>至<input id="center-export-to" type="date" /></label>
<label>借用状态<select id="center-export-loan-status"><option value="all">全部状态</option><option value="recorded">已登记借出</option><option value="approved">历史库存借出</option><option value="returned">历史已归还</option></select></label>
<button id="center-export-download" class="btn primary" type="button">下载数据</button>
</div>
<p class="muted" id="center-export-status" role="status"></p>
<p class="muted" id="center-export-status" role="status">Word 将筛选出的一楼活动合并成一个文档,包含活动名称、举办日期和照片。</p>
<p class="muted">程序读取:GET /api/center/data;字段说明:GET /api/center/schema。均需使用本人登录令牌。</p>
</details>
<div class="tabs center-tabs"><button class="tab active" data-center-tab="records">活动记录</button><button class="tab" data-center-tab="duty">一楼值班</button><button class="tab" data-center-tab="assets">物品清点与借出</button><button class="tab" data-center-tab="hall">展厅使用登记</button><button class="tab" data-center-tab="tutorials">设备使用教程</button></div>
<div class="tabs center-tabs"><button class="tab active" data-center-tab="records">活动记录</button><button class="tab" data-center-tab="tutorials">设备教程</button><button class="tab" data-center-tab="duty">一楼值班</button><button class="tab" data-center-tab="assets">物品清点与借出</button><button class="tab" data-center-tab="hall">展厅使用登记</button></div>
<section id="center-records">
<div class="filters center-toolbar"><input id="center-q" type="search" aria-label="搜索活动主题" placeholder="搜索活动主题" /><input id="center-from" type="date" aria-label="活动起始日期" /><input id="center-to" type="date" aria-label="活动截止日期" /><button id="center-new" class="btn primary">+ 记录一楼活动</button></div>
<div id="center-record-list" class="card-list"></div>
</section>
<section id="center-tutorials" class="hidden">
<div class="filters center-toolbar"><input id="tutorial-q" type="search" aria-label="搜索教室号、器材名或备注" placeholder="搜索教室号 / 器材名 / 备注" /><button id="tutorial-new" class="btn primary" type="button">+ 上传教程</button></div>
<p class="muted">教程视频仅登录成员可在线播放;原始视频只有上传者可以下载保存,其他人可在线观看。</p>
<div id="tutorial-list" class="tutorial-grid"></div>
<div id="tutorial-empty" class="empty hidden">还没有教程,点「+ 上传教程」添加第一份。</div>
<div class="form-actions"><button id="tutorial-more" class="btn hidden" type="button">加载更多</button></div>
<p class="muted" id="tutorial-status" role="status"></p>
</section>
<section id="center-duty" class="hidden">
<div class="center-duty-head">
<div>
@@ -210,11 +220,6 @@
<div class="filters center-toolbar"><button id="center-hall-refresh" class="btn">刷新登记数据</button><a id="center-hall-link" class="btn" href="#" target="_blank" rel="noopener">打开金山文档</a><span id="center-hall-status" class="muted" role="status"></span></div>
<div id="center-hall-list" class="card-list"></div>
</section>
<section id="center-tutorials" class="hidden">
<div class="page-head center-subhead"><div><h3>设备使用教程</h3><p class="muted">按教室和设备查找视频,登录成员均可上传和观看。</p></div><button id="center-add-tutorial" class="btn primary" type="button">+ 添加教程</button></div>
<div class="filters center-toolbar"><input id="center-tutorial-q" type="search" aria-label="搜索设备教程" placeholder="搜索教室号 / 设备名" /><button id="center-tutorial-refresh" class="btn" type="button">刷新</button></div>
<div id="center-tutorial-list" class="card-list"></div>
</section>
</div>
</main>
<main id="timetables-view" class="view hidden">
@@ -302,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">
@@ -363,7 +387,7 @@
<div id="toast" class="toast hidden" role="status" aria-live="polite"></div>
<script src="/js/app.js?v=51"></script>
<script src="/js/app.js?v=53"></script>
</div>
</body>
</html>
+318 -108
View File
@@ -26,7 +26,6 @@
});
const fmtDay = (ms) =>
new Date(ms).toLocaleDateString("zh-CN", { year: "numeric", month: "2-digit", day: "2-digit" });
const formatBytes = bytes => bytes >= MB ? `${(bytes / MB).toFixed(1)} MB` : `${Math.max(1, Math.ceil(bytes / 1024))} KB`;
const STATUS_LABEL = { joined: "已确认", attended: "已参加", absent: "缺席" };
const toLocalInput = (ms) => {
@@ -46,7 +45,17 @@
// ------------------------------------------------------------- API
const getToken = () => localStorage.getItem(TOKEN_KEY) || "";
const setToken = (t) => (t ? localStorage.setItem(TOKEN_KEY, t) : localStorage.removeItem(TOKEN_KEY));
function syncAuthCookie() {
const token = getToken();
const secure = location.protocol === 'https:' ? '; Secure' : '';
document.cookie = `${TOKEN_KEY}=${encodeURIComponent(token)}; Path=/; Max-Age=${token ? 30 * 24 * 60 * 60 : 0}; SameSite=Strict${secure}`;
}
function setToken(token) {
if (token) localStorage.setItem(TOKEN_KEY, token);
else localStorage.removeItem(TOKEN_KEY);
syncAuthCookie();
}
syncAuthCookie();
function apiErrorMessage(detail, status) {
if (typeof detail === "string" && detail) return detail;
@@ -126,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));
@@ -146,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++;
@@ -422,10 +432,15 @@
});
// ------------------------------------------------------------- 顶栏
$("#brand").addEventListener("click", () => show("feed"));
$("#new-activity-btn").addEventListener("click", () => openActivityForm(null, state.view === 'center' ? 'center' : 'normal'));
$("#menu-toggle").addEventListener("click", () => {
const open = $("#nav").classList.toggle("open");
$("#menu-toggle").setAttribute("aria-expanded", String(open));
});
$$("#nav a").forEach((a) =>
a.addEventListener("click", (e) => { e.preventDefault(); show(a.dataset.view); })
);
// ------------------------------------------------------------- 活动卡片
const initials = (name) => {
@@ -516,7 +531,6 @@
<h3><button class="activity-title" data-act="open">${esc(a.title)}</button></h3>
<div class="acard-meta">
${visTag}${statusTag}
${isCenter ? '<span class="tag cat">一楼记录</span>' : ''}
${full ? `<span class="tag full">已满 ${a.capacity} 人</span>` : ""}
<span class="meta-item">📅 ${fmtDate(a.start_at)}</span>
${a.location ? `<span class="meta-item">📍 ${esc(a.location)}</span>` : ""}
@@ -524,11 +538,12 @@
</div>
</div>
${a.description ? `<p class="acard-desc">${esc(a.description).slice(0, 160)}${a.description.length > 160 ? "…" : ""}</p>` : ""}
${a.record_type === 'center' ? '<span class="tag cat">赋能中心一楼活动记录</span>' : ''}
${materialButtons(a)}
${photoGallery(a.photo_ids)}
<div class="acard-foot">
<div class="faces">
${isCenter ? `<span class="faces-label">${a.organizer ? `由 ${esc(a.organizer.display_name)} 记录` : '全员可见'}</span>` : `${faces}${more}<span class="faces-label">${a.participant_count} 人${opts.showOrganizer && a.organizer ? ` · ${esc(a.organizer.display_name)} 记录` : ""}</span>`}
${isCenter ? `<span class="faces-label">仅作记录 · 全员可见${a.organizer ? ` · ${esc(a.organizer.display_name)} 记录` : ''}</span>` : `${faces}${more}<span class="faces-label">${a.participant_count} 人${opts.showOrganizer && a.organizer ? ` · ${esc(a.organizer.display_name)} 记录` : ""}</span>`}
</div>
<div class="acard-actions">${actions.join("")}</div>
</div>
@@ -891,33 +906,28 @@
return uploadFile('/api/center/materials', 'POST', file, onProgress, 'application/zip');
}
function uploadFile(path, method, file, onProgress, contentType, fields) {
function uploadFile(path, method, file, onProgress, contentType) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
materialUpload = xhr;
xhr.open(method, path);
xhr.setRequestHeader('Authorization', `Bearer ${getToken()}`);
if (contentType) xhr.setRequestHeader('Content-Type', contentType);
xhr.setRequestHeader('Content-Type', contentType);
xhr.timeout = 10 * 60 * 1000;
xhr.upload.onprogress = event => onProgress(event.loaded, event.lengthComputable ? event.total : file.size);
xhr.upload.onload = () => onProgress(file.size, file.size);
xhr.onload = () => {
let result;
try { result = JSON.parse(xhr.responseText); } catch { result = {}; }
if (xhr.status >= 200 && xhr.status < 300 && (result.id || result.timetable || result.ok)) resolve(result);
if (xhr.status >= 200 && xhr.status < 300 && (result.id || result.timetable)) resolve(result);
else reject(new Error(xhr.status === 413 ? (typeof result.detail === 'string' ? result.detail : '上传文件过大,请检查大小限制') : apiErrorMessage(result.detail, xhr.status)));
};
xhr.onerror = () => reject(new Error('照片或附件没有上传成功:网络中断或文件过大(每张照片≤8MB、ZIP≤100MB)'));
xhr.onerror = () => reject(new Error('上传失败,请检查网络后重试'));
xhr.ontimeout = () => reject(new Error('上传超时,请重试'));
xhr.onabort = () => reject(new Error('上传已取消'));
xhr.onloadend = () => { if (materialUpload === xhr) materialUpload = null; };
onProgress(0, file.size);
if (fields) {
const data = new FormData();
Object.entries(fields).forEach(([key, value]) => data.append(key, value));
data.append('video', file);
xhr.send(data);
} else xhr.send(file);
xhr.send(file);
});
}
@@ -938,11 +948,11 @@
}
}
function centerUploadFields(prefix, photoLabel = '照片') {
return `<label>${photoLabel}<input name="photos" type="file" accept="image/jpeg,image/png,image/webp" multiple /></label>
<p class="muted">可选JPG、PNG、WebP,自动转成统一JPEG;最多${CENTER_PHOTO_BATCH_LIMIT}张(含ZIP内照片),每张≤${CENTER_PHOTO_MAX_MB}MB。</p><div id="${prefix}-selected-photos" class="selected-photo-summary muted"></div>
function centerUploadFields(prefix) {
return `<label>活动照片<input name="photos" type="file" accept="image/jpeg,image/png,image/webp" multiple /></label>
<p class="muted">可直接多选相册照片或拍照,支持JPG、PNG、WebP并自动转为统一JPEG;每次最多${CENTER_PHOTO_BATCH_LIMIT}张(含ZIP内照片),每张不超过${CENTER_PHOTO_MAX_MB}MB。</p><div id="${prefix}-selected-photos" class="selected-photo-summary muted"></div>
<label>ZIP附件 <span class="hint-inline">(选填)</span><input name="materials" type="file" accept=".zip,application/zip" /></label>
<p class="muted">有PDF、Word、Excel等文档时打包成ZIP,最大${CENTER_ZIP_MAX_MB}MB。</p>`;
<p class="muted">需要附PDF、Word、Excel等文档时再上传ZIP,最大${CENTER_ZIP_MAX_MB}MB,可不含照片。</p>`;
}
function bindCenterUploads(form, box, label, meter, prefix) {
@@ -1050,12 +1060,10 @@
// ---- 新建 / 编辑活动
function openActivityForm(existing = null, defaultType = 'normal') {
const isEdit = !!existing;
const isCenter = existing?.record_type === 'center' || defaultType === 'center';
modal(`
<h3>${isEdit ? "编辑工作" : (isCenter ? "记录一楼活动" : "记录一项工作")}</h3>
<p class="modal-sub muted">${isCenter ? "提交后立即生效,一楼活动记录全员可见。" : "提交后立即生效,所有人可见。"}</p>
<h3>${isEdit ? "编辑工作" : "记录一项工作"}</h3>
<p class="modal-sub muted">提交后立即生效,所有人可见。</p>
<form id="act-form">
<label id="act-type-field">记录类型<select name="record_type"><option value="normal">普通工作记录</option><option value="center" hidden>一楼活动记录</option></select></label>
<label>工作名称 *<input name="title" required maxlength="120" value="${esc(existing?.title || "")}" placeholder="例如:周三晚例会" /></label>
<div class="form-row">
<label>开始时间 *<input name="start_at" type="datetime-local" required value="${existing ? toLocalInput(existing.start_at) : ""}" /></label>
@@ -1063,9 +1071,9 @@
</div>
<label>人数上限 <span class="hint-inline">(选填,留空不限人数)</span><input name="capacity" type="number" min="1" max="500" step="1" value="${existing?.capacity ?? ""}" placeholder="不限人数" /></label>
<label>备注 <span class="hint-inline">(选填)</span><textarea name="description" rows="3" maxlength="2000" placeholder="做什么、带什么、注意事项…">${esc(existing?.description || "")}</textarea></label>
<div id="act-photo-fields" class="hidden">${centerUploadFields('act', isCenter ? '活动照片' : '照片')}<p class="muted">${isEdit ? '照片和ZIP至少选择一种。编辑时会保留原照片和附件,所选内容追加保存。' : '照片和ZIP至少选择一种,ZIP可选。'}</p><div id="act-photo-preview">${photoGallery(existing?.photo_ids, '已有活动照片')}</div></div>
<div id="act-photo-fields">${centerUploadFields('act')}<p class="muted">照片和ZIP至少选择一种。编辑时会保留原照片和附件,所选内容追加保存。</p><div id="act-photo-preview">${photoGallery(existing?.photo_ids, '已有活动照片')}</div></div>
<label class="checkline" id="act-visibility"><input type="checkbox" name="visibility" ${!existing || existing.visibility === "public" ? "checked" : ""} /> 公开活动(所有人可见;不勾选则仅参加者可见)</label>
<p id="act-center-policy" class="muted hidden">全员可见,仅作活动记录,无需报名,也不计入参加统计。</p>
<p id="act-center-policy" class="muted hidden">全员可见,仅作活动记录,无需参加,也不计入参加统计。</p>
<div id="act-upload-progress" class="upload-progress hidden">
<p id="act-upload-status" role="status" aria-live="polite"></p>
<progress id="act-upload-meter" max="100" value="0" aria-labelledby="act-upload-status"></progress>
@@ -1077,23 +1085,23 @@
</div>
</form>`);
const activityForm = $('#act-form');
const recordType = existing?.record_type || defaultType;
const isCenterRecord = recordType === 'center';
if (!isCenterRecord) {
$('#act-photo-fields').classList.add('hidden');
$('#act-center-policy').classList.add('hidden');
}
const progressBox = $('#act-upload-progress');
const progressLabel = $('#act-upload-status');
const progressMeter = $('#act-upload-meter');
const errorBox = $('#act-error');
const collectUploads = bindCenterUploads(activityForm, progressBox, progressLabel, progressMeter, 'act');
activityForm.record_type.value = existing?.record_type || defaultType;
activityForm.record_type.disabled = defaultType === 'center';
const togglePhotos = () => {
const isCenter = activityForm.record_type.value === 'center';
$('#act-photo-fields').classList.toggle('hidden', !isCenter);
$('#act-visibility').classList.toggle('hidden', isCenter);
$('#act-type-field').classList.toggle('hidden', isCenter);
$('#act-center-policy').classList.toggle('hidden', !isCenter);
activityForm.visibility.disabled = isCenter;
if (isCenter && !activityForm.location.value.trim()) activityForm.location.value = '赋能中心一楼';
};
activityForm.record_type.addEventListener('change', togglePhotos); togglePhotos();
if (isCenterRecord) {
$('#act-visibility').classList.add('hidden');
$('#act-center-policy').classList.remove('hidden');
activityForm.visibility.disabled = true;
if (!activityForm.location.value.trim()) activityForm.location.value = '赋能中心一楼';
}
bindPhotoPreviews(activityForm);
$("#act-cancel").addEventListener("click", closeModal);
@@ -1110,21 +1118,17 @@
start_at: startMs,
location: f.location.value.trim(),
description: f.description.value.trim(),
visibility: f.record_type.value === 'center' || f.visibility.checked ? "public" : "private",
record_type: f.record_type.value,
visibility: isCenterRecord || f.visibility.checked ? "public" : "private",
record_type: recordType,
capacity: f.capacity.value ? Number(f.capacity.value) : null,
};
btn.disabled = true;
const typeWasDisabled = f.record_type.disabled;
f.record_type.disabled = true;
f.materials.disabled = true;
f.photos.disabled = true;
try {
if (body.record_type === 'center') {
if (!f.photos.files.length && !f.materials.files.length && !(existing?.photo_ids || []).length && !existing?.material_id && !existing?.materials?.length) throw new Error('请至少选择照片或ZIP附件');
btn.textContent = '正在上传…';
progressBox.classList.remove('hidden');
progressLabel.textContent = '正在准备照片…';
const uploaded = await collectUploads();
body.photo_ids = uploaded.photo_ids;
body.material_id = uploaded.material_id || existing?.material_id || null;
@@ -1145,7 +1149,6 @@
progressMeter.value = 0;
if (!progressBox.classList.contains('hidden')) progressLabel.textContent = '提交未完成,可重试;已上传成功的照片会复用。';
btn.disabled = false;
f.record_type.disabled = typeWasDisabled;
f.materials.disabled = false;
f.photos.disabled = false;
btn.textContent = isEdit ? '保存修改' : '提交记录';
@@ -1522,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;
@@ -1530,27 +1613,41 @@
catch (error) { toast(error.message,true); }
finally { button.disabled=false; }
});
const centerExportFormat = $('#center-export-format');
function updateCenterExportOrder() {
$('#center-export-order-field').classList.toggle('hidden', centerExportFormat.value !== 'word_activities');
}
centerExportFormat.addEventListener('change', updateCenterExportOrder);
updateCenterExportOrder();
$('#center-export-download').addEventListener('click', async () => {
const button = $('#center-export-download');button.disabled=true;$('#center-export-status').textContent='正在准备导出…';
const params = new URLSearchParams({ dataset:$('#center-export-dataset').value, format:$('#center-export-format').value });
const dataset = $('#center-export-dataset').value;
const format = centerExportFormat.value;
if (format === 'word_activities') $('#center-export-dataset').value = 'activities';
const params = new URLSearchParams({ dataset: format === 'word_activities' ? 'activities' : dataset, format });
if (format === 'word_activities') params.set('activity_order', $('#center-export-order').value);
for (const [id,key] of [['q','q'],['from','date_from'],['to','date_to'],['loan-status','loan_status']]) {
const value=$('#center-export-'+id).value;if(value)params.set(key,value);
}
try { await downloadCenterFile('/api/center/export?'+params,'center-export.json');$('#center-export-status').textContent='已下载,文件不包含联系方式,照片与材料包以引用形式提供。'; }
try {
const filename = format === 'word_activities' ? '一楼活动照片.docx' : `center-export.${format === 'csv' ? ($('#center-export-dataset').value === 'all' ? 'zip' : 'csv') : 'json'}`;
await downloadCenterFile('/api/center/export?'+params,filename);
$('#center-export-status').textContent = format === 'word_activities' ? '已下载 Word 文件,包含活动名称、举办日期和照片。' : '已下载,文件不包含联系方式,照片与材料包以引用形式提供。';
}
catch (error) { $('#center-export-status').textContent=error.message; }
finally {button.disabled=false;}
});
let centerRecords = [];
function openCenterFromHash() {
if (state.me && location.hash === '#timetables') { show('timetables'); return true; }
if (!state.me || !['#center', '#center-records', '#center-duty', '#center-assets', '#center-hall', '#center-tutorials'].includes(location.hash)) return false;
centerTab = location.hash === '#center-duty' ? 'duty' : location.hash === '#center-assets' ? 'assets' : location.hash === '#center-hall' ? 'hall' : location.hash === '#center-tutorials' ? 'tutorials' : 'records';
if (!state.me || !['#center', '#center-records', '#center-tutorials', '#center-duty', '#center-assets', '#center-hall'].includes(location.hash)) return false;
centerTab = location.hash === '#center-tutorials' ? 'tutorials' : location.hash === '#center-duty' ? 'duty' : location.hash === '#center-assets' ? 'assets' : location.hash === '#center-hall' ? 'hall' : 'records';
$$('[data-center-tab]').forEach(button => button.classList.toggle('active', button.dataset.centerTab === centerTab));
$('#center-records').classList.toggle('hidden', centerTab !== 'records');
$('#center-tutorials').classList.toggle('hidden', centerTab !== 'tutorials');
$('#center-duty').classList.toggle('hidden', centerTab !== 'duty');
$('#center-assets').classList.toggle('hidden', centerTab !== 'assets');
$('#center-hall').classList.toggle('hidden', centerTab !== 'hall');
$('#center-tutorials').classList.toggle('hidden', centerTab !== 'tutorials');
show('center');
return true;
}
@@ -1569,10 +1666,10 @@
const data = await api(`/activities?${p}`); centerRecords = data.items;
$('#center-record-list').innerHTML = data.items.map(a => activityCard(a)).join('') || '<div class="empty">暂无匹配的一楼活动,记录工作时请上传照片。</div>';
bindCardEvents($('#center-record-list'));
} else if (centerTab === 'tutorials') {
await loadTutorials();
} else if (centerTab === 'duty') {
await loadCenterDuty();
} else if (centerTab === 'tutorials') {
await loadCenterTutorials();
} else if (centerTab === 'hall') {
$('#center-hall-status').textContent = '正在读取金山文档登记表…';
const hall = await api('/center/hall-log');
@@ -1623,68 +1720,12 @@
history.replaceState(null, '', '#center-' + centerTab);
$$('[data-center-tab]').forEach(b => b.classList.toggle('active', b === button));
$('#center-records').classList.toggle('hidden', centerTab !== 'records');
$('#center-tutorials').classList.toggle('hidden', centerTab !== 'tutorials');
$('#center-duty').classList.toggle('hidden', centerTab !== 'duty');
$('#center-assets').classList.toggle('hidden', centerTab !== 'assets');
$('#center-hall').classList.toggle('hidden', centerTab !== 'hall');
$('#center-tutorials').classList.toggle('hidden', centerTab !== 'tutorials');
loadCenter();
}));
async function loadCenterTutorials() {
const data = await api('/center/tutorials?q=' + encodeURIComponent($('#center-tutorial-q').value.trim()));
$('#center-tutorial-list').innerHTML = data.items.length ? data.items.map(item => `
<article class="acard"><div class="acard-top"><div><h3>${esc(item.device_name)}</h3><div class="acard-meta"><span>教室 ${esc(item.classroom)}</span></div></div></div>
<div class="acard-foot"><span>${fmtDate(item.created_at)} · ${formatBytes(item.size_bytes)}</span><span>上传者:${esc(item.display_name)}</span></div>
<div class="tutorial-actions"><button class="btn primary" data-tutorial-play="${item.id}">▶ 播放教程</button>${item.can_delete ? `<button class="btn danger" data-tutorial-delete="${item.id}">删除</button>` : ''}</div></article>`).join('') : '<div class="empty-state"><p>还没有匹配的设备教程</p><p class="muted">添加一个视频,帮助大家快速上手。</p></div>';
}
$('#center-tutorial-q').addEventListener('input', debounce(loadCenterTutorials, 300));
$('#center-tutorial-refresh').addEventListener('click', loadCenterTutorials);
$('#center-add-tutorial').addEventListener('click', () => {
modal(`<h3>添加设备使用教程</h3><p class="modal-sub muted">视频仅登录成员可见。单个文件不超过 500MB。</p>
<form id="tutorial-form"><label>教室号<input name="classroom" required maxlength="40" placeholder="例如:101" /></label>
<label>设备名<input name="device_name" required maxlength="100" placeholder="例如:多媒体投影机" /></label>
<label>教程视频<input name="video" type="file" required accept="video/mp4,video/webm,video/quicktime,.m4v" /></label>
<div class="upload-progress hidden"><p>正在上传…</p><progress max="100" value="0"></progress></div>
<div class="form-error tutorial-upload-status" role="alert"></div><div class="form-actions"><button type="button" class="btn" id="tutorial-cancel">取消</button><button class="btn primary" type="submit">上传教程</button></div></form>`);
$('#tutorial-cancel').addEventListener('click', closeModal);
$('#tutorial-form').addEventListener('submit', async event => {
event.preventDefault();
const form = event.target; const submit = form.querySelector('[type=submit]');
const error = form.querySelector('.form-error'); const progress = form.querySelector('.upload-progress');
if (!form.reportValidity()) return;
submit.disabled = true; error.textContent = ''; progress.classList.remove('hidden');
try {
const result = await uploadFile('/api/center/tutorials', 'POST', form.video.files[0], (loaded, total) => {
progress.querySelector('progress').value = total ? loaded / total * 100 : 0;
progress.querySelector('p').textContent = `正在上传:${formatBytes(loaded)} / ${formatBytes(total)}`;
}, null, { classroom: form.classroom.value, device_name: form.device_name.value });
if (!result.ok) throw new Error('教程保存失败,请重试');
closeModal(); toast('教程已添加'); await loadCenterTutorials();
} catch (e) { error.textContent = e.message; submit.disabled = false; }
});
});
$('#center-tutorial-list').addEventListener('click', async event => {
const play = event.target.closest('[data-tutorial-play]');
const remove = event.target.closest('[data-tutorial-delete]');
if (play && !play.disabled) {
play.disabled = true;
play.textContent = '加载中…';
try {
const data = await api(`/center/tutorials/${encodeURIComponent(play.dataset.tutorialPlay)}/playback`, { method: 'POST' });
const response = await fetch(data.url, { headers: { Authorization: `Bearer ${getToken()}` } });
if (!response.ok) { const error = await response.json().catch(() => ({})); throw new Error(error.detail || '视频加载失败'); }
const url = URL.createObjectURL(await response.blob());
modal(`<h3>设备使用教程</h3><video class="tutorial-video" src="${url}" controls playsinline preload="metadata"></video><div class="form-actions"><button class="btn" id="tutorial-close">关闭</button></div>`);
$('#tutorial-close').addEventListener('click', closeModal);
modalCleanup = () => { const video = $('#modal-root video'); if (video) video.pause(); URL.revokeObjectURL(url); };
} catch (error) { toast(error.message, true); }
finally { play.disabled = false; play.textContent = '▶ 播放教程'; }
}
if (remove && !remove.disabled && confirm('确认删除这条教程吗?视频文件将一并删除。')) {
remove.disabled = true;
try { await api(`/center/tutorials/${encodeURIComponent(remove.dataset.tutorialDelete)}`, { method: 'DELETE' }); await loadCenterTutorials(); }
catch (error) { toast(error.message, true); remove.disabled = false; }
}
});
$('#center-new').addEventListener('click', () => openActivityForm(null, 'center'));
$('#center-hall-refresh').addEventListener('click', async () => {
try { await api('/center/hall-log?refresh=true'); } finally { await loadCenter(); }
@@ -1702,6 +1743,175 @@
<label>${isDuty ? '值班人及联系方式' : '使用单位联系人及联系方式'}<input name="duty" maxlength="200" value="${esc(current && current !== '—' ? current : '')}" placeholder="例如:张三 13800000000" /></label>`,
async f => { await api('/center/hall-log/duty', { method: 'POST', body: { row, column, value: f.duty.value.trim() } }); toast('已保存并同步到金山文档'); });
});
// ---- 设备使用教程
const TUTORIAL_PAGE = 60;
const tutorialState = { items: [], q: '', hasMore: false, seq: 0 };
let tutorialDebounce = null, tutorialProgressHandler = null;
const fmtBytes = (bytes) => {
if (!bytes) return '';
if (bytes >= 1024 ** 3) return (bytes / 1024 ** 3).toFixed(1) + ' GB';
if (bytes >= 1024 ** 2) return Math.round(bytes / 1024 ** 2) + ' MB';
return Math.max(1, Math.round(bytes / 1024)) + ' KB';
};
function tutorialCard(item, index) {
const canDownload = item.uploader_id === state.me?.id;
const src = `/api/center/tutorials/${encodeURIComponent(item.id)}`;
return `<article class="tutorial-card" data-tutorial="${esc(item.id)}">
<div class="tutorial-head"><b>${esc(item.room)}</b><span class="tag cat">${esc(item.equipment)}</span></div>
<video class="tutorial-video" controls preload="none" playsinline data-index="${index}" data-loaded="0"></video>
${item.note ? `<p class="tutorial-note">${esc(item.note)}</p>` : '<p class="tutorial-note muted">暂无备注</p>'}
<div class="tutorial-meta"><span class="muted">${esc(item.uploader)} · ${fmtDate(item.created_at)}${item.video_bytes ? ` · ${fmtBytes(item.video_bytes)}` : ''}</span>${canDownload ? `<button class="btn sm" type="button" data-tutorial-download="${esc(item.id)}">下载原视频</button>` : ''}</div>
</article>`;
}
function paintTutorials() {
const list = $('#tutorial-list');
list.innerHTML = tutorialState.items.map(tutorialCard).join('');
$('#tutorial-empty').classList.toggle('hidden', !!tutorialState.items.length || !!tutorialState.q);
$('#tutorial-more').classList.toggle('hidden', !tutorialState.hasMore);
$('#tutorial-empty').textContent = tutorialState.q ? '没有匹配的教程,换个教室号或器材名试试。' : '还没有教程,点「+ 上传教程」添加第一份。';
}
function playTutorial(index) {
const card = $('#tutorial-list article:nth-child(' + (index + 1) + ')');
const video = card?.querySelector('video');
const item = tutorialState.items[index];
if (!video || !item) return;
if (video.dataset.loaded === '0') {
video.addEventListener('error', () => toast('视频加载失败,请重新登录或稍后重试', true), { once: true });
video.src = `/api/center/tutorials/${encodeURIComponent(item.id)}`;
video.dataset.loaded = '1';
}
video.play().catch(() => {});
}
async function loadTutorials({ fresh = false } = {}) {
const seq = ++tutorialState.seq;
tutorialState.freshMode = fresh;
const p = new URLSearchParams({ limit: TUTORIAL_PAGE });
if (tutorialState.q) p.set('q', tutorialState.q);
const append = !fresh && $('#tutorial-more').dataset.mode === 'append';
$('#tutorial-more').dataset.mode = '';
if (append && tutorialState.items.length) p.set('offset', String(tutorialState.items.length));
$('#tutorial-status').textContent = tutorialState.items.length ? '正在加载更多…' : '正在读取教程…';
try {
const data = await api(`/center/tutorials?${p}`);
if (seq !== tutorialState.seq) return;
tutorialState.items = append ? tutorialState.items.concat(data.items) : data.items;
tutorialState.hasMore = data.has_more;
paintTutorials();
$('#tutorial-status').textContent = tutorialState.q
? `搜索「${tutorialState.q}」共 ${tutorialState.items.length} 条${data.has_more ? '(可加载更多)' : ''}`
: `共 ${tutorialState.items.length} 条教程${data.has_more ? ',还有更多' : ''}`;
} catch (error) {
$('#tutorial-status').textContent = '';
toast(error.message, true);
} finally {
if (seq === tutorialState.seq) tutorialState.freshMode = false;
}
}
function searchTutorials() {
clearTimeout(tutorialDebounce);
tutorialDebounce = setTimeout(() => {
tutorialState.q = $('#tutorial-q').value.trim();
tutorialState.items = [];
loadTutorials({ fresh: true });
}, 250);
}
function openTutorialForm() {
modal(`<h3>上传设备使用教程</h3>
<form id="tutorial-form" novalidate>
<label>教室号 *<input name="room" required maxlength="40" placeholder="例如:赋能中心一楼 A101" /></label>
<label>器材名 *<input name="equipment" required maxlength="100" placeholder="例如:激光切割机、投影仪" /></label>
<label>教程视频 * <span class="hint-inline">(MP4 / MOV / WebM,单个不超过 1GB)</span><input name="video" type="file" accept="video/mp4,video/quicktime,video/webm,.mp4,.mov,.webm" required /></label>
<label>备注 <span class="hint-inline">(选填)</span><textarea name="note" rows="3" maxlength="2000" placeholder="开机步骤、注意事项、常见问题…"></textarea></label>
<div class="upload-progress hidden" id="tutorial-progress"><p id="tutorial-progress-label" role="status" aria-live="polite"></p><progress id="tutorial-meter" max="100" value="0" aria-labelledby="tutorial-progress-label"></progress></div>
<div class="form-error" id="tutorial-error" role="alert"></div>
<div class="form-actions"><button type="button" class="btn" id="tutorial-cancel">取消</button><button type="submit" class="btn primary">上传并保存</button><button type="button" class="btn hidden" id="tutorial-abort">取消上传</button></div>
</form>`);
const form = $('#tutorial-form'), errorBox = $('#tutorial-error');
const box = $('#tutorial-progress'), label = $('#tutorial-progress-label'), meter = $('#tutorial-meter');
const button = form.querySelector('[type=submit]'), abortButton = $('#tutorial-abort');
let submitted = false;
$('#tutorial-cancel').addEventListener('click', () => { if (!submitted || !materialUpload) closeModal(); else abortButton.click(); });
abortButton.addEventListener('click', () => materialUpload?.abort());
form.video.addEventListener('change', () => {
const size = form.video.files[0]?.size || 0;
errorBox.textContent = size > 1024 ** 3 ? '视频超过 1GB,请先压缩再上传' : '';
});
const showProgress = (loaded, total) => {
box.classList.remove('hidden');
const pct = total ? Math.min(100, Math.round((loaded / total) * 100)) : 0;
meter.value = pct;
label.textContent = pct >= 100 ? `视频已上传,正在保存…(${fmtBytes(loaded)})` : `正在上传视频 ${pct}%(${fmtBytes(loaded)} / ${fmtBytes(total)})`;
};
tutorialProgressHandler = showProgress;
form.addEventListener('submit', async event => {
event.preventDefault();
if (button.disabled) return;
errorBox.textContent = '';
if (!form.reportValidity()) return;
const room = form.room.value.trim(), equipment = form.equipment.value.trim();
const file = form.video.files[0], note = form.note.value.trim();
if (!file) { errorBox.textContent = '请选择教程视频'; return; }
if (file.size > 1024 ** 3) { errorBox.textContent = '视频超过 1GB,请先压缩再上传'; return; }
submitted = true;
button.disabled = true; form.room.disabled = form.equipment.disabled = form.video.disabled = form.note.disabled = true;
abortButton.classList.remove('hidden');
button.textContent = '正在上传…';
const params = new URLSearchParams({ room, equipment, note });
const ext = (file.name.split('.').pop() || '').toLowerCase();
const type = file.type || ({ mp4: 'video/mp4', mov: 'video/quicktime', m4v: 'video/mp4', webm: 'video/webm' })[ext] || 'application/octet-stream';
try {
await uploadFile(`/api/center/tutorials?${params}`, 'POST', file, showProgress, type);
closeModal();
toast('教程已上传');
if (centerTab !== 'tutorials') { centerTab = 'tutorials'; history.replaceState(null, '', '#center-tutorials'); }
$$('[data-center-tab]').forEach(b => b.classList.toggle('active', b.dataset.centerTab === 'tutorials'));
$('#center-records').classList.add('hidden'); $('#center-tutorials').classList.remove('hidden');
$('#center-duty').classList.add('hidden'); $('#center-assets').classList.add('hidden'); $('#center-hall').classList.add('hidden');
tutorialState.items = []; tutorialState.q = ''; $('#tutorial-q').value = '';
await loadTutorials({ fresh: true });
} catch (error) {
submitted = false;
errorBox.textContent = error.message;
label.textContent = '上传未完成,可以直接重试。';
abortButton.classList.add('hidden');
button.disabled = false; button.textContent = '重新上传';
form.room.disabled = form.equipment.disabled = form.video.disabled = form.note.disabled = false;
if (!form.isConnected) { tutorialProgressHandler = null; return; }
}
tutorialProgressHandler = null;
});
}
$('#tutorial-new').addEventListener('click', openTutorialForm);
$('#tutorial-q').addEventListener('input', searchTutorials);
$('#tutorial-more').addEventListener('click', async () => {
if (tutorialState.freshMode) return;
$('#tutorial-more').dataset.mode = 'append';
await loadTutorials();
});
$('#tutorial-list').addEventListener('pointerenter', event => {
const video = event.target.closest('.tutorial-video');
if (video && !tutorialState.freshMode) playTutorial(Number(video.dataset.index));
}, true);
$('#tutorial-list').addEventListener('focusin', event => {
});
$('#tutorial-list').addEventListener('click', async event => {
const button = event.target.closest('[data-tutorial-download]');
if (button) {
const item = tutorialState.items.find(t => t.id === button.dataset.tutorialDownload);
button.disabled = true;
try {
const ext = (item?.video_file || '').split('.').pop() || 'mp4';
await downloadCenterFile(`/api/center/tutorials/${encodeURIComponent(button.dataset.tutorialDownload)}?preview=1`,
`${item?.room || '教程'}-${item?.equipment || ''}.${ext}`.replace(/[\\/:*?"<>|]/g, '_'));
} catch (error) { toast(error.message, true); }
finally { button.disabled = false; }
return;
}
const video = event.target.closest('.tutorial-video');
if (video) playTutorial(Number(video.dataset.index));
});
function openLoanForm() {
centerForm('登记借出',
`<p class="muted">这里只保存借出记录,不占用库存,也不要求物品已加入库存清单。借出理由全员可见,联系方式仅本人可见。</p>
+2 -2
View File
@@ -29,7 +29,7 @@
{"weekday": 7, "slot": "morning", "names": ["张胥轲"]},
{"weekday": 1, "slot": "afternoon", "names": ["任梦琪"]},
{"weekday": 2, "slot": "afternoon", "names": ["杜欣桐", "孙畅"]},
{"weekday": 3, "slot": "afternoon", "names": ["郑安然"]},
{"weekday": 3, "slot": "afternoon", "names": ["刘佩宁"]},
{"weekday": 4, "slot": "afternoon", "names": ["华秋豪"]},
{"weekday": 5, "slot": "afternoon", "names": ["刘洋"]},
{"weekday": 6, "slot": "afternoon", "names": ["薛含悦", "米文睿朴"]},
@@ -47,7 +47,7 @@
{"weekday": 2, "slot": "afternoon", "names": ["田宇恒"]},
{"weekday": 3, "slot": "afternoon", "names": ["刘一诺"]},
{"weekday": 4, "slot": "afternoon", "names": ["杜欣桐", "孙畅"]},
{"weekday": 5, "slot": "afternoon", "names": ["郑安然"]},
{"weekday": 5, "slot": "afternoon", "names": ["任梦琪"]},
{"weekday": 6, "slot": "afternoon", "names": ["林子歆"]},
{"weekday": 7, "slot": "afternoon", "names": ["武鑫"]}
]
+2 -2
View File
@@ -4,8 +4,8 @@ SQLAlchemy[asyncio]>=2.0.36,<3
aiosqlite>=0.20,<1
aiosmtplib>=3,<6
pydantic>=2.7,<3
Pillow>=11,<13
python-docx>=1.1,<2
Pillow>=10,<13
rapidocr>=3.10,<3.11
onnxruntime>=1.20,<2
# 仅测试时需要
httpx>=0.27,<1
+103 -102
View File
@@ -1,5 +1,6 @@
"""赋能中心一楼:照片、物品、每日清点、借还登记、展厅登记和值班入口。"""
import asyncio
import hashlib
import io
import json
import os
@@ -11,39 +12,16 @@ from pathlib import PurePosixPath
from datetime import datetime
from pathlib import Path
from fastapi import Depends, Form, HTTPException, Request, UploadFile
from fastapi.responses import FileResponse, StreamingResponse
from fastapi import Depends, HTTPException, Request
from fastapi.responses import FileResponse
from PIL.Image import DecompressionBombError
from pydantic import BaseModel, Field, field_validator
from sqlalchemy import select, insert, update, delete, func, text, or_
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
from .models import center_photos, center_materials, center_activity_materials, center_activity_meta, center_tutorials, center_items, center_loans, center_checks, activities, users
from .models import center_photos, center_materials, center_activity_materials, center_activity_meta, center_items, center_loans, center_checks, center_tutorials, activities, users
from .duty import BEIJING
from .security import now_ms, PHONE_PATTERN
class RangeResponse(StreamingResponse):
def __init__(self, path: Path, range_header: str | None, media_type: str):
size = path.stat().st_size
match = re.fullmatch(r'bytes=(\d+)-(\d*)', range_header or '')
start, end = (int(match[1]), int(match[2]) if match[2] else size - 1) if match else (0, size - 1)
if (range_header and not match) or start >= size or start > end:
super().__init__(b'', status_code=416, headers={'Content-Range': f'bytes */{size}'})
return
end = min(end, size - 1)
def chunks():
with path.open('rb') as source:
source.seek(start)
remaining = end - start + 1
while remaining:
chunk = source.read(min(1024 * 1024, remaining))
if not chunk: break
remaining -= len(chunk)
yield chunk
super().__init__(chunks(), status_code=206 if match else 200, media_type=media_type, headers={
'Content-Length': str(end - start + 1), 'Accept-Ranges': 'bytes',
'Content-Range': f'bytes {start}-{end}/{size}',
})
from .spa_static import range_safe_file
def required_text(value: str, message: str) -> str:
@@ -116,11 +94,25 @@ class MaterialIn(BaseModel):
MAX_PHOTOS_PER_UPLOAD = 50
MAX_PHOTO_BYTES = 8 * 1024 * 1024
MAX_TUTORIAL_BYTES = 500 * 1024 * 1024
TUTORIAL_TYPES = {'.mp4': 'video/mp4', '.m4v': 'video/x-m4v', '.mov': 'video/quicktime', '.webm': 'video/webm'}
MAX_ZIP_BYTES = 100 * 1024 * 1024
MAX_ZIP_EXPANDED_BYTES = 500 * 1024 * 1024
MAX_ZIP_ENTRY_BYTES = 50 * 1024 * 1024
# 设备教程视频:单段上传上限与格式白名单
MAX_TUTORIAL_BYTES = 1024 * 1024 * 1024
TUTORIAL_VIDEO_TYPES = {
'video/mp4': 'mp4', 'video/webm': 'webm', 'video/quicktime': 'mov',
'application/mp4': 'mp4', 'application/octet-stream': None,
}
TUTORIAL_PLAYLESS_TYPES = {'video/mp4', 'video/webm', 'video/quicktime', 'application/mp4'}
def detect_video_ext(head: bytes) -> str | None:
"""按文件头判断视频格式,避免仅凭浏览器声明的类型落盘错误后缀。"""
if len(head) >= 12 and head[4:8] == b'ftyp':
return 'mov' if head[8:12] in (b'qt ',) else 'mp4'
if head[:4] == b'\x1aE\xdf\xa3':
return 'webm'
return None
DAILY_PHOTO_LIMIT = 1000
UPLOAD_ORPHAN_TTL_MS = 24 * 60 * 60 * 1000
@@ -346,79 +338,6 @@ def install(app, get_db, current_user, photo_root, visible_clause):
path=photo_root()/(row['id']+'.zip')
if not path.is_file():raise HTTPException(404,'材料包文件不存在')
return FileResponse(path,media_type='application/zip',filename='center-materials-'+row['id']+'.zip')
@app.get('/api/center/tutorials')
async def tutorials(q: str = '', db=Depends(get_db), viewer=Depends(current_user)):
keyword = q.strip()[:100]
query = select(center_tutorials, users.c.display_name).join(users, users.c.id == center_tutorials.c.owner_id)
if keyword:
query = query.where(or_(center_tutorials.c.classroom.like('%' + keyword + '%'), center_tutorials.c.device_name.like('%' + keyword + '%')))
rows = (await db.execute(query.order_by(center_tutorials.c.created_at.desc()).limit(200))).mappings().all()
return {'items': [dict(row, can_delete=row['owner_id'] == viewer['id']) for row in rows]}
@app.post('/api/center/tutorials')
async def create_tutorial(classroom: str = Form(), device_name: str = Form(), video: UploadFile = Form(), db=Depends(get_db), viewer=Depends(current_user)):
classroom = classroom.strip()
device_name = device_name.strip()
if not classroom or not device_name: raise HTTPException(422, '教室号和设备名不能为空')
if len(classroom) > 40 or len(device_name) > 100: raise HTTPException(422, '教室号最多40字,设备名最多100字')
filename = (video.filename or '').strip()[:180]
extension = Path(filename).suffix.lower()
if extension not in TUTORIAL_TYPES: raise HTTPException(422, '仅支持MP4、WebM、MOV、M4V视频')
folder = photo_root() / 'tutorials'
folder.mkdir(parents=True, exist_ok=True)
video_key = uuid.uuid4().hex
path = folder / (video_key + extension)
size = 0
try:
with path.open('wb') as output:
while chunk := await video.read(1024 * 1024):
size += len(chunk)
if size > MAX_TUTORIAL_BYTES: raise HTTPException(413, '教程视频最大500MB')
await asyncio.to_thread(output.write, chunk)
if not size: raise HTTPException(422, '视频文件不能为空')
await db.execute(insert(center_tutorials).values(
id=uuid.uuid4().hex, classroom=classroom, device_name=device_name,
video_key=video_key, original_name=filename, media_type=TUTORIAL_TYPES[extension],
size_bytes=size, owner_id=viewer['id'], created_at=now_ms(),
))
await db.commit()
except Exception:
await db.rollback()
path.unlink(missing_ok=True)
raise
finally:
await video.close()
return {'ok': True}
@app.post('/api/center/tutorials/{tutorial_id}/playback')
async def tutorial_playback(tutorial_id: str, db=Depends(get_db), viewer=Depends(current_user)):
await tutorial_file(tutorial_id, db)
return {'url': f'/api/center/tutorials/{tutorial_id}/video'}
async def tutorial_file(tutorial_id: str, db):
if not re.fullmatch(r'[0-9a-f]{32}', tutorial_id): raise HTTPException(404, '教程不存在')
row = (await db.execute(select(center_tutorials).where(center_tutorials.c.id == tutorial_id))).mappings().first()
if not row: raise HTTPException(404, '教程不存在')
extension = next((ext for ext, mime in TUTORIAL_TYPES.items() if mime == row['media_type']), '.mp4')
path = photo_root() / 'tutorials' / (row['video_key'] + extension)
if not path.is_file(): raise HTTPException(404, '教程视频文件不存在')
return path, row
@app.get('/api/center/tutorials/{tutorial_id}/video')
async def tutorial_video(tutorial_id: str, request: Request, db=Depends(get_db), viewer=Depends(current_user)):
path, row = await tutorial_file(tutorial_id, db)
return RangeResponse(path, request.headers.get('Range'), row['media_type'])
@app.delete('/api/center/tutorials/{tutorial_id}')
async def delete_tutorial(tutorial_id: str, db=Depends(get_db), viewer=Depends(current_user)):
path, row = await tutorial_file(tutorial_id, db)
if row['owner_id'] != viewer['id']: raise HTTPException(403, '只能删除自己上传的教程')
await db.execute(delete(center_tutorials).where(center_tutorials.c.id == tutorial_id))
await db.commit()
path.unlink(missing_ok=True)
return {'ok': True}
@app.post('/api/center/photos')
async def upload_photo(request: Request, db=Depends(get_db), viewer=Depends(current_user)):
raw = bytearray()
@@ -454,6 +373,88 @@ def install(app, get_db, current_user, photo_root, visible_clause):
if not path.is_file(): raise HTTPException(404, '照片文件不存在')
return FileResponse(path, media_type='image/jpeg')
# ---------------------------------------------------------------- 设备使用教程
@app.get('/api/center/tutorials')
async def list_tutorials(q: str = '', offset: int = 0, limit: int = 60, db=Depends(get_db), viewer=Depends(current_user)):
keyword = q.strip()
if keyword and len(keyword) > 100: raise HTTPException(422, '搜索关键词最多100字')
offset, limit = max(0, offset), min(100, max(1, limit))
stmt = select(center_tutorials.c.id, center_tutorials.c.room, center_tutorials.c.equipment,
center_tutorials.c.note, center_tutorials.c.created_at, center_tutorials.c.uploader_id,
center_tutorials.c.video_file, center_tutorials.c.video_bytes,
users.c.display_name.label('uploader_name')).select_from(center_tutorials).outerjoin(users, users.c.id == center_tutorials.c.uploader_id)
for word in keyword.split():
like = '%' + word + '%'
stmt = stmt.where(or_(center_tutorials.c.room.like(like), center_tutorials.c.equipment.like(like), center_tutorials.c.note.like(like)))
rows = (await db.execute(stmt.order_by(center_tutorials.c.created_at.desc(), center_tutorials.c.id)
.offset(offset).limit(limit + 1))).mappings().all()
items = []
for r in rows[:limit]:
item = dict(r)
item['uploader'] = item.pop('uploader_name') or '未命名成员'
items.append(item)
return {'items': items, 'has_more': len(rows) > limit}
@app.post('/api/center/tutorials')
async def upload_tutorial(request: Request, room: str = '', equipment: str = '', note: str = '',
db=Depends(get_db), viewer=Depends(current_user)):
room, equipment, note = room.strip(), equipment.strip(), note.strip()
if not room or len(room) > 40: raise HTTPException(422, '请填写教室号(40字以内)')
if not equipment or len(equipment) > 100: raise HTTPException(422, '请填写器材名(100字以内)')
if len(note) > 2000: raise HTTPException(422, '备注最多2000字')
content_type = (request.headers.get('content-type') or '').split(';')[0].strip().lower()
if content_type not in TUTORIAL_VIDEO_TYPES: raise HTTPException(422, '教程视频仅支持 MP4、MOV 或 WebM')
received = 0
head = b''
path = None
photo_root().mkdir(parents=True, exist_ok=True)
staging_name = photo_root() / ('tutorial-' + uuid.uuid4().hex + '.part')
staging = os.fdopen(os.open(staging_name, os.O_WRONLY | os.O_CREAT | os.O_TRUNC), 'wb', buffering=1024 * 1024)
try:
async for chunk in request.stream():
if not head: head = chunk[:16]
received += len(chunk)
if received > MAX_TUTORIAL_BYTES: raise HTTPException(413, f'教程视频最大{MAX_TUTORIAL_BYTES // 1024 // 1024 // 1024}GB')
await asyncio.to_thread(staging.write, chunk)
staging.flush(); await asyncio.to_thread(os.fsync, staging.fileno())
staging.close()
if received <= 12: raise HTTPException(422, '教程视频为空,请重新选择')
ext = detect_video_ext(head)
if not ext: raise HTTPException(422, '无法识别视频格式,请上传 MP4、MOV 或 WebM')
key = uuid.uuid4().hex
path = photo_root() / (key + '.' + ext)
os.replace(staging_name, path)
try:
await db.execute(insert(center_tutorials).values(
id=key, room=room, equipment=equipment, video_file=key + '.' + ext, video_bytes=received,
note=note, uploader_id=viewer['id'], created_at=now_ms()))
await db.commit()
except Exception:
await db.rollback()
path.unlink(missing_ok=True)
raise
except BaseException:
staging.close()
staging_name.unlink(missing_ok=True)
raise
return {'id': key}
@app.api_route('/api/center/tutorials/{tutorial_id}', methods=['GET', 'HEAD'])
async def tutorial_video(tutorial_id: str, preview: str = '0', db=Depends(get_db), viewer=Depends(current_user)):
if not re.fullmatch(r'[0-9a-f]{32}', tutorial_id): raise HTTPException(404, '教程不存在')
row = (await db.execute(select(center_tutorials).where(center_tutorials.c.id == tutorial_id))).mappings().first()
if not row: raise HTTPException(404, '教程不存在')
path = photo_root() / row['video_file']
if not path.is_file(): raise HTTPException(404, '教程视频文件不存在')
ext = row['video_file'].rpartition('.')[2]
media_type = {'mp4': 'video/mp4', 'mov': 'video/quicktime', 'webm': 'video/webm'}.get(ext, 'application/octet-stream')
if preview == '1':
if viewer['id'] != row['uploader_id']:
raise HTTPException(403, '只有上传者可以下载原始视频')
filename = f'{row["room"]}-{row["equipment"]}.{ext}'
return range_safe_file(path, media_type=media_type, filename=filename)
return range_safe_file(path, media_type=media_type, stat_result=path.stat(), content_disposition_type='inline')
@app.get('/api/center/items')
async def items(q: str = '', db=Depends(get_db), viewer=Depends(current_user)):
rows = (await db.execute(select(center_items).where(center_items.c.name.like('%'+q.strip()+'%')).order_by(center_items.c.name))).mappings().all()
+2 -4
View File
@@ -13,7 +13,7 @@ from fastapi import Depends, HTTPException, Query
from pydantic import BaseModel, Field, field_validator
from sqlalchemy import insert, select
from .duty import BEIJING
from .duty import BEIJING, week_type_on
from .models import center_duty_leaves, users
from .security import now_ms
@@ -68,9 +68,7 @@ def _monday_for(value: date) -> date:
def _week_type(schedule: dict, week_start: date) -> str:
week_delta = (_monday_for(week_start) - schedule["anchor_day"]).days // 7
odd = week_delta % 2 == 0
return schedule["anchor_week"] if odd else ("even" if schedule["anchor_week"] == "odd" else "odd")
return week_type_on(schedule, week_start)
def _at_ms(day: date, clock: str) -> int:
+54 -3
View File
@@ -2,12 +2,17 @@
import csv
import io
import json
import re
import zipfile
from datetime import date, datetime, time, timedelta
from typing import Literal, Optional
from fastapi import Depends, HTTPException, Query
from fastapi.responses import Response
from PIL import Image
from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.shared import Inches
from sqlalchemy import select, func, or_, case
from .duty import BEIJING
from . import center
@@ -65,7 +70,44 @@ def csv_bytes(kind, rows):
return buffer.getvalue().encode('utf-8-sig')
def install(app, get_db, current_user, visible_clause):
def docx_bytes(rows, photo_root):
document = Document()
document.add_heading('赋能中心一楼活动记录', level=0)
for index, row in enumerate(rows, 1):
title = (row.get('title') or '').strip() or '未命名活动'
heading = document.add_heading(f'{index}. {title}', level=1)
heading.paragraph_format.keep_with_next = True
heading.paragraph_format.keep_together = True
event_date = datetime.fromtimestamp(row['start_at'] / 1000, BEIJING).date()
date_paragraph = document.add_paragraph(f'举办日期:{event_date.isoformat()}')
date_paragraph.paragraph_format.keep_with_next = True
photos = []
for photo_id in row.get('photo_ids') or []:
if not re.fullmatch(r'[0-9a-f]{32}', photo_id):
continue
path = photo_root() / (photo_id + '.jpg')
if not path.is_file():
continue
with Image.open(path) as image:
width, height = image.size
width_inches = 6.0
height_inches = width_inches * height / width if width else 4.5
if height_inches > 7.5:
height_inches = 7.5
width_inches = height_inches * width / height if height else 6.0
paragraph = document.add_paragraph()
paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
paragraph.paragraph_format.keep_together = True
paragraph.add_run().add_picture(str(path), width=Inches(width_inches), height=Inches(height_inches))
photos.append(photo_id)
if not photos:
document.add_paragraph('(暂无照片)')
output = io.BytesIO()
document.save(output)
return output.getvalue()
def install(app, get_db, current_user, visible_clause, photo_root):
@app.get('/api/center/schema')
async def schema(viewer=Depends(current_user)):
return {
@@ -87,7 +129,7 @@ def install(app, get_db, current_user, visible_clause):
'duty_leave_endpoint':'POST /api/center/duty/leave(仅排班成员本人可提交)',
'filters':{'dataset':['all',*FIELDS], 'q':'活动主题/地点/描述,物品名称,借用物品/理由/免登录姓名/学院/活动名称,清点备注/日期,值班姓名/事由', 'date_from':'YYYY-MM-DD,含当日,北京时间', 'date_to':'YYYY-MM-DD,含当日,北京时间', 'loan_status':['all','recorded','approved','borrowed(approved 的兼容别名)','returned']},
'semantics':{'timestamps':'数据行中的 *_at 为 Unix 毫秒时间戳,空值为null;generated_at 为带时区的 ISO 8601 字符串', 'inventory':'quantity=物品总数,borrowed/available只统计升级前的历史库存借出记录;新的借出登记与物品库存完全独立', 'loans':'status=recorded 表示仅登记借出;item_id 为空时 item_name 为登记人填写的物品名称;borrower_type=member 表示登录成员登记,guest 表示登录页免登录登记;新登记不扣减库存,也不要求物品已加入库存清单', 'date_filter':'活动按开始时间、借用按登记时间、清点按清点日期、值班请假按值班日期筛选;库存是当前状态,不受日期筛选影响', 'photos':'materials包含原材料和成员补充材料、上传人及关联时间;照片ID合并全部材料,下载需登录;旧照片记录的material_id可为null', 'privacy':'一楼活动全体登录成员可见,仅作记录,不参与参加和发起统计;借用联系方式、账号邮箱和手机号均不导出', 'checks':'details 中 expected=应在库,actual=实点在库;历史 borrowed 为当时占用的库存数量', 'duty':'单双周从2026-11-16起交替;请假必须在值班日期开始前提交;请假不进入活动统计,也不记录缺勤'},
'download':{'json':'完整匹配数据,不受分页参数影响;all包含全部五个数据集','csv':'单一数据集为CSV;all为ZIP,内含五个CSV,UTF-8 BOM;嵌套字段为JSON字符串'},
'download':{'json':'完整匹配数据,不受分页参数影响;all包含全部五个数据集','csv':'单一数据集为CSV;all为ZIP,内含五个CSV,UTF-8 BOM;嵌套字段为JSON字符串','word_activities':'dataset=activities 时导出一个DOCX,包含活动名称、北京时间举办日期和照片;activity_order=desc(默认,由近到远)或 asc(由远到近)'},
}
async def collect(db, viewer, dataset, q, start, end, loan_status, limit=None, offset=0):
@@ -150,10 +192,19 @@ def install(app, get_db, current_user, visible_clause):
return await collect(db,viewer,dataset,q,date_from,date_to,loan_status,limit,offset)
@app.get('/api/center/export')
async def export(dataset:Dataset='all',format:Literal['json','csv']='json',q:str=Query('',max_length=200),date_from:Optional[date]=None,date_to:Optional[date]=None,loan_status:LoanStatus='all',db=Depends(get_db),viewer=Depends(current_user)):
async def export(dataset:Dataset='all',format:Literal['json','csv','word_activities']='json',q:str=Query('',max_length=200),date_from:Optional[date]=None,date_to:Optional[date]=None,loan_status:LoanStatus='all',activity_order:Literal['asc','desc']='desc',db=Depends(get_db),viewer=Depends(current_user)):
if format == 'word_activities' and dataset != 'activities':
raise HTTPException(422, 'Word 导出仅支持一楼活动记录')
payload=await collect(db,viewer,dataset,q,date_from,date_to,loan_status)
stamp=datetime.now(BEIJING).strftime('%Y%m%d-%H%M%S')
if format=='json':body=json.dumps(payload,ensure_ascii=False,indent=2).encode('utf-8');extension='json';mime='application/json'
elif format=='word_activities':
rows = payload['data']['activities']
if activity_order == 'asc':
rows.sort(key=lambda row: row['start_at'])
body = docx_bytes(rows, photo_root)
extension = 'docx'
mime = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
elif dataset!='all':body=csv_bytes(dataset,payload['data'][dataset]);extension='csv';mime='text/csv; charset=utf-8'
else:
buffer=io.BytesIO()
+9 -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
@@ -201,6 +202,8 @@ async def get_db():
async def current_user(request: Request, db: AsyncSession = Depends(get_db)) -> dict:
header = request.headers.get("authorization", "")
token = header[7:].strip() if header.lower().startswith("bearer ") else ""
if not token:
token = request.cookies.get("worklog_token", "").strip()
if not token:
raise HTTPException(status_code=401, detail="请先登录")
row = (await db.execute(select(sessions).where(sessions.c.token == token_digest(token)))).mappings().first()
@@ -589,6 +592,9 @@ async def lifespan(_app: FastAPI):
columns = await conn.run_sync(lambda c: {col['name'] for col in inspect(c).get_columns('center_activity_meta')})
if 'material_id' not in columns:
await conn.execute(text('ALTER TABLE center_activity_meta ADD COLUMN material_id VARCHAR(32)'))
recruit_columns = await conn.run_sync(lambda c: {col['name'] for col in inspect(c).get_columns('recruit_announcements')})
if 'source_order' not in recruit_columns:
await conn.execute(text('ALTER TABLE recruit_announcements ADD COLUMN source_order INTEGER NOT NULL DEFAULT 0'))
await _migrate_legacy(conn)
# 一楼历史活动统一作为公开记录,历史参加数据保留存档但不再参与统计。
center_ids = select(center_activity_meta.c.activity_id)
@@ -767,7 +773,8 @@ async def _migrate_center_loan_schema(conn) -> None:
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)
center_export.install(app, get_db, current_user, visible_clause, lambda: _db_path.parent / 'uploads')
recruit.install(app, get_db, current_user, _db_path.parent / 'recruit-images')
def timetable_collectors():
values = os.getenv('WORKLOG_TIMETABLE_COLLECTORS')
@@ -806,7 +813,7 @@ async def security_headers(request: Request, call_next):
response.headers["Referrer-Policy"] = "no-referrer"
response.headers["Content-Security-Policy"] = (
"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; "
"img-src 'self' data: blob:; connect-src 'self'; object-src 'none'; base-uri 'none'; "
"img-src 'self' data: blob:; media-src 'self' blob:; connect-src 'self'; object-src 'none'; base-uri 'none'; "
"frame-ancestors 'none'; form-action 'self'"
)
if request.url.path.startswith(("/api/", "/join/", "/duty-confirm/", "/mail-test/")):
+28 -9
View File
@@ -143,14 +143,6 @@ center_activity_materials = Table('center_activity_materials', metadata,
Column('activity_id', String(36), ForeignKey('activities.id', ondelete='CASCADE'), primary_key=True),
Column('material_id', String(32), ForeignKey('center_materials.id'), primary_key=True),
Column('created_at', Integer, nullable=False))
center_tutorials = Table('center_tutorials', metadata,
Column('id', String(32), primary_key=True),
Column('classroom', String(40), nullable=False), Column('device_name', String(100), nullable=False),
Column('video_key', String(40), nullable=False, unique=True),
Column('original_name', String(180), nullable=False), Column('media_type', String(40), nullable=False),
Column('size_bytes', Integer, nullable=False), Column('owner_id', String(36), ForeignKey('users.id'), nullable=False),
Column('created_at', Integer, nullable=False))
Index('ix_center_tutorial_created', center_tutorials.c.created_at)
center_items = Table('center_items', metadata,
Column('id', String(32), primary_key=True), Column('name', String(100), nullable=False, unique=True),
Column('quantity', Integer, nullable=False), Column('created_at', Integer, nullable=False))
@@ -177,6 +169,16 @@ center_duty_leaves = Table('center_duty_leaves', metadata,
UniqueConstraint('duty_date', 'slot', 'user_id', name='uq_center_duty_leave_member'))
Index('ix_center_duty_leave_date_slot', center_duty_leaves.c.duty_date, center_duty_leaves.c.slot)
center_tutorials = Table('center_tutorials', metadata,
Column('id', String(36), primary_key=True),
Column('room', String(40), nullable=False), Column('equipment', String(100), nullable=False),
# 视频保存在 uploads/tutorials/{id}.{ext},这里只记文件名
Column('video_file', String(80), nullable=False), Column('video_bytes', Integer, nullable=False),
Column('note', Text, nullable=False, default=''),
Column('uploader_id', String(36), ForeignKey('users.id'), nullable=False),
Column('created_at', Integer, nullable=False))
Index('ix_center_tutorials_created', center_tutorials.c.created_at)
timetables = Table('timetables', metadata,
Column('user_id', String(36), ForeignKey('users.id', ondelete='CASCADE'), primary_key=True),
Column('week_type', String(4), primary_key=True),
@@ -185,8 +187,25 @@ 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('source_order', Integer, nullable=False, default=0),
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_tutorials, center_items, center_loans, center_checks, center_duty_leaves, timetables,
center_items, center_loans, center_checks, center_duty_leaves, center_tutorials, timetables,
recruit_announcements,
)
+472
View File
@@ -0,0 +1,472 @@
"""招聘公告同步、浏览和 Word / Markdown 导出。"""
from __future__ import annotations
import asyncio
import hashlib
import io
import logging
import re
from datetime import datetime
from html.parser import HTMLParser
from pathlib import Path
from typing import Literal
from urllib.parse import urljoin
import httpx
from docx import Document
from docx.shared import Cm, Pt
from fastapi import Depends, HTTPException, Query
from fastapi.responses import Response
from PIL import Image
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"
DETAIL_HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/131.0 Safari/537.36"}
logger = logging.getLogger(__name__)
MAX_IMAGE_EDGE = 1800
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 extract_detail_html(content: str) -> str:
"""提取详情页服务端渲染的正文和职位列表。"""
positions_match = re.search(
r'<div[^>]+class="(?:[^"]*\s)?selected-positions(?:\s[^"]*)?"',
content,
flags=re.I,
)
if not positions_match:
return ""
start = positions_match.start()
depth = 0
for match in re.finditer(r'<div\b[^>]*>|</div\s*>', content[start:], flags=re.I):
depth += 1 if match.group(0).startswith("<div") else -1
if depth == 0:
return content[start:start + match.end()].strip()
return content[start:].strip()
def image_url(src: str) -> str:
src = (src or "").strip()
if not src or src.startswith(("data:", "file:")):
return ""
if src.startswith("//"):
return "https:" + src
return urljoin(SOURCE + "/", src)
def content_blocks(content: str) -> list[tuple[str, str]]:
"""把公告 HTML 拆成按原顺序排列的文字段落和图片。"""
blocks: list[tuple[str, str]] = []
buffer: list[str] = []
skip = 0
class Parser(HTMLParser):
def flush(self):
text = re.sub(r"[ \t\r\f\v]+", " ", "".join(buffer)).strip()
if text:
blocks.append(("text", text))
buffer.clear()
def handle_starttag(self, tag, attrs):
nonlocal skip
if tag in {"script", "style"}:
skip += 1
if tag == "img":
self.flush()
src = dict(attrs).get("src", "")
source = image_url(src)
if source:
blocks.append(("image", source))
elif tag in {"p", "div", "section", "br", "tr", "li", "table", "h1", "h2", "h3", "h4"}:
self.flush()
def handle_endtag(self, tag):
nonlocal skip
if tag in {"script", "style"} and skip:
skip -= 1
elif tag in {"p", "div", "section", "br", "tr", "li", "table", "h1", "h2", "h3", "h4"}:
self.flush()
def handle_data(self, data):
if not skip:
buffer.append(data)
parser = Parser(convert_charrefs=True)
parser.feed(content or "")
parser.close()
parser.flush()
return blocks
def is_image_data(body: bytes) -> bool:
return (
body.startswith(b"\xff\xd8")
or body.startswith(b"\x89PNG\r\n\x1a\n")
or body.startswith((b"GIF87a", b"GIF89a", b"BM", b"II*\x00", b"MM\x00*"))
or (body[:4] == b"RIFF" and body[8:12] == b"WEBP")
)
def normalized_image(body: bytes) -> bytes | None:
try:
with Image.open(io.BytesIO(body)) as image:
image.seek(0)
image.load()
if max(image.size) > MAX_IMAGE_EDGE:
image.thumbnail((MAX_IMAGE_EDGE, MAX_IMAGE_EDGE), Image.Resampling.LANCZOS)
if image.mode in {"RGBA", "LA", "P"}:
background = Image.new("RGB", image.size, "white")
rgba = image.convert("RGBA")
background.paste(rgba, mask=rgba.getchannel("A"))
image = background
else:
image = image.convert("RGB")
output = io.BytesIO()
image.save(output, format="JPEG", quality=86, optimize=True)
return output.getvalue()
except Exception:
return None
def add_docx_picture(document, body: bytes) -> bool:
try:
document.add_picture(io.BytesIO(body), width=Cm(15))
return True
except Exception:
return False
async def fetch_image(client: httpx.AsyncClient, url: str) -> bytes | None:
headers = [
{"Referer": SOURCE + "/", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/131.0 Safari/537.36"},
{"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/131.0 Safari/537.36"},
{"Referer": SOURCE + "/", "User-Agent": "Mozilla/5.0 WorkLog/2.0"},
]
for attempt, request_headers in enumerate(headers, 1):
try:
response = await asyncio.wait_for(client.get(url, headers=request_headers), timeout=12)
response.raise_for_status()
body = response.content
if is_image_data(body):
normalized = normalized_image(body)
if normalized:
return normalized
except (httpx.HTTPError, asyncio.TimeoutError):
pass
if attempt < len(headers):
await asyncio.sleep(0.4 * attempt)
return None
def cache_file(cache_dir: Path | None, url: str) -> Path | None:
if cache_dir is None:
return None
return cache_dir / (hashlib.sha256(url.encode("utf-8")).hexdigest() + ".jpg")
async def get_image(client: httpx.AsyncClient, url: str, cache_dir: Path | None) -> bytes | None:
path = cache_file(cache_dir, url)
if path and path.exists():
try:
return path.read_bytes()
except OSError:
pass
body = await fetch_image(client, url)
if body and path:
try:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(body)
except OSError:
logger.warning("招聘公告图片缓存写入失败:%s", path)
return body
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):
last_error: Exception | None = None
for attempt in range(2):
try:
response = await asyncio.wait_for(
client.get(LIST_ENDPOINT, params={"pageNum": page, "pageSize": page_size}),
timeout=15,
)
response.raise_for_status()
payload = response.json()
if payload.get("code") != 0:
raise RuntimeError(payload.get("msg") or "招聘公告接口返回异常")
return payload
except (httpx.HTTPError, asyncio.TimeoutError, RuntimeError) as exc:
last_error = exc
if attempt == 0:
await asyncio.sleep(0.4)
raise RuntimeError("就业平台暂时无法访问") from last_error
async def fetch_detail_html(client: httpx.AsyncClient, gonggao_id: int) -> str:
last_error: Exception | None = None
for attempt in range(2):
try:
response = await asyncio.wait_for(
client.get(f"{DETAIL_ENDPOINT}/{gonggao_id}", headers=DETAIL_HEADERS),
timeout=15,
)
response.raise_for_status()
return response.text
except (httpx.HTTPError, asyncio.TimeoutError) as exc:
last_error = exc
if attempt == 0:
await asyncio.sleep(0.4)
raise RuntimeError(f"公告详情页获取失败({gonggao_id})") from last_error
async def sync_all(db, client: httpx.AsyncClient | None = None) -> dict:
owns_client = client is None
if owns_client:
client = httpx.AsyncClient(timeout=20, trust_env=False)
added = updated = 0
try:
first = await fetch_page(client, 1)
pages = max(1, int(first.get("extra", {}).get("pages") or 1))
page_size = 50
pages = max(pages, -(-len(first.get("rows") or []) // page_size))
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 [])
details: dict[int, str] = {}
for raw in rows:
content = str(raw.get("gonggaoContent") or "").strip()
if len(content) <= 20 and not raw.get("iswailian"):
try:
gonggao_id = int(raw["gonggaoId"])
await asyncio.sleep(0.15)
details[gonggao_id] = await fetch_detail_html(client, gonggao_id)
except (KeyError, TypeError, ValueError, RuntimeError):
logger.warning("公告详情补抓失败:%s", raw.get("gonggaoId"), exc_info=True)
finally:
if owns_client:
await client.aclose()
now = int(datetime.now(BEIJING).timestamp() * 1000)
source_order = {int(raw["gonggaoId"]): order for order, raw in enumerate(rows) if str(raw.get("gonggaoId") or "").isdigit()}
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": details.get(gonggao_id) and extract_detail_html(details[gonggao_id]) or 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 ""),
"source_order": source_order.get(gonggao_id, 0),
"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}
async def docx_bytes(rows, client: httpx.AsyncClient | None = None, cache_dir: Path | None = None) -> bytes:
owns_client = client is None
if owns_client:
client = httpx.AsyncClient(timeout=20, follow_redirects=True, trust_env=False)
sources = []
for row in rows:
for kind, value in content_blocks(row["content_html"]):
if kind == "image" and value not in sources:
sources.append(value)
try:
semaphore = asyncio.Semaphore(6)
async def limited(url):
async with semaphore:
return await get_image(client, url, cache_dir)
results = await asyncio.gather(*(limited(url) for url in sources))
finally:
if owns_client:
await client.aclose()
images = dict(zip(sources, results))
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 kind, value in content_blocks(row["content_html"]):
if kind == "text":
document.add_paragraph(value)
else:
body = images.get(value)
if body:
if not add_docx_picture(document, body):
document.add_paragraph("[公告图片格式不受支持]")
else:
document.add_paragraph("[公告图片未能下载]")
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)}")
for kind, value in content_blocks(row["content_html"]):
if kind == "text":
lines.extend([value, ""])
else:
lines.extend([f"![公告图片]({value})", ""])
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, cache_dir: Path | None = None):
@app.post("/api/recruit/sync")
async def sync(viewer=Depends(current_user), db=Depends(get_db)):
try:
return await sync_all(db)
except Exception as exc:
logger.exception("招聘公告同步失败")
detail = "同步失败:就业平台返回异常,请稍后重试"
cause = exc.__cause__ or exc
if isinstance(cause, (httpx.ConnectError, httpx.ConnectTimeout)):
detail = "同步失败:服务器无法连接就业平台,请检查服务器网络后重试"
elif isinstance(cause, asyncio.TimeoutError):
detail = "同步失败:就业平台响应超时,请稍后重试"
elif isinstance(cause, RuntimeError):
detail = f"同步失败:{cause}"
raise HTTPException(502, detail) from exc
@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.source_order.asc(), 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.source_order.asc(), 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":
try:
body = await docx_bytes(rows, cache_dir=cache_dir)
except Exception as exc:
logger.exception("招聘公告 Word 导出失败")
raise HTTPException(502, "Word 导出失败,请稍后重试;Markdown 导出仍可正常使用") from exc
extension, media_type = "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)),
})
+37
View File
@@ -0,0 +1,37 @@
"""静态文件响应:容忍媒体元素发出的异常 Range 头(#416 / #400)。"""
import os
from pathlib import Path
from starlette.datastructures import Headers
from starlette.responses import FileResponse
from starlette.types import Receive, Scope, Send
class RangeSafeFileResponse(FileResponse):
"""不可满足或无法解析的 Range 头退化为整文件 200 响应。
浏览器视频元素偶尔会发出 ``Range: bytes=12345-`` 这类超出文件长度的请求,
Starlette 会回 416,部分浏览器随即报错。这里只在可满足时走正常的 206 分段。
"""
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http" or "range" not in Headers(scope=scope):
await super().__call__(scope, receive, send)
return
if self.stat_result is None:
self.stat_result = os.stat(self.path)
self.set_stat_headers(self.stat_result)
try:
FileResponse._parse_range_header(Headers(scope=scope)["range"], self.stat_result.st_size)
except Exception:
scope = dict(scope)
raw = list(scope["headers"])
scope["headers"] = [(name, value) for name, value in raw if name.lower() not in (b"range", b"if-range")]
await super().__call__(scope, receive, send)
def range_safe_file(path: Path, media_type: str | None = None, filename: str | None = None,
stat_result=None, content_disposition_type: str = "attachment") -> FileResponse:
return RangeSafeFileResponse(path, media_type=media_type, filename=filename, stat_result=stat_result,
content_disposition_type=content_disposition_type)
+45
View File
@@ -47,6 +47,51 @@ def auth(token: str) -> dict:
return {"Authorization": f"Bearer {token}"}
class AuthCookieApiTest(unittest.IsolatedAsyncioTestCase):
@classmethod
def setUpClass(cls):
cls.directory = Path(tempfile.gettempdir()) / f"worklog-test-cookie-{uuid4().hex}"
cls.directory.mkdir()
with patch.dict(os.environ, {
"WORKLOG_DB": str(cls.directory / "test.db"),
"WORKLOG_PORT": "34199",
}):
import server.main as m
cls.m = m
@classmethod
def tearDownClass(cls):
import shutil
if cls.directory.resolve().parent != Path(tempfile.gettempdir()).resolve():
raise RuntimeError("Refusing to remove a test directory outside the temp root")
shutil.rmtree(cls.directory)
def setUp(self):
self.patch_dev = patch.object(self.m, "DEV_MODE", True)
self.patch_dev.start()
self.engine = self.m.create_async_engine("sqlite+aiosqlite:///:memory:", future=True)
self.sessions = self.m.async_sessionmaker(self.engine, expire_on_commit=False)
self.patch_session = patch.object(self.m, "SessionLocal", self.sessions)
self.patch_session.start()
def tearDown(self):
self.patch_session.stop()
self.patch_dev.stop()
async def asyncSetUp(self):
async with self.engine.begin() as conn:
await conn.run_sync(self.m.metadata.create_all)
self.client = AsyncClient(transport=ASGITransport(app=self.m.app), base_url="http://localhost")
async def asyncTearDown(self):
await self.client.aclose()
async def test_bearer_or_cookie_can_authenticate(self):
user = await register(self.client, 'cookietester')
self.assertEqual((await self.client.get('/api/auth/me', headers=auth(user['token']))).status_code, 200)
self.assertEqual((await self.client.get('/api/auth/me', cookies={'worklog_token': user['token']})).status_code, 200)
class ApiTestCase(unittest.IsolatedAsyncioTestCase):
@classmethod
def setUpClass(cls):
+53 -4
View File
@@ -3,9 +3,11 @@ import json
import csv
import zipfile
import tempfile
from datetime import datetime
from pathlib import Path
from unittest.mock import patch
from PIL import Image
from docx import Document
from sqlalchemy import insert
from test_api import ApiTestCase, auth, register
from server.models import center_items, center_loans, center_checks
@@ -88,10 +90,57 @@ class CenterExportTests(ApiTestCase):
self.assertEqual(guest_csv['guest_college'],'艺术学院')
self.assertNotIn('secret@example.test',archive.read('loans.csv').decode('utf-8-sig'))
self.assertNotIn('13900000777',archive.read('loans.csv').decode('utf-8-sig'))
recorded=(await self.client.get('/api/center/data?dataset=loans&loan_status=recorded&q=独立登记',headers=headers)).json()
self.assertEqual(len(recorded['data']['loans']),1)
self.assertEqual(recorded['data']['loans'][0]['item_name'],'=独立登记物品')
self.assertEqual((await self.client.get('/api/center/schema',headers=headers)).json()['schema_version'],4)
async def test_word_export_combines_visible_activities_and_photos(self):
owner=await register(self.client,'wordexport');headers=auth(owner['token'])
image=io.BytesIO();Image.new('RGB',(40,30),'green').save(image,'PNG')
directory=Path(self.m._db_path).parent
uploads=directory/'uploads';uploads.mkdir(parents=True,exist_ok=True)
photo_id='a'*32
(uploads/(photo_id+'.jpg')).write_bytes(image.getvalue())
first_start=int(datetime.fromisoformat('2026-11-20T00:30:00+08:00').timestamp()*1000)
second_start=int(datetime.fromisoformat('2026-11-21T00:30:00+08:00').timestamp()*1000)
stamp=self.m.now_ms()
async with self.m.SessionLocal() as db:
for activity_id,title,start_at in (
('word-one','Word导出活动',first_start),
('word-two','无照片活动',second_start),
):
await db.execute(insert(self.m.activities).values(
id=activity_id,title=title,start_at=start_at,location='',description='不应写入Word',
visibility='public',capacity=0,status='active',organizer_id=owner['user']['id'],
created_at=stamp,updated_at=stamp,
))
await db.execute(insert(self.m.center_activity_meta).values(
activity_id='word-one',photo_ids=json.dumps([photo_id]),material_id=None,
))
await db.execute(insert(self.m.center_activity_meta).values(
activity_id='word-two',photo_ids=json.dumps(['not-a-photo-id']),material_id=None,
))
await db.commit()
response=await self.client.get('/api/center/export?dataset=activities&format=word_activities',headers=headers)
self.assertEqual(response.status_code,200,response.text)
mime='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
self.assertEqual(response.headers['content-type'],mime)
self.assertTrue(response.headers['content-disposition'].endswith('.docx"'))
document=Document(io.BytesIO(response.content))
self.assertEqual([paragraph.text for paragraph in document.paragraphs if paragraph.text], [
'赋能中心一楼活动记录', '1. 无照片活动', '举办日期:2026-11-21', '(暂无照片)',
'2. Word导出活动', '举办日期:2026-11-20',
])
for paragraph in document.paragraphs:
if paragraph.style.name == 'Heading 1' or paragraph.text.startswith('举办日期:'):
self.assertTrue(paragraph.paragraph_format.keep_with_next)
self.assertEqual(len(document.inline_shapes),1)
ascending=await self.client.get('/api/center/export?dataset=activities&format=word_activities&activity_order=asc',headers=headers)
self.assertEqual(ascending.status_code,200,ascending.text)
ordered_document=Document(io.BytesIO(ascending.content))
self.assertEqual([paragraph.text for paragraph in ordered_document.paragraphs if paragraph.text], [
'赋能中心一楼活动记录', '1. Word导出活动', '举办日期:2026-11-20',
'2. 无照片活动', '举办日期:2026-11-21', '(暂无照片)',
])
response=await self.client.get('/api/center/export?dataset=items&format=word_activities',headers=headers)
self.assertEqual(response.status_code,422)
async def test_pagination_and_export_are_not_silently_truncated(self):
user=await register(self.client,'exportpagination');headers=auth(user['token'])
+83 -54
View File
@@ -1,67 +1,96 @@
import tempfile
import shutil
import uuid
from pathlib import Path
from unittest.mock import patch
from sqlalchemy import select
from test_api import ApiTestCase, auth, register
from server.models import center_tutorials
MP4_HEAD = b'\x00\x00\x00\x18ftypmp42\x00\x00\x00\x00mp42isom' + b'\x00' * 64
class CenterTutorialTests(ApiTestCase):
def setUp(self):
super().setUp()
self.files = tempfile.TemporaryDirectory()
self.root = Path(self.files.name)
self.path_patch = patch.object(self.m, '_db_path', self.root / 'test.db')
self.path_patch.start()
base = Path(__file__).resolve().parent.parent / 'outputs' / 'tests'
self.root = base / ('center-tutorials-' + uuid.uuid4().hex)
self.path_patch = patch.object(self.m, '_db_path', self.root / 'test.db'); self.path_patch.start()
def tearDown(self):
self.path_patch.stop()
self.files.cleanup()
super().tearDown()
self.path_patch.stop(); shutil.rmtree(self.root, ignore_errors=True); super().tearDown()
async def upload(self, user, classroom='101', device='投影机', content=b'0123456789', name='guide.mp4'):
return await self.client.post('/api/center/tutorials', headers=auth(user['token']), data={
'classroom': classroom, 'device_name': device,
}, files={'video': (name, content, 'video/mp4')})
async def test_upload_search_stream_and_owner_delete(self):
owner = await register(self.client, 'tutorialowner')
other = await register(self.client, 'tutorialother')
self.assertEqual((await self.client.get('/api/center/tutorials')).status_code, 401)
response = await self.upload(owner)
async def upload(self, user, room='A101', equipment='激光切割机', note='先断电再开盖', body=MP4_HEAD,
content_type='video/mp4'):
response = await self.client.post('/api/center/tutorials', headers={**auth(user['token']),
'content-type': content_type},
params={'room': room, 'equipment': equipment, 'note': note}, content=body)
self.assertEqual(response.status_code, 200, response.text)
self.assertEqual((await self.upload(owner, name='guide.exe')).status_code, 422)
self.assertEqual((await self.upload(owner, classroom=' ', device='')).status_code, 422)
items = (await self.client.get('/api/center/tutorials?q=投影', headers=auth(other['token']))).json()['items']
self.assertEqual(len(items), 1)
tutorial = items[0]
self.assertEqual(tutorial['classroom'], '101')
self.assertEqual(tutorial['device_name'], '投影机')
self.assertTrue(tutorial['can_delete'] is False)
self.assertEqual((await self.client.get('/api/center/tutorials?q=202', headers=auth(other['token']))).json()['items'], [])
self.assertEqual((await self.client.delete('/api/center/tutorials/' + tutorial['id'], headers=auth(other['token']))).status_code, 403)
self.assertEqual((await self.client.get('/api/center/tutorials/' + tutorial['id'] + '/video')).status_code, 401)
playback = await self.client.post('/api/center/tutorials/' + tutorial['id'] + '/playback', headers=auth(other['token']))
self.assertEqual(playback.status_code, 200, playback.text)
url = playback.json()['url']
self.assertNotIn(owner['token'], url)
video = await self.client.get(url, headers={**auth(other['token']), 'Range': 'bytes=2-5'})
self.assertEqual(video.status_code, 206)
self.assertEqual(video.content, b'2345')
self.assertEqual(video.headers['Content-Range'], 'bytes 2-5/10')
self.assertEqual((await self.client.get(url, headers={**auth(other['token']), 'Range': 'bytes=20-25'})).status_code, 416)
async with self.sessions() as db:
row = (await db.execute(select(center_tutorials))).mappings().one()
path = self.root / 'uploads' / 'tutorials' / (row['video_key'] + '.mp4')
self.assertEqual(path.read_bytes(), b'0123456789')
self.assertEqual((await self.client.delete('/api/center/tutorials/' + tutorial['id'], headers=auth(owner['token']))).status_code, 200)
self.assertFalse(path.exists())
self.assertEqual((await self.client.get('/api/center/tutorials/' + tutorial['id'] + '/video', headers=auth(owner['token']))).status_code, 404)
return response.json()['id']
async def test_video_limit_removes_partial_file(self):
user = await register(self.client, 'tutoriallimit')
with patch.object(self.m.center, 'MAX_TUTORIAL_BYTES', 5):
response = await self.upload(user)
self.assertEqual(response.status_code, 413)
self.assertEqual(list((self.root / 'uploads' / 'tutorials').glob('*')), [])
async def test_upload_list_and_range_streaming(self):
user = await register(self.client, 'tutorialowner'); headers = auth(user['token'])
tid = await self.upload(user)
stored = self.root / 'uploads' / (tid + '.mp4')
self.assertEqual(stored.read_bytes(), MP4_HEAD)
listed = await self.client.get('/api/center/tutorials', headers=headers)
self.assertEqual(listed.status_code, 200, listed.text)
item = listed.json()['items'][0]
self.assertEqual((item['room'], item['equipment'], item['note'], item['video_bytes']),
('A101', '激光切割机', '先断电再开盖', len(MP4_HEAD)))
self.assertEqual(item['uploader'], user['user']['display_name'])
full = await self.client.get('/api/center/tutorials/' + tid, headers=headers)
self.assertEqual((full.status_code, full.headers['content-type']), (200, 'video/mp4'))
self.assertEqual(full.content, MP4_HEAD)
part = await self.client.get('/api/center/tutorials/' + tid, headers={**headers, 'range': 'bytes=0-9'})
self.assertEqual((part.status_code, part.content), (206, MP4_HEAD[:10]))
past_end = await self.client.get('/api/center/tutorials/' + tid, headers={**headers, 'range': 'bytes=9999-'})
self.assertEqual(past_end.status_code, 200)
self.assertEqual(past_end.content, MP4_HEAD)
async def test_search_matches_room_equipment_and_note(self):
user = await register(self.client, 'tutorialsearch'); headers = auth(user['token'])
await self.upload(user, room='B202', equipment='投影仪', note='遥控器在讲台')
await self.upload(user, room='A101', equipment='激光切割机', note='')
self.assertEqual([i['room'] for i in (await self.client.get('/api/center/tutorials?q=B202', headers=headers)).json()['items']], ['B202'])
self.assertEqual([i['equipment'] for i in (await self.client.get('/api/center/tutorials?q=激光', headers=headers)).json()['items']], ['激光切割机'])
self.assertEqual([i['room'] for i in (await self.client.get('/api/center/tutorials?q=遥控器', headers=headers)).json()['items']], ['B202'])
self.assertEqual((await self.client.get('/api/center/tutorials?q=不存在', headers=headers)).json(), {'items': [], 'has_more': False})
async def test_only_uploader_can_download_original(self):
owner = await register(self.client, 'tutdlowner'); other = await register(self.client, 'tutdlother')
tid = await self.upload(owner)
self.assertEqual((await self.client.get('/api/center/tutorials/' + tid + '?preview=1', headers=auth(owner['token']))).status_code, 200)
self.assertEqual((await self.client.get('/api/center/tutorials/' + tid + '?preview=1', headers=auth(other['token']))).status_code, 403)
self.assertEqual((await self.client.get('/api/center/tutorials/' + tid, headers=auth(other['token']))).status_code, 200)
async def test_rejects_invalid_uploads_and_cleans_staging(self):
user = await register(self.client, 'tutorialinvalid'); headers = auth(user['token'])
base = {'content-type': 'video/mp4'}
cases = [
({'equipment': '投影仪'}, MP4_HEAD, 422),
({'room': 'A101'}, MP4_HEAD, 422),
({'room': 'A101', 'equipment': '投影仪'}, b'\x00\x01\x02GIF89a' + b'\x00' * 40, 422),
({'room': 'A101', 'equipment': '投影仪'}, b'', 422),
({'room': 'A' * 41, 'equipment': '投影仪'}, MP4_HEAD, 422),
]
for params, body, status in cases:
response = await self.client.post('/api/center/tutorials', headers={**headers, **base}, params=params, content=body)
self.assertEqual(response.status_code, status, (params, response.text))
gif = await self.client.post('/api/center/tutorials', headers={**headers, 'content-type': 'image/gif'},
params={'room': 'A101', 'equipment': '投影仪'}, content=MP4_HEAD)
self.assertEqual(gif.status_code, 422)
uploads = self.root / 'uploads'
leftovers = [p.name for p in uploads.iterdir()] if uploads.is_dir() else []
self.assertEqual(leftovers, [])
self.assertEqual((await self.client.get('/api/center/tutorials', headers=headers)).json()['items'], [])
async def test_requires_login(self):
self.assertEqual((await self.client.get('/api/center/tutorials')).status_code, 401)
self.assertEqual((await self.client.post('/api/center/tutorials', params={'room': 'A', 'equipment': 'B'},
headers={'content-type': 'video/mp4'}, content=MP4_HEAD)).status_code, 401)
async def test_lists_newest_first_with_paging(self):
user = await register(self.client, 'tutorialpage'); headers = auth(user['token'])
ids = [await self.upload(user, room=f'C{i:02d}', equipment='器材') for i in range(5)]
first = (await self.client.get('/api/center/tutorials?limit=2', headers=headers)).json()
self.assertEqual([i['id'] for i in first['items']], ids[::-1][:2]); self.assertTrue(first['has_more'])
rest = (await self.client.get('/api/center/tutorials?limit=2&offset=2', headers=headers)).json()
self.assertEqual([i['id'] for i in rest['items']], ids[::-1][2:4]); self.assertTrue(rest['has_more'])
+95
View File
@@ -0,0 +1,95 @@
from __future__ import annotations
import unittest
from unittest.mock import patch
from unittest.mock import AsyncMock
import base64
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><img src="https://example.com/a.png"><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": "",
}
PNG = base64.b64decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=")
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})
detail = await self.client.get('/api/recruit/announcements/1', headers=auth(owner['token']))
self.assertEqual(detail.json()['content_html'], '<p>第一段</p><img src="https://example.com/a.png"><div>第二段</div>')
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'], '测试公告')
with patch.object(recruit, 'fetch_image', new=AsyncMock(return_value=PNG)):
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))
self.assertEqual(len(document.inline_shapes), 1)
response = await self.client.get('/api/recruit/export', params={'ids': '1', 'format': 'markdown'}, headers=auth(owner['token']))
self.assertIn('第一段', response.text)
self.assertIn('![公告图片](https://example.com/a.png)', response.text)
self.assertIn('原文链接', response.text)
response = await self.client.get('/api/recruit/export', headers=auth(owner['token']))
self.assertEqual(response.status_code, 422)
async def test_sync_fetches_detail_for_empty_content(self):
owner = await register(self.client, 'recruit-detail')
raw = dict(RAW, gonggaoId=2, gonggaoContent='<p><br></p>')
fetch = AsyncMock(return_value={"code": 0, "rows": [raw], "extra": {"pages": 1}})
fetch_detail = AsyncMock(return_value='''
<div class="txt"><p><br></p></div>
<div class="selected-positions">
<span>职位列表</span>
<table><tr><td>外贸业务员</td></tr></table>
</div>
''')
with patch.object(recruit, 'fetch_page', new=fetch), patch.object(recruit, 'fetch_detail_html', new=fetch_detail):
data = (await self.client.post('/api/recruit/sync', headers=auth(owner['token']))).json()
self.assertEqual(data, {'fetched': 1, 'added': 1, 'updated': 0})
fetch_detail.assert_awaited_once()
detail = (await self.client.get('/api/recruit/announcements/2', headers=auth(owner['token']))).json()
self.assertIn('外贸业务员', detail['content_html'])
async def test_list_and_export_follow_source_order(self):
owner = await register(self.client, 'recruit-order')
rows = [
dict(RAW, gonggaoId=21, checkTime='2020-01-01 00:00:00'),
dict(RAW, gonggaoId=22, checkTime='2020-01-02 00:00:00'),
dict(RAW, gonggaoId=23, checkTime='2020-01-03 00:00:00'),
]
fetch = AsyncMock(return_value={"code": 0, "rows": rows, "extra": {"pages": 1}})
with patch.object(recruit, 'fetch_page', new=fetch):
await self.client.post('/api/recruit/sync', headers=auth(owner['token']))
data = (await self.client.get('/api/recruit/announcements', headers=auth(owner['token']))).json()
self.assertEqual([item['gonggao_id'] for item in data['items']], [21, 22, 23])
response = await self.client.get('/api/recruit/export', params={'ids': '23,21,22', 'format': 'markdown'}, headers=auth(owner['token']))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.headers['X-Recruit-Export-Count'], '3')
self.assertLess(response.text.find('测试公告'), response.text.find('原文链接'))