停止记录和补记值班缺勤,移除缺勤入口并保留历史数据

This commit is contained in:
2026-11-08 11:41:29 +08:00
parent 6377a42a8f
commit 0663b44cdc
10 changed files with 50 additions and 115 deletions
-2
View File
@@ -576,8 +576,6 @@ button:focus-visible, a:focus-visible, [tabindex]:focus-visible { outline: 3px s
#change-email-panel summary:focus-visible { outline: 3px solid #28664f80; outline-offset: 4px; } #change-email-panel summary:focus-visible { outline: 3px solid #28664f80; outline-offset: 4px; }
#change-email-form .form-hint { margin: 8px 0 0; overflow-wrap: anywhere; } #change-email-form .form-hint { margin: 8px 0 0; overflow-wrap: anywhere; }
#change-email-result:empty { display: none; } #change-email-result:empty { display: none; }
.duty-absence-row { display: flex; align-items: center; gap: 10px 16px; flex-wrap: wrap; padding: 12px 0; border-bottom: 1px solid var(--line); }
.duty-absence-row b { color: var(--ink); }
.duty-row-actions { display: flex; gap: 8px; flex-wrap: wrap; justify-content: flex-end; } .duty-row-actions { display: flex; gap: 8px; flex-wrap: wrap; justify-content: flex-end; }
.settings-divider { border: 0; border-top: 1px solid var(--line); margin: 24px 0; } .settings-divider { border: 0; border-top: 1px solid var(--line); margin: 24px 0; }
@media (max-width: 520px) { .duty-reminder-row { flex-wrap: wrap; } .duty-row-actions { width: 100%; } } @media (max-width: 520px) { .duty-reminder-row { flex-wrap: wrap; } .duty-row-actions { width: 100%; } }
+3 -9
View File
@@ -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=14" /> <link rel="stylesheet" href="/assets/styles.css?v=15" />
</head> </head>
<body> <body>
<div id="app"> <div id="app">
@@ -131,12 +131,6 @@
<div class="duty-clock hidden" id="duty-clock"><span id="duty-countdown-label">本轮剩余</span><strong id="duty-countdown" role="timer" aria-live="off"></strong></div> <div class="duty-clock hidden" id="duty-clock"><span id="duty-countdown-label">本轮剩余</span><strong id="duty-countdown" role="timer" aria-live="off"></strong></div>
<div id="duty-reminders" class="duty-reminders"></div> <div id="duty-reminders" class="duty-reminders"></div>
</section> </section>
<details id="duty-absences" class="stats-help">
<summary>值班缺勤记录</summary>
<p>本轮结束仍未在网站或邮件中确认,记为“未确认缺勤”。此记录不代表实际到岗核验,值班不计入活动统计。</p>
<div id="duty-absence-list" role="status"></div>
<button id="duty-absence-more" class="btn sm hidden" type="button">查看更多</button>
</details>
<div id="feed-stats" class="stats-row"></div> <div id="feed-stats" class="stats-row"></div>
<div id="feed-list" class="card-list"></div> <div id="feed-list" class="card-list"></div>
<div id="feed-empty" class="empty hidden">还没有活动记录,点右上角「+ 记录活动」创建第一条吧。</div> <div id="feed-empty" class="empty hidden">还没有活动记录,点右上角「+ 记录活动」创建第一条吧。</div>
@@ -250,7 +244,7 @@
<p id="pf-test-email-status" class="muted" role="status"></p> <p id="pf-test-email-status" class="muted" role="status"></p>
<hr class="settings-divider" /> <hr class="settings-divider" />
<label>按钮邮件测试<select id="pf-test-button-kind"><option value="duty">值班确认按钮</option><option value="activity">活动参加按钮</option></select></label> <label>按钮邮件测试<select id="pf-test-button-kind"><option value="duty">值班确认按钮</option><option value="activity">活动参加按钮</option></select></label>
<p class="muted">测试按钮跳转和确认,不改变正式活动、值班和缺勤记录。与连通性测试共用 2 分钟冷却。</p> <p class="muted">测试按钮跳转和确认,不改变正式活动和值班记录。与连通性测试共用 2 分钟冷却。</p>
<button class="btn" id="pf-test-button-email" type="button">发送按钮测试邮件</button> <button class="btn" id="pf-test-button-email" type="button">发送按钮测试邮件</button>
<p id="pf-test-button-status" class="muted" role="status"></p> <p id="pf-test-button-status" class="muted" role="status"></p>
</div> </div>
@@ -278,7 +272,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=21"></script> <script src="/js/app.js?v=22"></script>
</div> </div>
</body> </body>
</html> </html>
-23
View File
@@ -651,29 +651,6 @@
}); });
setInterval(updateTestEmailButton, 1000); setInterval(updateTestEmailButton, 1000);
// ------------------------------------------------------------- 我的记录
let absenceOffset = 0;
let absencesLoading = false;
async function loadDutyAbsences(append = false) {
if (absencesLoading) return;
absencesLoading = true;
$("#duty-absence-more").disabled = true;
if (!append) { absenceOffset = 0; $("#duty-absence-list").textContent = "正在加载…"; }
try {
const data = await api(`/duty/absences?limit=20&offset=${absenceOffset}`);
const html = data.items.map((r) => `<div class="duty-absence-row"><b>${esc(r.name)}</b><span>${esc(r.day)} · ${esc(r.slot)}</span><span class="tag absent">未确认缺勤</span></div>`).join("");
if (append) $("#duty-absence-list").insertAdjacentHTML("beforeend", html);
else $("#duty-absence-list").innerHTML = html || "暂无未确认缺勤记录。";
absenceOffset += data.items.length;
$("#duty-absence-more").classList.toggle("hidden", data.items.length < 20);
} catch (error) {
if (!append) $("#duty-absence-list").textContent = error.message;
else toast(error.message, true);
} finally { absencesLoading = false; $("#duty-absence-more").disabled = false; }
}
$("#duty-absences").addEventListener("toggle", () => { if ($("#duty-absences").open) loadDutyAbsences(); });
$("#duty-absence-more").addEventListener("click", () => loadDutyAbsences(true));
// ------------------------------------------------------------- 我的记录 // ------------------------------------------------------------- 我的记录
async function loadMine() { async function loadMine() {
const data = await api("/auth/me"); const data = await api("/auth/me");
+1 -1
View File
@@ -43,7 +43,7 @@ python -m server.duty --date 2026-11-09 --db /app/data/worklog.db --emails /app/
值班邮件使用独立的确认页面及入口,不创建活动和参加记录,也不影响活动次数与出席率。邮件客户端即使将确认表单标为跨站,仍可通过邮件令牌及页面签发的独立表单凭据完成确认;其他接口继续执行原有跨站保护。 值班邮件使用独立的确认页面及入口,不创建活动和参加记录,也不影响活动次数与出席率。邮件客户端即使将确认表单标为跨站,仍可通过邮件令牌及页面签发的独立表单凭据完成确认;其他接口继续执行原有跨站保护。
每轮结束仍未确认邮件,单独保存为“未确认缺勤”,不代表实际到岗核验。活动墙可展开“值班缺勤记录”查看并分页加载。记录从此功能首次运行当天开始,服务重启会补记已开始跟踪期间错过的排班;开始跟踪前的历史日期不会自动判缺勤。已按时确认者不记缺勤,相同排班不会重复入账。 值班不再记录或补记缺勤,未确认只保留为回执状态。活动墙不再显示缺勤记录入口。已有历史缺勤数据保留,兼容接口仅以只读方式提供历史记录,不再产生新记录;值班确认与邮件提醒功能继续使用。
每人每轮自动和手动提醒合计最多尝试 3 次,失败尝试也计入上限。手动补发仅限活动墙正在展示的本轮或下一轮,距上次尝试至少 1 分钟。已确认后该轮不再发送。状态保存在 duty-reminders.db 中,刷新、重启和并发点击均不会重置限额。 每人每轮自动和手动提醒合计最多尝试 3 次,失败尝试也计入上限。手动补发仅限活动墙正在展示的本轮或下一轮,距上次尝试至少 1 分钟。已确认后该轮不再发送。状态保存在 duty-reminders.db 中,刷新、重启和并发点击均不会重置限额。
-2
View File
@@ -201,8 +201,6 @@ async def reminder_loop(schedule_path, state_path, get_accounts, send_email, ove
while True: while True:
try: try:
schedule = load_schedule(schedule_path) schedule = load_schedule(schedule_path)
from .duty_receipts import sync_absences
await asyncio.to_thread(sync_absences, state_path, schedule, datetime.now(BEIJING))
if schedule["enabled"]: if schedule["enabled"]:
overrides = json.loads(Path(overrides_path).read_text(encoding="utf-8-sig")) if overrides_path and Path(overrides_path).exists() else {} overrides = json.loads(Path(overrides_path).read_text(encoding="utf-8-sig")) if overrides_path and Path(overrides_path).exists() else {}
result = await send_due(schedule, datetime.now(BEIJING), await get_accounts(), send_email, state_path, overrides, base_url) result = await send_due(schedule, datetime.now(BEIJING), await get_accounts(), send_email, state_path, overrides, base_url)
+7 -32
View File
@@ -6,7 +6,6 @@ import sqlite3
import time import time
from contextlib import closing from contextlib import closing
from html import escape from html import escape
from datetime import date, datetime, timedelta
def connect(path): def connect(path):
@@ -16,8 +15,6 @@ def connect(path):
con.execute("CREATE TABLE IF NOT EXISTS duty_receipts (day TEXT, slot TEXT, name TEXT, attempts INTEGER DEFAULT 0, sent_count INTEGER DEFAULT 0, last_attempt REAL DEFAULT 0, last_sent REAL DEFAULT 0, confirmed REAL DEFAULT 0, PRIMARY KEY(day,slot,name))") con.execute("CREATE TABLE IF NOT EXISTS duty_receipts (day TEXT, slot TEXT, name TEXT, attempts INTEGER DEFAULT 0, sent_count INTEGER DEFAULT 0, last_attempt REAL DEFAULT 0, last_sent REAL DEFAULT 0, confirmed REAL DEFAULT 0, PRIMARY KEY(day,slot,name))")
con.execute("CREATE TABLE IF NOT EXISTS duty_confirmations (digest TEXT PRIMARY KEY, targets TEXT NOT NULL, expires REAL NOT NULL)") con.execute("CREATE TABLE IF NOT EXISTS duty_confirmations (digest TEXT PRIMARY KEY, targets TEXT NOT NULL, expires REAL NOT NULL)")
con.execute("CREATE TABLE IF NOT EXISTS duty_confirmation_forms (digest TEXT PRIMARY KEY, nonce_hash TEXT NOT NULL)") con.execute("CREATE TABLE IF NOT EXISTS duty_confirmation_forms (digest TEXT PRIMARY KEY, nonce_hash TEXT NOT NULL)")
con.execute("CREATE TABLE IF NOT EXISTS duty_absences (day TEXT, slot TEXT, name TEXT, end_at REAL NOT NULL, recorded_at REAL NOT NULL, PRIMARY KEY(day,slot,name))")
con.execute("CREATE TABLE IF NOT EXISTS duty_audit_state (key TEXT PRIMARY KEY, value TEXT NOT NULL)")
con.execute("CREATE TABLE IF NOT EXISTS mail_button_tests (digest TEXT PRIMARY KEY, kind TEXT NOT NULL, expires REAL NOT NULL, confirmed REAL NOT NULL DEFAULT 0)") con.execute("CREATE TABLE IF NOT EXISTS mail_button_tests (digest TEXT PRIMARY KEY, kind TEXT NOT NULL, expires REAL NOT NULL, confirmed REAL NOT NULL DEFAULT 0)")
return con return con
@@ -162,36 +159,14 @@ def button_test(path, token, now, consume=False):
return row['kind'] return row['kind']
def sync_absences(path, schedule, now):
from .duty import BEIJING, duties_on
now = now.astimezone(BEIJING)
with closing(connect(path)) as con:
con.execute("BEGIN IMMEDIATE")
cursor = con.execute("SELECT value FROM duty_audit_state WHERE key='day'").fetchone()
first = max(date.fromisoformat(schedule["anchor_date"]), date.fromisoformat(cursor[0]) if cursor else now.date())
if schedule["enabled"]:
day = first
while day <= now.date():
_, assignments = duties_on(schedule, day)
for name, slots in assignments.items():
for slot in slots:
clock = schedule.get("slot_times", {}).get(slot)
if not clock:
continue
end = datetime.combine(day, datetime.strptime(clock, '%H:%M').time(), BEIJING) + timedelta(minutes=schedule.get('duration_minutes', 105))
if end > now:
continue
ensure(con, day.isoformat(), slot, name, None)
row = con.execute("SELECT confirmed FROM duty_receipts WHERE day=? AND slot=? AND name=?", (day.isoformat(), slot, name)).fetchone()
if not row[0] or row[0] > end.timestamp():
con.execute("INSERT OR IGNORE INTO duty_absences VALUES (?,?,?,?,?)", (day.isoformat(), slot, name, end.timestamp(), now.timestamp()))
day += timedelta(days=1)
con.execute("INSERT OR REPLACE INTO duty_audit_state VALUES ('day',?)", (now.date().isoformat(),))
con.commit()
def absence_records(path, limit=50, offset=0): def absence_records(path, limit=50, offset=0):
with closing(connect(path)) as con: """只读兼容历史缺勤记录,不再创建、生成或补记缺勤。"""
if not path.exists():
return []
with closing(sqlite3.connect(path.resolve().as_uri() + '?mode=ro', uri=True)) as con:
con.row_factory = sqlite3.Row
if not con.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='duty_absences'").fetchone():
return []
rows = con.execute("SELECT * FROM duty_absences ORDER BY day DESC,end_at DESC,name LIMIT ? OFFSET ?", (limit, offset)).fetchall() rows = con.execute("SELECT * FROM duty_absences ORDER BY day DESC,end_at DESC,name LIMIT ? OFFSET ?", (limit, offset)).fetchall()
return [{"day": r['day'], "slot": r['slot'], "name": r['name'], "end_at": int(r['end_at'] * 1000), "recorded_at": int(r['recorded_at'] * 1000), "reason": "未确认缺勤"} for r in rows] return [{"day": r['day'], "slot": r['slot'], "name": r['name'], "end_at": int(r['end_at'] * 1000), "recorded_at": int(r['recorded_at'] * 1000), "reason": "未确认缺勤"} for r in rows]
+4 -10
View File
@@ -1249,7 +1249,6 @@ async def current_duty(_viewer: dict = Depends(current_user), db: AsyncSession =
return duty_status({"enabled": False}, datetime.now(BEIJING)) return duty_status({"enabled": False}, datetime.now(BEIJING))
try: try:
schedule = load_schedule(path) schedule = load_schedule(path)
await asyncio.to_thread(duty_receipts.sync_absences, _duty_state(), schedule, datetime.now(BEIJING))
data = duty_status(schedule, datetime.now(BEIJING)) data = duty_status(schedule, datetime.now(BEIJING))
accounts = [dict(r) for r in (await db.execute(select(users.c.id, users.c.display_name, users.c.email))).mappings()] accounts = [dict(r) for r in (await db.execute(select(users.c.id, users.c.display_name, users.c.email))).mappings()]
overrides = _duty_overrides() overrides = _duty_overrides()
@@ -1275,13 +1274,8 @@ def _duty_state():
@app.get("/api/duty/absences") @app.get("/api/duty/absences")
async def list_duty_absences(_viewer: dict = Depends(current_user), limit: int = Query(50, ge=1, le=100), offset: int = Query(0, ge=0)): async def list_duty_absences(_viewer: dict = Depends(current_user), limit: int = Query(50, ge=1, le=100), offset: int = Query(0, ge=0)):
path = Path(os.getenv("WORKLOG_DUTY_SCHEDULE", str(PROJECT_DIR / "duty/schedule.json"))) # 兼容旧客户端读取历史数据,不再创建或补记任何缺勤记录。
if path.exists(): return {"items": await asyncio.to_thread(duty_receipts.absence_records, _duty_state(), limit, offset), "recording_enabled": False}
try:
await asyncio.to_thread(duty_receipts.sync_absences, _duty_state(), load_schedule(path), datetime.now(BEIJING))
except (ValueError, KeyError, TypeError, OSError) as exc:
raise HTTPException(status_code=503, detail="值班安排暂时无法读取") from exc
return {"items": await asyncio.to_thread(duty_receipts.absence_records, _duty_state(), limit, offset)}
@app.post("/api/auth/test-email") @app.post("/api/auth/test-email")
@@ -1320,7 +1314,7 @@ async def test_button_email(payload: ButtonTestIn, viewer: dict = Depends(curren
token = await asyncio.to_thread(duty_receipts.create_button_test, _duty_state(), payload.kind, time.time()) token = await asyncio.to_thread(duty_receipts.create_button_test, _duty_state(), payload.kind, time.time())
label = '值班确认' if payload.kind == 'duty' else '活动参加' label = '值班确认' if payload.kind == 'duty' else '活动参加'
url = _site_base_url() + '/mail-test/' + token url = _site_base_url() + '/mail-test/' + token
text = f'这是{label}按钮测试邮件。打开链接后请点击页面中的确认按钮。仅用于测试,不改变正式活动、值班或缺勤记录。链接24小时内有效。\n{url}' text = f'这是{label}按钮测试邮件。打开链接后请点击页面中的确认按钮。仅用于测试,不改变正式活动和值班记录。链接24小时内有效。\n{url}'
html = f'<div style="font-family:sans-serif;line-height:1.8"><h2>{label}按钮测试</h2><p>仅测试邮件按钮跳转和确认,不改变正式记录。链接24小时内有效。</p><a href="{escape(url, quote=True)}" style="display:inline-block;padding:12px 24px;background:#28664f;color:white;border-radius:8px;text-decoration:none">{label}(测试)</a></div>' html = f'<div style="font-family:sans-serif;line-height:1.8"><h2>{label}按钮测试</h2><p>仅测试邮件按钮跳转和确认,不改变正式记录。链接24小时内有效。</p><a href="{escape(url, quote=True)}" style="display:inline-block;padding:12px 24px;background:#28664f;color:white;border-radius:8px;text-decoration:none">{label}(测试)</a></div>'
await _send_email(email, f'【WorkLog测试】{label}按钮', text, html) await _send_email(email, f'【WorkLog测试】{label}按钮', text, html)
return {'ok': True, 'retry_after': 120} return {'ok': True, 'retry_after': 120}
@@ -1342,7 +1336,7 @@ async def confirm_button_test(token: str, request: Request):
if not await asyncio.to_thread(duty_receipts.validate_activity_form, _duty_state(), token, nonce, 'mail-test'): if not await asyncio.to_thread(duty_receipts.validate_activity_form, _duty_state(), token, nonce, 'mail-test'):
return HTMLResponse(_confirmation_page('请重新打开测试邮件,再点击确认。', title='邮件按钮测试'), status_code=403) return HTMLResponse(_confirmation_page('请重新打开测试邮件,再点击确认。', title='邮件按钮测试'), status_code=403)
await asyncio.to_thread(duty_receipts.button_test, _duty_state(), token, time.time(), True) await asyncio.to_thread(duty_receipts.button_test, _duty_state(), token, time.time(), True)
return HTMLResponse(_confirmation_page('按钮测试确认成功,正式活动、值班和缺勤记录未发生变化。', title=label + '测试')) return HTMLResponse(_confirmation_page('按钮测试确认成功,正式活动和值班记录未发生变化。', title=label + '测试'))
class DutySiteConfirmIn(BaseModel): class DutySiteConfirmIn(BaseModel):
+6 -5
View File
@@ -118,10 +118,9 @@ class WorkLogApiTests(ApiTestCase):
self.assertFalse((await db.execute(select(self.m.participations))).all()) self.assertFalse((await db.execute(select(self.m.participations))).all())
async def test_confirm_own_duty_on_site_without_email(self): async def test_confirm_own_duty_on_site_without_email(self):
from datetime import datetime, timedelta from datetime import datetime
from unittest.mock import AsyncMock from unittest.mock import AsyncMock
from server.duty import BEIJING, ROOT, load_schedule, duty_status from server.duty import BEIJING, ROOT, load_schedule, duty_status
from server import duty_receipts
schedule = load_schedule(ROOT / 'duty/schedule.json') schedule = load_schedule(ROOT / 'duty/schedule.json')
data = duty_status(schedule, datetime.now(BEIJING)) data = duty_status(schedule, datetime.now(BEIJING))
shift = data['current'] or data['next'] shift = data['current'] or data['next']
@@ -150,9 +149,10 @@ class WorkLogApiTests(ApiTestCase):
self.assertEqual(receipt['attempts'], 0) self.assertEqual(receipt['attempts'], 0)
self.assertEqual(receipt['sent_count'], 0) self.assertEqual(receipt['sent_count'], 0)
send.assert_not_called() send.assert_not_called()
end = datetime.fromtimestamp(shift['end_at'] / 1000, BEIJING) import sqlite3
duty_receipts.sync_absences(Path(directory) / 'state.db', schedule, end + timedelta(seconds=1)) with sqlite3.connect(Path(directory) / 'state.db') as state:
self.assertNotIn(name, [r['name'] for r in duty_receipts.absence_records(Path(directory) / 'state.db')]) self.assertFalse(state.execute("SELECT 1 FROM sqlite_master WHERE name IN ('duty_absences','duty_audit_state')").fetchall())
state.close()
async with self.sessions() as db: async with self.sessions() as db:
self.assertFalse((await db.execute(select(self.m.activities))).all()) self.assertFalse((await db.execute(select(self.m.activities))).all())
self.assertFalse((await db.execute(select(self.m.participations))).all()) self.assertFalse((await db.execute(select(self.m.participations))).all())
@@ -213,6 +213,7 @@ class WorkLogApiTests(ApiTestCase):
self.assertEqual((await self.client.get('/api/duty/absences')).status_code, 401) self.assertEqual((await self.client.get('/api/duty/absences')).status_code, 401)
absence_response = await self.client.get('/api/duty/absences', headers=auth(u['token'])) absence_response = await self.client.get('/api/duty/absences', headers=auth(u['token']))
self.assertEqual(absence_response.status_code, 200) self.assertEqual(absence_response.status_code, 200)
self.assertFalse(absence_response.json()['recording_enabled'])
self.assertNotIn('email', absence_response.text) self.assertNotIn('email', absence_response.text)
async def test_test_email_only_uses_current_account_and_limits_two_minutes(self): async def test_test_email_only_uses_current_account_and_limits_two_minutes(self):
+15 -2
View File
@@ -4,12 +4,25 @@ import unittest
from contextlib import closing from contextlib import closing
from datetime import date, datetime from datetime import date, datetime
from pathlib import Path from pathlib import Path
from unittest.mock import AsyncMock from unittest.mock import AsyncMock, patch
from server.duty import BEIJING, ROOT, duties_on, duty_status, load_schedule, resolve_recipients, send_due from server.duty import BEIJING, ROOT, duties_on, duty_status, load_schedule, resolve_recipients, send_due, reminder_loop
class DutyTests(unittest.IsolatedAsyncioTestCase): class DutyTests(unittest.IsolatedAsyncioTestCase):
async def test_scheduler_never_creates_absences_after_shift_or_restart(self):
import server.duty as duty
accounts = AsyncMock(return_value=[])
send = AsyncMock()
with patch.object(duty, 'datetime', wraps=datetime) as clock, patch.object(duty.asyncio, 'sleep', new_callable=AsyncMock) as sleep:
clock.now.return_value = datetime(2026, 11, 6, 20, tzinfo=BEIJING)
sleep.side_effect = asyncio.CancelledError()
for _ in range(2):
with self.assertRaises(asyncio.CancelledError):
await reminder_loop(ROOT / 'duty/schedule.json', self.state, accounts, send)
self.assertFalse(self.state.exists())
send.assert_not_called()
def setUp(self): def setUp(self):
self.tmp = tempfile.TemporaryDirectory() self.tmp = tempfile.TemporaryDirectory()
self.state = Path(self.tmp.name) / "reminders.db" self.state = Path(self.tmp.name) / "reminders.db"
+14 -29
View File
@@ -14,24 +14,6 @@ class ReceiptsTests(unittest.IsolatedAsyncioTestCase):
self.assertIsNone(r.confirm_on_site(*args, 1100, 1100)) self.assertIsNone(r.confirm_on_site(*args, 1100, 1100))
self.assertEqual(r.reserve(self.path, '2026-11-06', {'同学': ['一二节']}, 'a@example.test', 2000, 1001), (None, {})) self.assertEqual(r.reserve(self.path, '2026-11-06', {'同学': ['一二节']}, 'a@example.test', 2000, 1001), (None, {}))
def test_absence_only_after_end_and_separate_from_confirmation(self):
from datetime import datetime
from server.duty import BEIJING, ROOT, load_schedule
schedule = load_schedule(ROOT / 'duty/schedule.json')
before = datetime(2026, 11, 6, 10, 14, tzinfo=BEIJING)
r.sync_absences(self.path, schedule, before)
self.assertFalse(r.absence_records(self.path))
token, _ = r.reserve(self.path, '2026-11-06', {'华秋豪': ['一二节']}, 'a@example.test', before.timestamp() + 3600, before.timestamp())
r.confirmation(self.path, token, before.timestamp(), True)
r.sync_absences(self.path, schedule, before.replace(hour=10, minute=15))
self.assertFalse(r.absence_records(self.path))
r.sync_absences(self.path, schedule, before.replace(hour=12, minute=10))
records = r.absence_records(self.path)
self.assertEqual({record['name'] for record in records}, {'孙鹏', '武鑫'})
self.assertTrue(all(record['reason'] == '未确认缺勤' for record in records))
r.sync_absences(self.path, schedule, before.replace(hour=12, minute=11))
self.assertEqual(len(r.absence_records(self.path)), 2)
def test_form_nonce_required_and_get_does_not_confirm(self): def test_form_nonce_required_and_get_does_not_confirm(self):
token, _ = r.reserve(self.path, '2026-11-06', {'同学': ['一二节']}, 'a@example.test', 2000, 1000) token, _ = r.reserve(self.path, '2026-11-06', {'同学': ['一二节']}, 'a@example.test', 2000, 1000)
nonce = r.issue_confirmation_form(self.path, token, 1001) nonce = r.issue_confirmation_form(self.path, token, 1001)
@@ -41,17 +23,20 @@ class ReceiptsTests(unittest.IsolatedAsyncioTestCase):
self.assertIsNotNone(r.confirmation(self.path, token, 1003, True, nonce, True)) self.assertIsNotNone(r.confirmation(self.path, token, 1003, True, nonce, True))
self.assertEqual(r.status(self.path, '2026-11-06', '一二节', '同学', 'a@example.test', 1003)['confirmed_at'], 1003000) self.assertEqual(r.status(self.path, '2026-11-06', '一二节', '同学', 'a@example.test', 1003)['confirmed_at'], 1003000)
def test_absences_catch_up_after_restart_without_backfilling_earlier_dates(self): def test_legacy_absences_are_read_only_and_missing_store_is_not_created(self):
from datetime import datetime import sqlite3
from server.duty import BEIJING, ROOT, load_schedule self.assertEqual(r.absence_records(self.path), [])
schedule = load_schedule(ROOT / 'duty/schedule.json') self.assertFalse(self.path.exists())
r.sync_absences(self.path, schedule, datetime(2026, 11, 6, 7, tzinfo=BEIJING)) # 旧数据库中的历史记录保留,正常回执操作不会再写入该表。
self.assertFalse(r.absence_records(self.path)) from contextlib import closing
# 模拟周末停机,周一恢复后补记周五已跟踪的六名同学。 with closing(sqlite3.connect(self.path)) as con:
r.sync_absences(self.path, schedule, datetime(2026, 11, 9, 9, tzinfo=BEIJING)) con.execute("CREATE TABLE duty_absences (day TEXT,slot TEXT,name TEXT,end_at REAL,recorded_at REAL)")
records = r.absence_records(self.path) con.execute("INSERT INTO duty_absences VALUES ('2026-11-06','一二节','历史同学',1000,1001)")
self.assertEqual(len(records), 6) con.commit()
self.assertEqual({row['day'] for row in records}, {'2026-11-06'}) before = r.absence_records(self.path)
r.status(self.path, '2026-11-09', '一二节', '新同学', 'new@example.test', 2000)
r.confirm_on_site(self.path, '2026-11-09', '一二节', '新同学', 'new@example.test', 2000, 3000)
self.assertEqual(r.absence_records(self.path), before)
def setUp(self): def setUp(self):
self.tmp = tempfile.TemporaryDirectory() self.tmp = tempfile.TemporaryDirectory()