Compare commits

..
2 Commits
Author SHA1 Message Date
azzz 8a6c2b9f6f Merge branch 'main' of https://git.bansonic.top/azzz/worklog
# Conflicts:
#	dist/index.html
#	server/center.py
#	server/center_duty.py
#	server/center_export.py
#	server/duty.py
#	server/hall_log.py
#	server/timetables.py
2026-11-22 14:39:40 +08:00
azzz 982f0df41c 重构共享逻辑并修复值班提醒回执去重 2026-11-22 14:32:13 +08:00
14 changed files with 216 additions and 152 deletions
+4 -4
View File
@@ -25,7 +25,7 @@
<span id="topbar-name"></span>
<button class="btn ghost sm" id="logout-btn">退出</button>
</div>
<button class="btn primary" id="new-activity-btn">+ 记录活动</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>
@@ -154,7 +154,7 @@
</section>
<div id="feed-stats" class="stats-row"></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>
</div>
</main>
@@ -243,7 +243,7 @@
</div>
<div id="mine-stats" class="stats-row"></div>
<div id="mine-list" class="card-list"></div>
<div id="mine-empty" class="empty hidden">还没有记录。去活动墙报名,或点「+ 记录活动」自己发起一条。</div>
<div id="mine-empty" class="empty hidden">还没有记录。去活动墙报名,或点「+ 记录工作」自己发起一条。</div>
</div>
</main>
@@ -358,7 +358,7 @@
<div id="toast" class="toast hidden" role="status" aria-live="polite"></div>
<script src="/js/app.js?v=47"></script>
<script src="/js/app.js?v=48"></script>
</div>
</body>
</html>
+4 -4
View File
@@ -1050,11 +1050,11 @@
function openActivityForm(existing = null, defaultType = 'normal') {
const isEdit = !!existing;
modal(`
<h3>${isEdit ? "编辑活动" : "记录一场活动"}</h3>
<h3>${isEdit ? "编辑工作" : "记录一项工作"}</h3>
<p class="modal-sub muted">提交后立即生效,所有人可见。</p>
<form id="act-form">
<label>记录类型<select name="record_type"><option value="normal">普通活动记录</option><option value="center">赋能中心一楼活动记录</option></select></label>
<label>活动名称 *<input name="title" required maxlength="120" value="${esc(existing?.title || "")}" placeholder="例如:周三晚例会" /></label>
<label>记录类型<select name="record_type"><option value="normal">普通工作记录</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>
<label>地点<input name="location" maxlength="120" value="${esc(existing?.location || "")}" placeholder="如:3 号会议室" /></label>
@@ -1561,7 +1561,7 @@
if ($('#center-from').value) p.set('date_from', Date.parse($('#center-from').value + 'T00:00:00+08:00'));
if ($('#center-to').value) p.set('date_to', Date.parse($('#center-to').value + 'T23:59:59.999+08:00'));
const data = await api(`/activities?${p}`); centerRecords = data.items;
$('#center-record-list').innerHTML = data.items.map(a => activityCard(a)).join('') || '<div class="empty">暂无匹配的一楼活动,记录活动时请上传照片。</div>';
$('#center-record-list').innerHTML = data.items.map(a => activityCard(a)).join('') || '<div class="empty">暂无匹配的一楼活动,记录工作时请上传照片。</div>';
bindCardEvents($('#center-record-list'));
} else if (centerTab === 'duty') {
await loadCenterDuty();
+29 -23
View File
@@ -1,19 +1,17 @@
"""赋能中心一楼:照片、物品、每日清点与借还。"""
"""赋能中心一楼:照片、物品、每日清点、借还登记、展厅登记和值班入口。"""
import asyncio
import io
import json
import os
import re
import time
import uuid
import warnings
import zipfile
from pathlib import PurePosixPath
from datetime import datetime
from pathlib import Path
from typing import Literal
from fastapi import Depends, HTTPException, Query, Request
from fastapi import Depends, HTTPException, Request
from fastapi.responses import FileResponse
from PIL.Image import DecompressionBombError
from pydantic import BaseModel, Field, field_validator
@@ -21,6 +19,14 @@ 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_items, center_loans, center_checks, activities, users
from .duty import BEIJING
from .security import now_ms, PHONE_PATTERN
def required_text(value: str, message: str) -> str:
value = value.strip()
if not value:
raise ValueError(message)
return value
class ItemIn(BaseModel):
@@ -30,8 +36,7 @@ class ItemIn(BaseModel):
@field_validator('name')
@classmethod
def clean_name(cls, value):
if not value.strip(): raise ValueError('物品名称不能为空')
return value.strip()
return required_text(value, '物品名称不能为空')
class LoanBaseIn(BaseModel):
@@ -42,8 +47,7 @@ class LoanBaseIn(BaseModel):
@field_validator('reason', 'contact')
@classmethod
def required_text(cls, value):
if not value.strip(): raise ValueError('申请理由和联系方式不能为空')
return value.strip()
return required_text(value, '申请理由和联系方式不能为空')
class LoanIn(LoanBaseIn):
@@ -52,8 +56,7 @@ class LoanIn(LoanBaseIn):
@field_validator('item_name')
@classmethod
def clean_item_name(cls, value):
if not value.strip(): raise ValueError('借出物品不能为空')
return value.strip()
return required_text(value, '借出物品不能为空')
class PublicLoanIn(BaseModel):
@@ -66,16 +69,13 @@ class PublicLoanIn(BaseModel):
@field_validator('name', 'college', 'activity_name', 'note')
@classmethod
def required_public_text(cls, value):
value = value.strip()
if not value:
raise ValueError('姓名、学院、活动名称和物品备注不能为空')
return value
return required_text(value, '姓名、学院、活动名称和物品备注不能为空')
@field_validator('phone')
@classmethod
def valid_phone(cls, value):
value = value.strip()
if not re.fullmatch(r'1[3-9]\d{9}', value):
if not re.fullmatch(PHONE_PATTERN, value):
raise ValueError('请填写正确的 11 位手机号')
return value
@@ -99,7 +99,11 @@ DAILY_PHOTO_LIMIT = 1000
UPLOAD_ORPHAN_TTL_MS = 24 * 60 * 60 * 1000
def now_ms(): return int(time.time() * 1000)
def inventory_use():
"""统计升级前仍占用库存的历史借出;新登记不扣库存。"""
return select(center_loans.c.item_id, func.sum(center_loans.c.quantity)).where(
center_loans.c.status == 'approved', center_loans.c.returned_at.is_(None)
).group_by(center_loans.c.item_id)
async def cleanup_orphan_uploads(db, root: Path, before_ms: int) -> tuple[int, int]:
@@ -262,7 +266,7 @@ def convert_package(raw):
def install(app, get_db, current_user, photo_root, visible_clause):
from .hall_log import snapshot as hall_log_snapshot
from .hall_log import write_cell as hall_log_write
from .hall_log import DEFAULT_LINK_ID, write_cell as hall_log_write
@app.get('/api/center/hall-log')
async def hall_log(refresh: bool = False, viewer=Depends(current_user)):
@@ -272,14 +276,15 @@ def install(app, get_db, current_user, photo_root, visible_clause):
class HallLogDutyIn(BaseModel):
row: int = Field(ge=2, le=502)
value: str = Field(default='', max_length=200)
column: int = Field(default=8, ge=7, le=8) # 7=使用单位联系人及联系方式,8=赋能部值班人员及联系方式
@app.post('/api/center/hall-log/duty')
async def hall_log_duty(payload: HallLogDutyIn, viewer=Depends(current_user)):
"""填写展厅登记的"值班人"列,写回金山文档并留编辑日志。"""
"""填写展厅登记的"联系人"或"值班人"列,写回金山文档并留编辑日志。"""
editor = viewer.get('display_name') or viewer.get('username') or viewer['id']
await asyncio.to_thread(hall_log_write, os.getenv('WORKLOG_HALL_LOG_LINK_ID') or 'cnC7HwRAxKf9', payload.row, 8, payload.value.strip(), editor)
await asyncio.to_thread(hall_log_write, os.getenv('WORKLOG_HALL_LOG_LINK_ID') or DEFAULT_LINK_ID, payload.row, payload.column, payload.value.strip(), editor)
await hall_log_snapshot(force=True)
return {'ok': True, 'row': payload.row, 'value': payload.value.strip(), 'editor': editor}
return {'ok': True, 'row': payload.row, 'column': payload.column, 'value': payload.value.strip(), 'editor': editor}
@app.post('/api/center/materials')
async def upload_material(request:Request,db=Depends(get_db),viewer=Depends(current_user)):
@@ -353,7 +358,7 @@ def install(app, get_db, current_user, photo_root, visible_clause):
@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()
borrowed = dict((await db.execute(select(center_loans.c.item_id, func.sum(center_loans.c.quantity)).where(center_loans.c.status=='approved', center_loans.c.returned_at.is_(None)).group_by(center_loans.c.item_id))).all())
borrowed = dict((await db.execute(inventory_use())).all())
day = datetime.now(BEIJING).date().isoformat()
check = (await db.execute(select(center_checks).where(center_checks.c.day == day))).mappings().first()
return {'items': [{**r, 'borrowed': borrowed.get(r['id'], 0), 'available': r['quantity']-borrowed.get(r['id'],0)} for r in rows], 'day': day, 'checked_today': bool(check), 'check': dict(check) if check else None}
@@ -421,6 +426,7 @@ def install(app, get_db, current_user, photo_root, visible_clause):
center_loans.c.guest_college, center_loans.c.guest_activity_name,
).select_from(center_loans).outerjoin(center_items,center_items.c.id==center_loans.c.item_id).outerjoin(users,users.c.id==center_loans.c.user_id)
if status=='recorded':stmt=stmt.where(center_loans.c.status=='recorded')
# borrowed 是历史接口名;现在只对应旧库存借出记录 approved。
elif status in ('approved','borrowed'):stmt=stmt.where(center_loans.c.status=='approved')
elif status=='returned':stmt=stmt.where(center_loans.c.status==status)
elif status!='all':raise HTTPException(422,'无效借用状态')
@@ -436,7 +442,7 @@ def install(app, get_db, current_user, photo_root, visible_clause):
if not row:raise HTTPException(404,'借用记录不存在')
if row['user_id']!=viewer['id']:raise HTTPException(403,'仅借用人可以登记归还')
if row['status']=='returned':return {'ok':True}
if row['status']!='approved':raise HTTPException(409,'仅历史库存借出记录可归还')
if row['status']!='approved':raise HTTPException(409,'仅历史库存借出记录可归还;新登记借出不走库存归还')
await db.execute(update(center_loans).where(center_loans.c.id==loan_id,center_loans.c.returned_at.is_(None)).values(returned_at=now_ms(),status='returned'))
await db.commit(); return {'ok':True}
@@ -449,7 +455,7 @@ def install(app, get_db, current_user, photo_root, visible_clause):
raise HTTPException(409,'今天的清点已由其他成员提交,只有提交人可以修正')
rows=(await db.execute(select(center_items))).mappings().all()
if not rows or set(payload.quantities)!={r['id'] for r in rows}:raise HTTPException(422,'请逐项清点全部物品,物品列表如有变化请刷新')
used=dict((await db.execute(select(center_loans.c.item_id,func.sum(center_loans.c.quantity)).where(center_loans.c.status=='approved',center_loans.c.returned_at.is_(None)).group_by(center_loans.c.item_id))).all())
used=dict((await db.execute(inventory_use())).all())
details=[]
for row in rows:
count=payload.quantities[row['id']]
+1 -5
View File
@@ -4,7 +4,6 @@ from __future__ import annotations
import json
import os
import re
import time
import uuid
from datetime import date, datetime, time as dt_time, timedelta
from pathlib import Path
@@ -16,15 +15,12 @@ from sqlalchemy import insert, select
from .duty import BEIJING
from .models import center_duty_leaves, users
from .security import now_ms
ROOT = Path(__file__).resolve().parent.parent
WEEKDAY_LABELS = ("周一", "周二", "周三", "周四", "周五", "周六", "周日")
def now_ms() -> int:
return int(time.time() * 1000)
def normalize_name(value: str) -> str:
return re.sub(r"\s+", "", value or "")
+4 -3
View File
@@ -11,6 +11,7 @@ from fastapi.responses import Response
from sqlalchemy import select, func, or_, case
from .duty import BEIJING
from . import center
from .csv_utils import csv_safe_value
from .models import (
activities,
users,
@@ -58,7 +59,7 @@ def csv_bytes(kind, rows):
for key in FIELDS[kind]:
value = row.get(key)
if isinstance(value, (dict,list)): value = json.dumps(value, ensure_ascii=False)
if isinstance(value, str) and value.lstrip().startswith(('=','+','-','@','\t','\r')): value = "'"+value
value = csv_safe_value(value)
values[key] = value
writer.writerow(values)
return buffer.getvalue().encode('utf-8-sig')
@@ -84,7 +85,7 @@ def install(app, get_db, current_user, visible_clause):
'public_loan_endpoint':'POST /api/center/public-loans(登录页免登录登记)',
'duty_endpoint':'GET /api/center/duty?week_start=YYYY-MM-DD(返回完整单双周排班、当前值班和本人请假状态)',
'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','returned']},
'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字符串'},
}
@@ -137,7 +138,7 @@ def install(app, get_db, current_user, visible_clause):
r['material_url']='/api/center/materials/'+r['material_id'] if r['material_id'] else None
rows=[{field:r.get(field) for field in FIELDS[key]} for r in rows]
elif key=='items':
borrowed=dict((await db.execute(select(center_loans.c.item_id,func.sum(center_loans.c.quantity)).where(center_loans.c.status=='approved',center_loans.c.returned_at.is_(None)).group_by(center_loans.c.item_id))).all())
borrowed=dict((await db.execute(center.inventory_use())).all())
for r in rows:r['borrowed']=borrowed.get(r['id'],0);r['available']=r['quantity']-r['borrowed']
elif key=='checks':
for r in rows:r['details']=json.loads(r['details'])
+8
View File
@@ -0,0 +1,8 @@
"""CSV 导出的通用安全处理。"""
def csv_safe_value(value):
"""防止电子表格将文本解释成公式。"""
if isinstance(value, str) and value.lstrip().startswith(('=', '+', '-', '@', '\t', '\r')):
return "'" + value
return value
+39 -28
View File
@@ -12,11 +12,36 @@ from contextlib import closing
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
from .security import valid_email
BEIJING = timezone(timedelta(hours=8))
log = logging.getLogger("worklog.duty")
ROOT = Path(__file__).resolve().parent.parent
def claim(state_path, day, email, now):
Path(state_path).parent.mkdir(parents=True, exist_ok=True)
with closing(sqlite3.connect(state_path, timeout=10)) as con:
con.execute("CREATE TABLE IF NOT EXISTS deliveries (day TEXT, email TEXT, status TEXT, attempts INTEGER, updated REAL, PRIMARY KEY(day,email))")
con.execute("BEGIN IMMEDIATE")
row = con.execute("SELECT status,attempts,updated FROM deliveries WHERE day=? AND email=?", (day, email)).fetchone()
if row and (row[0] == "sent" or row[1] >= 3 or now - row[2] < 900):
con.rollback()
return False
if row:
con.execute("UPDATE deliveries SET status='sending', attempts=attempts+1, updated=? WHERE day=? AND email=?", (now, day, email))
else:
con.execute("INSERT INTO deliveries VALUES (?,?,'sending',1,?)", (day, email, now))
con.commit()
return True
def finish(state_path, day, email, status):
with closing(sqlite3.connect(state_path, timeout=10)) as con:
con.execute("UPDATE deliveries SET status=?,updated=? WHERE day=? AND email=?", (status, time.time(), day, email))
con.commit()
def load_schedule(path):
data = json.loads(Path(path).read_text(encoding="utf-8-sig"))
if data.get("version") != 1 or type(data.get("enabled")) is not bool:
@@ -56,13 +81,18 @@ def load_schedule(path):
return data
def duties_on(schedule, day):
def week_type_on(schedule, day):
anchor = date.fromisoformat(schedule["anchor_date"])
monday = anchor - timedelta(days=anchor.weekday())
offset = (day - monday).days // 7
week = schedule["anchor_week"]
if offset % 2:
week = "even" if week == "odd" else "odd"
return week
def duties_on(schedule, day):
week = week_type_on(schedule, day)
assignments = defaultdict(list)
for entry in schedule["weeks"][week]:
if entry["weekday"] == day.isoweekday():
@@ -85,7 +115,7 @@ def resolve_recipients(assignments, accounts, overrides=None):
continue
else:
email = matches[0]["email"]
if not isinstance(email, str) or "@" not in email or any(c.isspace() for c in email):
if not valid_email(email):
missing[name] = "邮箱无效或为空"
continue
email = email.strip().lower()
@@ -134,37 +164,18 @@ def duty_status(schedule, now):
return result
def claim(state_path, day, email, now):
Path(state_path).parent.mkdir(parents=True, exist_ok=True)
with closing(sqlite3.connect(state_path, timeout=10)) as con:
con.execute("CREATE TABLE IF NOT EXISTS deliveries (day TEXT, email TEXT, status TEXT, attempts INTEGER, updated REAL, PRIMARY KEY(day,email))")
con.execute("BEGIN IMMEDIATE")
row = con.execute("SELECT status,attempts,updated FROM deliveries WHERE day=? AND email=?", (day, email)).fetchone()
if row and (row[0] == "sent" or row[1] >= 3 or now - row[2] < 900):
con.rollback()
return False
if row:
con.execute("UPDATE deliveries SET status='sending', attempts=attempts+1, updated=? WHERE day=? AND email=?", (now, day, email))
else:
con.execute("INSERT INTO deliveries VALUES (?,?,'sending',1,?)", (day, email, now))
con.commit()
return True
def finish(state_path, day, email, status):
with closing(sqlite3.connect(state_path, timeout=10)) as con:
con.execute("UPDATE deliveries SET status=?,updated=? WHERE day=? AND email=?", (status, time.time(), day, email))
con.commit()
def due_batches(schedule, now):
"""晚上汇总和每个节次分别生成任务;节次开始后不补发过期提醒。"""
"""晚上汇总和每个节次分别生成任务;节次开始后不补发过期提醒。
第三项 key 是发给回执层的日期键:晚间汇总沿用旧版纯日期,
值班前提醒使用 ``日期#before:节次``,因此同一天的多个节次可以
各自去重,而不会互相吞掉。
"""
batches = []
anchor = date.fromisoformat(schedule["anchor_date"])
target = now.date() + timedelta(days=schedule["reminder_days_before"])
if target >= anchor and now.strftime("%H:%M") >= schedule["reminder_time"]:
week, assignments = duties_on(schedule, target)
# 沿用旧版日期键,保留已发晚间邮件的去重记录。
batches.append((target, week, assignments, target.isoformat(), "值班汇总提醒"))
before = schedule.get("before_minutes", 0)
if before and now.date() >= anchor:
@@ -197,7 +208,7 @@ async def send_due(schedule, now, accounts, send_email, state_path, overrides=No
body = f"机构:{organization}\n日期:{target.isoformat()}(周{'一二三四五六日'[target.weekday()]},{'单' if week == 'odd' else '双'}周)\n" + "、".join(f"{slot} {clocks[slot]} 开始" for slot in sorted(slots)) + "\n以上时间均为北京时间。请准时值班。"
subject = f"{schedule.get('title', organization + '值班')}|{label}|{target.isoformat()}"
try:
sent = await send_notice(state_path, target.isoformat(), names, email, max(ends).timestamp(), send_email, subject, body, base_url, now.timestamp())
sent = await send_notice(state_path, key, names, email, max(ends).timestamp(), send_email, subject, body, base_url, now.timestamp())
except Exception:
result["failed"] += 1
await asyncio.to_thread(finish, state_path, key, email, "failed")
+20 -16
View File
@@ -1,5 +1,4 @@
"""值班提醒回执;独立 SQLite 保存每人每轮的发送次数和确认状态。"""
import hashlib
"""值班提醒回执、确认表单nonce、邮件按钮测试和旧缺勤记录兼容。"""
import json
import secrets
import sqlite3
@@ -7,6 +6,8 @@ import time
from contextlib import closing
from html import escape
from .security import token_digest
def connect(path):
path.parent.mkdir(parents=True, exist_ok=True)
@@ -22,8 +23,11 @@ def connect(path):
def ensure(con, day, slot, name, email):
# 导入旧版成功发送记录;新版已有回执后不重复导入。
count, last = 0, 0
if email and con.execute("SELECT 1 FROM sqlite_master WHERE name='deliveries'").fetchone():
rows = con.execute("SELECT updated FROM deliveries WHERE email=? AND status='sent' AND day IN (?,?)", (email, day, f"{day}#before:{slot}")).fetchall()
exists = con.execute("SELECT 1 FROM duty_receipts WHERE day=? AND slot=? AND name=?", (day, slot, name)).fetchone()
if not exists and email and con.execute("SELECT 1 FROM sqlite_master WHERE name='deliveries'").fetchone():
# 只有当前任务已发送的记录才能算作既有回执;旧表可能由当前调度器
# 预先写入 sending/failed,不能因为新行刚刚创建就把 slot 判成已发过。
rows = con.execute("SELECT updated FROM deliveries WHERE email=? AND status='sent' AND updated > 0 AND day IN (?,?)", (email, day, f"{day}#before:{slot}")).fetchall()
count = len(rows)
last = max((r[0] for r in rows), default=0)
con.execute("INSERT OR IGNORE INTO duty_receipts(day,slot,name,attempts,sent_count,last_attempt,last_sent) VALUES (?,?,?,?,?,?,?)", (day, slot, name, count, count, last, last))
@@ -54,7 +58,7 @@ def reserve(path, day, names, email, expires, now):
return None, {}
token = secrets.token_urlsafe(32)
targets = [(day, slot, name) for name, slots in selected.items() for slot in slots]
con.execute("INSERT INTO duty_confirmations VALUES (?,?,?)", (hashlib.sha256(token.encode()).hexdigest(), json.dumps(targets), expires))
con.execute("INSERT INTO duty_confirmations VALUES (?,?,?)", (token_digest(token), json.dumps(targets), expires))
con.commit()
return token, selected
@@ -81,21 +85,21 @@ def confirm_on_site(path, day, slot, name, email, now, end_at):
def issue_confirmation_form(path, token, now):
with closing(connect(path)) as con:
digest = hashlib.sha256(token.encode()).hexdigest()
digest = token_digest(token)
row = con.execute("SELECT expires FROM duty_confirmations WHERE digest=?", (digest,)).fetchone()
if row is None or row[0] <= now:
return None
nonce = secrets.token_urlsafe(32)
con.execute("INSERT OR REPLACE INTO duty_confirmation_forms VALUES (?,?)", (digest, hashlib.sha256(nonce.encode()).hexdigest()))
con.execute("INSERT OR REPLACE INTO duty_confirmation_forms VALUES (?,?)", (digest, token_digest(nonce)))
con.commit()
return nonce
def issue_activity_form(path, token, namespace='activity'):
digest = hashlib.sha256((namespace + ':' + token).encode()).hexdigest()
digest = token_digest(namespace + ':' + token)
nonce = secrets.token_urlsafe(32)
with closing(connect(path)) as con:
con.execute("INSERT OR REPLACE INTO duty_confirmation_forms VALUES (?,?)", (digest, hashlib.sha256(nonce.encode()).hexdigest()))
con.execute("INSERT OR REPLACE INTO duty_confirmation_forms VALUES (?,?)", (digest, token_digest(nonce)))
con.commit()
return nonce
@@ -103,21 +107,21 @@ def issue_activity_form(path, token, namespace='activity'):
def validate_activity_form(path, token, nonce, namespace='activity'):
if not nonce:
return False
digest = hashlib.sha256((namespace + ':' + token).encode()).hexdigest()
digest = token_digest(namespace + ':' + token)
with closing(connect(path)) as con:
row = con.execute("SELECT nonce_hash FROM duty_confirmation_forms WHERE digest=?", (digest,)).fetchone()
return bool(row and secrets.compare_digest(row[0], hashlib.sha256(nonce.encode()).hexdigest()))
return bool(row and secrets.compare_digest(row[0], token_digest(nonce)))
def confirmation(path, token, now, consume=False, form_token=None, require_form=False):
with closing(connect(path)) as con:
con.execute("BEGIN IMMEDIATE")
row = con.execute("SELECT * FROM duty_confirmations WHERE digest=?", (hashlib.sha256(token.encode()).hexdigest(),)).fetchone()
row = con.execute("SELECT * FROM duty_confirmations WHERE digest=?", (token_digest(token),)).fetchone()
if row is None or row["expires"] <= now:
return None
if consume and require_form:
form = con.execute("SELECT nonce_hash FROM duty_confirmation_forms WHERE digest=?", (hashlib.sha256(token.encode()).hexdigest(),)).fetchone()
if form is None or not form_token or not secrets.compare_digest(form[0], hashlib.sha256(form_token.encode()).hexdigest()):
form = con.execute("SELECT nonce_hash FROM duty_confirmation_forms WHERE digest=?", (token_digest(token),)).fetchone()
if form is None or not form_token or not secrets.compare_digest(form[0], token_digest(form_token)):
return None
targets = json.loads(row["targets"])
if consume:
@@ -142,13 +146,13 @@ def reserve_test(path, email, now):
def create_button_test(path, kind, now):
token = secrets.token_urlsafe(32)
with closing(connect(path)) as con:
con.execute("INSERT INTO mail_button_tests(digest,kind,expires) VALUES (?,?,?)", (hashlib.sha256(token.encode()).hexdigest(), kind, now + 86400))
con.execute("INSERT INTO mail_button_tests(digest,kind,expires) VALUES (?,?,?)", (token_digest(token), kind, now + 86400))
con.commit()
return token
def button_test(path, token, now, consume=False):
digest = hashlib.sha256(token.encode()).hexdigest()
digest = token_digest(token)
with closing(connect(path)) as con:
row = con.execute("SELECT * FROM mail_button_tests WHERE digest=? AND expires>?", (digest, now)).fetchone()
if not row:
+12 -7
View File
@@ -90,16 +90,20 @@ def _unwrap(payload: dict, label: str) -> dict:
return detail
def worksheet_id(link_id: str, token: str | None = None) -> int:
sheets = _call_tool('sheet.get_sheets_info', {'link_id': link_id}, token)
info = _unwrap(sheets, '工作表信息')['sheetsInfo'][0]
return info['sheetId']
def fetch_rows(link_id: str = DEFAULT_LINK_ID) -> list[dict[str, str]]:
"""读取展厅使用登记表,返回去掉空行的记录列表。"""
token = os.getenv('KINGSOFT_DOCS_TOKEN') or None
cli = _cli_path()
sheets = _call_tool('sheet.get_sheets_info', {'link_id': link_id}, token)
info = sheets['data']['detail']['sheetsInfo'][0]
sheet_id = info['sheetId']
info = _call_tool('sheet.get_sheets_info', {'link_id': link_id}, token)['data']['detail']['sheetsInfo'][0]
current_sheet_id = info['sheetId']
row_to = min(info.get('rowTo', 0), 1 + MAX_ROWS)
col_to = min(info.get('colTo', len(FIELDS) - 1), len(FIELDS) - 1)
data = _call_tool('sheet.get_range_data', {'link_id': link_id, 'worksheet_id': sheet_id,
data = _call_tool('sheet.get_range_data', {'link_id': link_id, 'worksheet_id': current_sheet_id,
'range': {'rowFrom': 0, 'rowTo': row_to, 'colFrom': 0, 'colTo': col_to}}, token)
grid = _parse_grid(data['data']['detail']['rangeData'], row_to, col_to)
header = grid[1] if len(grid) > 1 else FIELDS
@@ -115,14 +119,15 @@ def fetch_rows(link_id: str = DEFAULT_LINK_ID) -> list[dict[str, str]]:
def write_cell(link_id: str, row_index: int, col_index: int, value: str, editor: str) -> None:
"""写入一个单元格(0 基索引),并记录谁改了什么。"""
token = os.getenv('KINGSOFT_DOCS_TOKEN')
current_worksheet_id = worksheet_id(link_id, token)
op = {'opType': 'formula', 'rowFrom': row_index, 'rowTo': row_index, 'colFrom': col_index, 'colTo': col_index, 'formula': value}
if token:
_call_tool('sheet.update_range_data', {'link_id': link_id, 'worksheet_id': 1, 'range_data': [op]}, token)
_call_tool('sheet.update_range_data', {'link_id': link_id, 'worksheet_id': current_worksheet_id, 'range_data': [op]}, token)
else:
cli = _cli_path()
if not cli:
raise RuntimeError('未找到金山文档命令行工具,请配置 KINGSOFT_DOCS_TOKEN 环境变量')
args = json.dumps({'link_id': link_id, 'worksheet_id': 1, 'range_data': [op]}, ensure_ascii=False)
args = json.dumps({'link_id': link_id, 'worksheet_id': current_worksheet_id, 'range_data': [op]}, ensure_ascii=False)
completed = subprocess.run([cli, 'sheet', 'update-range-data', args], capture_output=True, timeout=20)
if completed.returncode != 0:
raise RuntimeError(f'金山文档写入失败: {completed.stderr.decode("utf-8", "ignore").strip()[:200]}')
+62
View File
@@ -0,0 +1,62 @@
"""邮件链接落地页:一键参加活动与邮件按钮测试。"""
from __future__ import annotations
from html import escape
JOIN_PAGE = """\
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>一键参加 · WorkLog</title>
<style>
body {{ margin:0; min-height:100vh; display:flex; align-items:center; justify-content:center;
background:#f3f4f6; font-family:'Segoe UI','PingFang SC','Microsoft YaHei',sans-serif; }}
.card {{ max-width:420px; margin:24px; background:#fff; border-radius:14px; padding:36px 32px;
text-align:center; box-shadow:0 4px 24px rgba(0,0,0,.08); }}
h1 {{ margin:0 0 10px; font-size:20px; color:#111827; }}
p {{ margin:0 0 6px; font-size:14px; color:#6b7280; line-height:1.6; }}
.btn {{ display:inline-block; margin-top:18px; background:#2563eb; color:#fff; text-decoration:none;
font-size:15px; font-weight:600; padding:11px 30px; border-radius:8px; }}
.ok {{ color:#059669; }} .err {{ color:#dc2626; }}
</style>
</head>
<body><div class="card"><div id="box"><p>正在处理…</p></div></div></body>
</html>"""
def join_page(message: str, state: str, activity_title: str = "", extra: str = "") -> str:
icon = "✓" if state == "ok" else ("?" if state == "confirm" else "✕")
button = '<a class="btn" href="/">打开 WorkLog</a>' if state == "ok" else ""
title_html = (
f'<p style="font-size:16px;color:#111827;font-weight:600;">{escape(activity_title)}</p>'
if activity_title
else ""
)
heading = {"ok": "记录成功", "confirm": "确认参加", "err": "无法完成"}[state]
return JOIN_PAGE.replace(
'<div id="box"><p>正在处理…</p></div>',
f'<div id="box"><div class="{state}" style="font-size:40px;line-height:1;">{icon}</div>'
f"<h1>{heading}</h1>{title_html}"
f"<p>{escape(str(message))}</p>{button}{extra}</div>",
)
def confirmation_page(message: str, nonce: str | None = None, title: str = '值班邮件确认', button_label: str = '确认已知晓值班安排') -> str:
form = (
f'<form method="post"><input type="hidden" name="confirmation_token" value="{escape(nonce, quote=True)}">'
f'<button type="submit">{escape(button_label)}</button></form>'
if nonce
else ""
)
return (
f'<!doctype html><html lang="zh-CN"><meta charset="utf-8">'
f'<meta name="viewport" content="width=device-width,initial-scale=1"><title>{escape(title)} · WorkLog</title>'
f"<style>body{{font:16px/1.8 system-ui,sans-serif;background:#f5f7f5;color:#263c35;margin:0;padding:32px 20px}}"
f"main{{max-width:480px;margin:8vh auto;background:white;border:1px solid #e1e8e3;border-radius:16px;padding:28px}}"
f"h1{{font-size:24px}}button{{background:#28664f;color:white;border:0;border-radius:8px;padding:12px 20px;"
f"font:inherit;cursor:pointer}}p{{overflow-wrap:anywhere}}</style>"
f"<main><h1>{escape(title)}</h1><p>{escape(message)}</p>{form}</main></html>"
)
+4 -50
View File
@@ -35,7 +35,8 @@ from sqlalchemy.schema import CreateIndex
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
from .models import activities, auth_limits, email_verifications, join_links, metadata, participations, sessions, users
from .security import hash_password, new_token, token_digest, verify_password
from .security import EMAIL_PATTERN, PHONE_PATTERN, hash_password, new_token, now_ms, token_digest, verify_password
from .mail_pages import confirmation_page, join_page
from .backup import backup_loop, parse_time
from .duty import BEIJING, duty_status, load_schedule, reminder_loop
from .duty import resolve_recipients
@@ -135,10 +136,6 @@ SessionLocal = async_sessionmaker(engine, expire_on_commit=False)
# ---------------------------------------------------------------- 基础工具
def now_ms() -> int:
return int(time.time() * 1000)
def new_id() -> str:
return uuid.uuid4().hex
@@ -339,10 +336,6 @@ async def user_stats(db: AsyncSession, user_id: str, *, public_only: bool = Fals
# ---------------------------------------------------------------- 请求模型
EMAIL_PATTERN = r"^[^@\s]+@[^@\s]+\.[^@\s]+$"
PHONE_PATTERN = r"^1[3-9][0-9]{9}$"
class EmailCodeIn(BaseModel):
email_code: str = Field(min_length=6, max_length=6, pattern=r"^[0-9]{6}$")
@@ -1576,9 +1569,7 @@ async def confirm_duty(token: str, request: Request):
return HTMLResponse(_confirmation_page("已确认值班安排,谢谢。本次确认仅记录值班回执。"))
def _confirmation_page(message: str, nonce: str | None = None, title='值班邮件确认', button_label='确认已知晓值班安排'):
form = f'<form method="post"><input type="hidden" name="confirmation_token" value="{escape(nonce, quote=True)}"><button type="submit">{escape(button_label)}</button></form>' if nonce else ''
return f'<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{escape(title)} · WorkLog</title><style>body{{font:16px/1.8 system-ui,sans-serif;background:#f5f7f5;color:#263c35;margin:0;padding:32px 20px}}main{{max-width:480px;margin:8vh auto;background:white;border:1px solid #e1e8e3;border-radius:16px;padding:28px}}h1{{font-size:24px}}button{{background:#28664f;color:white;border:0;border-radius:8px;padding:12px 20px;font:inherit;cursor:pointer}}p{{overflow-wrap:anywhere}}</style><main><h1>{escape(title)}</h1><p>{escape(message)}</p>{form}</main></html>'
_confirmation_page = confirmation_page
@app.get("/api/stats/overview")
async def overview(db: AsyncSession = Depends(get_db), _viewer: dict = Depends(current_user)) -> dict:
@@ -2012,44 +2003,7 @@ async def update_participation(
# ---------------------------------------------------------------- 邮件一键参加
JOIN_PAGE = """\
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>一键参加 · WorkLog</title>
<style>
body {{ margin:0; min-height:100vh; display:flex; align-items:center; justify-content:center;
background:#f3f4f6; font-family:'Segoe UI','PingFang SC','Microsoft YaHei',sans-serif; }}
.card {{ max-width:420px; margin:24px; background:#fff; border-radius:14px; padding:36px 32px;
text-align:center; box-shadow:0 4px 24px rgba(0,0,0,.08); }}
h1 {{ margin:0 0 10px; font-size:20px; color:#111827; }}
p {{ margin:0 0 6px; font-size:14px; color:#6b7280; line-height:1.6; }}
.btn {{ display:inline-block; margin-top:18px; background:#2563eb; color:#fff; text-decoration:none;
font-size:15px; font-weight:600; padding:11px 30px; border-radius:8px; }}
.ok {{ color:#059669; }} .err {{ color:#dc2626; }}
</style>
</head>
<body><div class="card"><div id="box"><p>正在处理…</p></div></div></body>
</html>"""
def _join_page(message: str, state: str, activity_title: str = "", extra: str = "") -> str:
icon = "✓" if state == "ok" else ("?" if state == "confirm" else "✕")
btn = (
f'<a class="btn" href="/">打开 WorkLog</a>'
if state == "ok"
else ""
)
title_html = f'<p style="font-size:16px;color:#111827;font-weight:600;">{escape(activity_title)}</p>' if activity_title else ""
heading = {"ok": "记录成功", "confirm": "确认参加", "err": "无法完成"}[state]
return JOIN_PAGE.format().replace(
'<div id="box"><p>正在处理…</p></div>',
f'<div id="box"><div class="{state}" style="font-size:40px;line-height:1;">{icon}</div>'
f'<h1>{heading}</h1>{title_html}'
f'<p>{escape(str(message))}</p>{btn}{extra}</div>',
)
_join_page = join_page
@app.get("/join/{token}", include_in_schema=False)
+7 -4
View File
@@ -1,7 +1,6 @@
"""数据库表结构(SQLAlchemy Core)。
四张表:users(账号)、sessions(登录会话)、activities(活动)、
participations(参加记录,也就是"某人参加过某活动"这一事实)。
账号与会话、活动与参加记录之外,还包括赋能中心一楼和课表收取相关表。
时间统一存毫秒时间戳整数,前端用 new Date(ms) 渲染。
"""
@@ -131,8 +130,6 @@ join_links = Table(
)
Index("ix_join_links_activity", join_links.c.activity_id)
TABLES = (users, sessions, email_verifications, activities, participations, join_links)
center_photos = Table('center_photos', metadata,
Column('id', String(32), primary_key=True), Column('owner_id', String(36), ForeignKey('users.id'), nullable=False),
Column('created_at', Integer, nullable=False))
@@ -179,3 +176,9 @@ timetables = Table('timetables', metadata,
Column('structure', Text, nullable=False), Column('ocr_status', String(20), nullable=False),
Column('created_at', Integer, nullable=False), Column('updated_at', Integer, nullable=False),
Column('confirmed_at', Integer, nullable=True))
TABLES = (
users, sessions, email_verifications, activities, participations, join_links,
center_photos, center_materials, center_activity_materials, center_activity_meta,
center_items, center_loans, center_checks, center_duty_leaves, timetables,
)
+17
View File
@@ -4,10 +4,14 @@ from __future__ import annotations
import hashlib
import hmac
import re
import secrets
import time
ALGORITHM = "pbkdf2_sha256"
ITERATIONS = 240_000
EMAIL_PATTERN = r"^[^@\s]+@[^@\s]+\.[^@\s]+$"
PHONE_PATTERN = r"^1[3-9][0-9]{9}$"
def hash_password(password: str) -> str:
@@ -38,3 +42,16 @@ def new_token() -> str:
def token_digest(token: str) -> str:
"""数据库只保存高熵令牌的摘要,数据库副本不能直接充当登录凭据。"""
return hashlib.sha256(token.encode("utf-8")).hexdigest()
def now_ms() -> int:
"""当前的 Unix 毫秒时间戳。"""
return int(time.time() * 1000)
def valid_email(value: str) -> bool:
return isinstance(value, str) and re.fullmatch(EMAIL_PATTERN, value) is not None
def valid_phone(value: str) -> bool:
return isinstance(value, str) and re.fullmatch(PHONE_PATTERN, value) is not None
+5 -8
View File
@@ -4,7 +4,6 @@ import csv
import io
import json
import secrets
import time
import uuid
from pathlib import Path
from typing import Literal
@@ -16,6 +15,8 @@ from sqlalchemy import select, text, update
from sqlalchemy.dialects.sqlite import insert
from .models import timetables, users
from .security import now_ms
from .csv_utils import csv_safe_value
from . import timetable_ocr as ocr
Week = Literal['odd', 'even']
@@ -42,9 +43,6 @@ class ReprocessSelection(BaseModel):
force_confirmed: bool = False
def now_ms(): return int(time.time() * 1000)
def public_file(row):
structure = json.loads(row['structure'])
for cell in structure['cells']:
@@ -157,7 +155,6 @@ def install(app, get_db, current_user, file_root, collector_emails, admin_key):
structure['cells'] = [{**cell.model_dump(), 'source': 'manual', 'confidence': 1} for cell in payload.cells]
values = {**row, 'structure': json.dumps(structure, ensure_ascii=False), 'updated_at': max(now_ms(), row['updated_at'] + 1),
'confirmed_at': now_ms() if payload.confirm else None}
from sqlalchemy import update
await db.execute(update(timetables).where(timetables.c.user_id == viewer['id'], timetables.c.week_type == week).values(
structure=values['structure'], updated_at=values['updated_at'], confirmed_at=values['confirmed_at']))
await db.commit()
@@ -169,9 +166,9 @@ def install(app, get_db, current_user, file_root, collector_emails, admin_key):
'states': {'busy': '有课', 'free': '无课', 'unknown': '待确认'},
'export': {'url': '/api/timetables/export?format=json&confirmed_only=false', 'header': 'X-Timetable-Admin-Key',
'scope': '管理员密钥验证通过后导出全部课表'},
'privacy': '登录且管理员密钥正确时可导出全部课表;不包含邮箱、手机号和管理员密钥',
'privacy': '登录且管理员密钥正确时可导出全部课表;不包含邮箱、手机号、管理员密钥和 OCR 原文',
'eligibility': '仅已确认课表中的free时段可列为可值班;unknown不能当作空闲',
'scope': '按当前值班时间整理周一至周五的四个时段;完整识别文字另存raw_text,夜间和周末未参与可值班判断'}
'scope': '按当前值班时间整理周一至周五的四个时段;OCR 原文不持久化,夜间和周末不参与可值班判断'}
@app.get('/api/timetables/export')
async def export(request: Request, format: Literal['json', 'csv'] = 'json', confirmed_only: bool = False,
@@ -203,7 +200,7 @@ def install(app, get_db, current_user, file_root, collector_emails, admin_key):
row.update(start=slots[cell['slot']]['start'], end=slots[cell['slot']]['end'], confirmed=bool(record['confirmed_at']),
eligible=bool(record['confirmed_at']) and cell['status'] == 'free', ocr_status=record['ocr_status'],
recognition_failed=record['recognition_failed'])
writer.writerow({key: "'"+value if isinstance(value, str) and value.lstrip().startswith(('=','+','-','@')) else value for key,value in row.items()})
writer.writerow({key: csv_safe_value(value) for key, value in row.items()})
for person in missing:
writer.writerow({key: '' for key in fields} | {'user_id': person['user_id'], 'display_name': person['display_name'],
'department': person['department'], 'week_type': '未提交', 'status': 'missing', 'confirmed': False,