重构共享逻辑并修复值班提醒回执去重
This commit is contained in:
+107
-59
@@ -35,15 +35,17 @@ 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
|
||||
from . import duty_receipts
|
||||
from . import center
|
||||
from . import center_duty
|
||||
from . import center_export
|
||||
from . import timetables as timetable_routes
|
||||
from .models import center_activity_meta
|
||||
from .models import center_activity_meta, center_items, center_loans
|
||||
import json
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent
|
||||
@@ -134,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
|
||||
|
||||
@@ -338,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}$")
|
||||
|
||||
@@ -635,7 +629,7 @@ async def lifespan(_app: FastAPI):
|
||||
|
||||
async def _migrate_legacy(conn) -> None:
|
||||
"""老库平滑升级:users 补 phone 列;username 列允许为空(新注册只靠邮箱识别);
|
||||
activities 的历史 pending 全部放行为 approved。"""
|
||||
activities 的历史 pending 全部放行为 approved;一楼旧借用记录按库存安全迁移。"""
|
||||
def _reflect(sync_conn):
|
||||
insp = inspect(sync_conn)
|
||||
names = insp.get_table_names()
|
||||
@@ -668,6 +662,8 @@ async def _migrate_legacy(conn) -> None:
|
||||
await conn.execute(
|
||||
text("UPDATE activities SET status='approved' WHERE status IN ('pending','rejected')")
|
||||
)
|
||||
if "center_loans" in tables and "center_items" in tables:
|
||||
await _migrate_center_loans(conn)
|
||||
|
||||
if "category" in activity_cols:
|
||||
# SQLite 3.35+ 支持直接 DROP COLUMN
|
||||
@@ -684,13 +680,93 @@ async def _migrate_legacy(conn) -> None:
|
||||
await conn.execute(update(table).where(table.c.token == token).values(token=token_digest(token)))
|
||||
|
||||
|
||||
app = FastAPI(title="WorkLog 活动记录", version="2.0.0", lifespan=lifespan)
|
||||
def center_approvers():
|
||||
values = os.getenv('WORKLOG_CENTER_APPROVERS')
|
||||
emails = values.split(',') if values is not None else cfg('center', 'approver_emails', [])
|
||||
return {email.strip().lower() for email in emails if email.strip()}
|
||||
async def _migrate_center_loans(conn) -> None:
|
||||
"""扩展借出记录以支持与库存无关的登记,并迁移旧待审批记录。"""
|
||||
await _migrate_center_loan_schema(conn)
|
||||
rows = (await conn.execute(
|
||||
select(center_loans)
|
||||
.where(center_loans.c.status == 'pending')
|
||||
.order_by(center_loans.c.created_at, center_loans.c.id)
|
||||
)).mappings().all()
|
||||
if not rows:
|
||||
return
|
||||
totals = dict((await conn.execute(select(center_items.c.id, center_items.c.quantity))).all())
|
||||
active = dict((await conn.execute(
|
||||
select(center_loans.c.item_id, func.coalesce(func.sum(center_loans.c.quantity), 0))
|
||||
.where(center_loans.c.status == 'approved', center_loans.c.returned_at.is_(None))
|
||||
.group_by(center_loans.c.item_id)
|
||||
)).all())
|
||||
for row in rows:
|
||||
if row['returned_at'] is not None:
|
||||
await conn.execute(
|
||||
update(center_loans).where(center_loans.c.id == row['id']).values(status='returned')
|
||||
)
|
||||
continue
|
||||
used = active.get(row['item_id'], 0)
|
||||
available = max(0, totals.get(row['item_id'], 0) - used)
|
||||
if row['quantity'] > 0 and row['quantity'] <= available:
|
||||
await conn.execute(
|
||||
update(center_loans).where(center_loans.c.id == row['id']).values(status='approved')
|
||||
)
|
||||
active[row['item_id']] = used + row['quantity']
|
||||
else:
|
||||
await conn.execute(
|
||||
update(center_loans).where(center_loans.c.id == row['id']).values(
|
||||
status='rejected',
|
||||
reviewed_at=None,
|
||||
review_note='免审批迁移:库存不足,原待审批记录未借出',
|
||||
)
|
||||
)
|
||||
|
||||
center.install(app, get_db, current_user, lambda: _db_path.parent / 'uploads', visible_clause, center_approvers)
|
||||
|
||||
async def _migrate_center_loan_schema(conn) -> None:
|
||||
"""SQLite 中支持库存外登记和登录页免登录借出,同时完整保留历史记录。"""
|
||||
def _inspect(sync_conn):
|
||||
columns = {column["name"]: column for column in inspect(sync_conn).get_columns("center_loans")}
|
||||
item_id = columns.get("item_id")
|
||||
user_id = columns.get("user_id")
|
||||
if not item_id or not user_id:
|
||||
return False
|
||||
required = {"item_name", "guest_name", "guest_phone", "guest_college", "guest_activity_name"}
|
||||
return (
|
||||
not required.issubset(columns)
|
||||
or not item_id.get("nullable", False)
|
||||
or not user_id.get("nullable", False)
|
||||
)
|
||||
|
||||
if not await conn.run_sync(_inspect):
|
||||
return
|
||||
|
||||
legacy = "center_loans_legacy_schema"
|
||||
await conn.execute(text(f"ALTER TABLE center_loans RENAME TO {legacy}"))
|
||||
await conn.run_sync(center_loans.create)
|
||||
source_columns = {
|
||||
column["name"]
|
||||
for column in await conn.run_sync(lambda c: inspect(c).get_columns(legacy))
|
||||
}
|
||||
|
||||
def source(name, fallback="NULL"):
|
||||
return name if name in source_columns else fallback
|
||||
|
||||
await conn.execute(text(f"""
|
||||
INSERT INTO center_loans (
|
||||
id, item_id, item_name, user_id, quantity, reason, contact,
|
||||
guest_name, guest_phone, guest_college, guest_activity_name,
|
||||
created_at, returned_at, status, reviewer_id, reviewed_at, review_note
|
||||
)
|
||||
SELECT
|
||||
id, item_id, {source('item_name')}, user_id, quantity, reason, contact,
|
||||
{source('guest_name')}, {source('guest_phone')}, {source('guest_college')}, {source('guest_activity_name')},
|
||||
created_at, {source('returned_at')}, {source('status', "'approved'")},
|
||||
{source('reviewer_id')}, {source('reviewed_at')}, {source('review_note', "''")}
|
||||
FROM {legacy}
|
||||
"""))
|
||||
await conn.execute(text(f"DROP TABLE {legacy}"))
|
||||
|
||||
|
||||
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)
|
||||
|
||||
def timetable_collectors():
|
||||
@@ -735,6 +811,16 @@ async def security_headers(request: Request, call_next):
|
||||
)
|
||||
if request.url.path.startswith(("/api/", "/join/", "/duty-confirm/", "/mail-test/")):
|
||||
response.headers["Cache-Control"] = "no-store"
|
||||
elif request.method in ("GET", "HEAD") and (
|
||||
request.url.path == "/"
|
||||
or request.url.path.endswith(".html")
|
||||
or not Path(request.url.path).suffix
|
||||
):
|
||||
# 让入口 HTML 每次重新校验,避免新脚本上线后仍被旧页面长期引用。
|
||||
response.headers["Cache-Control"] = "no-cache"
|
||||
elif request.method in ("GET", "HEAD") and Path(request.url.path).suffix in (".js", ".css"):
|
||||
# 前端资源通过 ?v= 更新版本号;保留 ETag 校验以便紧急修复时立即生效。
|
||||
response.headers["Cache-Control"] = "public, max-age=0, must-revalidate"
|
||||
if request.url.path.startswith(("/join/", "/duty-confirm/", "/mail-test/")):
|
||||
kind = "test" if request.url.path.startswith("/mail-test/") else ("duty" if request.url.path.startswith("/duty-confirm/") else "activity")
|
||||
origin_kind = "none" if not origin else ("null" if origin == "null" else ("trusted" if origin in (own_origin, trusted_origin) else "other"))
|
||||
@@ -1451,7 +1537,8 @@ async def remind_duty(payload: DutyRemindIn, viewer: dict = Depends(current_user
|
||||
email = next(iter(recipients))
|
||||
start = datetime.fromtimestamp(shift["start_at"] / 1000, BEIJING)
|
||||
try:
|
||||
sent = await duty_receipts.send_notice(_duty_state(), start.date().isoformat(), {payload.name: [shift["slot"]]}, email, shift["end_at"] / 1000, _send_email, "值班提醒", f"日期:{start:%Y-%m-%d},{start:%H:%M} 开始(北京时间)", _site_base_url())
|
||||
duty_title = data.get("title", "值班提醒")
|
||||
sent = await duty_receipts.send_notice(_duty_state(), start.date().isoformat(), {payload.name: [shift["slot"]]}, email, shift["end_at"] / 1000, _send_email, f"{duty_title}|邮件提醒", f"机构:{data.get('organization', '招生就业服务队')}\n日期:{start:%Y-%m-%d},{start:%H:%M} 开始(北京时间)", _site_base_url())
|
||||
except HTTPException:
|
||||
raise
|
||||
if not sent:
|
||||
@@ -1482,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:
|
||||
@@ -1918,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)
|
||||
|
||||
Reference in New Issue
Block a user