增加课表管理员密钥导出
This commit is contained in:
@@ -18,3 +18,6 @@ WORKLOG_DEV_MODE=false
|
|||||||
|
|
||||||
# 课表收取负责人(注册邮箱,多个用逗号分隔;留空时仅本人可查看自己的课表)
|
# 课表收取负责人(注册邮箱,多个用逗号分隔;留空时仅本人可查看自己的课表)
|
||||||
# WORKLOG_TIMETABLE_COLLECTORS=collector@example.com
|
# WORKLOG_TIMETABLE_COLLECTORS=collector@example.com
|
||||||
|
|
||||||
|
# 课表全量导出管理员密钥(覆盖 config.toml 中的默认值)
|
||||||
|
# WORKLOG_TIMETABLE_ADMIN_KEY=replace-with-a-long-random-key
|
||||||
|
|||||||
+4
-4
@@ -31,13 +31,13 @@
|
|||||||
|
|
||||||
## 权限和负责人
|
## 权限和负责人
|
||||||
|
|
||||||
所有登录成员可查看成员姓名、部门及单周/双周提交和核对状态。图片、课程内容和识别文字仅本人及指定的收取负责人可查看。本人只能修改自己的课表,负责人可查看和导出全部课表,但不能修改别人的课表。
|
所有登录成员可查看成员姓名、部门及单周/双周提交和核对状态。图片、课程内容和识别文字仅本人及指定的收取负责人可查看。本人只能修改自己的课表,负责人可查看全部课表,但不能修改别人的课表。全量导出还必须在页面输入管理员密钥。
|
||||||
|
|
||||||
在 `config.toml` 配置 `[timetable] collector_emails = ["负责人注册邮箱"]`,或设置 `WORKLOG_TIMETABLE_COLLECTORS`(多个邮箱逗号分隔,忽略大小写),修改后重启服务。当前负责人为空,成员仍可提交和修改自己的课表,配置负责人后即可统一收取。邮箱、手机号及授权令牌不放进收取列表或导出数据。
|
在 `config.toml` 配置 `[timetable] collector_emails = ["负责人注册邮箱"]`,或设置 `WORKLOG_TIMETABLE_COLLECTORS`(多个邮箱逗号分隔,忽略大小写),修改后重启服务。全量导出密钥配置为 `[timetable] admin_export_key`,生产环境可用 `WORKLOG_TIMETABLE_ADMIN_KEY` 覆盖。当前负责人为空,成员仍可提交和修改自己的课表,配置负责人后即可统一查看。邮箱、手机号、管理员密钥及授权令牌不放进收取列表或导出数据。
|
||||||
|
|
||||||
## 程序读取与导出
|
## 程序读取与导出
|
||||||
|
|
||||||
所有接口均需要 `Authorization: Bearer <登录会话令牌>`。
|
所有接口均需要 `Authorization: Bearer <登录会话令牌>`;导出接口还必须提供 `X-Timetable-Admin-Key: <管理员密钥>`。
|
||||||
|
|
||||||
| 接口 | 用途 |
|
| 接口 | 用途 |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
@@ -50,7 +50,7 @@
|
|||||||
| `GET /api/timetables/export?format=json` | 完整结构,适合程序和AI读取 |
|
| `GET /api/timetables/export?format=json` | 完整结构,适合程序和AI读取 |
|
||||||
| `GET /api/timetables/export?format=csv` | 每个课表20行,便于表格整理 |
|
| `GET /api/timetables/export?format=csv` | 每个课表20行,便于表格整理 |
|
||||||
|
|
||||||
默认 `confirmed_only=true`,只导出已核对课表;传 `false` 可包含草稿。成员导出自己,收取负责人导出所有成员。JSON 中 `structure.cells` 每项包含 `day=1..5`、`slot`、`status=busy/free/unknown`、`courses`、`confidence`、`source` 和 `eligible`。时段时间见顶层 `slots`,记录的 `week_type` 为 `odd` / `even`。时间戳为 Unix 毫秒。
|
默认 `confirmed_only=true`,只导出已核对课表;传 `false` 可包含草稿。管理员密钥正确时导出全部成员,密钥错误或缺失时拒绝下载。JSON 中 `structure.cells` 每项包含 `day=1..5`、`slot`、`status=busy/free/unknown`、`courses`、`confidence`、`source` 和 `eligible`。时段时间见顶层 `slots`,记录的 `week_type` 为 `odd` / `even`。时间戳为 Unix 毫秒。
|
||||||
|
|
||||||
**排班时必须使用 `eligible=true` 的时段**,即课表已确认且该时段明确为空闲;没有上传、未核对、未知时段都不能视为有空。JSON 包含核对时间及整理结果,不以原图下载链接的可访问性判断空闲。CSV 为 UTF-8 BOM,保护可能被电子表格当作公式的文本内容。
|
**排班时必须使用 `eligible=true` 的时段**,即课表已确认且该时段明确为空闲;没有上传、未核对、未知时段都不能视为有空。JSON 包含核对时间及整理结果,不以原图下载链接的可访问性判断空闲。CSV 为 UTF-8 BOM,保护可能被电子表格当作公式的文本内容。
|
||||||
|
|
||||||
|
|||||||
@@ -49,3 +49,5 @@ approver_emails = []
|
|||||||
[timetable]
|
[timetable]
|
||||||
# 课表收取负责人:填写注册邮箱;可查阅和导出全部课表,不能修改他人课表。
|
# 课表收取负责人:填写注册邮箱;可查阅和导出全部课表,不能修改他人课表。
|
||||||
collector_emails = []
|
collector_emails = []
|
||||||
|
# 全量课表导出密钥。生产环境请用 WORKLOG_TIMETABLE_ADMIN_KEY 注入,避免提交明文密钥。
|
||||||
|
admin_export_key = ""
|
||||||
|
|||||||
Vendored
+2
@@ -649,6 +649,8 @@ button:focus-visible, a:focus-visible, [tabindex]:focus-visible { outline: 3px s
|
|||||||
.timetable-grid textarea { margin-top:6px; font-size:12px; min-width:0; }
|
.timetable-grid textarea { margin-top:6px; font-size:12px; min-width:0; }
|
||||||
.timetable-editor .form-actions { flex-wrap:wrap; }
|
.timetable-editor .form-actions { flex-wrap:wrap; }
|
||||||
#timetables-view .center-export .checkline { flex-direction:row; align-items:center; align-self:center; margin:0; }
|
#timetables-view .center-export .checkline { flex-direction:row; align-items:center; align-self:center; margin:0; }
|
||||||
|
#timetables-view .timetable-admin-key-field { flex:1 1 230px; min-width:190px; }
|
||||||
|
#timetables-view #timetable-admin-key { width:100%; }
|
||||||
#timetable-confirmed-only { min-width:18px; min-height:18px; width:18px; height:18px; flex:0 0 18px; padding:0; }
|
#timetable-confirmed-only { min-width:18px; min-height:18px; width:18px; height:18px; flex:0 0 18px; padding:0; }
|
||||||
.timetable-warnings { padding:12px 14px; background:#fff7e7; border-radius:8px; font-size:13px; }
|
.timetable-warnings { padding:12px 14px; background:#fff7e7; border-radius:8px; font-size:13px; }
|
||||||
.timetable-text { white-space:pre-wrap; overflow-wrap:anywhere; max-height:220px; overflow:auto; }
|
.timetable-text { white-space:pre-wrap; overflow-wrap:anywhere; max-height:220px; overflow:auto; }
|
||||||
|
|||||||
Vendored
+3
-3
@@ -5,7 +5,7 @@
|
|||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<title>WorkLog · 活动记录</title>
|
<title>WorkLog · 活动记录</title>
|
||||||
<meta name="theme-color" content="#f5f7f5" />
|
<meta name="theme-color" content="#f5f7f5" />
|
||||||
<link rel="stylesheet" href="/assets/styles.css?v=23" />
|
<link rel="stylesheet" href="/assets/styles.css?v=24" />
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="app">
|
<div id="app">
|
||||||
@@ -185,7 +185,7 @@
|
|||||||
<div class="page-head center-subhead"><div><h3>收取进度</h3><p class="muted" id="timetable-summary" role="status"></p></div></div>
|
<div class="page-head center-subhead"><div><h3>收取进度</h3><p class="muted" id="timetable-summary" role="status"></p></div></div>
|
||||||
<div class="filters center-toolbar"><input id="timetable-q" type="search" aria-label="搜索课表成员" placeholder="搜索姓名 / 部门" /><select id="timetable-filter" aria-label="课表提交状态"><option value="all">全部成员</option><option value="complete">单双周已交齐</option><option value="incomplete">尚未交齐</option><option value="missing">均未提交</option></select><button id="timetable-refresh" class="btn">刷新</button></div>
|
<div class="filters center-toolbar"><input id="timetable-q" type="search" aria-label="搜索课表成员" placeholder="搜索姓名 / 部门" /><select id="timetable-filter" aria-label="课表提交状态"><option value="all">全部成员</option><option value="complete">单双周已交齐</option><option value="incomplete">尚未交齐</option><option value="missing">均未提交</option></select><button id="timetable-refresh" class="btn">刷新</button></div>
|
||||||
<div id="timetable-members" class="card-list"></div>
|
<div id="timetable-members" class="card-list"></div>
|
||||||
<details class="center-export center-subhead"><summary>导出排班数据</summary><p class="muted" id="timetable-export-note"></p><div class="filters"><label>格式<select id="timetable-export-format"><option value="json">JSON</option><option value="csv">CSV</option></select></label><label class="checkline"><input id="timetable-confirmed-only" type="checkbox" checked /> 仅导出已核对课表</label><button id="timetable-export" class="btn primary">下载数据</button></div><p class="muted" id="timetable-export-status" role="status"></p></details>
|
<details class="center-export center-subhead"><summary>导出排班数据</summary><p class="muted" id="timetable-export-note"></p><div class="filters"><label>格式<select id="timetable-export-format"><option value="json">JSON</option><option value="csv">CSV</option></select></label><label class="checkline"><input id="timetable-confirmed-only" type="checkbox" checked /> 仅导出已核对课表</label><label class="timetable-admin-key-field">管理员密钥<input id="timetable-admin-key" type="password" autocomplete="off" autocapitalize="none" spellcheck="false" placeholder="输入后导出全部课表" required /></label><button id="timetable-export" class="btn primary">下载数据</button></div><p class="muted" id="timetable-export-status" role="status"></p></details>
|
||||||
</div>
|
</div>
|
||||||
</main>
|
</main>
|
||||||
<main id="mine-view" class="view hidden">
|
<main id="mine-view" class="view hidden">
|
||||||
@@ -322,7 +322,7 @@
|
|||||||
|
|
||||||
<div id="toast" class="toast hidden" role="status" aria-live="polite"></div>
|
<div id="toast" class="toast hidden" role="status" aria-live="polite"></div>
|
||||||
|
|
||||||
<script src="/js/app.js?v=34"></script>
|
<script src="/js/app.js?v=35"></script>
|
||||||
</div>
|
</div>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
Vendored
+21
-5
@@ -1215,7 +1215,7 @@
|
|||||||
const label = `${weekLabel(week)}:${item.submitted ? item.confirmed ? '已核对' : '已交待核对' : '未交'}`;
|
const label = `${weekLabel(week)}:${item.submitted ? item.confirmed ? '已核对' : '已交待核对' : '未交'}`;
|
||||||
return item.submitted && person.can_read ? `<button class="btn sm" data-timetable-view="${week}" data-user-id="${person.id}">${label}</button>` : `<span class="tag ${item.submitted ? 'attended' : ''}">${label}</span>`;
|
return item.submitted && person.can_read ? `<button class="btn sm" data-timetable-view="${week}" data-user-id="${person.id}">${label}</button>` : `<span class="tag ${item.submitted ? 'attended' : ''}">${label}</span>`;
|
||||||
}).join('')}</div></article>`).join('') || '<div class="empty">没有符合筛选条件的成员。</div>';
|
}).join('')}</div></article>`).join('') || '<div class="empty">没有符合筛选条件的成员。</div>';
|
||||||
$('#timetable-export-note').textContent = (data.can_collect ? '你可以导出所有成员的课表。' : '你可以导出自己的课表;收取负责人可统一导出全部。') + '只有已核对课表中的空闲时段可列为可值班,待确认不能当作空闲。';
|
$('#timetable-export-note').textContent = '输入管理员密钥后可导出全部课表。只有已核对课表中的空闲时段可列为可值班,待确认不能当作空闲。';
|
||||||
} catch (error) { if (version === timetableRequest) toast(error.message, true); }
|
} catch (error) { if (version === timetableRequest) toast(error.message, true); }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1364,14 +1364,30 @@
|
|||||||
$('#timetable-export').addEventListener('click', async () => {
|
$('#timetable-export').addEventListener('click', async () => {
|
||||||
const button = $('#timetable-export'); button.disabled = true;
|
const button = $('#timetable-export'); button.disabled = true;
|
||||||
const format = $('#timetable-export-format').value;
|
const format = $('#timetable-export-format').value;
|
||||||
try { await downloadCenterFile('/api/timetables/export?format=' + format + '&confirmed_only=' + $('#timetable-confirmed-only').checked, 'timetables.' + format); $('#timetable-export-status').textContent = '数据已下载。'; }
|
const keyInput = $('#timetable-admin-key');
|
||||||
catch (error) { $('#timetable-export-status').textContent = error.message; }
|
const key = keyInput.value;
|
||||||
|
$('#timetable-export-status').textContent = '';
|
||||||
|
if (!key) {
|
||||||
|
$('#timetable-export-status').textContent = '请输入管理员密钥';
|
||||||
|
keyInput.focus();
|
||||||
|
button.disabled = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await downloadCenterFile('/api/timetables/export?format=' + format + '&confirmed_only=' + $('#timetable-confirmed-only').checked, 'timetables.' + format, { 'X-Timetable-Admin-Key': key });
|
||||||
|
$('#timetable-export-status').textContent = '全部课表已下载。';
|
||||||
|
keyInput.value = '';
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
$('#timetable-export-status').textContent = error.message;
|
||||||
|
if (/密钥/.test(error.message)) { keyInput.value = ''; keyInput.focus(); }
|
||||||
|
}
|
||||||
finally { button.disabled = false; }
|
finally { button.disabled = false; }
|
||||||
});
|
});
|
||||||
|
|
||||||
let centerTab = 'records';
|
let centerTab = 'records';
|
||||||
async function downloadCenterFile(path, fallback) {
|
async function downloadCenterFile(path, fallback, extraHeaders = {}) {
|
||||||
const response = await fetch(path, { headers: { Authorization: `Bearer ${getToken()}` } });
|
const response = await fetch(path, { headers: { ...extraHeaders, Authorization: `Bearer ${getToken()}` } });
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
const error = await response.json().catch(() => ({}));
|
const error = await response.json().catch(() => ({}));
|
||||||
throw new Error(typeof error.detail === 'string' ? error.detail : '下载失败,请检查筛选条件或重新登录');
|
throw new Error(typeof error.detail === 'string' ? error.detail : '下载失败,请检查筛选条件或重新登录');
|
||||||
|
|||||||
+4
-1
@@ -698,7 +698,10 @@ def timetable_collectors():
|
|||||||
emails = values.split(',') if values is not None else cfg('timetable', 'collector_emails', [])
|
emails = values.split(',') if values is not None else cfg('timetable', 'collector_emails', [])
|
||||||
return {email.strip().lower() for email in emails if email.strip()}
|
return {email.strip().lower() for email in emails if email.strip()}
|
||||||
|
|
||||||
timetable_routes.install(app, get_db, current_user, lambda: _db_path.parent / 'timetables', timetable_collectors)
|
def timetable_admin_key():
|
||||||
|
return os.getenv('WORKLOG_TIMETABLE_ADMIN_KEY', str(cfg('timetable', 'admin_export_key', '')))
|
||||||
|
|
||||||
|
timetable_routes.install(app, get_db, current_user, lambda: _db_path.parent / 'timetables', timetable_collectors, timetable_admin_key)
|
||||||
|
|
||||||
|
|
||||||
@app.exception_handler(IntegrityError)
|
@app.exception_handler(IntegrityError)
|
||||||
|
|||||||
+16
-6
@@ -3,6 +3,7 @@ import asyncio
|
|||||||
import csv
|
import csv
|
||||||
import io
|
import io
|
||||||
import json
|
import json
|
||||||
|
import secrets
|
||||||
import time
|
import time
|
||||||
import uuid
|
import uuid
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@@ -48,7 +49,7 @@ def public_file(row):
|
|||||||
'created_at': row['created_at'], 'updated_at': row['updated_at'], 'confirmed_at': row['confirmed_at']}
|
'created_at': row['created_at'], 'updated_at': row['updated_at'], 'confirmed_at': row['confirmed_at']}
|
||||||
|
|
||||||
|
|
||||||
def install(app, get_db, current_user, file_root, collector_emails):
|
def install(app, get_db, current_user, file_root, collector_emails, admin_key):
|
||||||
def can_collect(viewer):
|
def can_collect(viewer):
|
||||||
return viewer['email'].strip().lower() in collector_emails()
|
return viewer['email'].strip().lower() in collector_emails()
|
||||||
|
|
||||||
@@ -152,16 +153,22 @@ def install(app, get_db, current_user, file_root, collector_emails):
|
|||||||
async def schema(viewer=Depends(current_user)):
|
async def schema(viewer=Depends(current_user)):
|
||||||
return {'schema_version': 1, 'week_types': {'odd': '单周', 'even': '双周'}, 'days': ocr.DAYS, 'slots': ocr.SLOTS,
|
return {'schema_version': 1, 'week_types': {'odd': '单周', 'even': '双周'}, 'days': ocr.DAYS, 'slots': ocr.SLOTS,
|
||||||
'states': {'busy': '有课', 'free': '无课', 'unknown': '待确认'},
|
'states': {'busy': '有课', 'free': '无课', 'unknown': '待确认'},
|
||||||
'export': '/api/timetables/export?format=json&confirmed_only=true',
|
'export': {'url': '/api/timetables/export?format=json&confirmed_only=true', 'header': 'X-Timetable-Admin-Key',
|
||||||
'privacy': '本人可导出自己的课表;收取负责人可导出全部;不包含邮箱和手机号',
|
'scope': '管理员密钥验证通过后导出全部课表'},
|
||||||
|
'privacy': '登录且管理员密钥正确时可导出全部课表;不包含邮箱、手机号和管理员密钥',
|
||||||
'eligibility': '仅已确认课表中的free时段可列为可值班;unknown不能当作空闲',
|
'eligibility': '仅已确认课表中的free时段可列为可值班;unknown不能当作空闲',
|
||||||
'scope': '按当前值班时间整理周一至周五的四个时段;完整识别文字另存raw_text,夜间和周末未参与可值班判断'}
|
'scope': '按当前值班时间整理周一至周五的四个时段;完整识别文字另存raw_text,夜间和周末未参与可值班判断'}
|
||||||
|
|
||||||
@app.get('/api/timetables/export')
|
@app.get('/api/timetables/export')
|
||||||
async def export(format: Literal['json', 'csv'] = 'json', confirmed_only: bool = True,
|
async def export(request: Request, format: Literal['json', 'csv'] = 'json', confirmed_only: bool = True,
|
||||||
db=Depends(get_db), viewer=Depends(current_user)):
|
db=Depends(get_db), viewer=Depends(current_user)):
|
||||||
|
expected = admin_key()
|
||||||
|
supplied = request.headers.get('X-Timetable-Admin-Key', '')
|
||||||
|
if not expected:
|
||||||
|
raise HTTPException(503, '课表导出管理员密钥尚未配置')
|
||||||
|
if not supplied or not secrets.compare_digest(supplied.encode('utf-8'), expected.encode('utf-8')):
|
||||||
|
raise HTTPException(401, '管理员密钥错误')
|
||||||
query = select(timetables, users.c.display_name, users.c.department).join(users).order_by(users.c.display_name, timetables.c.user_id, timetables.c.week_type)
|
query = select(timetables, users.c.display_name, users.c.department).join(users).order_by(users.c.display_name, timetables.c.user_id, timetables.c.week_type)
|
||||||
if not can_collect(viewer): query = query.where(timetables.c.user_id == viewer['id'])
|
|
||||||
if confirmed_only: query = query.where(timetables.c.confirmed_at.is_not(None))
|
if confirmed_only: query = query.where(timetables.c.confirmed_at.is_not(None))
|
||||||
found = (await db.execute(query)).mappings().all()
|
found = (await db.execute(query)).mappings().all()
|
||||||
records = [{**public_file(row), 'user_id': row['user_id'], 'display_name': row['display_name'], 'department': row['department']} for row in found]
|
records = [{**public_file(row), 'user_id': row['user_id'], 'display_name': row['display_name'], 'department': row['department']} for row in found]
|
||||||
@@ -182,7 +189,10 @@ def install(app, get_db, current_user, file_root, collector_emails):
|
|||||||
eligible=bool(record['confirmed_at']) and cell['status'] == 'free')
|
eligible=bool(record['confirmed_at']) and cell['status'] == 'free')
|
||||||
writer.writerow({key: "'"+value if isinstance(value, str) and value.lstrip().startswith(('=','+','-','@')) else value for key,value in row.items()})
|
writer.writerow({key: "'"+value if isinstance(value, str) and value.lstrip().startswith(('=','+','-','@')) else value for key,value in row.items()})
|
||||||
body = buffer.getvalue().encode('utf-8-sig'); mime = 'text/csv; charset=utf-8'
|
body = buffer.getvalue().encode('utf-8-sig'); mime = 'text/csv; charset=utf-8'
|
||||||
return Response(body, media_type=mime, headers={'Content-Disposition': f'attachment; filename="timetables.{format}"'})
|
return Response(body, media_type=mime, headers={
|
||||||
|
'Content-Disposition': f'attachment; filename="timetables.{format}"',
|
||||||
|
'Cache-Control': 'no-store',
|
||||||
|
})
|
||||||
|
|
||||||
@app.get('/api/timetables/{user_id}/{week}')
|
@app.get('/api/timetables/{user_id}/{week}')
|
||||||
async def detail(user_id: str, week: Week, db=Depends(get_db), viewer=Depends(current_user)):
|
async def detail(user_id: str, week: Week, db=Depends(get_db), viewer=Depends(current_user)):
|
||||||
|
|||||||
@@ -15,6 +15,8 @@ from server import timetable_ocr as ocr
|
|||||||
from server.models import timetables
|
from server.models import timetables
|
||||||
from test_api import ApiTestCase, auth, register
|
from test_api import ApiTestCase, auth, register
|
||||||
|
|
||||||
|
ADMIN_KEY = 'timetable-test-admin'
|
||||||
|
|
||||||
|
|
||||||
def image_bytes(color='blue'):
|
def image_bytes(color='blue'):
|
||||||
stream = io.BytesIO(); Image.new('RGB', (30, 30), color).save(stream, 'PNG')
|
stream = io.BytesIO(); Image.new('RGB', (30, 30), color).save(stream, 'PNG')
|
||||||
@@ -61,9 +63,10 @@ class TimetableTests(ApiTestCase):
|
|||||||
self.db_path_patch = patch.object(self.m, '_db_path', self.root/'test.db'); self.db_path_patch.start()
|
self.db_path_patch = patch.object(self.m, '_db_path', self.root/'test.db'); self.db_path_patch.start()
|
||||||
self.ocr_patch = patch('server.timetable_ocr.recognize', side_effect=lambda raw: recognized()); self.ocr_patch.start()
|
self.ocr_patch = patch('server.timetable_ocr.recognize', side_effect=lambda raw: recognized()); self.ocr_patch.start()
|
||||||
self.collector_patch = patch.dict(os.environ, WORKLOG_TIMETABLE_COLLECTORS=''); self.collector_patch.start()
|
self.collector_patch = patch.dict(os.environ, WORKLOG_TIMETABLE_COLLECTORS=''); self.collector_patch.start()
|
||||||
|
self.admin_patch = patch.dict(os.environ, WORKLOG_TIMETABLE_ADMIN_KEY=ADMIN_KEY); self.admin_patch.start()
|
||||||
|
|
||||||
def tearDown(self):
|
def tearDown(self):
|
||||||
self.collector_patch.stop(); self.ocr_patch.stop(); self.db_path_patch.stop(); self.files.cleanup()
|
self.admin_patch.stop(); self.collector_patch.stop(); self.ocr_patch.stop(); self.db_path_patch.stop(); self.files.cleanup()
|
||||||
super().tearDown()
|
super().tearDown()
|
||||||
|
|
||||||
async def upload(self, user, week='odd', color='blue'):
|
async def upload(self, user, week='odd', color='blue'):
|
||||||
@@ -77,6 +80,9 @@ class TimetableTests(ApiTestCase):
|
|||||||
if cell['status']=='unknown': cell['status']='free'
|
if cell['status']=='unknown': cell['status']='free'
|
||||||
return await self.client.patch('/api/timetables/me/'+timetable['week_type'],headers=auth(user['token']),json={'revision':timetable['revision'],'cells':cells,'confirm':confirm})
|
return await self.client.patch('/api/timetables/me/'+timetable['week_type'],headers=auth(user['token']),json={'revision':timetable['revision'],'cells':cells,'confirm':confirm})
|
||||||
|
|
||||||
|
def export_headers(self, user, key=ADMIN_KEY):
|
||||||
|
return {**auth(user['token']), 'X-Timetable-Admin-Key': key}
|
||||||
|
|
||||||
async def test_authenticated_image_only_validation(self):
|
async def test_authenticated_image_only_validation(self):
|
||||||
for path in ['/api/timetables','/api/timetables/schema','/api/timetables/export']:
|
for path in ['/api/timetables','/api/timetables/schema','/api/timetables/export']:
|
||||||
self.assertEqual((await self.client.get(path)).status_code,401)
|
self.assertEqual((await self.client.get(path)).status_code,401)
|
||||||
@@ -129,21 +135,22 @@ class TimetableTests(ApiTestCase):
|
|||||||
owner = await register(self.client,'timetableexport'); other = await register(self.client,'timetableexportother')
|
owner = await register(self.client,'timetableexport'); other = await register(self.client,'timetableexportother')
|
||||||
item = await self.upload(owner); await self.upload(owner,'even'); await self.upload(other)
|
item = await self.upload(owner); await self.upload(owner,'even'); await self.upload(other)
|
||||||
path = '/api/timetables/me/odd'; headers = auth(owner['token'])
|
path = '/api/timetables/me/odd'; headers = auth(owner['token'])
|
||||||
|
self.assertEqual((await self.client.get('/api/timetables/export',headers=headers)).status_code,401)
|
||||||
|
self.assertEqual((await self.client.get('/api/timetables/export',headers=self.export_headers(owner,'wrong-key'))).status_code,401)
|
||||||
result = await self.client.patch(path,headers=headers,json={'revision':item['revision'],'cells':item['structure']['cells'],'confirm':True})
|
result = await self.client.patch(path,headers=headers,json={'revision':item['revision'],'cells':item['structure']['cells'],'confirm':True})
|
||||||
self.assertEqual(result.status_code,422)
|
self.assertEqual(result.status_code,422)
|
||||||
duplicate = [item['structure']['cells'][0]]*20
|
duplicate = [item['structure']['cells'][0]]*20
|
||||||
self.assertEqual((await self.client.patch(path,headers=headers,json={'revision':item['revision'],'cells':duplicate})).status_code,422)
|
self.assertEqual((await self.client.patch(path,headers=headers,json={'revision':item['revision'],'cells':duplicate})).status_code,422)
|
||||||
self.assertEqual((await self.client.get('/api/timetables/export',headers=headers)).json()['records'],[])
|
self.assertEqual((await self.client.get('/api/timetables/export',headers=self.export_headers(owner))).json()['records'],[])
|
||||||
result = await self.confirm(owner,item); self.assertEqual(result.status_code,200,result.text)
|
result = await self.confirm(owner,item); self.assertEqual(result.status_code,200,result.text)
|
||||||
data = await self.client.get('/api/timetables/export',headers=headers)
|
data = await self.client.get('/api/timetables/export',headers=self.export_headers(owner))
|
||||||
self.assertEqual(len(data.json()['records']),1); self.assertNotIn(owner['user']['email'],data.text)
|
self.assertEqual(len(data.json()['records']),1); self.assertNotIn(owner['user']['email'],data.text)
|
||||||
csv_response = await self.client.get('/api/timetables/export?format=csv',headers=headers)
|
self.assertEqual(data.headers['cache-control'],'no-store')
|
||||||
|
csv_response = await self.client.get('/api/timetables/export?format=csv',headers=self.export_headers(owner))
|
||||||
rows = list(csv.DictReader(io.StringIO(csv_response.content.decode('utf-8-sig'))))
|
rows = list(csv.DictReader(io.StringIO(csv_response.content.decode('utf-8-sig'))))
|
||||||
self.assertEqual(len(rows),20); self.assertEqual(sum(row['eligible']=='True' for row in rows),19)
|
self.assertEqual(len(rows),20); self.assertEqual(sum(row['eligible']=='True' for row in rows),19)
|
||||||
all_own = (await self.client.get('/api/timetables/export?confirmed_only=false',headers=headers)).json()['records']
|
all_records = (await self.client.get('/api/timetables/export?confirmed_only=false',headers=self.export_headers(owner))).json()['records']
|
||||||
self.assertEqual(len(all_own),2)
|
self.assertEqual(len(all_records),3)
|
||||||
with patch.dict(os.environ,WORKLOG_TIMETABLE_COLLECTORS=owner['user']['email']):
|
|
||||||
self.assertEqual(len((await self.client.get('/api/timetables/export?confirmed_only=false',headers=headers)).json()['records']),3)
|
|
||||||
|
|
||||||
async def test_recognition_failure_preserves_image_for_manual_correction(self):
|
async def test_recognition_failure_preserves_image_for_manual_correction(self):
|
||||||
user = await register(self.client,'timetablefallback')
|
user = await register(self.client,'timetablefallback')
|
||||||
|
|||||||
Reference in New Issue
Block a user