Files
2026-10-29 16:27:16 +08:00

3852 lines
204 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""LinkUp FastAPI backend.
The API intentionally keeps the same JSON contract as the former Node service,
so the existing browser client can switch runtimes without a frontend rewrite.
Database access is asynchronous through SQLAlchemy; the configured driver can
be SQLite, MySQL or PostgreSQL.
"""
from __future__ import annotations
import asyncio
import base64
import hashlib
import hmac
import json
import os
import re
import secrets
import time
import tomllib
import uuid
from datetime import date, datetime, timedelta, timezone
from email.message import EmailMessage
from pathlib import Path
from statistics import mean, median
from typing import Any
import aiosmtplib
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from fastapi import FastAPI, File, HTTPException, Query, Request, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from sqlalchemy import and_, delete, func, insert, inspect, or_, select, text, update
from sqlalchemy.exc import OperationalError
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
try:
from db_schema import (
TABLES, account_sanctions, admin_audit_logs, credit_adjustments, email_verifications, invite_codes,
invite_relations, login_logs, login_verifications, metadata, password_resets,
point_entries, official_task_claims, official_tasks, notifications, reports, sessions, student_verifications,
conversations, messages, chat_send_limits, public_credit_history_audits,
reliability_events,
task_defaults, task_participants, task_proofs, tasks, user_known_ips, user_stats,
users,
)
except ModuleNotFoundError:
from backend.db_schema import (
TABLES, account_sanctions, admin_audit_logs, credit_adjustments, email_verifications, invite_codes,
invite_relations, login_logs, login_verifications, metadata, password_resets,
point_entries, official_task_claims, official_tasks, notifications, reports, sessions, student_verifications,
conversations, messages, chat_send_limits, public_credit_history_audits,
reliability_events,
task_defaults, task_participants, task_proofs, tasks, user_known_ips, user_stats,
users,
)
BASE_DIR = Path(__file__).resolve().parent
def _load_dotenv(path: Path) -> None:
if not path.exists():
return
for raw_line in path.read_text(encoding="utf-8").splitlines():
line = raw_line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, value = line.split("=", 1)
key, value = key.strip(), value.strip().strip("\"'")
if key and key not in os.environ:
os.environ[key] = value
_load_dotenv(BASE_DIR / ".env")
CONFIG_PATH = Path(os.getenv("LINKUP_CONFIG", str(BASE_DIR / "config.toml")))
if not CONFIG_PATH.is_absolute():
CONFIG_PATH = (BASE_DIR / CONFIG_PATH).resolve()
try:
with CONFIG_PATH.open("rb") as handle:
CONFIG = tomllib.load(handle)
except FileNotFoundError:
CONFIG = {}
def cfg(section: str, key: str, default: Any = "") -> Any:
return CONFIG.get(section, {}).get(key, default)
HOST = os.getenv("HOST", str(cfg("app", "host", "0.0.0.0")))
PORT = int(os.getenv("PORT", cfg("app", "port", 34173)))
WORKERS = int(os.getenv("APP_WORKERS", cfg("app", "workers", 2)))
FRONTEND_DIR = (BASE_DIR / str(cfg("app", "frontend_dir", "../dist"))).resolve()
ENVIRONMENT = os.getenv("NODE_ENV", str(cfg("app", "environment", "production")))
TEST_MODE = ENVIRONMENT == "test"
DB_DRIVER = os.getenv("DATABASE_DRIVER", str(cfg("database", "driver", "sqlite"))).lower()
DATABASE_PATH = os.getenv("DATABASE_PATH", str(cfg("database", "path", "./data/linkup.db")))
DATABASE_URL = os.getenv("DATABASE_URL", str(cfg("database", "url", ""))).strip()
if DB_DRIVER == "sqlite":
db_path = Path(DATABASE_PATH)
if not db_path.is_absolute():
db_path = (BASE_DIR / db_path).resolve()
db_path.parent.mkdir(parents=True, exist_ok=True)
DATABASE_URL = f"sqlite+aiosqlite:///{db_path.as_posix()}"
elif DB_DRIVER in {"mysql", "mysql+pymysql", "mysql+asyncmy"}:
DB_DRIVER = "mysql"
if DATABASE_URL.startswith("mysql://"):
DATABASE_URL = "mysql+asyncmy://" + DATABASE_URL[len("mysql://"):]
elif DATABASE_URL.startswith("mysql+pymysql://"):
DATABASE_URL = "mysql+asyncmy://" + DATABASE_URL[len("mysql+pymysql://"):]
if not DATABASE_URL:
raise RuntimeError("DATABASE_URL is required when DATABASE_DRIVER=mysql")
elif DB_DRIVER in {"postgres", "postgresql", "postgresql+asyncpg"}:
DB_DRIVER = "postgresql"
if DATABASE_URL.startswith("postgresql://"):
DATABASE_URL = "postgresql+asyncpg://" + DATABASE_URL[len("postgresql://"):]
if not DATABASE_URL:
raise RuntimeError("DATABASE_URL is required when DATABASE_DRIVER=postgresql")
else:
raise RuntimeError("DATABASE_DRIVER must be sqlite, mysql or postgresql")
POOL_SIZE = int(os.getenv("DB_POOL_SIZE", cfg("database", "pool_size", 20)))
MAX_OVERFLOW = int(os.getenv("DB_MAX_OVERFLOW", cfg("database", "max_overflow", 40)))
POOL_RECYCLE = int(os.getenv("DB_POOL_RECYCLE", cfg("database", "pool_recycle", 1800)))
SMTP_HOST = os.getenv("SMTP_HOST", str(cfg("smtp", "host", "smtp.163.com")))
SMTP_PORT = int(os.getenv("SMTP_PORT", cfg("smtp", "port", 465)))
SMTP_USER = os.getenv("SMTP_USER", str(cfg("smtp", "user", "")))
SMTP_PASS = os.getenv("SMTP_PASS", str(cfg("smtp", "password", "")))
PROOF_DIR = Path(os.getenv("TASK_PROOF_DIR", str(cfg("storage", "proof_dir", "./data/task-proofs"))))
if not PROOF_DIR.is_absolute():
PROOF_DIR = (BASE_DIR / PROOF_DIR).resolve()
MAX_PROOF_BYTES = int(os.getenv("TASK_PROOF_MAX_MB", cfg("storage", "max_proof_mb", 8))) * 1024 * 1024
PROOF_DIR.mkdir(parents=True, exist_ok=True)
OTP_PEPPER = os.getenv("OTP_PEPPER", str(cfg("security", "otp_pepper", "")))
ADMIN_EMAILS = {
item.strip().lower()
for item in os.getenv("ADMIN_EMAILS", str(cfg("security", "admin_emails", ""))).split(",")
if item.strip()
}
FRONTEND_ORIGIN = os.getenv("FRONTEND_ORIGIN", str(cfg("security", "frontend_origin", ""))).strip()
ADMIN_SANCTION_CONTACT = str(cfg("security", "sanction_contact", "管理员联系方式待配置")).strip() or "管理员联系方式待配置"
PRIVACY_POLICY_VERSION = "v1.2"
PRIVACY_POLICY = {
"version": PRIVACY_POLICY_VERSION,
"effectiveAt": "2026-09-21",
"title": "LinkUp 用户隐私政策",
"sections": [
{"title": "一、我们收集什么信息", "content": "注册时收集姓名、昵称、学号、学校和邮箱;使用快递代取时收集手机号、取件码、取件点、送达位置,以及接单人提交的取件照片和送达照片等任务信息;为保障账号安全,记录登录 IP、设备与浏览器信息;举报、认证和客服过程会保留必要的处理记录。"},
{"title": "二、我们如何使用信息", "content": "用于完成邮箱验证、校园分区、任务匹配、积分结算、信用与安全风控、学生身份认证、举报处理和服务通知。快递任务完成时,两张交付凭证会发送至发布者注册邮箱,用于核对单号、包裹外观和送达位置。对外展示以昵称、学校、信用分、失信率等必要信息为主,不公开身份证号、邮箱验证码、取件码和任务凭证照片等敏感信息。信用调整记录将以脱敏形式(变动分值与调整类型,不含详细原因)在公开主页展示。"},
{"title": "三、信息共享", "content": "我们不会出售个人信息。完成任务所必需的信息只会在任务双方之间按权限展示;如发生安全事件、违法举报或法律要求,我们可能依法向学校、平台合作方或有关机关提供必要信息。"},
{"title": "四、保存与删除", "content": "账号存续期间保存账号、任务和积分记录;认证、举报及财务相关记录按业务和法律要求保留。你可以通过客服申请更正或删除可删除的信息,法律要求保留的记录除外。"},
{"title": "五、信息安全", "content": "我们采取访问控制、验证码保护、密码单向散列和敏感认证信息加密等措施。请妥善保管邮箱、密码和取件信息,发现异常请立即举报或联系客服。"},
{"title": "六、联系我们", "content": "如需查询、更正、删除个人信息或提出隐私问题,请通过 LinkUp 客服联系平台管理员。隐私政策更新后,我们会在页面提示并在必要时重新征得同意。"},
],
}
CREDIT_CATEGORIES = ("违约处理", "违规处理", "奖励", "邀请连带", "更正")
ADMIN_CREDIT_REASONS = (
{"value": "task_owner_completion", "label": "任务正常完成—发单者", "defaultDelta": 1, "category": "奖励", "taskRequired": True},
{"value": "task_claimer_completion", "label": "任务正常完成—接单者", "defaultDelta": 2, "category": "奖励", "taskRequired": True},
{"value": "cancel_early", "label": "距截止时间 2 小时及以上取消", "defaultDelta": 0, "category": "更正", "taskRequired": True},
{"value": "cancel_late", "label": "距截止时间不足 2 小时取消", "defaultDelta": -3, "category": "违约处理", "taskRequired": True, "breach": True},
{"value": "no_show", "label": "无故未履约、超时或失联", "defaultDelta": -8, "category": "违约处理", "taskRequired": True, "breach": True},
{"value": "fraud", "label": "虚假完成、冒领或伪造凭证", "defaultDelta": -15, "category": "违规处理", "taskRequired": True, "breach": True},
{"value": "appeal_upheld", "label": "申诉成立,撤销原处罚(按原处罚恢复)", "defaultDelta": None, "category": "更正", "reversalRequired": True},
{"value": "invite_abuse", "label": "查实恶意邀请或串通违规", "defaultDelta": -1, "category": "邀请连带", "inviteeRequired": True},
{"value": "other", "label": "其他", "defaultDelta": None, "category": "更正", "noteRequired": True},
)
CHAT_MESSAGE_MAX_LENGTH = 200
CHAT_MESSAGES_PER_HOUR = 30
INVITE_WITHDRAWABLE_THRESHOLD = 80
NORMAL_COMPLETION_CREDIT_CAP_7D = 5
BREACH_RATE_WINDOW_DAYS = 90
BREACH_RATE_MIN_COMMITMENTS = 3
ACCOUNT_SANCTION_CATEGORIES = ("多次失约", "涉嫌欺诈", "骚扰他人", "其他违规")
SANCTION_SCOPES = ("publish", "claim", "withdraw")
LOGIN_LOG_RETENTION_MS = 90 * 24 * 60 * 60_000
CANCELLATION_WINDOW_DAYS = 30
CANCELLATION_LIMIT = 3
CANCELLATION_RESTRICTION_DAYS = 7
RIDER_CANCELLATION_COOLDOWN_MS = 30 * 60_000
PUBLISHER_CANCELLATION_GRACE_MS = 10 * 60_000
def invite_threshold_reached(stats: dict[str, Any]) -> bool:
return int(stats.get("withdrawable_points") or 0) >= INVITE_WITHDRAWABLE_THRESHOLD
engine_kwargs: dict[str, Any] = {"pool_pre_ping": True, "pool_recycle": POOL_RECYCLE}
if DB_DRIVER == "sqlite":
engine_kwargs["connect_args"] = {"check_same_thread": False, "timeout": 60}
else:
engine_kwargs.update(pool_size=POOL_SIZE, max_overflow=MAX_OVERFLOW)
engine = create_async_engine(DATABASE_URL, **engine_kwargs)
SessionLocal = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
app = FastAPI(title="LinkUp API", version="0.2.0")
app.add_middleware(
CORSMiddleware,
allow_origins=[FRONTEND_ORIGIN] if FRONTEND_ORIGIN else ["*"],
allow_credentials=False,
allow_methods=["*"],
allow_headers=["*"],
)
SCHOOL_OPTIONS = [
"山东管理学院", "山东大学", "中国海洋大学", "中国石油大学(华东)", "青岛大学", "济南大学",
"山东师范大学", "山东财经大学", "山东科技大学", "青岛科技大学", "青岛理工大学", "山东建筑大学",
"齐鲁工业大学", "山东农业大学", "山东中医药大学", "曲阜师范大学", "烟台大学", "鲁东大学",
"聊城大学", "临沂大学", "青岛农业大学", "潍坊学院", "滨州学院", "德州学院", "菏泽学院",
"北京大学", "清华大学", "中国人民大学", "北京师范大学", "复旦大学", "上海交通大学",
"浙江大学", "南京大学", "武汉大学", "华中科技大学", "中山大学", "四川大学", "厦门大学",
]
EMAIL_PATTERN = re.compile(r"^[^\s@]+@[^\s@]+\.[^\s@]+$")
STUDENT_ID_PATTERN = re.compile(r"^[A-Za-z0-9_-]{4,32}$")
SEND_WINDOWS: dict[str, list[int]] = {}
VERIFICATION_KEY = hashlib.sha256(f"{OTP_PEPPER}:student-verification".encode()).digest()
# 密码登录风控参数。旧账号的 password_hash 为空时仍保留邮箱验证码登录。
TRUST_PROXY = os.getenv(
"TRUST_PROXY", os.getenv("TRUST_PROXY_HEADERS", str(cfg("security", "trust_proxy", "false")))
).strip().lower() in {"1", "true", "yes", "on"}
PBKDF2_ITERATIONS = 200_000
LOGIN_FAILURE_LIMIT = 5
LOGIN_FAILURE_WINDOW_MS = 15 * 60 * 1000
RISK_FAILURE_THRESHOLD = 2
KNOWN_IPS_PER_USER = 8
login_failures: dict[str, list[int]] = {}
# 积分钱包规则:充值 1 元 = 100 积分;提现按 100 积分 = 0.75 元结算。
# 提现支持任意正整数积分,到账金额按人民币分向下取整,避免浮点误差。
POINTS_PER_YUAN = 100
WITHDRAW_MIN_POINTS = 1
WITHDRAW_CENTS_PER_100_POINTS = 75
def now_ms() -> int:
return int(time.time() * 1000)
def normalize(value: Any) -> str:
return str(value or "").strip()
def normalize_email(value: Any) -> str:
return normalize(value).lower()
def new_id() -> str:
return str(uuid.uuid4())
def is_admin(user: dict[str, Any]) -> bool:
return normalize_email(user.get("email")) in ADMIN_EMAILS
def hash_code(email: str, code: str) -> str:
return hmac.new(OTP_PEPPER.encode(), f"{email}:{code}".encode(), hashlib.sha256).hexdigest()
def hash_token(token: str) -> str:
return hashlib.sha256(token.encode()).hexdigest()
def client_ip(request: Request) -> str:
"""取得客户端 IP;反向代理部署时读取可信代理透传的地址。"""
if TRUST_PROXY:
real_ip = request.headers.get("x-real-ip")
if real_ip:
return real_ip.strip()[:64]
forwarded = request.headers.get("x-forwarded-for")
if forwarded:
first = forwarded.split(",")[0].strip()
if first:
return first[:64]
return request.client.host if request.client else "unknown"
def hash_password(password: str) -> str:
salt = secrets.token_hex(16)
digest = hashlib.pbkdf2_hmac(
"sha256", password.encode(), salt.encode(), PBKDF2_ITERATIONS
).hex()
return f"pbkdf2_sha256${PBKDF2_ITERATIONS}${salt}${digest}"
def verify_password(password: str, stored: str) -> bool:
try:
algo, iterations, salt, digest = str(stored).split("$", 3)
if algo != "pbkdf2_sha256":
return False
candidate = hashlib.pbkdf2_hmac(
"sha256", password.encode(), salt.encode(), int(iterations)
).hex()
return hmac.compare_digest(candidate, digest)
except (TypeError, ValueError):
return False
def recent_login_failures(ip: str) -> int:
stamps = [stamp for stamp in login_failures.get(ip, []) if now_ms() - stamp < LOGIN_FAILURE_WINDOW_MS]
login_failures[ip] = stamps
return len(stamps)
def record_login_failure(ip: str) -> None:
recent_login_failures(ip)
login_failures.setdefault(ip, []).append(now_ms())
def mask_email(email: str) -> str:
name, _, domain = email.partition("@")
return f"{name[:2]}***@{domain}" if name else email
async def write_login_log(
db: AsyncSession, request: Request, *, user_id: str | None, email: str,
success: bool, method: str,
) -> None:
timestamp = now_ms()
await db.execute(insert(login_logs).values(
id=new_id(), user_id=user_id,
email_attempted=mask_email(email) if email else None,
success=bool(success), method=method,
ip=client_ip(request)[:64], user_agent=request.headers.get("user-agent", "")[:400],
created_at=timestamp,
))
await db.execute(delete(login_logs).where(login_logs.c.created_at < timestamp - LOGIN_LOG_RETENTION_MS))
async def is_known_ip(db: AsyncSession, user_id: str, ip: str) -> bool:
return bool(await one(db, select(user_known_ips).where(and_(
user_known_ips.c.user_id == user_id, user_known_ips.c.ip == ip,
))))
async def mark_known_ip(db: AsyncSession, user_id: str, ip: str) -> None:
timestamp = now_ms()
key = and_(user_known_ips.c.user_id == user_id, user_known_ips.c.ip == ip)
if await one(db, select(user_known_ips).where(key)):
await db.execute(update(user_known_ips).where(key).values(last_seen=timestamp))
return
known = await all_rows(
db,
select(user_known_ips).where(user_known_ips.c.user_id == user_id)
.order_by(user_known_ips.c.last_seen.desc()),
)
if len(known) >= KNOWN_IPS_PER_USER:
oldest = known[-1]["ip"]
await db.execute(delete(user_known_ips).where(and_(
user_known_ips.c.user_id == user_id, user_known_ips.c.ip == oldest,
)))
await db.execute(insert(user_known_ips).values(
user_id=user_id, ip=ip, first_seen=timestamp, last_seen=timestamp,
))
def valid_school(value: str, preferred: str = "") -> bool:
return bool(value and (value in SCHOOL_OPTIONS or (preferred and value == preferred)))
def json_load(value: Any, fallback: Any = None) -> Any:
if not value:
return fallback
try:
return json.loads(value)
except (TypeError, ValueError):
return fallback
async def one(db: AsyncSession, statement) -> dict[str, Any] | None:
row = (await db.execute(statement)).mappings().first()
return dict(row) if row else None
async def all_rows(db: AsyncSession, statement) -> list[dict[str, Any]]:
return [dict(row) for row in (await db.execute(statement)).mappings().all()]
async def deduct_points(
db: AsyncSession, user_id: str, amount: int, *, timestamp: int | None = None,
) -> int | None:
"""Deduct locked points first, then free points; caller owns the transaction."""
amount = int(amount)
if amount < 0:
raise ValueError("amount must not be negative")
# SQLite ignores FOR UPDATE, so reserve its writer slot before reading.
await db.execute(update(user_stats).where(
user_stats.c.user_id == user_id,
).values(updated_at=user_stats.c.updated_at))
stats = await one(db, select(user_stats).where(
user_stats.c.user_id == user_id,
).with_for_update())
if not stats:
return None
balance = int(stats["points_balance"] or 0)
withdrawable = int(stats["withdrawable_points"] or 0)
if not 0 <= withdrawable <= balance:
return None
if amount == 0:
return 0
if balance < amount:
return None
locked_part = min(max(0, balance - withdrawable), amount)
free_part = amount - locked_part
result = await db.execute(update(user_stats).where(and_(
user_stats.c.user_id == user_id,
user_stats.c.points_balance >= amount,
user_stats.c.withdrawable_points >= free_part,
)).values(
points_balance=user_stats.c.points_balance - amount,
withdrawable_points=user_stats.c.withdrawable_points - free_part,
updated_at=timestamp if timestamp is not None else now_ms(),
))
return free_part if result.rowcount else None
async def stats_for(db: AsyncSession, user_id: str) -> dict[str, Any]:
row = await one(db, select(user_stats).where(user_stats.c.user_id == user_id))
if row:
return row
timestamp = now_ms()
await db.execute(insert(user_stats).values(user_id=user_id, points_balance=750, credit_score=70, updated_at=timestamp))
await db.commit()
return {"user_id": user_id, "points_balance": 750, "withdrawable_points": 0, "credit_score": 70,
"breach_count": 0, "commitments_count": 0, "completed_tasks": 0, "current_streak": 0, "updated_at": timestamp}
async def reliability_summary(db: AsyncSession, user_id: str) -> dict[str, Any]:
cutoff = now_ms() - BREACH_RATE_WINDOW_DAYS * 24 * 60 * 60_000
commitments = int(await db.scalar(select(func.count()).select_from(tasks).where(and_(
tasks.c.claimed_at >= cutoff, or_(tasks.c.user_id == user_id, tasks.c.claimer_id == user_id),
))) or 0)
breaches = int(await db.scalar(select(func.count(func.distinct(reliability_events.c.task_id))).where(and_(
reliability_events.c.user_id == user_id, reliability_events.c.kind == "breach",
reliability_events.c.status == "confirmed", reliability_events.c.task_id.is_not(None),
reliability_events.c.created_at >= cutoff,
))) or 0)
rate = round(breaches / commitments * 1000) / 10 if commitments >= BREACH_RATE_MIN_COMMITMENTS else None
return {
"breachRate": rate, "breachRateLabel": f"{rate:.1f}%" if rate is not None else "记录较少",
"breachCount90d": breaches, "commitments90d": commitments,
"windowDays": BREACH_RATE_WINDOW_DAYS,
}
async def record_credit_change(
db: AsyncSession, user_id: str, requested_delta: int, category: str, reason: str,
*, actor_id: str = "system", task_id: str | None = None, invitee_id: str | None = None,
rule_key: str | None = None,
note: str | None = None, reverses_id: str | None = None,
) -> dict[str, Any]:
# SQLite ignores SELECT FOR UPDATE; this harmless write acquires its
# transaction write lock before applying score caps or idempotency checks.
await db.execute(update(user_stats).where(user_stats.c.user_id == user_id).values(
updated_at=user_stats.c.updated_at,
))
stats = await one(db, select(user_stats).where(user_stats.c.user_id == user_id).with_for_update())
if not stats:
timestamp = now_ms()
await db.execute(insert(user_stats).values(
user_id=user_id, points_balance=750, credit_score=70, updated_at=timestamp,
))
stats = {"credit_score": 70, "breach_count": 0}
# Serialize same-user idempotency checks with the locked stats row.
if rule_key:
existing = await one(db, select(credit_adjustments).where(credit_adjustments.c.rule_key == rule_key))
if existing:
return {"id": existing["id"], "delta": int(existing["delta"]),
"before": existing["before_score"], "after": existing["after_score"], "duplicate": True}
requested_delta = int(requested_delta)
if rule_key and rule_key.startswith("task-completion:") and requested_delta > 0:
week_cutoff = now_ms() - 7 * 24 * 60 * 60_000
given = int(await db.scalar(select(func.coalesce(func.sum(credit_adjustments.c.delta), 0)).where(and_(
credit_adjustments.c.user_id == user_id,
credit_adjustments.c.rule_key.like("task-completion:%"),
credit_adjustments.c.created_at >= week_cutoff,
))) or 0)
requested_delta = min(requested_delta, max(0, NORMAL_COMPLETION_CREDIT_CAP_7D - given))
before = max(0, min(100, int(stats.get("credit_score") or 0)))
after = max(0, min(100, before + requested_delta))
applied = after - before
timestamp = now_ms()
adjustment_id = new_id()
await db.execute(update(user_stats).where(user_stats.c.user_id == user_id).values(
credit_score=after, updated_at=timestamp,
**({"breach_count": user_stats.c.breach_count + 1}
if rule_key and rule_key.startswith(("task-cancel-short:", "task-publisher-cancel-picked:")) else {}),
))
await db.execute(insert(credit_adjustments).values(
id=adjustment_id, user_id=user_id, admin_id=actor_id, delta=applied,
reason=reason[:400], category=category, before_score=before, after_score=after,
task_id=task_id, invitee_id=invitee_id, rule_key=rule_key, note=(note or "")[:400] or None,
reverses_id=reverses_id, created_at=timestamp,
))
return {"id": adjustment_id, "delta": applied, "before": before, "after": after, "duplicate": False}
async def record_reliability_event(
db: AsyncSession, *, event_key: str, user_id: str, kind: str, status: str,
task_id: str | None = None, invitee_id: str | None = None,
adjustment_id: str | None = None, reviewed_by: str | None = None,
note: str | None = None, timestamp: int | None = None,
) -> None:
if await one(db, select(reliability_events.c.id).where(reliability_events.c.event_key == event_key)):
return
await db.execute(insert(reliability_events).values(
id=new_id(), event_key=event_key, user_id=user_id, task_id=task_id,
invitee_id=invitee_id, kind=kind, status=status, adjustment_id=adjustment_id,
created_at=timestamp or now_ms(), reviewed_by=reviewed_by,
note=(note or "")[:400] or None,
))
async def apply_cancellation_frequency_limit(
db: AsyncSession, *, user_id: str, role: str, timestamp: int,
) -> bool:
"""Apply separate rolling cancellation limits for publishers and riders."""
cutoff = timestamp - CANCELLATION_WINDOW_DAYS * 24 * 60 * 60_000
role_match = tasks.c.user_id == user_id if role == "publisher" else tasks.c.claimer_id == user_id
count = int(await db.scalar(select(func.count()).select_from(tasks).where(and_(
tasks.c.status == "cancelled", tasks.c.cancelled_by == user_id,
tasks.c.cancelled_at >= cutoff, role_match,
))) or 0)
if count < CANCELLATION_LIMIT:
return False
await db.execute(update(user_stats).where(user_stats.c.user_id == user_id).values(
updated_at=user_stats.c.updated_at,
))
stats = await one(db, select(user_stats).where(user_stats.c.user_id == user_id).with_for_update())
field = "publish_restricted_until" if role == "publisher" else "claim_restricted_until"
if not stats or int(stats.get(field) or 0) > timestamp:
return False
await db.execute(update(user_stats).where(user_stats.c.user_id == user_id).values(
**{field: timestamp + CANCELLATION_RESTRICTION_DAYS * 24 * 60 * 60_000},
updated_at=timestamp,
))
return True
async def settle_task_completion_credit(db: AsyncSession, task: dict[str, Any]) -> dict[str, dict[str, Any]]:
user_ids = [task["user_id"], task.get("claimer_id")]
user_ids = sorted({user_id for user_id in user_ids if user_id})
dispute = await db.scalar(select(reports.c.id).where(and_(
reports.c.target_type == "task", reports.c.target_id == task["id"], reports.c.status == "open",
)).limit(1))
if dispute:
for user_id in user_ids:
await record_reliability_event(
db, event_key=f"completion-review:{task['id']}:{user_id}",
user_id=user_id, task_id=task["id"], kind="completion_review",
status="pending", note="任务有待处理举报,完成信用分待管理员核实。",
)
return {}
results: dict[str, dict[str, Any]] = {}
for user_id in user_ids:
is_owner = user_id == task["user_id"]
base_delta = 1 if is_owner else 2
role = "发单者" if is_owner else "接单者"
result = await record_credit_change(
db, user_id, base_delta, "奖励", f"任务正常完成—{role}",
task_id=task["id"], rule_key=f"task-completion:{task['id']}:{user_id}",
)
results[user_id] = result
if result["delta"] and not result["duplicate"]:
await add_notification(
db, user_id, "credit_adjusted", "任务完成信用奖励",
f"任务完成—{role},信用分 {result['delta']:+d}(当前 {result['after']} 分)。",
f"task:{task['id']}",
)
return results
async def verification_summary(db: AsyncSession, user_id: str) -> dict[str, Any]:
record = await one(db, select(student_verifications).where(student_verifications.c.user_id == user_id))
# 人脸识别尚未上线;接入其可信数据源时只需替换此凭证值。
face_verified = False
expired = bool(record and record["status"] == "approved" and record["report_expires_on"] < datetime.now().strftime("%Y-%m-%d"))
chsi_verified = bool(record and record["status"] == "approved" and not expired)
level = 3 if chsi_verified and face_verified else 2 if chsi_verified or face_verified else 1
label = "双重认证" if level == 3 else "学信网已认证" if chsi_verified else "人脸已认证" if face_verified else "邮箱已验证"
if not record:
return {"level": level, "status": "unsubmitted", "label": label, "faceVerified": face_verified}
return {
"level": level,
"status": "expired" if expired else record["status"],
"label": label,
"faceVerified": face_verified,
"reportExpiresOn": record["report_expires_on"],
"submittedAt": record["submitted_at"],
**({"reviewNote": record["review_note"]} if record["status"] == "rejected" else {}),
"codeLast4": record["online_code_last4"],
}
async def public_user(db: AsyncSession, row: dict[str, Any]) -> dict[str, Any]:
stats = await stats_for(db, row["id"])
verification = await verification_summary(db, row["id"])
reliability = await reliability_summary(db, row["id"])
return {
"id": row["id"], "name": row["name"], "nickname": row["nickname"],
"studentId": row["student_id"], "school": row["school"], "email": row["email"],
"createdAt": row["created_at"],
"stats": {
"pointsBalance": int(stats.get("points_balance", 0)),
"withdrawablePoints": int(stats.get("withdrawable_points", 0)),
"creditScore": int(stats.get("credit_score", 70)),
**reliability,
"completedTasks": int(stats.get("completed_tasks", 0)),
"currentStreak": int(stats.get("current_streak", 0)),
},
"verification": verification,
"isAdmin": is_admin(row),
}
async def current_user(request: Request, db: AsyncSession, *, include_banned: bool = False) -> dict[str, Any] | None:
header = normalize(request.headers.get("authorization"))
if not header.startswith("Bearer "):
return None
token_hash = hash_token(header[7:].strip())
stmt = select(
users.c.id, users.c.name, users.c.nickname, users.c.student_id,
users.c.school, users.c.email, users.c.email_verified_at, users.c.created_at,
users.c.status, users.c.status_until,
sessions.c.id.label("session_id"), sessions.c.expires_at,
).select_from(sessions.join(users, users.c.id == sessions.c.user_id)).where(sessions.c.token_hash == token_hash)
row = await one(db, stmt)
if not row or int(row["expires_at"]) < now_ms():
return None
await refresh_account_status(db, row)
await db.commit()
if row.get("status") == "banned":
if row.get("status_until") is None or int(row["status_until"]) > now_ms():
return row if include_banned else None
return row
async def require_user(request: Request, db: AsyncSession) -> dict[str, Any]:
user = await current_user(request, db)
if not user:
raise HTTPException(401, "请先登录")
return user
async def refresh_account_status(db: AsyncSession, user: dict[str, Any], timestamp: int | None = None) -> dict[str, Any]:
timestamp = timestamp or now_ms()
active = await all_rows(db, select(account_sanctions).where(and_(
account_sanctions.c.user_id == user["id"],
account_sanctions.c.action.in_(("ban", "restrict")),
account_sanctions.c.lifted_at.is_(None),
or_(account_sanctions.c.expires_at.is_(None), account_sanctions.c.expires_at > timestamp),
)).order_by(account_sanctions.c.created_at.desc()))
bans = [item for item in active if item["action"] == "ban"]
restrictions = [item for item in active if item["action"] == "restrict"]
if bans:
status, status_until = "banned", bans[0].get("expires_at")
elif restrictions:
status = "restricted"
status_until = None if any(item.get("expires_at") is None for item in restrictions) else max(int(item["expires_at"]) for item in restrictions)
else:
status, status_until = "active", None
if user.get("status") != status or user.get("status_until") != status_until:
await db.execute(update(users).where(users.c.id == user["id"]).values(
status=status, status_until=status_until,
))
user["status"], user["status_until"] = status, status_until
return user
async def ensure_not_sanctioned(db: AsyncSession, user: dict[str, Any], scope: str) -> None:
timestamp = now_ms()
sanction = await one(db, select(account_sanctions).where(and_(
account_sanctions.c.user_id == user["id"], account_sanctions.c.action == "restrict",
account_sanctions.c.scope == scope, account_sanctions.c.lifted_at.is_(None),
or_(account_sanctions.c.expires_at.is_(None), account_sanctions.c.expires_at > timestamp),
)).order_by(account_sanctions.c.created_at.desc()).limit(1))
if sanction:
expires = sanction.get("expires_at")
if expires:
date = datetime.fromtimestamp(int(expires) / 1000, tz=timezone.utc).astimezone().strftime("%Y-%m-%d")
raise HTTPException(403, f"该功能已被限制至 {date}")
raise HTTPException(403, "该功能已被永久限制,请联系平台管理员")
async def send_mail(to: str, code: str, scene: str = "register") -> None:
if TEST_MODE:
return
if not SMTP_USER or not SMTP_PASS:
raise HTTPException(503, "邮件服务尚未配置")
message = EmailMessage()
message["From"] = f"LinkUp 校园互助 <{SMTP_USER}>"
message["To"] = to
subjects = {"register": "注册验证码", "login": "登录验证码", "reset": "重置密码验证码"}
message["Subject"] = f"LinkUp {subjects.get(scene, '验证码')}"
message.set_content(f"你的 LinkUp 验证码是:{code}。验证码 10 分钟内有效,请勿转发给他人。")
await aiosmtplib.send(
message, hostname=SMTP_HOST, port=SMTP_PORT, username=SMTP_USER,
password=SMTP_PASS, use_tls=SMTP_PORT == 465, timeout=20,
)
PROOF_KINDS = {
"pickup": "取件照片",
"delivery": "送达照片",
}
# 跑腿代办类目注册表:第一版为静态枚举,新增类目只需在此登记字段、
# 文案与标题生成;接单/凭证/结算流水线按 type='errand' 统一复用。
# 平台只结算积分,不做任何真实资金托管;涉及垫付的类目仅在表单与
# 详情页展示 advance_notice 提示线下当面结算。
ERRAND_CATEGORIES: dict[str, dict[str, Any]] = {
"快递代取": {
"points": (200, 1500),
"pickup_codes": True,
"require": ("phone", "pickupPlace", "destination"),
"missing": "请填写取件地点、送达位置和取件码",
"title": lambda school, v: f"{school} · {v['pickupPlace']} → {v['destination']}",
"detail": lambda v: f"校内送到 {v['destination']}",
"note": lambda v: ";".join(item for item in [
f"快递描述:{v['sizeDesc']}" if v.get("sizeDesc") else "",
f"共 {len(v['pickupCodes'])} 个取件码" if len(v["pickupCodes"]) > 1 else "",
v.get("note", ""),
] if item) or None,
"defaults": {"pickup_place": "pickupPlace", "destination": "destination"},
"proof_labels": {"pickup": "取件照片", "delivery": "送达照片"},
"proof_intro": "取件时拍清快递单号和包裹外观;送到宿舍楼下后拍清送达位置和包裹完好情况。",
"email_note": "邮件附件包含接单人在快递站拍摄的取件照片,以及送达指定位置后拍摄的送达照片。请核对快递单号、取件前外观、送达位置和包裹完好情况。",
"advance_notice": None,
},
"带饭代买": {
"points": (200, 1500),
"require": ("phone", "shop", "destination"),
"missing": "请填写购买店铺和送达位置",
"title": lambda school, v: f"{school} · {v['shop']} → {v['destination']}",
"detail": lambda v: f"带买并送达 {v['destination']}",
"note": lambda v: ";".join(item for item in [
f"物品描述:{v['items']}" if v.get("items") else "",
v.get("note", ""),
] if item) or None,
"defaults": {"pickup_place": "shop", "destination": "destination"},
"proof_labels": {"pickup": "取餐照片", "delivery": "送达照片"},
"proof_intro": "取餐后拍清店铺名和物品外观;送达后拍清交付位置和餐品完好情况。",
"email_note": "邮件附件包含接单人在店铺拍摄的取餐照片,以及送达指定位置后拍摄的送达照片。请核对餐品数量、外观和送达位置。",
"advance_notice": "物品费用请线下当面结算,平台不提供资金托管",
},
"代排队": {
"points": (200, 1500),
"require": ("phone", "queuePlace", "matter"),
"missing": "请填写排队地点和事项描述",
"title": lambda school, v: f"{school} · {v['queuePlace']} 代排队",
"detail": lambda v: v["matter"],
"note": lambda v: ";".join(item for item in [
f"时段说明:{v['timeSlot']}" if v.get("timeSlot") else "",
v.get("note", ""),
] if item) or None,
"defaults": {"pickup_place": "queuePlace", "destination": None},
"proof_labels": {"pickup": "排队现场照片", "delivery": "办理完成照片"},
"proof_intro": "排到后拍清现场叫号或所在位置;办理完成后拍清办理结果。",
"email_note": "邮件附件包含接单人在现场拍摄的排队照片,以及办理完成后拍摄的结果照片。请核对办理结果与约定一致。",
"advance_notice": None,
},
"代打印/文件取送": {
"points": (200, 1500),
"require": ("phone", "pickupPlace", "destination"),
"missing": "请填写取件地点和交付位置",
"title": lambda school, v: f"{school} · {v['pickupPlace']} → {v['destination']}",
"detail": lambda v: f"送达 {v['destination']}",
"note": lambda v: ";".join(item for item in [
f"打印要求:{v['requirement']}" if v.get("requirement") else "",
v.get("note", ""),
] if item) or None,
"defaults": {"pickup_place": "pickupPlace", "destination": "destination"},
"proof_labels": {"pickup": "取件照片", "delivery": "送达照片"},
"proof_intro": "取件时拍清文件包装和份数;送达后拍清交付位置和文件完好情况。",
"email_note": "邮件附件包含接单人取件时拍摄的照片,以及送达指定位置后拍摄的照片。请核对文件份数、装订和完好情况。",
"advance_notice": "打印材料等费用请线下当面结算,平台不提供资金托管",
},
}
ERRAND_TYPE = "errand"
def errand_spec(task_or_category: Any) -> dict[str, Any]:
"""按任务行或类目名取注册表项;未知类目回落快递代取的通用文案。"""
category = task_or_category.get("category") if isinstance(task_or_category, dict) else task_or_category
return ERRAND_CATEGORIES.get(category) or ERRAND_CATEGORIES["快递代取"]
def detect_proof_image(data: bytes) -> tuple[str, str] | None:
"""按文件头识别允许的图片类型,不能只信任浏览器上传的 Content-Type。"""
if data.startswith(b"\xff\xd8\xff"):
return ".jpg", "image/jpeg"
if data.startswith(b"\x89PNG\r\n\x1a\n"):
return ".png", "image/png"
if len(data) >= 12 and data[:4] == b"RIFF" and data[8:12] == b"WEBP":
return ".webp", "image/webp"
return None
async def send_task_proof_email(to: str, task_title: str,
proof_files: list[tuple[str, Path, str]],
category: str = "快递代取") -> None:
"""任务完成前,将两张凭证照作为附件发给任务发布者。"""
if TEST_MODE:
return
if not SMTP_USER or not SMTP_PASS:
raise HTTPException(503, "邮件服务尚未配置,暂时不能完成任务")
spec = errand_spec(category)
message = EmailMessage()
message["From"] = f"LinkUp 校园互助 <{SMTP_USER}>"
message["To"] = to
message["Subject"] = f"LinkUp {category}完成凭证"
message.set_content(
f"你的{category}任务“{task_title}”已完成。\n\n"
f"{spec['email_note']}\n\n"
"如发现异常,请及时在 LinkUp 任务详情中举报。"
)
for label, path, mime_type in proof_files:
data = await asyncio.to_thread(path.read_bytes)
_, subtype = mime_type.split("/", 1)
message.add_attachment(data, maintype="image", subtype=subtype,
filename=f"{label}{path.suffix.lower()}")
await aiosmtplib.send(
message, hostname=SMTP_HOST, port=SMTP_PORT, username=SMTP_USER,
password=SMTP_PASS, use_tls=SMTP_PORT == 465, timeout=30,
)
async def issue_session(db: AsyncSession, user_id: str, request: Request | None = None) -> str:
token = secrets.token_urlsafe(32)
timestamp = now_ms()
await db.execute(delete(sessions).where(sessions.c.expires_at < timestamp))
await db.execute(insert(sessions).values(
id=new_id(), user_id=user_id, token_hash=hash_token(token),
expires_at=timestamp + 30 * 24 * 60 * 60_000, created_at=timestamp,
ip=client_ip(request) if request else None,
user_agent=(request.headers.get("user-agent", "")[:400] if request else None),
))
await db.commit()
return token
def encrypt_verification(value: str) -> tuple[str, str, str]:
iv = secrets.token_bytes(12)
encrypted = AESGCM(VERIFICATION_KEY).encrypt(iv, value.encode(), None)
return (
base64.urlsafe_b64encode(encrypted[:-16]).decode().rstrip("="),
base64.urlsafe_b64encode(iv).decode().rstrip("="),
base64.urlsafe_b64encode(encrypted[-16:]).decode().rstrip("="),
)
def decrypt_verification(record: dict[str, Any]) -> str:
def decode(value: str) -> bytes:
return base64.urlsafe_b64decode(str(value) + "=" * (-len(str(value)) % 4))
encrypted = decode(record["online_code_cipher"]) + decode(record["online_code_tag"])
return AESGCM(VERIFICATION_KEY).decrypt(decode(record["online_code_iv"]), encrypted, None).decode()
async def _init_database_unlocked() -> None:
async with engine.begin() as connection:
await connection.run_sync(metadata.create_all)
if DB_DRIVER == "sqlite":
await connection.execute(text("PRAGMA journal_mode=WAL"))
await connection.execute(text("PRAGMA busy_timeout=60000"))
# metadata.create_all creates new tables, while these columns also
# need a safe additive migration for existing SQLite/MySQL installs.
migrations = {
"credit_adjustments": {
"category": "VARCHAR(16)", "before_score": "INTEGER", "after_score": "INTEGER",
"task_id": "VARCHAR(64)", "rule_key": "VARCHAR(128)", "note": "VARCHAR(400)",
"invitee_id": "VARCHAR(64)",
"reverses_id": "VARCHAR(64)", "reversed_by": "VARCHAR(64)", "reversed_at": "BIGINT",
},
"reports": {
"target_user_id": "VARCHAR(64)",
"conversation_id": "VARCHAR(64)",
"message_snapshot": "TEXT",
},
"tasks": {"claimed_at": "BIGINT", "cancelled_at": "BIGINT", "cancelled_by": "VARCHAR(64)"},
"user_stats": {"claim_restricted_until": "BIGINT", "publish_restricted_until": "BIGINT"},
"users": {"status": "VARCHAR(16) NOT NULL DEFAULT 'active'", "status_until": "BIGINT"},
"sessions": {"ip": "VARCHAR(64)", "user_agent": "VARCHAR(400)"},
# Earlier ban/restrict deployments had the internal reason only;
# keep their history and add the public-facing category in place.
"account_sanctions": {"category": "VARCHAR(32)"},
}
for table_name, columns in migrations.items():
present = await connection.run_sync(
lambda sync_connection, table_name=table_name:
{column["name"] for column in inspect(sync_connection).get_columns(table_name)}
)
for column_name, column_type in columns.items():
if column_name not in present:
await connection.execute(text(
f"ALTER TABLE {table_name} ADD COLUMN {column_name} {column_type}"
))
# Idempotency and single-reversal guarantees for the append-only ledger.
indexes = await connection.run_sync(
lambda sync_connection: {index["name"] for index in inspect(sync_connection).get_indexes("credit_adjustments")}
)
for index_name, column_name in [
("uq_credit_adjustments_rule_key_idx", "rule_key"),
("uq_credit_adjustments_reverses_idx", "reverses_id"),
]:
if index_name not in indexes:
try:
statement = f"CREATE UNIQUE INDEX {index_name} ON credit_adjustments ({column_name})"
if DB_DRIVER != "mysql":
statement = statement.replace("CREATE UNIQUE INDEX", "CREATE UNIQUE INDEX IF NOT EXISTS", 1)
await connection.execute(text(statement))
except Exception:
# Existing duplicate legacy values are not auto-rewritten;
# NULL legacy values remain valid and hidden from public history.
pass
invite_indexes = await connection.run_sync(
lambda sync_connection: {index["name"] for index in inspect(sync_connection).get_indexes("invite_codes")}
)
if "uq_invite_codes_owner_idx" not in invite_indexes:
try:
statement = "CREATE UNIQUE INDEX uq_invite_codes_owner_idx ON invite_codes (owner_id)"
if DB_DRIVER != "mysql":
statement = statement.replace("CREATE UNIQUE INDEX", "CREATE UNIQUE INDEX IF NOT EXISTS", 1)
await connection.execute(text(statement))
except Exception:
# Preserve existing rows; new issuance is serialized on user_stats.
pass
try:
await connection.execute(text("ALTER TABLE tasks ADD COLUMN claimer_id VARCHAR(64)"))
except Exception:
pass
try:
await connection.execute(text("ALTER TABLE tasks ADD COLUMN school VARCHAR(160)"))
except Exception:
pass
task_columns = await connection.run_sync(
lambda sync_connection: {column["name"] for column in inspect(sync_connection).get_columns("tasks")}
)
if "completed_at" not in task_columns:
await connection.execute(text("ALTER TABLE tasks ADD COLUMN completed_at BIGINT"))
# 旧库没有完成时间;用发布时间兜底,使存量已完成任务可排序和展示。
await connection.execute(text(
"UPDATE tasks SET completed_at = created_at WHERE status = 'done' AND completed_at IS NULL"
))
await connection.execute(text(
"UPDATE tasks SET claimed_at = COALESCE(completed_at, created_at) "
"WHERE status IN ('claimed','done') AND claimer_id IS NOT NULL AND claimed_at IS NULL"
))
# 跑腿代办统一大类:存量快递代取任务一次性回填为 errand + 类目名,
# 之后接单/凭证/完成流水线只认 type='errand',不做长期双读别名。
# 极简旧表(手工建的遗留库)可能缺 type/category 列,先探测再回填。
if DB_DRIVER == "sqlite":
create_sql = await connection.scalar(text(
"SELECT sql FROM sqlite_master WHERE type='table' AND name='tasks'"
))
if create_sql and "CHECK(type IN ('express','partner'))" in create_sql:
# 旧 Node 服务给 type 留下的 CHECK 不含 errand;SQLite 只能重建表放宽约束。
rebuilt = create_sql.replace("tasks", "tasks_new", 1).replace(
"CHECK(type IN ('express','partner'))",
"CHECK(type IN ('express','partner','errand'))",
)
await connection.execute(text(rebuilt))
await connection.execute(text("INSERT INTO tasks_new SELECT * FROM tasks"))
await connection.execute(text("DROP TABLE tasks"))
await connection.execute(text("ALTER TABLE tasks_new RENAME TO tasks"))
await connection.execute(text(
"CREATE INDEX IF NOT EXISTS idx_tasks_status_created ON tasks(status, created_at)"
))
await connection.execute(text(
"CREATE INDEX IF NOT EXISTS idx_tasks_claimer ON tasks(claimer_id)"
))
if {"type", "category"} <= task_columns:
await connection.execute(text(
"UPDATE tasks SET type = 'errand', category = '快递代取' WHERE type = 'express'"
))
default_columns = await connection.run_sync(
lambda sync_connection: {column["name"] for column in inspect(sync_connection).get_columns("task_defaults")}
)
if "category" not in default_columns:
# task_defaults 升级为按类目分别保存常用字段:重建为 (user_id, category) 复合主键。
await connection.execute(text(
"CREATE TABLE task_defaults_new (user_id VARCHAR(64) NOT NULL, category VARCHAR(32) NOT NULL,"
" school VARCHAR(160) NOT NULL, phone VARCHAR(32) NOT NULL, pickup_place VARCHAR(240),"
" destination VARCHAR(240), updated_at BIGINT NOT NULL, PRIMARY KEY (user_id, category))"
))
await connection.execute(text(
"INSERT INTO task_defaults_new (user_id, category, school, phone, pickup_place, destination, updated_at)"
" SELECT user_id, '快递代取', school, phone, pickup_place, destination, updated_at FROM task_defaults"
))
await connection.execute(text("DROP TABLE task_defaults"))
await connection.execute(text("ALTER TABLE task_defaults_new RENAME TO task_defaults"))
try:
await connection.execute(text("ALTER TABLE users ADD COLUMN privacy_policy_version VARCHAR(32)"))
except Exception:
pass
try:
await connection.execute(text("ALTER TABLE users ADD COLUMN privacy_policy_accepted_at BIGINT"))
except Exception:
pass
try:
# 兼容旧库:密码列允许为空,旧账号仍可走邮箱验证码登录。
await connection.execute(text("ALTER TABLE users ADD COLUMN password_hash VARCHAR(256)"))
except Exception:
pass
try:
# 旧版本把学校写在 place;首次启动时补齐独立分区字段。
await connection.execute(text("UPDATE tasks SET school = place WHERE school IS NULL"))
except Exception:
pass
try:
index_sql = "CREATE INDEX idx_task_participants_user_task ON task_participants (user_id, task_id)"
if DB_DRIVER != "mysql":
index_sql = index_sql.replace("CREATE INDEX", "CREATE INDEX IF NOT EXISTS", 1)
await connection.execute(text(index_sql))
except Exception:
# MySQL 没有通用的 CREATE INDEX IF NOT EXISTS;索引已存在时安全忽略。
pass
async with SessionLocal() as db:
rows = await all_rows(db, select(users.c.id, users.c.created_at))
for row in rows:
existing = await one(db, select(user_stats.c.user_id).where(user_stats.c.user_id == row["id"]))
if not existing:
await db.execute(insert(user_stats).values(
user_id=row["id"], points_balance=750, credit_score=70,
updated_at=row["created_at"],
))
entry = await one(db, select(point_entries.c.id).where(
and_(point_entries.c.user_id == row["id"], point_entries.c.reason == "注册赠送")
))
if not entry:
await db.execute(insert(point_entries).values(
id=new_id(), user_id=row["id"], delta=750, withdrawable_delta=0,
reason="注册赠送", created_at=row["created_at"],
))
await db.commit()
async def init_database() -> None:
"""Serialize MySQL schema initialization across Uvicorn workers."""
if DB_DRIVER != "mysql":
await _init_database_unlocked()
return
lock_name = "linkup_init_database"
async with engine.connect() as lock_connection:
acquired = await lock_connection.scalar(
text("SELECT GET_LOCK(:lock_name, 60)"), {"lock_name": lock_name}
)
if int(acquired or 0) != 1:
raise RuntimeError("Timed out waiting for the MySQL startup lock")
try:
await _init_database_unlocked()
finally:
await lock_connection.execute(
text("SELECT RELEASE_LOCK(:lock_name)"), {"lock_name": lock_name}
)
@app.on_event("startup")
async def startup() -> None:
await init_database()
@app.on_event("shutdown")
async def shutdown() -> None:
await engine.dispose()
@app.exception_handler(HTTPException)
async def http_error_handler(_: Request, exc: HTTPException) -> JSONResponse:
content = exc.detail if isinstance(exc.detail, dict) else {"error": str(exc.detail)}
return JSONResponse(status_code=exc.status_code, content=content)
async def db_session():
async with SessionLocal() as db:
yield db
VERIFICATION_SCENES = {
"register": email_verifications,
"login": login_verifications,
"reset": password_resets,
}
async def issue_email_code(db: AsyncSession, email: str, ip: str, scene: str = "register") -> dict[str, Any]:
"""生成并发送注册、登录风控或重置密码验证码。"""
table = VERIFICATION_SCENES[scene]
recent = [stamp for stamp in SEND_WINDOWS.get(ip, []) if now_ms() - stamp < 60 * 60_000]
if len(recent) >= 10:
raise HTTPException(429, "验证码发送过于频繁,请稍后再试")
previous = await one(db, select(table).where(table.c.email == email))
if previous and now_ms() - int(previous["sent_at"]) < 60_000:
wait_seconds = max(1, int((60_000 - (now_ms() - int(previous["sent_at"]))) / 1000))
raise HTTPException(429, f"请在 {wait_seconds} 秒后重试")
code = f"{secrets.randbelow(1_000_000):06d}"
timestamp = now_ms()
values = {"email": email, "code_hash": hash_code(email, code), "expires_at": timestamp + 600_000,
"sent_at": timestamp, "attempts": 0, "consumed_at": None}
if previous:
await db.execute(update(table).where(table.c.email == email).values(**values))
else:
await db.execute(insert(table).values(**values))
await db.commit()
try:
await send_mail(email, code, scene)
except Exception:
raise HTTPException(502, "验证码发送失败,请稍后重试")
recent.append(timestamp)
SEND_WINDOWS[ip] = recent
return {"expiresIn": 600, **({"testCode": code} if TEST_MODE else {})}
async def send_code_common(request: Request, db: AsyncSession, login: bool) -> dict[str, Any]:
body = await request.json()
email = normalize_email(body.get("email"))
if not EMAIL_PATTERN.match(email) or len(email) > 254:
raise HTTPException(400, "请输入有效邮箱")
existing = await one(db, select(users).where(users.c.email == email))
if (not login and existing) or (login and not existing):
raise HTTPException(409 if not login else 404, "该邮箱已注册" if not login else "该邮箱尚未注册")
scene = "login" if login else "register"
return {"ok": True, **(await issue_email_code(db, email, client_ip(request), scene))}
async def verify_code(db: AsyncSession, table, email: str, code: str) -> None:
record = await one(db, select(table).where(table.c.email == email))
if not record or record["consumed_at"] or int(record["expires_at"]) < now_ms():
raise HTTPException(400, "验证码无效或已过期")
if int(record["attempts"]) >= 5:
raise HTTPException(429, "验证码尝试次数过多,请重新获取")
if not hmac.compare_digest(str(record["code_hash"]), hash_code(email, code)):
await db.execute(update(table).where(table.c.email == email).values(attempts=int(record["attempts"]) + 1))
await db.commit()
raise HTTPException(400, "验证码错误")
await db.execute(update(table).where(table.c.email == email).values(consumed_at=now_ms()))
async def task_item(db: AsyncSession, row: dict[str, Any], viewer_id: str | None,
joined_counts: dict[str, int] | None = None,
joined_by_me: set[str] | None = None,
breach_cache: dict[str, dict[str, Any]] | None = None) -> dict[str, Any]:
breach_cache = breach_cache if breach_cache is not None else {}
if row["user_id"] not in breach_cache:
breach_cache[row["user_id"]] = await reliability_summary(db, row["user_id"])
reliability = breach_cache[row["user_id"]]
owner = viewer_id == row["user_id"]
claimer = viewer_id and viewer_id == row.get("claimer_id")
payload = {
"id": row["id"], "userId": row["user_id"], "type": row["type"],
"title": row["title"], "route": row["detail"], "place": row["place"],
"deadline": row["deadline"], "reward": int(row["reward"] or 0), "note": row["note"],
"category": row["category"], "joined": f"{int((joined_counts or {}).get(row['id'], 0))}/{row['slots']}" if row.get("slots") else None,
"user": row.get("nickname") or row.get("name"), "credit": int(row.get("credit_score") or 70),
"userCreatedAt": row.get("user_created_at"), "userBreachRate": reliability["breachRateLabel"],
"userBreachLabel": reliability["breachRateLabel"], "userCommitments90d": reliability["commitments90d"],
"createdAt": row["created_at"], "completedAt": row.get("completed_at"),
"status": row["status"], "mine": owner,
"claimedByMe": bool(claimer),
"joinedByMe": bool(viewer_id and row["id"] in (joined_by_me or set())),
}
if owner or claimer:
payload["phone"] = row.get("contact")
if claimer:
payload["pickupCodes"] = json_load(row.get("pickup_codes"), [])
return payload
async def task_rows(db: AsyncSession, status: str, viewer_id: str | None = None,
school: str | None = None) -> list[dict[str, Any]]:
stmt = select(
tasks, users.c.nickname, users.c.name, users.c.created_at.label("user_created_at"),
user_stats.c.credit_score, user_stats.c.breach_count, user_stats.c.commitments_count,
).select_from(
tasks.join(users, users.c.id == tasks.c.user_id).outerjoin(user_stats, user_stats.c.user_id == tasks.c.user_id)
)
stmt = stmt.where(tasks.c.status == status)
if status == "open" and viewer_id:
# 自己发布的待接单任务仍只在「我的任务」里管理。
stmt = stmt.where(tasks.c.user_id != viewer_id)
if school:
stmt = stmt.where(tasks.c.school == school)
if status == "done":
stmt = stmt.order_by(tasks.c.completed_at.desc(), tasks.c.created_at.desc(), tasks.c.id.desc()).limit(10)
else:
stmt = stmt.order_by(tasks.c.created_at.desc())
return await all_rows(db, stmt)
@app.get("/api/health")
async def health() -> dict[str, Any]:
return {"ok": True, "runtime": "fastapi", "database": DB_DRIVER}
@app.get("/api/auth/me")
async def auth_me(request: Request) -> dict[str, Any]:
async with SessionLocal() as local_db:
user = await current_user(request, local_db)
if not user:
raise HTTPException(401, "登录已过期,请重新登录")
return {"ok": True, "user": await public_user(local_db, user)}
@app.get("/api/privacy-policy")
async def privacy_policy() -> dict[str, Any]:
"""返回当前生效的隐私政策,供注册页和帮助页面展示。"""
return {"ok": True, **PRIVACY_POLICY}
@app.post("/api/auth/send-code")
async def auth_send_code(request: Request) -> dict[str, Any]:
async with SessionLocal() as db:
return await send_code_common(request, db, False)
@app.post("/api/auth/send-login-code")
async def auth_send_login_code(request: Request) -> dict[str, Any]:
async with SessionLocal() as db:
return await send_code_common(request, db, True)
@app.post("/api/auth/register", status_code=201)
async def auth_register(request: Request) -> dict[str, Any]:
body = await request.json()
name, nickname = normalize(body.get("name")), normalize(body.get("nickname"))
student_id, school = normalize(body.get("studentId")), normalize(body.get("school"))
email, code = normalize_email(body.get("email")), normalize(body.get("code"))
invite_code = normalize(body.get("inviteCode"))
password = str(body.get("password") or "")
password_confirm = str(body.get("passwordConfirm") or "")
privacy_consent = body.get("privacyConsent") in {True, "true", "1", "on", "yes"}
privacy_version = normalize(body.get("privacyPolicyVersion"))
if not name or len(name) > 80 or not nickname or len(nickname) > 80:
raise HTTPException(400, "请填写有效姓名和昵称")
if not STUDENT_ID_PATTERN.match(student_id):
raise HTTPException(400, "学号格式不正确")
if not school or len(school) > 160 or not EMAIL_PATTERN.match(email):
raise HTTPException(400, "请填写有效学校和邮箱")
if len(password) < 8:
raise HTTPException(400, "密码至少 8 位")
if password != password_confirm:
raise HTTPException(400, "两次输入的密码不一致")
if not privacy_consent or privacy_version != PRIVACY_POLICY_VERSION:
raise HTTPException(400, "请阅读并同意当前版本的隐私政策")
async with SessionLocal() as db:
await verify_code(db, email_verifications, email, code)
if await one(db, select(users.c.id).where(users.c.student_id == student_id)):
raise HTTPException(409, "该学号已注册,一个学号只能注册一个账号")
if await one(db, select(users.c.id).where(users.c.email == email)):
raise HTTPException(409, "该邮箱已注册")
inviter = None
if invite_code:
inviter = await one(db, select(invite_codes).where(invite_codes.c.code == invite_code))
if not inviter or int(inviter["used_count"]) >= int(inviter["max_uses"]):
raise HTTPException(400, "邀请码无效或已被用完")
inviter_stats = await stats_for(db, inviter["owner_id"])
if int(inviter_stats["credit_score"]) < 90:
raise HTTPException(400, "邀请码拥有者信用分需达到 90 分")
timestamp = now_ms()
user_id = new_id()
await db.execute(insert(users).values(
id=user_id, name=name, nickname=nickname, student_id=student_id, school=school,
email=email, email_verified_at=timestamp, password_hash=hash_password(password),
privacy_policy_version=privacy_version, privacy_policy_accepted_at=timestamp,
created_at=timestamp,
))
await db.execute(insert(user_stats).values(
user_id=user_id, points_balance=750, credit_score=90 if inviter else 70, updated_at=timestamp,
))
await db.execute(insert(point_entries).values(
id=new_id(), user_id=user_id, delta=750, withdrawable_delta=0, reason="注册赠送", created_at=timestamp,
))
if inviter:
await db.execute(update(invite_codes).where(invite_codes.c.id == inviter["id"]).values(used_count=int(inviter["used_count"]) + 1))
await db.execute(insert(invite_relations).values(invitee_id=user_id, inviter_id=inviter["owner_id"], created_at=timestamp))
await db.execute(insert(credit_adjustments).values(
id=new_id(), user_id=user_id, admin_id="system", delta=20,
reason="邀请注册奖励", category="奖励", before_score=70, after_score=90,
rule_key=f"invite-registration:{user_id}", note="受邀完成注册",
created_at=timestamp,
))
await db.execute(update(user_stats).where(user_stats.c.user_id == inviter["owner_id"]).values(
points_balance=user_stats.c.points_balance + 300,
updated_at=timestamp,
))
await db.execute(insert(point_entries).values(
id=new_id(), user_id=inviter["owner_id"], delta=300, withdrawable_delta=0, reason="邀请奖励", created_at=timestamp,
))
await db.execute(delete(email_verifications).where(email_verifications.c.email == email))
await db.commit()
await mark_known_ip(db, user_id, client_ip(request))
token = await issue_session(db, user_id, request)
row = await one(db, select(users).where(users.c.id == user_id))
return {"ok": True, "token": token, "user": await public_user(db, row)}
@app.post("/api/auth/login")
async def auth_login(request: Request) -> dict[str, Any]:
body = await request.json()
email = normalize_email(body.get("email"))
password = str(body.get("password") or "")
code = normalize(body.get("code"))
ip = client_ip(request)
async with SessionLocal() as db:
user = None
method = "code" if code and not password else "password"
try:
user = await one(db, select(users).where(users.c.email == email))
if user:
method = "code" if not user.get("password_hash") else "password"
if user.get("status") == "banned":
until = user.get("status_until")
if until is None or int(until) > now_ms():
sanction = await one(db, select(account_sanctions).where(and_(
account_sanctions.c.user_id == user["id"], account_sanctions.c.action == "ban",
account_sanctions.c.lifted_at.is_(None),
or_(account_sanctions.c.expires_at.is_(None), account_sanctions.c.expires_at > now_ms()),
)).order_by(account_sanctions.c.created_at.desc()).limit(1))
category = (sanction or {}).get("category") or "账号违规"
message = f"账号已被封禁(原因:{category})"
if until:
restore_date = datetime.fromtimestamp(int(until) / 1000, tz=timezone.utc).astimezone().strftime("%Y-%m-%d")
message += f",至 {restore_date} 恢复"
raise HTTPException(403, f"{message}。如有异议,请联系管理员:{ADMIN_SANCTION_CONTACT}")
await db.execute(update(users).where(users.c.id == user["id"]).values(
status="active", status_until=None,
))
user["status"] = "active"
user["status_until"] = None
if recent_login_failures(ip) >= LOGIN_FAILURE_LIMIT:
raise HTTPException(429, "登录失败次数过多,请 15 分钟后再试")
if not user.get("password_hash"):
if not code:
raise HTTPException(400, "该账号尚未设置密码,请使用邮箱验证码登录")
await verify_code(db, login_verifications, email, code)
await db.execute(delete(login_verifications).where(login_verifications.c.email == email))
await mark_known_ip(db, user["id"], ip)
token = await issue_session(db, user["id"], request)
await write_login_log(db, request, user_id=user["id"], email=email, success=True, method=method)
await db.commit()
return {"ok": True, "token": token, "user": await public_user(db, user)}
if not password:
raise HTTPException(400, "请输入密码")
if not verify_password(password, user["password_hash"]):
record_login_failure(ip)
remaining = LOGIN_FAILURE_LIMIT - recent_login_failures(ip)
hint = f",还可尝试 {remaining} 次" if 0 < remaining <= 2 else ""
raise HTTPException(401, f"邮箱或密码错误{hint}")
if recent_login_failures(ip) >= RISK_FAILURE_THRESHOLD or not await is_known_ip(db, user["id"], ip):
if not code:
payload = await issue_email_code(db, email, ip, "login")
return {"ok": False, "needCode": True, "sentTo": mask_email(email), **payload}
await verify_code(db, login_verifications, email, code)
await db.execute(delete(login_verifications).where(login_verifications.c.email == email))
login_failures.pop(ip, None)
await mark_known_ip(db, user["id"], ip)
token = await issue_session(db, user["id"], request)
await write_login_log(db, request, user_id=user["id"], email=email, success=True, method=method)
await db.commit()
return {"ok": True, "token": token, "user": await public_user(db, user)}
raise HTTPException(404, "该邮箱尚未注册")
except HTTPException:
await db.rollback()
await write_login_log(db, request, user_id=(user or {}).get("id"), email=email,
success=False, method=method)
await db.commit()
raise
@app.post("/api/auth/logout")
async def auth_logout(request: Request) -> dict[str, bool]:
header = normalize(request.headers.get("authorization"))
if header.startswith("Bearer "):
async with SessionLocal() as db:
await db.execute(delete(sessions).where(sessions.c.token_hash == hash_token(header[7:].strip())))
await db.commit()
return {"ok": True}
@app.post("/api/auth/send-reset-code")
async def auth_send_reset_code(request: Request) -> dict[str, Any]:
body = await request.json()
email = normalize_email(body.get("email"))
if not EMAIL_PATTERN.match(email) or len(email) > 254:
raise HTTPException(400, "请输入有效邮箱")
async with SessionLocal() as db:
if not await one(db, select(users.c.id).where(users.c.email == email)):
raise HTTPException(404, "该邮箱尚未注册")
return {"ok": True, **(await issue_email_code(db, email, client_ip(request), "reset"))}
@app.post("/api/auth/reset-password")
async def auth_reset_password(request: Request) -> dict[str, bool]:
body = await request.json()
email = normalize_email(body.get("email"))
code = normalize(body.get("code"))
password = str(body.get("password") or "")
password_confirm = str(body.get("passwordConfirm") or "")
if not EMAIL_PATTERN.match(email) or len(email) > 254:
raise HTTPException(400, "请输入有效邮箱")
if len(password) < 8:
raise HTTPException(400, "密码至少 8 位")
if password != password_confirm:
raise HTTPException(400, "两次输入的密码不一致")
async with SessionLocal() as db:
user = await one(db, select(users.c.id).where(users.c.email == email))
if not user:
raise HTTPException(404, "该邮箱尚未注册")
await verify_code(db, password_resets, email, code)
await db.execute(delete(password_resets).where(password_resets.c.email == email))
await db.execute(update(users).where(users.c.id == user["id"]).values(password_hash=hash_password(password)))
await db.execute(delete(sessions).where(sessions.c.user_id == user["id"]))
await db.commit()
return {"ok": True}
@app.get("/api/points/entries")
async def list_points(request: Request) -> dict[str, Any]:
async with SessionLocal() as db:
user = await require_user(request, db)
rows = await all_rows(db, select(point_entries.c.delta, point_entries.c.reason, point_entries.c.created_at)
.where(point_entries.c.user_id == user["id"]).order_by(point_entries.c.created_at.desc()).limit(50))
stats = await stats_for(db, user["id"])
return {"ok": True, "entries": [
{"delta": int(row["delta"]), "reason": row["reason"], "createdAt": row["created_at"]} for row in rows
], "balance": int(stats["points_balance"]), "withdrawable": int(stats["withdrawable_points"])}
@app.post("/api/points/recharge")
async def recharge_points(request: Request) -> dict[str, Any]:
"""积分充值:1 元 = 100 积分(原型阶段无支付网关,接口直接记账)。"""
body = await request.json()
try:
amount_yuan = int(body.get("amount"))
except (TypeError, ValueError):
raise HTTPException(400, "请输入有效的充值金额")
if not 1 <= amount_yuan <= 50000:
raise HTTPException(400, "充值金额需为 1—50000 元的整数")
points = amount_yuan * POINTS_PER_YUAN
async with SessionLocal() as db:
user = await require_user(request, db)
await stats_for(db, user["id"])
timestamp = now_ms()
await db.execute(update(user_stats).where(user_stats.c.user_id == user["id"]).values(
points_balance=user_stats.c.points_balance + points,
withdrawable_points=user_stats.c.withdrawable_points + points,
updated_at=timestamp,
))
await db.execute(insert(point_entries).values(
id=new_id(), user_id=user["id"], delta=points, withdrawable_delta=points,
reason=f"充值 {amount_yuan} 元", created_at=timestamp,
))
await db.commit()
stats = await stats_for(db, user["id"])
return {"ok": True, "points": points, "amountYuan": amount_yuan,
"balance": int(stats["points_balance"]), "withdrawable": int(stats["withdrawable_points"])}
@app.post("/api/points/withdraw")
async def withdraw_points(request: Request) -> dict[str, Any]:
"""积分提现:任意正整数积分均可提现,100 积分按 0.75 元结算并按分向下取整。"""
body = await request.json()
try:
points = int(body.get("points"))
except (TypeError, ValueError):
raise HTTPException(400, "请输入有效的提现积分")
if points < WITHDRAW_MIN_POINTS:
raise HTTPException(400, "提现积分需为正整数")
async with SessionLocal() as db:
user = await require_user(request, db)
await ensure_not_sanctioned(db, user, "withdraw")
await db.rollback()
async with db.begin():
stats = await one(db, select(user_stats).where(user_stats.c.user_id == user["id"]).with_for_update())
if not stats or int(stats["withdrawable_points"]) < points or int(stats["points_balance"]) < points:
raise HTTPException(400, "可提现积分不足")
# 100 积分 = 75 分;使用整数运算并向下取整到人民币分。
amount_cents = points * WITHDRAW_CENTS_PER_100_POINTS // 100
amount_yuan = round(amount_cents / 100, 2)
timestamp = now_ms()
await db.execute(update(user_stats).where(user_stats.c.user_id == user["id"]).values(
points_balance=user_stats.c.points_balance - points,
withdrawable_points=user_stats.c.withdrawable_points - points,
updated_at=timestamp,
))
await db.execute(insert(point_entries).values(
id=new_id(), user_id=user["id"], delta=-points, withdrawable_delta=-points,
reason=f"提现 {points} 积分(按 100 积分=0.75 元结算)", created_at=timestamp,
))
return {"ok": True, "amountYuan": amount_yuan, "amountCents": amount_cents}
@app.get("/api/credit/summary")
async def credit_summary(request: Request) -> dict[str, Any]:
"""返回当前用户的校园信用详情和管理员调整记录。"""
async with SessionLocal() as db:
user = await require_user(request, db)
stats = await stats_for(db, user["id"])
commitments = int(stats["commitments_count"] or 0)
reliability = await reliability_summary(db, user["id"])
history = await all_rows(db, select(
credit_adjustments.c.id, credit_adjustments.c.delta, credit_adjustments.c.reason,
credit_adjustments.c.created_at, credit_adjustments.c.before_score,
credit_adjustments.c.after_score, credit_adjustments.c.category,
credit_adjustments.c.task_id, credit_adjustments.c.note,
credit_adjustments.c.reverses_id, credit_adjustments.c.reversed_at,
).where(credit_adjustments.c.user_id == user["id"])
.order_by(credit_adjustments.c.created_at.desc()).limit(30))
pending_events = await all_rows(db, select(
reliability_events.c.task_id, reliability_events.c.kind, reliability_events.c.created_at,
).where(and_(
reliability_events.c.user_id == user["id"], reliability_events.c.status == "pending",
)).order_by(reliability_events.c.created_at.desc()).limit(30))
pending_cases: dict[tuple[str | None, str], dict[str, Any]] = {}
for event in pending_events:
key = (event["task_id"], event["kind"])
pending_cases.setdefault(key, {
"taskId": event["task_id"], "kind": event["kind"],
"status": "pending", "createdAt": event["created_at"],
})
return {
"ok": True,
"creditScore": int(stats["credit_score"] or 70),
**reliability,
"breachCount": int(stats["breach_count"] or 0),
"commitments": commitments,
"completedTasks": int(stats["completed_tasks"] or 0),
"currentStreak": int(stats["current_streak"] or 0),
"invitationEligible": invite_threshold_reached(stats),
"withdrawablePoints": int(stats["withdrawable_points"] or 0),
"pendingCases": list(pending_cases.values()),
"history": [{
"id": row["id"], "delta": int(row["delta"]), "reason": row["reason"],
"createdAt": row["created_at"], "before": row["before_score"],
"after": row["after_score"], "category": row["category"],
"taskId": row["task_id"], "note": row["note"],
"reversesId": row["reverses_id"], "reversedAt": row["reversed_at"],
} for row in history],
}
async def school_options(db: AsyncSession) -> list[str]:
registered = await all_rows(db, select(users.c.school).distinct().order_by(users.c.school))
return list(dict.fromkeys(item for item in [*[row["school"] for row in registered], *SCHOOL_OPTIONS] if item))
@app.get("/api/schools")
async def list_schools(request: Request) -> dict[str, Any]:
async with SessionLocal() as db:
user = await current_user(request, db)
preferred = normalize(user.get("school")) if user else ""
schools = list(dict.fromkeys([preferred, *await school_options(db)]))
return {"ok": True, "preferred": preferred or None, "items": [item for item in schools if item]}
@app.get("/api/tasks")
async def list_tasks(request: Request, school: str | None = None) -> dict[str, Any]:
async with SessionLocal() as db:
user = await current_user(request, db)
viewer_id = user["id"] if user else None
# 不传筛选时保留原来的本校/管理员/访客学校范围。
if school is None:
selected_school = None if user and is_admin(user) else (normalize(user.get("school")) if user else None)
else:
if school != "all" and school not in await school_options(db):
raise HTTPException(400, "请选择有效的学校")
selected_school = None if school == "all" else school
rows = []
for status in ("open", "claimed", "done"):
rows += await task_rows(db, status=status, viewer_id=viewer_id, school=selected_school)
task_ids = list(dict.fromkeys(row["id"] for row in rows))
joined_counts: dict[str, int] = {}
joined_by_me: set[str] = set()
if task_ids:
joined_counts = dict((await db.execute(
select(task_participants.c.task_id, func.count())
.where(task_participants.c.task_id.in_(task_ids))
.group_by(task_participants.c.task_id)
)).all())
if viewer_id:
joined_by_me = set((await db.scalars(
select(task_participants.c.task_id).where(and_(
task_participants.c.user_id == viewer_id,
task_participants.c.task_id.in_(task_ids),
))
)).all())
breach_cache: dict[str, dict[str, Any]] = {}
items = []
for row in rows:
items.append(await task_item(db, row, viewer_id, joined_counts, joined_by_me, breach_cache))
return {"ok": True, "items": items}
def official_task_payload(row: dict[str, Any], claim_count: int, user_count: int,
mine_count: int = 0) -> dict[str, Any]:
quota = int(row["total_quota"] or 0)
per_account = int(row["per_account_limit"])
return {
"id": row["id"], "title": row["title"], "detail": row["detail"],
"reward": int(row["reward"]), "perAccountLimit": per_account,
"totalQuota": quota, "status": row["status"], "deadline": row["deadline"],
"createdAt": row["created_at"], "claimCount": claim_count,
"claimedUsers": user_count,
"remainingTotal": max(0, quota - claim_count) if quota else None,
"myClaimCount": mine_count,
"remainingClaims": max(0, per_account - mine_count),
"limitReached": mine_count >= per_account,
}
async def official_task_claim_counts(db: AsyncSession) -> tuple[dict[str, int], dict[str, int]]:
claim_rows = await all_rows(db, select(
official_task_claims.c.task_id, official_task_claims.c.user_id,
))
counts: dict[str, int] = {}
users_by_task: dict[str, set[str]] = {}
for claim in claim_rows:
task_id = claim["task_id"]
counts[task_id] = counts.get(task_id, 0) + 1
users_by_task.setdefault(task_id, set()).add(claim["user_id"])
return counts, {task_id: len(user_ids) for task_id, user_ids in users_by_task.items()}
@app.get("/api/official-tasks")
async def list_official_tasks(request: Request) -> dict[str, Any]:
async with SessionLocal() as db:
user = await current_user(request, db)
now = now_ms()
rows = await all_rows(db, select(official_tasks).where(and_(
official_tasks.c.status == "active",
or_(official_tasks.c.deadline.is_(None), official_tasks.c.deadline > now),
)).order_by(official_tasks.c.created_at.desc()))
counts, user_counts = await official_task_claim_counts(db)
my_counts: dict[str, int] = {}
if user and rows:
my_claim_rows = await all_rows(db, select(official_task_claims.c.task_id).where(and_(
official_task_claims.c.user_id == user["id"],
official_task_claims.c.task_id.in_([row["id"] for row in rows]),
)))
for claim in my_claim_rows:
my_counts[claim["task_id"]] = my_counts.get(claim["task_id"], 0) + 1
items = []
for row in rows:
claim_count = counts.get(row["id"], 0)
quota = int(row["total_quota"] or 0)
if quota and claim_count >= quota:
continue
items.append(official_task_payload(
row, claim_count, user_counts.get(row["id"], 0), my_counts.get(row["id"], 0),
))
return {"ok": True, "items": items}
@app.post("/api/official-tasks/{task_id}/claim")
async def claim_official_task(task_id: str, request: Request) -> dict[str, Any]:
async with SessionLocal() as db:
user = await current_user(request, db, include_banned=True)
if not user:
raise HTTPException(401, "请先登录")
if user.get("status") == "banned":
raise HTTPException(403, "账号当前不可领取官方任务")
await ensure_not_sanctioned(db, user, "claim")
await db.rollback()
try:
async with db.begin():
if DB_DRIVER == "sqlite":
# SQLite ignores FOR UPDATE; reserve the writer lock before
# counting claims so the final slot/claim cannot be oversold.
await db.execute(text("BEGIN IMMEDIATE"))
task = await one(db, select(official_tasks).where(
official_tasks.c.id == task_id,
).with_for_update())
if not task:
raise HTTPException(404, "官方任务不存在")
now = now_ms()
if task["status"] != "active" or (task.get("deadline") and int(task["deadline"]) <= now):
raise HTTPException(409, "官方任务已下线")
mine = int(await db.scalar(select(func.count()).select_from(official_task_claims).where(and_(
official_task_claims.c.task_id == task_id,
official_task_claims.c.user_id == user["id"],
))) or 0)
if mine >= int(task["per_account_limit"]):
raise HTTPException(409, "您已达到领取上限")
claim_count = int(await db.scalar(select(func.count()).select_from(official_task_claims).where(
official_task_claims.c.task_id == task_id,
)) or 0)
quota = int(task["total_quota"] or 0)
if quota and claim_count >= quota:
raise HTTPException(409, "名额已领完")
reward = int(task["reward"])
await db.execute(insert(official_task_claims).values(
id=new_id(), task_id=task_id, user_id=user["id"], reward=reward, created_at=now,
))
credited = await db.execute(update(user_stats).where(
user_stats.c.user_id == user["id"],
).values(
points_balance=user_stats.c.points_balance + reward, updated_at=now,
))
if credited.rowcount == 0:
# Keep this compatible with legacy accounts missing stats.
await db.execute(insert(user_stats).values(
user_id=user["id"], points_balance=750 + reward, withdrawable_points=0,
credit_score=70, breach_count=0, commitments_count=0,
completed_tasks=0, current_streak=0, updated_at=now,
))
await db.execute(insert(point_entries).values(
id=new_id(), user_id=user["id"], delta=reward, withdrawable_delta=0,
reason=f"官方任务 · {task['title']}"[:400], created_at=now,
))
except OperationalError as error:
if DB_DRIVER == "sqlite" and ("database is locked" in str(error).lower() or "sqlite_busy" in str(error).lower()):
raise HTTPException(409, "领取名额已被领取") from error
raise
return {"ok": True, "reward": reward, "myClaimCount": mine + 1,
"remainingClaims": max(0, int(task["per_account_limit"]) - mine - 1)}
@app.get("/api/task-defaults")
async def get_task_defaults(request: Request, category: str = "快递代取") -> dict[str, Any]:
"""返回当前用户在指定跑腿类目下最近一次发布的常用字段。"""
if category not in ERRAND_CATEGORIES:
raise HTTPException(400, "请选择有效的跑腿类目")
async with SessionLocal() as db:
user = await require_user(request, db)
row = await one(db, select(task_defaults).where(and_(
task_defaults.c.user_id == user["id"], task_defaults.c.category == category,
)))
if not row:
return {"ok": True, "defaults": None}
return {"ok": True, "defaults": {
"school": row["school"], "phone": row["phone"],
"pickupPlace": row["pickup_place"], "destination": row["destination"],
"updatedAt": row["updated_at"],
}}
@app.get("/api/notifications")
async def list_notifications(request: Request) -> dict[str, Any]:
async with SessionLocal() as db:
user = await require_user(request, db)
rows = await all_rows(db, select(notifications).where(
notifications.c.user_id == user["id"]
).order_by(notifications.c.created_at.desc()).limit(50))
unread = await db.scalar(select(func.count()).select_from(notifications).where(
and_(notifications.c.user_id == user["id"], notifications.c.read_at.is_(None))
))
return {"ok": True, "unread": int(unread or 0), "items": [{
"id": row["id"], "kind": row["kind"], "title": row["title"],
"content": row["content"], "link": row["link"],
"read": row["read_at"] is not None, "createdAt": row["created_at"],
} for row in rows]}
@app.post("/api/notifications/{notification_id}/read")
async def mark_notification_read(notification_id: str, request: Request) -> dict[str, bool]:
async with SessionLocal() as db:
user = await require_user(request, db)
result = await db.execute(update(notifications).where(and_(
notifications.c.id == notification_id,
notifications.c.user_id == user["id"],
notifications.c.read_at.is_(None),
)).values(read_at=now_ms()))
await db.commit()
if not result.rowcount:
raise HTTPException(404, "通知不存在或已读")
return {"ok": True}
@app.post("/api/notifications/read-all")
async def mark_all_notifications_read(request: Request) -> dict[str, bool]:
async with SessionLocal() as db:
user = await require_user(request, db)
await db.execute(update(notifications).where(and_(
notifications.c.user_id == user["id"],
notifications.c.read_at.is_(None),
)).values(read_at=now_ms()))
await db.commit()
return {"ok": True}
async def require_public_profile_visibility(
db: AsyncSession, viewer: dict[str, Any] | None, target: dict[str, Any],
) -> None:
"""Keep every public-profile-adjacent endpoint on the same visibility rule."""
if viewer and not is_admin(viewer) and target["school"] != viewer["school"]:
visible_task = await db.scalar(select(tasks.c.id).where(and_(
tasks.c.user_id == target["id"], tasks.c.status == "open",
)).limit(1))
if not visible_task:
raise HTTPException(404, "该用户没有可查看的公开任务")
@app.get("/api/users/{user_id}/profile")
async def public_profile(user_id: str, request: Request) -> dict[str, Any]:
async with SessionLocal() as db:
viewer = await current_user(request, db)
row = await one(db, select(users).where(users.c.id == user_id))
if not row:
raise HTTPException(404, "用户不存在")
await require_public_profile_visibility(db, viewer, row)
stats = await stats_for(db, user_id)
reliability = await reliability_summary(db, user_id)
return {"ok": True, "user": {
"id": row["id"], "nickname": row["nickname"], "school": row["school"], "createdAt": row["created_at"],
"creditScore": int(stats["credit_score"]), **reliability,
"completedTasks": int(stats["completed_tasks"]), "currentStreak": int(stats["current_streak"]),
"verification": await verification_summary(db, user_id),
}}
@app.get("/api/users/{user_id}/credit-history")
async def public_credit_history(
user_id: str, request: Request, negativeOnly: bool = False,
) -> dict[str, Any]:
async with SessionLocal() as db:
viewer = await current_user(request, db)
target = await one(db, select(users).where(users.c.id == user_id))
if not target:
raise HTTPException(404, "用户不存在")
await require_public_profile_visibility(db, viewer, target)
predicate = [credit_adjustments.c.user_id == user_id, credit_adjustments.c.category.is_not(None)]
if negativeOnly:
predicate.append(credit_adjustments.c.delta < 0)
stmt = select(
credit_adjustments.c.delta, credit_adjustments.c.category, credit_adjustments.c.created_at,
).where(and_(*predicate)).order_by(
credit_adjustments.c.created_at.desc(), credit_adjustments.c.id.desc(),
).limit(30)
rows = await all_rows(db, stmt)
total = await db.scalar(select(func.count()).select_from(credit_adjustments).where(
and_(credit_adjustments.c.user_id == user_id, *(
[credit_adjustments.c.delta < 0] if negativeOnly else []
))
))
# Count every non-returned row (including old, unclassified free text)
# without reading or serializing its reason/admin/timestamp.
hidden_count = max(0, int(total or 0) - len(rows))
await db.execute(insert(public_credit_history_audits).values(
id=new_id(), viewer_id=viewer["id"] if viewer else None,
target_id=user_id, ts=now_ms(),
))
await db.commit()
return {"ok": True, "hiddenCount": hidden_count, "items": [{
"delta": int(row["delta"]), "category": row["category"],
"date": datetime.fromtimestamp(int(row["created_at"]) / 1000, timezone.utc).date().isoformat(),
} for row in rows]}
def conversation_peer(row: dict[str, Any], user_id: str) -> str:
return row["user_b"] if row["user_a"] == user_id else row["user_a"]
async def require_conversation_member(
db: AsyncSession, conversation_id: str, user_id: str,
) -> tuple[dict[str, Any], str]:
conversation = await one(db, select(conversations).where(conversations.c.id == conversation_id))
if not conversation or user_id not in {conversation["user_a"], conversation["user_b"]}:
raise HTTPException(404, "会话不存在")
return conversation, conversation_peer(conversation, user_id)
def message_payload(row: dict[str, Any]) -> dict[str, Any]:
return {
"id": row["id"], "senderId": row["sender_id"], "content": row["content"],
"createdAt": row["created_at"],
}
@app.post("/api/chats", status_code=201)
async def create_or_get_chat(request: Request) -> dict[str, Any]:
async with SessionLocal() as db:
user = await require_user(request, db)
body = await request.json()
target_id = normalize(body.get("userId"))
if not target_id or target_id == user["id"]:
raise HTTPException(400, "不能与自己发起私聊")
target = await one(db, select(users).where(users.c.id == target_id))
if not target:
raise HTTPException(404, "用户不存在")
await require_public_profile_visibility(db, user, target)
user_a, user_b = sorted((user["id"], target_id))
conversation = await one(db, select(conversations).where(and_(
conversations.c.user_a == user_a, conversations.c.user_b == user_b,
)))
if conversation:
return {"ok": True, "id": conversation["id"], "peer": {
"id": target["id"], "nickname": target["nickname"],
}}
timestamp = now_ms()
chat_id = new_id()
await db.execute(insert(conversations).values(
id=chat_id, user_a=user_a, user_b=user_b,
created_at=timestamp, last_message_at=timestamp,
))
try:
await db.commit()
except Exception:
# A concurrent POST can win the unique (user_a,user_b) constraint.
await db.rollback()
conversation = await one(db, select(conversations).where(and_(
conversations.c.user_a == user_a, conversations.c.user_b == user_b,
)))
if not conversation:
raise
chat_id = conversation["id"]
return {"ok": True, "id": chat_id, "peer": {
"id": target["id"], "nickname": target["nickname"],
}}
@app.get("/api/chats")
async def list_chats(request: Request) -> dict[str, Any]:
async with SessionLocal() as db:
user = await require_user(request, db)
rows = await all_rows(db, select(conversations).where(or_(
conversations.c.user_a == user["id"], conversations.c.user_b == user["id"],
)).order_by(conversations.c.last_message_at.desc()).limit(50))
items = []
for row in rows:
peer_id = conversation_peer(row, user["id"])
peer = await one(db, select(users.c.id, users.c.nickname).where(users.c.id == peer_id))
latest = await one(db, select(messages).where(
messages.c.conversation_id == row["id"],
).order_by(messages.c.created_at.desc(), messages.c.id.desc()).limit(1))
items.append({
"id": row["id"], "peer": peer,
"lastMessage": message_payload(latest) if latest else None,
"lastMessageAt": row["last_message_at"],
})
return {"ok": True, "items": items}
@app.get("/api/chats/{conversation_id}/messages")
async def list_chat_messages(conversation_id: str, request: Request) -> dict[str, Any]:
async with SessionLocal() as db:
user = await require_user(request, db)
conversation, peer_id = await require_conversation_member(db, conversation_id, user["id"])
peer = await one(db, select(users.c.id, users.c.nickname).where(users.c.id == peer_id))
rows = await all_rows(db, select(messages).where(
messages.c.conversation_id == conversation_id,
).order_by(messages.c.created_at.desc(), messages.c.id.desc()).limit(50))
await db.execute(update(messages).where(and_(
messages.c.conversation_id == conversation_id,
messages.c.sender_id == peer_id, messages.c.read_at.is_(None),
)).values(read_at=now_ms()))
await db.commit()
return {"ok": True, "id": conversation["id"], "peer": peer,
"items": [message_payload(row) for row in rows]}
@app.post("/api/chats/{conversation_id}/messages", status_code=201)
async def send_chat_message(conversation_id: str, request: Request) -> dict[str, Any]:
async with SessionLocal() as db:
user = await require_user(request, db)
conversation, peer_id = await require_conversation_member(db, conversation_id, user["id"])
body = await request.json()
content = body.get("content")
if not isinstance(content, str):
raise HTTPException(400, "消息须为 1—200 字纯文本")
content = content.strip()
if not content or len(content) > CHAT_MESSAGE_MAX_LENGTH:
raise HTTPException(400, "消息须为 1—200 字纯文本")
timestamp = now_ms()
# An upsert takes a durable per-sender write/row lock before checking
# the global hourly cap, including on SQLite deployments.
if DB_DRIVER == "mysql":
from sqlalchemy.dialects.mysql import insert as dialect_insert
elif DB_DRIVER == "postgresql":
from sqlalchemy.dialects.postgresql import insert as dialect_insert
else:
from sqlalchemy.dialects.sqlite import insert as dialect_insert
lock_stmt = dialect_insert(chat_send_limits).values(user_id=user["id"], locked_at=timestamp)
if DB_DRIVER == "mysql":
lock_stmt = lock_stmt.on_duplicate_key_update(locked_at=timestamp)
else:
lock_stmt = lock_stmt.on_conflict_do_update(
index_elements=[chat_send_limits.c.user_id], set_={"locked_at": timestamp},
)
await db.execute(lock_stmt)
recent_count = await db.scalar(select(func.count()).select_from(messages).where(and_(
messages.c.sender_id == user["id"],
messages.c.created_at > timestamp - 60 * 60_000,
)))
if int(recent_count or 0) >= CHAT_MESSAGES_PER_HOUR:
raise HTTPException(429, "每小时最多发送 30 条私聊消息,请稍后再试")
# Re-read the conversation under a row lock so concurrent senders are
# serialized and message timestamps remain strictly ordered per chat.
conversation = await one(db, select(conversations).where(
conversations.c.id == conversation_id,
).with_for_update())
timestamp = max(now_ms(), int(conversation["last_message_at"]) + 1)
latest = await one(db, select(messages.c.sender_id).where(
messages.c.conversation_id == conversation_id,
).order_by(messages.c.created_at.desc(), messages.c.id.desc()).limit(1))
if latest and latest["sender_id"] == user["id"]:
raise HTTPException(403, "对方回复后才能继续发送")
message_id = new_id()
await db.execute(insert(messages).values(
id=message_id, conversation_id=conversation_id, sender_id=user["id"],
content=content, created_at=timestamp,
))
await db.execute(update(conversations).where(conversations.c.id == conversation["id"]).values(
last_message_at=timestamp,
))
await add_notification(
db, peer_id, "chat_message", "收到一条私聊消息",
f"{user['nickname']} 给你发来了一条私聊消息", f"chat:{conversation_id}", timestamp,
)
await db.commit()
return {"ok": True, "message": message_payload({
"id": message_id, "sender_id": user["id"], "content": content, "created_at": timestamp,
})}
async def parse_task_body(request: Request, user: dict[str, Any]) -> dict[str, Any]:
body = await request.json()
task_type = normalize(body.get("type"))
if task_type == "express":
# 旧客户端别名:写入即归一为统一大类,读取侧不再有 express 行。
task_type, body["category"] = ERRAND_TYPE, "快递代取"
if task_type not in {ERRAND_TYPE, "partner"}:
raise HTTPException(400, "任务类型无效")
if task_type == ERRAND_TYPE and normalize(body.get("category")) not in ERRAND_CATEGORIES:
raise HTTPException(400, "请选择有效的跑腿类目")
school = normalize(body.get("school"))
preferred_school = normalize(user.get("school"))
if not valid_school(school, preferred_school):
raise HTTPException(400, "请选择列表中的学校")
if school != preferred_school:
raise HTTPException(403, "任务只能发布到自己的学校区域")
deadline = int(body.get("deadline") or 0)
if deadline < now_ms() or deadline > now_ms() + 30 * 24 * 60 * 60_000:
raise HTTPException(400, "请选择有效的截止时间(今天至未来 30 天内)")
return {**body, "type": task_type, "school": school, "deadline": deadline}
async def save_task_defaults(db: AsyncSession, user_id: str, body: dict[str, Any],
category: str, mapping: dict[str, Any], timestamp: int) -> None:
"""保存最近一次成功发布的跑腿任务常用字段,按用户与类目分别覆盖更新。"""
values = {
"school": normalize(body.get("school")),
"phone": normalize(body.get("phone")),
"pickup_place": normalize(body.get(mapping["pickup_place"])) if mapping.get("pickup_place") else "",
"destination": normalize(body.get(mapping["destination"])) if mapping.get("destination") else "",
"updated_at": timestamp,
}
existing = await one(db, select(task_defaults.c.user_id).where(and_(
task_defaults.c.user_id == user_id, task_defaults.c.category == category,
)))
if existing:
await db.execute(update(task_defaults).where(and_(
task_defaults.c.user_id == user_id, task_defaults.c.category == category,
)).values(**values))
else:
await db.execute(insert(task_defaults).values(user_id=user_id, category=category, **values))
async def add_notification(db: AsyncSession, user_id: str, kind: str, title: str,
content: str, link: str | None = None,
timestamp: int | None = None) -> None:
await db.execute(insert(notifications).values(
id=new_id(), user_id=user_id, kind=kind[:32], title=title[:120],
content=content[:400], link=(link or "")[:240] or None,
created_at=timestamp or now_ms(),
))
async def task_proof_status(db: AsyncSession, task_id: str) -> dict[str, Any]:
rows = await all_rows(db, select(task_proofs).where(task_proofs.c.task_id == task_id))
by_kind = {row["kind"]: row for row in rows}
items = {
kind: {
"uploaded": kind in by_kind,
"filename": by_kind[kind]["original_name"] if kind in by_kind else None,
"uploadedAt": by_kind[kind]["created_at"] if kind in by_kind else None,
}
for kind in PROOF_KINDS
}
return {"items": items, "ready": all(item["uploaded"] for item in items.values())}
@app.post("/api/tasks", status_code=201)
async def create_task(request: Request) -> dict[str, Any]:
async with SessionLocal() as db:
user = await require_user(request, db)
await ensure_not_sanctioned(db, user, "publish")
body = await parse_task_body(request, user)
task_type, timestamp = body["type"], now_ms()
# MySQL 下锁住用户统计行,避免并发发布把 10 条上限冲破;SQLite 由 WAL 写锁串行化。
await db.execute(select(user_stats.c.user_id).where(user_stats.c.user_id == user["id"]).with_for_update())
stats = await stats_for(db, user["id"])
if int(stats.get("publish_restricted_until") or 0) > timestamp:
retry_days = max(1, (int(stats["publish_restricted_until"]) - timestamp + 86_400_000 - 1) // 86_400_000)
raise HTTPException(403, f"近期取消任务次数较多,暂时限制发单,请在 {retry_days} 天后重试")
active_count = await db.scalar(select(func.count()).select_from(tasks).where(and_(
or_(tasks.c.user_id == user["id"], tasks.c.claimer_id == user["id"]),
tasks.c.status.in_(["open", "claimed"]),
)))
if int(active_count or 0) >= 10:
raise HTTPException(409, "未完成任务已达到 10 条,请先完成任务后再发布")
if task_type == ERRAND_TYPE:
category = body["category"]
spec = ERRAND_CATEGORIES[category]
phone = normalize(body.get("phone"))
if not re.fullmatch(r"[\d\-+ ]{6,20}", phone):
raise HTTPException(400, "请填写有效手机号")
fields = {key: normalize(body.get(key)) for key in spec["require"]}
if any(not fields[key] for key in spec["require"]):
raise HTTPException(400, spec["missing"])
codes: list[str] = []
if spec.get("pickup_codes"):
raw_codes = body.get("pickupCodes")
codes = [normalize(item) for item in raw_codes if normalize(item)] if isinstance(raw_codes, list) else []
if not codes:
raise HTTPException(400, "请填写取件地点、送达位置和取件码")
fields["pickupCodes"] = codes
reward = int(body.get("reward") or 0)
points_min, points_max = spec["points"]
if reward < points_min or reward > points_max:
raise HTTPException(400, f"任务积分需为 {points_min}—{points_max} 的整数")
if int(stats["points_balance"]) < reward:
raise HTTPException(400, f"积分余额不足,发布任务至少需要 {reward} 积分")
fields["sizeDesc"] = normalize(body.get("sizeDesc"))
fields["note"] = normalize(body.get("note"))[:200]
values = dict(id=new_id(), user_id=user["id"], type=ERRAND_TYPE,
title=spec["title"](body["school"], fields), detail=spec["detail"](fields),
place=body["school"], school=body["school"],
deadline=body["deadline"], reward=reward, note=spec["note"](fields),
contact=phone,
pickup_codes=json.dumps(codes, ensure_ascii=False) if spec.get("pickup_codes") else None,
category=category, slots=None, status="open", created_at=timestamp)
else:
title, contact, category, experience = normalize(body.get("title")), normalize(body.get("contact")), normalize(body.get("category")), normalize(body.get("experience"))[:300]
slots = int(body.get("slots") or 0)
if not title or not contact or category not in {"考研自习", "竞赛组队", "运动健身", "兴趣社交"} or not 1 <= slots <= 20:
raise HTTPException(400, "请填写有效的组队任务信息")
link = normalize(body.get("link"))
if link and not re.fullmatch(r"https?://.{4,200}", link):
raise HTTPException(400, "链接格式不正确")
values = dict(id=new_id(), user_id=user["id"], type=task_type, title=title, detail=experience or "期待你的加入",
place=body["school"], school=body["school"], deadline=body["deadline"], reward=0,
note=f"组队链接(待人工审核后展示):{link}" if link else None, contact=contact,
pickup_codes=None, category=category, slots=slots, status="open", created_at=timestamp)
await db.execute(insert(tasks).values(**values))
if task_type == ERRAND_TYPE:
await save_task_defaults(db, user["id"], body, values["category"],
ERRAND_CATEGORIES[values["category"]]["defaults"], timestamp)
await add_notification(
db, user["id"], "task_created", "任务已发布",
f"{values['title']} 已进入 {body['school']} 的任务池。",
f"task:{values['id']}", timestamp,
)
await db.commit()
return {"ok": True, "id": values["id"]}
@app.post("/api/tasks/{task_id}/cancel")
async def cancel_task(task_id: str, request: Request) -> dict[str, Any]:
async with SessionLocal() as db:
user = await require_user(request, db)
await db.rollback()
try:
async with db.begin():
if DB_DRIVER == "sqlite":
# Serialize SQLite writers before reading the state. FOR UPDATE
# is ignored by SQLite, so the conditional UPDATE remains the
# cross-database source of truth below.
await db.execute(text("BEGIN IMMEDIATE"))
task = await one(db, select(tasks).where(tasks.c.id == task_id).with_for_update())
if not task or task["status"] == "cancelled":
raise HTTPException(404, "任务不存在")
admin = is_admin(user)
is_owner = task["user_id"] == user["id"]
is_claimer = task.get("claimer_id") == user["id"]
status = task["status"]
if status not in {"open", "claimed"}:
raise HTTPException(409, "已完成的任务不能取消")
if status == "open" and not (is_owner or admin):
raise HTTPException(403, "只能由发布者取消未接单任务")
if status == "claimed" and not (is_claimer or is_owner or admin):
raise HTTPException(403, "只有任务双方或管理员可以取消任务")
timestamp = now_ms()
publisher_cancel = status == "claimed" and is_owner and not admin
owner_band = None
compensation = 0
reward = int(task.get("reward") or 0)
proofs = {}
if status == "claimed" and task["type"] == ERRAND_TYPE:
proof_rows = await all_rows(db, select(task_proofs).where(task_proofs.c.task_id == task_id))
proofs = {row["kind"]: row for row in proof_rows}
pickup_uploaded = "pickup" in proofs
delivery_uploaded = "delivery" in proofs
if publisher_cancel and pickup_uploaded and delivery_uploaded:
raise HTTPException(409, "任务已送达,请通过完成确认或举报处理")
if is_claimer and not admin and status == "claimed":
claimed_at = int(task.get("claimed_at") or 0)
if not claimed_at:
raise HTTPException(409, "任务接单时间缺失,请联系管理员处理")
if timestamp - claimed_at < RIDER_CANCELLATION_COOLDOWN_MS:
raise HTTPException(409, "接单后 30 分钟内不能取消任务,请稍后再试")
if publisher_cancel:
if pickup_uploaded:
owner_band, compensation = "picked", reward // 2
elif task.get("claimed_at") and timestamp - int(task["claimed_at"]) <= PUBLISHER_CANCELLATION_GRACE_MS:
owner_band = "grace"
else:
owner_band, compensation = "empty_late", reward * 20 // 100
transitioned = await db.execute(update(tasks).where(and_(
tasks.c.id == task_id, tasks.c.status == status,
)).values(status="cancelled", cancelled_at=timestamp, cancelled_by=user["id"]))
if transitioned.rowcount == 0:
raise HTTPException(409, "任务状态已变化,请刷新后重试")
if status == "claimed" and publisher_cancel:
owner_refund = reward - compensation
if owner_refund:
await db.execute(update(user_stats).where(user_stats.c.user_id == task["user_id"]).values(
points_balance=user_stats.c.points_balance + owner_refund, updated_at=timestamp,
))
await db.execute(insert(point_entries).values(
id=new_id(), user_id=task["user_id"], delta=owner_refund, withdrawable_delta=0,
reason=f"任务撤单退款 · {task['title']}"[:400], created_at=timestamp,
))
if compensation and task.get("claimer_id"):
await db.execute(update(user_stats).where(user_stats.c.user_id == task["claimer_id"]).values(
points_balance=user_stats.c.points_balance + compensation, updated_at=timestamp,
))
comp_reason = "已取件撤单补偿" if owner_band == "picked" else "空跑补偿"
await db.execute(insert(point_entries).values(
id=new_id(), user_id=task["claimer_id"], delta=compensation, withdrawable_delta=0,
reason=f"{comp_reason} · {task['title']}"[:400], created_at=timestamp,
))
elif status == "claimed" and reward > 0:
# Claimer/admin cancellations return the full claimed reward.
await db.execute(update(user_stats).where(user_stats.c.user_id == task["user_id"]).values(
points_balance=user_stats.c.points_balance + reward, updated_at=timestamp,
))
await db.execute(insert(point_entries).values(
id=new_id(), user_id=task["user_id"], delta=reward, withdrawable_delta=0,
reason=f"任务取消退款 · {task['title']}"[:400], created_at=timestamp,
))
rider_report_pending = False
if publisher_cancel and owner_band == "picked":
open_report = await db.scalar(select(reports.c.id).where(and_(
reports.c.target_type == "task", reports.c.target_id == task_id,
reports.c.status == "open",
)).limit(1))
rider_report_pending = bool(open_report)
await record_reliability_event(
db, event_key=f"task-publisher-cancel-review:{task_id}:{task['user_id']}",
user_id=task["user_id"], task_id=task_id, kind="task_review",
status="pending", note=(
"发布者在接单人上传取件照后撤单;"
+ ("任务存在未处理举报,信用责任交管理员核实。" if rider_report_pending
else "暂按发布者违约处理;如接单人责任成立,管理员可撤销处罚。")
), timestamp=timestamp,
)
if not rider_report_pending:
adjustment = await record_credit_change(
db, task["user_id"], -3, "违约处理", "已取件后发布者撤单 · -3",
task_id=task_id, rule_key=f"task-publisher-cancel-picked:{task_id}:{task['user_id']}",
)
await record_reliability_event(
db, event_key=f"task-publisher-cancel-breach:{task_id}:{task['user_id']}",
user_id=task["user_id"], task_id=task_id, kind="breach", status="confirmed",
adjustment_id=adjustment["id"], note="接单人已取件后发布者撤单。", timestamp=timestamp,
)
await add_notification(
db, task["user_id"], "credit_adjusted", "信用分已调整",
f"已取件后发布者撤单,信用分 {adjustment['delta']:+d}。", "profile", timestamp,
)
restriction_applied = False
restriction_role = None
if status == "claimed" and is_claimer and not admin:
restriction_applied = await apply_cancellation_frequency_limit(
db, user_id=user["id"], role="rider", timestamp=timestamp,
)
restriction_role = "rider" if restriction_applied else None
elif is_owner and not admin:
restriction_applied = await apply_cancellation_frequency_limit(
db, user_id=user["id"], role="publisher", timestamp=timestamp,
)
restriction_role = "publisher" if restriction_applied else None
if status == "claimed" and is_claimer and not admin:
if task.get("deadline") is None:
await record_reliability_event(
db, event_key=f"task-cancel-review:{task_id}:{user['id']}",
user_id=user["id"], task_id=task_id, kind="task_review",
status="pending", note="任务缺少截止时间,取消责任待管理员核实。", timestamp=timestamp,
)
elif await db.scalar(select(reports.c.id).where(and_(
reports.c.target_type == "task", reports.c.target_id == task_id,
reports.c.status == "open",
)).limit(1)):
await record_reliability_event(
db, event_key=f"task-cancel-dispute:{task_id}:{user['id']}",
user_id=user["id"], task_id=task_id, kind="task_review",
status="pending", note="取消时任务存在待处理举报,信用处理需管理员核实。", timestamp=timestamp,
)
elif int(task["deadline"]) - timestamp < 2 * 60 * 60_000:
adjustment = await record_credit_change(
db, user["id"], -3, "违约处理", "距截止时间不足 2 小时取消 · -3",
task_id=task_id, rule_key=f"task-cancel-short:{task_id}:{user['id']}",
)
await record_reliability_event(
db, event_key=f"task-cancel-breach:{task_id}:{user['id']}",
user_id=user["id"], task_id=task_id, kind="breach", status="confirmed",
adjustment_id=adjustment["id"], note="距截止时间不足 2 小时主动取消。", timestamp=timestamp,
)
await add_notification(
db, user["id"], "credit_adjusted", "信用分已调整",
f"距截止时间不足 2 小时取消,信用分 {adjustment['delta']:+d}。", "profile", timestamp,
)
else:
# TODO(product): keep this hook as the cancellation bands
# evolve; current policy is >=2h: 0, <2h: -3.
await record_credit_change(
db, user["id"], 0, "更正", "距截止时间 2 小时及以上取消 · 0",
task_id=task_id, rule_key=f"task-cancel-early:{task_id}:{user['id']}",
)
elif status == "claimed" and admin and task.get("claimer_id"):
await record_reliability_event(
db, event_key=f"task-admin-cancel-review:{task_id}:{task['claimer_id']}",
user_id=task["claimer_id"], task_id=task_id, kind="task_review",
status="pending", reviewed_by=user["id"],
note="管理员结束进行中任务,接单责任待审核。", timestamp=timestamp,
)
if status == "claimed":
rider_notice = f"任务“{task['title']}”已取消。"
if publisher_cancel:
if owner_band == "grace":
rider_notice = f"任务“{task['title']}”在接单 10 分钟内、取件前取消;无需补偿,发布者已收到全额退款。"
elif owner_band == "empty_late":
rider_notice = f"任务“{task['title']}”在取件前取消,你已收到 {compensation} 积分空跑补偿。"
elif owner_band == "picked":
rider_notice = f"任务“{task['title']}”在取件后取消,你已收到 {compensation} 积分补偿。包裹仍在骑手处,请双方协商取回,纠纷走举报。"
if rider_report_pending:
rider_notice += "任务有未处理举报,发布者信用责任将由管理员核实。"
owner_notice = f"进行中任务“{task['title']}”已取消,已退回 {reward - compensation} 积分。"
else:
owner_notice = f"任务“{task['title']}”已取消,接单积分已退回你的余额。"
if restriction_applied:
restricted_action = "接单" if restriction_role == "rider" else "发单"
if restriction_role == "rider":
rider_notice += f"你近 30 天取消任务已达 {CANCELLATION_LIMIT} 次,接单功能限制 7 天。"
else:
owner_notice += f"你近 30 天撤单已达 {CANCELLATION_LIMIT} 次,发单功能限制 7 天。"
await add_notification(
db, task["user_id"], "task_cancelled", "进行中任务已取消",
owner_notice,
f"task:{task_id}", timestamp,
)
if task.get("claimer_id") and task["claimer_id"] != task["user_id"]:
await add_notification(
db, task["claimer_id"], "task_cancelled", "进行中任务已取消",
rider_notice,
f"task:{task_id}", timestamp,
)
elif restriction_applied:
await add_notification(
db, task["user_id"], "task_cancelled", "近期发单功能已限制",
f"你近 30 天撤单已达 {CANCELLATION_LIMIT} 次,发单功能限制 7 天。",
f"task:{task_id}", timestamp,
)
except OperationalError as error:
if DB_DRIVER == "sqlite" and ("database is locked" in str(error).lower() or "sqlite_busy" in str(error).lower()):
raise HTTPException(409, "任务状态已变化,请刷新后重试") from error
raise
return {
"ok": True,
"refunded": bool(status == "claimed" and (reward - compensation > 0 if publisher_cancel else reward > 0)),
"band": owner_band,
"ownerRefund": (reward - compensation) if publisher_cancel else (reward if status == "claimed" else 0),
"riderCompensation": compensation if publisher_cancel else 0,
"creditReviewPending": rider_report_pending if publisher_cancel else False,
"restrictionApplied": restriction_applied,
}
@app.post("/api/tasks/{task_id}/join", status_code=201)
async def join_task(task_id: str, request: Request) -> dict[str, Any]:
"""组队任务申请加入:记录参与者并实时返回名额占用。"""
async with SessionLocal() as db:
user = await require_user(request, db)
await ensure_not_sanctioned(db, user, "claim")
await db.rollback()
async with db.begin():
task = await one(db, select(tasks).where(tasks.c.id == task_id).with_for_update())
if not task or task["status"] == "cancelled":
raise HTTPException(404, "任务不存在")
if task["type"] != "partner":
raise HTTPException(400, "只有组队任务可以申请加入")
if task["user_id"] == user["id"]:
raise HTTPException(400, "不能加入自己发布的组队")
if task["status"] != "open":
raise HTTPException(409, "该组队已结束")
if await one(db, select(task_participants).where(and_(
task_participants.c.task_id == task_id, task_participants.c.user_id == user["id"],
))):
raise HTTPException(409, "你已申请过该组队")
joined = int(await db.scalar(select(func.count()).select_from(task_participants)
.where(task_participants.c.task_id == task_id)) or 0)
slots = int(task.get("slots") or 0)
if slots and joined >= slots:
raise HTTPException(409, "组队名额已满")
await db.execute(insert(task_participants).values(
task_id=task_id, user_id=user["id"], created_at=now_ms(),
))
await add_notification(
db, task["user_id"], "partner_joined", "新的组队申请",
f"{user['nickname']} 申请加入你的组队“{task['title']}”,当前名额 {joined + 1}/{slots}。",
f"task:{task_id}",
)
joined_text = f"{joined + 1}/{slots}" if slots else None
return {"ok": True, "joined": joined_text}
@app.post("/api/tasks/{task_id}/claim")
async def claim_task(task_id: str, request: Request) -> dict[str, Any]:
async with SessionLocal() as db:
user = await require_user(request, db)
await ensure_not_sanctioned(db, user, "claim")
# 非待接单任务始终返回冲突;开放任务的认证检查仍发生在行锁之前。
current = await one(db, select(tasks.c.status, tasks.c.type).where(tasks.c.id == task_id))
if not current or current["status"] == "cancelled":
raise HTTPException(404, "任务不存在")
if current["status"] != "open":
raise HTTPException(409, "任务已被其他同学接单或完成")
verification = await verification_summary(db, user["id"])
if verification["level"] < 2:
raise HTTPException(403, {
"error": "L2 及以上认证才能接单,请在「我的」页完成认证",
"code": "VERIFICATION_REQUIRED",
"verification": verification,
})
await db.rollback()
try:
async with db.begin():
if DB_DRIVER == "sqlite":
# SQLite ignores FOR UPDATE; acquire the writer slot before
# reading transactional state, then use conditional writes.
await db.execute(text("BEGIN IMMEDIATE"))
task = await one(db, select(tasks).where(tasks.c.id == task_id).with_for_update())
if not task or task["status"] == "cancelled":
raise HTTPException(404, "任务不存在")
if task["type"] != ERRAND_TYPE:
raise HTTPException(400, "组队任务请在详情内申请加入")
if task["user_id"] == user["id"]:
raise HTTPException(400, "不能接自己发布的任务")
if task["status"] != "open":
raise HTTPException(409, "任务已被其他同学接单")
await db.execute(select(user_stats.c.user_id).where(user_stats.c.user_id == user["id"]).with_for_update())
user_stats_row = await one(db, select(user_stats).where(user_stats.c.user_id == user["id"]))
if int((user_stats_row or {}).get("claim_restricted_until") or 0) > now_ms():
retry_days = max(1, (int(user_stats_row["claim_restricted_until"]) - now_ms() + 86_400_000 - 1) // 86_400_000)
raise HTTPException(403, f"近期取消任务次数较多,暂时限制接单,请在 {retry_days} 天后重试")
active_count = await db.scalar(select(func.count()).select_from(tasks).where(and_(
or_(tasks.c.user_id == user["id"], tasks.c.claimer_id == user["id"]),
tasks.c.status.in_(["open", "claimed"]),
)))
if int(active_count or 0) >= 10:
raise HTTPException(409, "未完成任务已达到 10 条,请先完成任务后再接单")
reward = int(task["reward"] or 0)
claimed_at = now_ms()
transitioned = await db.execute(update(tasks).where(and_(
tasks.c.id == task_id, tasks.c.status == "open",
)).values(status="claimed", claimer_id=user["id"], claimed_at=claimed_at))
if transitioned.rowcount == 0:
raise HTTPException(409, "任务已被其他同学接单")
free_part = await deduct_points(db, task["user_id"], reward, timestamp=claimed_at)
if free_part is None:
raise HTTPException(409, "发布者积分余额不足,任务已暂不可接")
await db.execute(insert(point_entries).values(
id=new_id(), user_id=task["user_id"], delta=-reward, withdrawable_delta=-free_part,
reason=f"任务被接单 · {task['title']}"[:400], created_at=claimed_at,
))
await db.execute(update(user_stats).where(user_stats.c.user_id == task["user_id"]).values(
commitments_count=user_stats.c.commitments_count + 1, updated_at=claimed_at,
))
await db.execute(update(user_stats).where(user_stats.c.user_id == user["id"]).values(
commitments_count=user_stats.c.commitments_count + 1, updated_at=claimed_at,
))
await add_notification(
db, task["user_id"], "task_claimed", "任务已被接单",
f"你的任务“{task['title']}”已被同学接下,请按任务信息完成交接。",
f"task:{task_id}",
)
except OperationalError as error:
if DB_DRIVER == "sqlite" and ("database is locked" in str(error).lower() or "sqlite_busy" in str(error).lower()):
raise HTTPException(409, "任务已被其他同学接单") from error
raise
return {"ok": True, "contact": task["contact"], "pickupCodes": json_load(task["pickup_codes"], [])}
@app.post("/api/tasks/{task_id}/proofs/{kind}")
async def upload_task_proof(task_id: str, kind: str, request: Request,
photo: UploadFile = File(...)) -> dict[str, Any]:
if kind not in PROOF_KINDS:
raise HTTPException(404, "凭证类型不存在")
data = await photo.read(MAX_PROOF_BYTES + 1)
await photo.close()
if not data:
raise HTTPException(400, "请选择需要上传的照片")
if len(data) > MAX_PROOF_BYTES:
raise HTTPException(413, f"单张照片不能超过 {MAX_PROOF_BYTES // 1024 // 1024}MB")
detected = detect_proof_image(data)
if not detected:
raise HTTPException(400, "仅支持 JPG、PNG 或 WebP 图片")
extension, mime_type = detected
relative_path = Path(task_id) / f"{kind}-{uuid.uuid4().hex}{extension}"
destination = PROOF_DIR / relative_path
destination.parent.mkdir(parents=True, exist_ok=True)
await asyncio.to_thread(destination.write_bytes, data)
previous_path: Path | None = None
committed = False
try:
async with SessionLocal() as db:
user = await require_user(request, db)
task = await one(db, select(tasks).where(tasks.c.id == task_id))
if not task or task["type"] != ERRAND_TYPE:
raise HTTPException(404, "跑腿任务不存在")
if task["status"] != "claimed":
raise HTTPException(409, "只有进行中的任务可以上传凭证")
if task.get("claimer_id") != user["id"]:
raise HTTPException(403, "只有接单人可以上传任务凭证")
existing = await one(db, select(task_proofs).where(and_(
task_proofs.c.task_id == task_id, task_proofs.c.kind == kind,
)))
values = {
"uploader_id": user["id"],
"file_path": relative_path.as_posix(),
"original_name": Path(photo.filename or f"{kind}{extension}").name[:240],
"mime_type": mime_type,
"file_size": len(data),
"created_at": now_ms(),
}
if existing:
previous_path = PROOF_DIR / str(existing["file_path"])
await db.execute(update(task_proofs).where(and_(
task_proofs.c.task_id == task_id, task_proofs.c.kind == kind,
)).values(**values))
else:
await db.execute(insert(task_proofs).values(task_id=task_id, kind=kind, **values))
status = await task_proof_status(db, task_id)
labels = errand_spec(task)["proof_labels"]
await add_notification(
db, task["user_id"], "task_proof_uploaded", "凭证已上传",
f"任务“{task['title']}”的{labels[kind]}已上传。"
+ ("两张凭证均已齐全,可以确认完成。" if status["ready"] else ""),
f"task:{task_id}",
)
await db.commit()
committed = True
except Exception:
if not committed and destination.is_file():
await asyncio.to_thread(destination.unlink)
raise
if previous_path and previous_path != destination and previous_path.is_file():
try:
await asyncio.to_thread(previous_path.unlink)
except OSError:
pass
return {"ok": True, "proofs": status}
@app.post("/api/tasks/{task_id}/complete")
async def complete_task(task_id: str, request: Request) -> dict[str, Any]:
async with SessionLocal() as db:
user = await require_user(request, db)
await db.rollback()
async with db.begin():
task = await one(db, select(tasks).where(tasks.c.id == task_id).with_for_update())
if not task or task["status"] != "claimed":
raise HTTPException(409, "任务当前无法完成")
if user["id"] not in {task["user_id"], task["claimer_id"]}:
raise HTTPException(403, "只有任务双方可以确认完成")
if task["type"] != ERRAND_TYPE:
raise HTTPException(400, "只有跑腿代办任务需要交付确认")
labels = errand_spec(task)["proof_labels"]
proof_rows = await all_rows(db, select(task_proofs).where(task_proofs.c.task_id == task_id))
proof_by_kind = {row["kind"]: row for row in proof_rows}
missing = [labels[kind] for kind in PROOF_KINDS if kind not in proof_by_kind]
if missing:
raise HTTPException(409, f"请由接单人先上传{'和'.join(missing)}")
proof_files: list[tuple[str, Path, str]] = []
for kind, label in labels.items():
row = proof_by_kind[kind]
path = PROOF_DIR / str(row["file_path"])
if not path.is_file():
raise HTTPException(409, f"{label}文件缺失,请接单人重新上传")
proof_files.append((label, path, str(row["mime_type"])))
owner = await one(db, select(users.c.email).where(users.c.id == task["user_id"]))
if not owner or not owner.get("email"):
raise HTTPException(409, "发布者邮箱不可用,暂时不能完成任务")
try:
await send_task_proof_email(str(owner["email"]), task["title"], proof_files,
category=task["category"] or "快递代取")
except HTTPException:
raise
except Exception:
raise HTTPException(502, "凭证邮件发送失败,任务尚未完成,请稍后重试")
await db.execute(update(tasks).where(tasks.c.id == task_id).values(
status="done", completed_at=now_ms(),
))
if task["claimer_id"]:
reward = int(task["reward"] or 0)
await db.execute(update(user_stats).where(user_stats.c.user_id == task["claimer_id"]).values(
points_balance=user_stats.c.points_balance + reward,
withdrawable_points=user_stats.c.withdrawable_points + reward,
completed_tasks=user_stats.c.completed_tasks + 1,
current_streak=user_stats.c.current_streak + 1,
updated_at=now_ms(),
))
await db.execute(insert(point_entries).values(
id=new_id(), user_id=task["claimer_id"], delta=reward, withdrawable_delta=reward,
reason=f"完成{task['category'] or '快递代取'} · {task['title']}"[:400], created_at=now_ms(),
))
await db.execute(update(user_stats).where(user_stats.c.user_id == task["user_id"]).values(
completed_tasks=user_stats.c.completed_tasks + 1,
current_streak=user_stats.c.current_streak + 1,
updated_at=now_ms(),
))
await settle_task_completion_credit(db, dict(task))
await add_notification(
db, task["user_id"], "task_completed", "任务已完成",
f"你的任务“{task['title']}”已确认完成,积分已结算,两张凭证照片已发送至注册邮箱。",
f"task:{task_id}",
)
await add_notification(
db, task["claimer_id"], "task_completed", "任务已完成",
f"你接取的任务“{task['title']}”已确认完成,积分已到账。",
f"task:{task_id}",
)
return {"ok": True}
@app.get("/api/my/tasks")
async def my_tasks(request: Request) -> dict[str, Any]:
async with SessionLocal() as db:
user = await require_user(request, db)
ownership = or_(tasks.c.user_id == user["id"], tasks.c.claimer_id == user["id"])
active_count = await db.scalar(select(func.count()).select_from(tasks).where(and_(ownership, tasks.c.status.in_(["open", "claimed"]))))
active_rows = await all_rows(db, select(tasks).where(and_(ownership, tasks.c.status.in_(["open", "claimed"]))).order_by(tasks.c.created_at.desc()))
completed_rows = await all_rows(db, select(tasks).where(and_(ownership, tasks.c.status == "done")).order_by(tasks.c.created_at.desc()).limit(20))
rows = active_rows + completed_rows
return {"ok": True, "items": [
{"id": row["id"], "type": row["type"], "title": row["title"], "place": row["place"],
"deadline": row["deadline"], "reward": int(row["reward"] or 0), "status": row["status"],
"role": "claimed" if row["claimer_id"] == user["id"] else "published",
"phone": row.get("contact") if row["claimer_id"] == user["id"] else None,
"createdAt": row["created_at"]}
for row in rows
], "activeCount": int(active_count or 0), "activeLimit": 10, "completedLimit": 20}
@app.get("/api/my/tasks/{task_id}")
async def my_task_detail(task_id: str, request: Request) -> dict[str, Any]:
"""我相关任务的完整详情:发布者可看组队申请人,双方可见联系方式。"""
async with SessionLocal() as db:
user = await require_user(request, db)
task = await one(db, select(tasks).where(tasks.c.id == task_id))
if not task:
raise HTTPException(404, "任务不存在")
is_owner = task["user_id"] == user["id"]
is_claimer = task.get("claimer_id") == user["id"]
if not (is_owner or is_claimer or is_admin(user)):
raise HTTPException(403, "只能查看自己发布或接受的任务")
participants = []
if task["type"] == "partner" and is_owner:
rows = await all_rows(db, select(
task_participants.c.user_id, task_participants.c.created_at,
users.c.nickname, users.c.school, user_stats.c.credit_score,
).select_from(task_participants
.join(users, users.c.id == task_participants.c.user_id)
.outerjoin(user_stats, user_stats.c.user_id == task_participants.c.user_id)
).where(task_participants.c.task_id == task_id)
.order_by(task_participants.c.created_at))
participants = [{"userId": r["user_id"], "nickname": r["nickname"], "school": r["school"],
"credit": int(r["credit_score"] or 70), "joinedAt": r["created_at"]}
for r in rows]
proofs = await task_proof_status(db, task_id) if task["type"] == ERRAND_TYPE else None
detail = {
"id": task["id"], "type": task["type"], "title": task["title"],
"detail": task["detail"], "place": task["place"], "deadline": task["deadline"],
"reward": int(task["reward"] or 0), "note": task["note"], "category": task["category"],
"slots": task.get("slots"), "status": task["status"], "createdAt": task["created_at"],
"claimedAt": task.get("claimed_at"),
"role": "owner" if is_owner else "claimer", "contact": task.get("contact"),
"pickupCodes": json_load(task.get("pickup_codes"), []) if (is_claimer or is_owner) else [],
"participants": participants,
"proofs": proofs,
}
return {"ok": True, "task": detail}
@app.post("/api/reports", status_code=201)
async def create_report(request: Request) -> dict[str, Any]:
async with SessionLocal() as db:
user = await require_user(request, db)
body = await request.json()
target_type, target_id, reason = normalize(body.get("targetType")), normalize(body.get("targetId")), normalize(body.get("reason"))[:400]
if target_type not in {"task", "chat"} or not target_id:
raise HTTPException(400, "举报对象无效")
if len(reason) < 5:
raise HTTPException(400, "请填写举报理由(5—200 字)")
if await one(db, select(reports.c.id).where(and_(
reports.c.reporter_id == user["id"], reports.c.target_type == target_type,
reports.c.target_id == target_id, reports.c.status == "open",
))):
raise HTTPException(409, "你已经举报过该目标")
target_user_id = None
conversation_id = None
message_snapshot = None
if target_type == "task":
if not await one(db, select(tasks.c.id).where(tasks.c.id == target_id)):
raise HTTPException(404, "被举报任务不存在")
else:
conversation, peer_id = await require_conversation_member(db, target_id, user["id"])
target_user_id = normalize(body.get("targetUserId"))
if target_user_id != peer_id:
raise HTTPException(400, "举报对象无效")
conversation_id = conversation["id"]
recent = await all_rows(db, select(
messages.c.sender_id, messages.c.content, messages.c.created_at,
).where(messages.c.conversation_id == conversation_id).order_by(
messages.c.created_at.desc(), messages.c.id.desc(),
).limit(20))
message_snapshot = json.dumps([{
"senderId": row["sender_id"], "content": row["content"],
"createdAt": row["created_at"],
} for row in recent], ensure_ascii=False)
report_id = new_id()
await db.execute(insert(reports).values(
id=report_id, reporter_id=user["id"], target_type=target_type,
target_id=target_id, target_user_id=target_user_id,
conversation_id=conversation_id, message_snapshot=message_snapshot,
reason=reason, status="open", created_at=now_ms(),
))
await db.commit()
return {"ok": True, "id": report_id}
async def admin_required(request: Request, db: AsyncSession) -> dict[str, Any]:
user = await require_user(request, db)
if not is_admin(user):
raise HTTPException(403, "无管理权限")
return user
async def write_admin_audit(
db: AsyncSession, request: Request, admin: dict[str, Any], action: str,
target_user_id: str | None, detail: str,
) -> None:
timestamp = now_ms()
await db.execute(insert(admin_audit_logs).values(
id=new_id(), admin_id=admin["id"], action=action[:80],
target_user_id=target_user_id, detail=detail[:400],
ip=client_ip(request)[:64], created_at=timestamp,
))
await db.execute(delete(admin_audit_logs).where(
admin_audit_logs.c.created_at < timestamp - LOGIN_LOG_RETENTION_MS,
))
def official_integer(value: Any, label: str, minimum: int, maximum: int | None = None) -> int:
if isinstance(value, bool):
raise HTTPException(400, f"{label}格式无效")
try:
number = int(value)
except (TypeError, ValueError):
raise HTTPException(400, f"{label}格式无效") from None
if str(value).strip() not in {str(number), f"+{number}"}:
raise HTTPException(400, f"{label}必须为整数")
if number < minimum or (maximum is not None and number > maximum):
suffix = f"—{maximum}" if maximum is not None else "及以上"
raise HTTPException(400, f"{label}须为 {minimum}{suffix}")
return number
def official_deadline(value: Any) -> int | None:
if value in (None, ""):
return None
if isinstance(value, bool):
raise HTTPException(400, "下架时间格式无效")
try:
return int(value)
except (TypeError, ValueError):
try:
return int(datetime.fromisoformat(str(value)).timestamp() * 1000)
except (TypeError, ValueError, OverflowError):
raise HTTPException(400, "下架时间格式无效") from None
@app.get("/api/admin/official-tasks")
async def admin_list_official_tasks(request: Request) -> dict[str, Any]:
async with SessionLocal() as db:
await admin_required(request, db)
rows = await all_rows(db, select(official_tasks).order_by(official_tasks.c.created_at.desc()))
counts, user_counts = await official_task_claim_counts(db)
return {"ok": True, "items": [{
**official_task_payload(row, counts.get(row["id"], 0), user_counts.get(row["id"], 0)),
"adminId": row["admin_id"],
} for row in rows]}
@app.post("/api/admin/official-tasks", status_code=201)
async def admin_create_official_task(request: Request) -> dict[str, Any]:
async with SessionLocal() as db:
admin = await admin_required(request, db)
try:
body = await request.json()
except Exception:
raise HTTPException(400, "请求内容无效") from None
if not isinstance(body, dict):
raise HTTPException(400, "请求内容无效")
title = normalize(body.get("title"))
detail = normalize(body.get("detail"))
if not title or len(title) > 60:
raise HTTPException(400, "标题长度须为 1—60 字")
if len(detail) > 500:
raise HTTPException(400, "详情不能超过 500 字")
reward = official_integer(body.get("reward"), "单次奖励", 1, 5000)
per_account_limit = official_integer(body.get("perAccountLimit", body.get("per_account_limit")), "每账号限领次数", 1, 99)
total_quota = official_integer(body.get("totalQuota", body.get("total_quota", 0)), "总名额", 0)
deadline = official_deadline(body.get("deadline"))
timestamp, task_id = now_ms(), new_id()
await db.execute(insert(official_tasks).values(
id=task_id, admin_id=admin["id"], title=title, detail=detail,
reward=reward, per_account_limit=per_account_limit,
total_quota=total_quota, status="active", deadline=deadline,
created_at=timestamp,
))
await write_admin_audit(
db, request, admin, "official_task_created", None,
f"task={task_id}; title={title}; reward={reward}; perAccountLimit={per_account_limit}; totalQuota={total_quota}",
)
await db.commit()
task = {"id": task_id, "admin_id": admin["id"], "title": title, "detail": detail,
"reward": reward, "per_account_limit": per_account_limit, "total_quota": total_quota,
"status": "active", "deadline": deadline, "created_at": timestamp}
return {"ok": True, "task": official_task_payload(task, 0, 0)}
@app.post("/api/admin/official-tasks/{task_id}/close")
async def admin_close_official_task(task_id: str, request: Request) -> dict[str, bool]:
async with SessionLocal() as db:
admin = await admin_required(request, db)
task = await one(db, select(official_tasks).where(official_tasks.c.id == task_id))
if not task:
raise HTTPException(404, "官方任务不存在")
if task["status"] == "active":
await db.execute(update(official_tasks).where(and_(
official_tasks.c.id == task_id, official_tasks.c.status == "active",
)).values(status="closed"))
await write_admin_audit(
db, request, admin, "official_task_closed", None,
f"task={task_id}; title={task['title']}",
)
await db.commit()
return {"ok": True}
def date_only(timestamp: int | None) -> str | None:
if timestamp is None:
return None
return datetime.fromtimestamp(int(timestamp) / 1000, tz=timezone.utc).astimezone().strftime("%Y-%m-%d")
@app.get("/api/admin/login-logs")
async def admin_login_logs(
request: Request, user_id: str | None = None, ip: str | None = None,
success: str | None = None, method: str | None = None, offset: int = 0,
) -> dict[str, Any]:
async with SessionLocal() as db:
await admin_required(request, db)
predicates = []
if user_id:
predicates.append(login_logs.c.user_id == user_id)
if ip:
predicates.append(login_logs.c.ip == ip[:64])
if success is not None:
if success.lower() not in {"true", "false", "1", "0"}:
raise HTTPException(400, "success 筛选值无效")
predicates.append(login_logs.c.success == (success.lower() in {"true", "1"}))
if method:
if method not in {"password", "code"}:
raise HTTPException(400, "登录方式无效")
predicates.append(login_logs.c.method == method)
if offset < 0:
raise HTTPException(400, "offset 不能小于 0")
stmt = select(login_logs).order_by(login_logs.c.created_at.desc(), login_logs.c.id.desc()).limit(100).offset(offset)
if predicates:
stmt = stmt.where(and_(*predicates))
rows = await all_rows(db, stmt)
return {"ok": True, "items": [{
"id": row["id"], "userId": row["user_id"], "emailAttempted": row["email_attempted"],
"success": bool(row["success"]), "method": row["method"], "ip": row["ip"],
"userAgent": row["user_agent"], "createdAt": row["created_at"],
} for row in rows], "nextOffset": offset + len(rows) if len(rows) == 100 else None}
@app.get("/api/admin/audit-logs")
async def admin_audit_log_list(
request: Request, admin_id: str | None = None, action: str | None = None, offset: int = 0,
) -> dict[str, Any]:
async with SessionLocal() as db:
await admin_required(request, db)
if offset < 0:
raise HTTPException(400, "offset 不能小于 0")
predicates = []
if admin_id:
predicates.append(admin_audit_logs.c.admin_id == admin_id)
if action:
predicates.append(admin_audit_logs.c.action == action[:80])
stmt = select(admin_audit_logs).order_by(admin_audit_logs.c.created_at.desc(), admin_audit_logs.c.id.desc()).limit(100).offset(offset)
if predicates:
stmt = stmt.where(and_(*predicates))
rows = await all_rows(db, stmt)
return {"ok": True, "items": [{
"id": row["id"], "adminId": row["admin_id"], "action": row["action"],
"targetUserId": row["target_user_id"], "detail": row["detail"],
"ip": row["ip"], "createdAt": row["created_at"],
} for row in rows], "nextOffset": offset + len(rows) if len(rows) == 100 else None}
@app.get("/api/admin/users/{user_id}/security")
async def admin_user_security(user_id: str, request: Request) -> dict[str, Any]:
async with SessionLocal() as db:
await admin_required(request, db)
if not await one(db, select(users.c.id).where(users.c.id == user_id)):
raise HTTPException(404, "用户不存在")
ips = await all_rows(db, select(user_known_ips).where(user_known_ips.c.user_id == user_id).order_by(user_known_ips.c.last_seen.desc()))
active_sessions = await all_rows(db, select(sessions.c.id, sessions.c.ip, sessions.c.user_agent,
sessions.c.created_at, sessions.c.expires_at).where(and_(
sessions.c.user_id == user_id, sessions.c.expires_at > now_ms(),
)).order_by(sessions.c.created_at.desc()))
recent = await all_rows(db, select(login_logs).where(login_logs.c.user_id == user_id).order_by(
login_logs.c.created_at.desc(), login_logs.c.id.desc(),
).limit(20))
return {"ok": True,
"knownIps": [{"ip": row["ip"], "firstSeen": row["first_seen"], "lastSeen": row["last_seen"]} for row in ips],
"sessions": [{"id": row["id"], "ip": row["ip"], "userAgent": row["user_agent"],
"createdAt": row["created_at"], "expiresAt": row["expires_at"]} for row in active_sessions],
"loginLogs": [{"id": row["id"], "emailAttempted": row["email_attempted"],
"success": bool(row["success"]), "method": row["method"], "ip": row["ip"],
"userAgent": row["user_agent"], "createdAt": row["created_at"]} for row in recent],
}
@app.get("/api/admin/users/{user_id}/sanctions")
async def admin_user_sanctions(user_id: str, request: Request) -> dict[str, Any]:
async with SessionLocal() as db:
await admin_required(request, db)
if not await one(db, select(users.c.id).where(users.c.id == user_id)):
raise HTTPException(404, "用户不存在")
rows = await all_rows(db, select(account_sanctions).where(
account_sanctions.c.user_id == user_id,
).order_by(account_sanctions.c.created_at.desc()).limit(100))
admin_ids = {row["admin_id"] for row in rows} | {row["lifted_by"] for row in rows if row.get("lifted_by")}
admin_rows = await all_rows(db, select(users.c.id, users.c.name, users.c.nickname).where(users.c.id.in_(admin_ids))) if admin_ids else []
admin_names = {row["id"]: row["name"] or row["nickname"] for row in admin_rows}
timestamp = now_ms()
return {"ok": True, "items": [{
"id": row["id"], "action": row["action"], "scope": row["scope"],
"category": row.get("category"), "reason": row["reason"],
"adminId": row["admin_id"], "adminName": admin_names.get(row["admin_id"], "管理员"),
"createdAt": row["created_at"], "expiresAt": row.get("expires_at"),
"liftedAt": row.get("lifted_at"), "liftedBy": row.get("lifted_by"),
"liftedByName": admin_names.get(row.get("lifted_by"), "管理员") if row.get("lifted_by") else None,
"active": row["action"] in {"ban", "restrict"} and row.get("lifted_at") is None
and (row.get("expires_at") is None or int(row["expires_at"]) > timestamp),
} for row in rows]}
@app.post("/api/admin/users/{user_id}/sanctions")
async def manage_user_sanction(user_id: str, request: Request) -> dict[str, Any]:
async with SessionLocal() as db:
admin = await admin_required(request, db)
body = await request.json()
action = normalize(body.get("action"))
reason = normalize(body.get("reason"))[:400]
if action not in {"ban", "restrict", "lift"}:
raise HTTPException(400, "处理动作无效")
if not reason:
raise HTTPException(400, "请填写仅管理员可见的处理理由")
target = await one(db, select(users).where(users.c.id == user_id))
if not target:
raise HTTPException(404, "用户不存在")
if user_id == admin["id"]:
raise HTTPException(400, "不能对自己的账号执行制裁")
if is_admin(target):
raise HTTPException(400, "不能对管理员账号执行制裁")
timestamp = now_ms()
if action == "lift":
lifted = await db.execute(update(account_sanctions).where(and_(
account_sanctions.c.user_id == user_id,
account_sanctions.c.action.in_(("ban", "restrict")),
account_sanctions.c.lifted_at.is_(None),
or_(account_sanctions.c.expires_at.is_(None), account_sanctions.c.expires_at > timestamp),
)).values(lifted_at=timestamp, lifted_by=admin["id"]))
if not lifted.rowcount:
raise HTTPException(400, "该账号当前没有生效中的处理")
await db.execute(insert(account_sanctions).values(
id=new_id(), user_id=user_id, admin_id=admin["id"], action="lift", scope="all",
category=None, reason=reason, created_at=timestamp, expires_at=None,
lifted_at=None, lifted_by=None,
))
await db.execute(update(users).where(users.c.id == user_id).values(status="active", status_until=None))
await add_notification(
db, user_id, "account_sanction", "账号限制已解除",
f"管理员已解除账号限制。如有疑问,请联系管理员:{ADMIN_SANCTION_CONTACT}",
"profile", timestamp,
)
await write_admin_audit(db, request, admin, "account_sanction_lift", user_id, reason)
await db.commit()
return {"ok": True, "status": "active"}
category = normalize(body.get("category"))
if category not in ACCOUNT_SANCTION_CATEGORIES:
raise HTTPException(400, "请选择有效的制裁原因分类")
raw_scopes = body.get("scopes", body.get("scope", []))
if isinstance(raw_scopes, str):
raw_scopes = [raw_scopes]
if action == "ban":
if not isinstance(raw_scopes, list) or any(not isinstance(scope, str) for scope in raw_scopes):
raise HTTPException(400, "封禁范围固定为全站")
if raw_scopes and set(raw_scopes) != {"all"}:
raise HTTPException(400, "封禁范围固定为全站")
scopes = ["all"]
else:
if not isinstance(raw_scopes, list) or any(not isinstance(scope, str) for scope in raw_scopes):
raise HTTPException(400, "请选择至少一个有效限制维度")
scopes = sorted(set(raw_scopes))
if not scopes or any(scope not in SANCTION_SCOPES for scope in scopes):
raise HTTPException(400, "请选择至少一个有效限制维度")
duration = body.get("duration_days", body.get("durationDays"))
if duration == "permanent":
expires_at = None
else:
try:
duration_days = int(duration)
except (TypeError, ValueError):
raise HTTPException(400, "请选择有效的限制时长")
if isinstance(duration, bool) or not 1 <= duration_days <= 3650:
raise HTTPException(400, "限制时长需为 1—3650 天")
expires_at = timestamp + duration_days * 24 * 60 * 60_000
for scope in scopes:
await db.execute(insert(account_sanctions).values(
id=new_id(), user_id=user_id, admin_id=admin["id"], action=action,
scope=scope, category=category, reason=reason, created_at=timestamp,
expires_at=expires_at, lifted_at=None, lifted_by=None,
))
if action == "restrict":
await refresh_account_status(db, {**target, "status": target.get("status"), "status_until": target.get("status_until")}, timestamp)
scope_labels = {"publish": "发单", "claim": "接单", "withdraw": "提现"}
abilities = "、".join(scope_labels[scope] for scope in scopes)
until_text = f",至 {date_only(expires_at)} 恢复" if expires_at else ",永久限制"
await add_notification(
db, user_id, "account_sanction", "账号部分功能已限制",
f"账号因“{category}”被限制{abilities}{until_text}。如有异议,请联系管理员:{ADMIN_SANCTION_CONTACT}",
"profile", timestamp,
)
else:
await db.execute(update(users).where(users.c.id == user_id).values(
status="banned", status_until=expires_at,
))
await db.execute(delete(sessions).where(sessions.c.user_id == user_id))
await add_notification(
db, user_id, "account_sanction", "账号已被封禁",
f"账号因“{category}”已被封禁{f',至 {date_only(expires_at)} 恢复' if expires_at else ',永久封禁'}。如有异议,请联系管理员:{ADMIN_SANCTION_CONTACT}",
"profile", timestamp,
)
active_tasks = await all_rows(db, select(tasks).where(and_(
tasks.c.status.in_(("open", "claimed")),
or_(tasks.c.user_id == user_id, tasks.c.claimer_id == user_id),
)).with_for_update())
for task in active_tasks:
reward = int(task.get("reward") or 0)
if task["user_id"] == user_id and task["status"] == "open":
await db.execute(update(tasks).where(and_(tasks.c.id == task["id"], tasks.c.status == "open")).values(
status="cancelled", cancelled_at=timestamp, cancelled_by=admin["id"],
))
elif task["user_id"] == user_id and task["status"] == "claimed":
await db.execute(update(tasks).where(and_(tasks.c.id == task["id"], tasks.c.status == "claimed")).values(
status="cancelled", cancelled_at=timestamp, cancelled_by=admin["id"],
))
if reward:
await db.execute(update(user_stats).where(user_stats.c.user_id == user_id).values(
points_balance=user_stats.c.points_balance + reward, updated_at=timestamp,
))
await db.execute(insert(point_entries).values(
id=new_id(), user_id=user_id, delta=reward, withdrawable_delta=0,
reason=f"账号处理撤单退款 · {task['title']}"[:400], created_at=timestamp,
))
if task.get("claimer_id"):
await add_notification(db, task["claimer_id"], "task_cancelled", "进行中任务已取消",
"任务因发布者账号被处理已取消,已付出的时间与精力可经举报申请核实补偿。",
f"task:{task['id']}", timestamp)
elif task.get("claimer_id") == user_id and task["status"] == "claimed":
if reward:
await db.execute(update(user_stats).where(user_stats.c.user_id == task["user_id"]).values(
points_balance=user_stats.c.points_balance + reward, updated_at=timestamp,
))
await db.execute(insert(point_entries).values(
id=new_id(), user_id=task["user_id"], delta=reward, withdrawable_delta=0,
reason=f"接单账号处理退款 · {task['title']}"[:400], created_at=timestamp,
))
await db.execute(update(tasks).where(and_(tasks.c.id == task["id"], tasks.c.status == "claimed")).values(
status="open", claimer_id=None, claimed_at=None,
))
await add_notification(db, task["user_id"], "task_cancelled", "任务已重新开放接单",
"接单者账号被处理,任务已重新开放接单;已扣任务积分已退回。",
f"task:{task['id']}", timestamp)
await write_admin_audit(db, request, admin, f"account_sanction_{action}", user_id,
f"category={category};scope={','.join(scopes)};duration={duration};reason={reason}")
await db.commit()
return {"ok": True, "status": "banned" if action == "ban" else "restricted",
"expiresAt": expires_at, "category": category, "scopes": scopes}
@app.get("/api/admin/reports")
async def admin_reports(request: Request, status: str = "open") -> dict[str, Any]:
async with SessionLocal() as db:
await admin_required(request, db)
status = status if status in {"open", "reviewed", "dismissed"} else "open"
task_owner = users.alias("task_owner")
reported_user = users.alias("reported_user")
stmt = select(
reports, users.c.name.label("reporter_name"), users.c.nickname.label("reporter_nickname"), users.c.email.label("reporter_email"),
tasks.c.title.label("task_title"), tasks.c.detail.label("task_detail"), tasks.c.type.label("task_type"),
tasks.c.reward.label("task_reward"), tasks.c.status.label("task_status"),
task_owner.c.name.label("task_owner_name"), task_owner.c.nickname.label("task_owner_nickname"),
task_owner.c.student_id.label("task_owner_student_id"),
reports.c.target_user_id.label("reported_user_id"),
reports.c.conversation_id.label("reported_conversation_id"),
reported_user.c.nickname.label("reported_user_nickname"),
).select_from(
reports.join(users, users.c.id == reports.c.reporter_id)
.outerjoin(tasks, tasks.c.id == reports.c.target_id)
.outerjoin(task_owner, task_owner.c.id == tasks.c.user_id)
.outerjoin(reported_user, reported_user.c.id == reports.c.target_user_id)
).where(reports.c.status == status).order_by(reports.c.created_at.desc()).limit(100)
rows = await all_rows(db, stmt)
items = []
for row in rows:
task = None
if row["task_title"]:
task = {
"title": row["task_title"], "detail": row["task_detail"], "type": row["task_type"],
"reward": int(row["task_reward"] or 0), "status": row["task_status"],
"owner": {"name": row["task_owner_name"], "nickname": row["task_owner_nickname"], "studentId": row["task_owner_student_id"]},
}
items.append({
"id": row["id"],
"reporter": {"id": row["reporter_id"], "name": row["reporter_name"], "nickname": row["reporter_nickname"], "email": row["reporter_email"]},
"targetType": row["target_type"], "targetId": row["target_id"], "task": task, "reason": row["reason"],
"targetUser": ({"id": row["reported_user_id"], "nickname": row["reported_user_nickname"]}
if row["reported_user_id"] else None),
"conversationId": row["reported_conversation_id"],
"messageSnapshot": json_load(row.get("message_snapshot"), []),
"status": row["status"], "handlingNote": row["handling_note"], "createdAt": row["created_at"], "handledAt": row["handled_at"],
})
return {"ok": True, "items": items}
@app.post("/api/admin/reports/{report_id}/handle")
async def handle_report(report_id: str, request: Request) -> dict[str, bool]:
async with SessionLocal() as db:
admin = await admin_required(request, db)
body = await request.json()
decision, note = normalize(body.get("decision")), normalize(body.get("note"))[:400]
if decision not in {"reviewed", "dismissed"}:
raise HTTPException(400, "处理结果无效")
report = await one(db, select(reports).where(reports.c.id == report_id).with_for_update())
if not report:
raise HTTPException(404, "举报记录不存在")
if report["status"] != "open":
raise HTTPException(409, "该举报已经处理")
await db.execute(update(reports).where(reports.c.id == report_id).values(
status=decision, handling_note=note or None, handled_by=admin["id"], handled_at=now_ms(),
))
if report["target_type"] == "task":
await db.execute(update(reliability_events).where(and_(
reliability_events.c.task_id == report["target_id"],
reliability_events.c.kind == "task_review",
reliability_events.c.event_key.like("task-publisher-cancel-review:%"),
reliability_events.c.status == "pending",
)).values(status="dismissed" if decision == "dismissed" else "reviewed", reviewed_by=admin["id"]))
if decision == "dismissed" and report["target_type"] == "task":
# Dismissing the last open report clears automatic completion review;
# confirmed penalties still require a separate explicit admin adjustment.
still_open = await db.scalar(select(reports.c.id).where(and_(
reports.c.target_type == "task", reports.c.target_id == report["target_id"],
reports.c.status == "open", reports.c.id != report_id,
)).limit(1))
if not still_open:
await db.execute(update(reliability_events).where(and_(
reliability_events.c.task_id == report["target_id"],
reliability_events.c.kind == "completion_review",
reliability_events.c.status == "pending",
)).values(status="dismissed", reviewed_by=admin["id"]))
await db.execute(update(reliability_events).where(and_(
reliability_events.c.task_id == report["target_id"],
reliability_events.c.kind == "task_review",
reliability_events.c.event_key.like("task-cancel-dispute:%"),
reliability_events.c.status == "pending",
)).values(status="dismissed", reviewed_by=admin["id"]))
task = await one(db, select(tasks).where(tasks.c.id == report["target_id"]))
if task and task["status"] == "done":
await settle_task_completion_credit(db, dict(task))
audit_target = report.get("target_user_id")
if not audit_target and report["target_type"] == "task":
audit_target = await db.scalar(select(tasks.c.user_id).where(tasks.c.id == report["target_id"]))
await write_admin_audit(db, request, admin, f"report_{decision}", audit_target,
f"report={report_id}; target={report['target_type']}:{report['target_id']}; note={note}")
await db.commit()
return {"ok": True}
@app.get("/api/student-verification")
async def get_student_verification(request: Request) -> dict[str, Any]:
async with SessionLocal() as db:
user = await require_user(request, db)
return {"ok": True, "verification": await verification_summary(db, user["id"])}
@app.post("/api/student-verification")
async def submit_student_verification(request: Request) -> dict[str, Any]:
async with SessionLocal() as db:
user = await require_user(request, db)
body = await request.json()
online_code = re.sub(r"\s+", "", normalize(body.get("onlineCode")).upper())
expires_on = normalize(body.get("reportExpiresOn"))
if not re.fullmatch(r"[A-Z0-9-]{8,32}", online_code):
raise HTTPException(400, "请输入有效的学信网在线验证码")
try:
expires_at = datetime.strptime(expires_on, "%Y-%m-%d").replace(tzinfo=timezone.utc).timestamp() * 1000
except ValueError:
raise HTTPException(400, "请选择验证报告有效期")
if expires_at < now_ms() or expires_at > now_ms() + 2 * 365 * 24 * 60 * 60_000:
raise HTTPException(400, "验证报告有效期不正确")
cipher, iv, tag = encrypt_verification(online_code)
existing = await one(db, select(student_verifications).where(student_verifications.c.user_id == user["id"]))
values = dict(
user_id=user["id"], online_code_cipher=cipher, online_code_iv=iv, online_code_tag=tag,
online_code_last4=online_code[-4:], report_expires_on=expires_on,
status="pending", review_note=None, submitted_at=now_ms(), reviewed_at=None, reviewed_by=None,
)
if existing:
await db.execute(update(student_verifications).where(student_verifications.c.user_id == user["id"]).values(**values))
else:
await db.execute(insert(student_verifications).values(id=new_id(), **values))
await db.commit()
return {"ok": True, "verification": await verification_summary(db, user["id"])}
@app.get("/api/admin/student-verifications")
async def admin_student_verifications(request: Request, status: str = "pending") -> dict[str, Any]:
async with SessionLocal() as db:
await admin_required(request, db)
status = status if status in {"pending", "approved", "rejected"} else "pending"
stmt = select(
student_verifications, users.c.name, users.c.nickname, users.c.student_id,
users.c.school, users.c.email,
).select_from(student_verifications.join(users, users.c.id == student_verifications.c.user_id)).where(
student_verifications.c.status == status
).order_by(student_verifications.c.submitted_at.asc())
rows = await all_rows(db, stmt)
items = []
for row in rows:
items.append({
"id": row["id"], "name": row["name"], "nickname": row["nickname"], "studentId": row["student_id"],
"school": row["school"], "email": row["email"], "onlineCode": decrypt_verification(row),
"codeLast4": row["online_code_last4"], "reportExpiresOn": row["report_expires_on"],
"status": row["status"], "reviewNote": row["review_note"], "submittedAt": row["submitted_at"], "reviewedAt": row["reviewed_at"],
})
return {"ok": True, "items": items}
@app.post("/api/admin/student-verifications/{verification_id}/review")
async def review_student_verification(verification_id: str, request: Request) -> dict[str, bool]:
async with SessionLocal() as db:
admin = await admin_required(request, db)
body = await request.json()
decision, note = normalize(body.get("decision")), normalize(body.get("note"))[:400]
if decision not in {"approved", "rejected"}:
raise HTTPException(400, "审核结果无效")
record = await one(db, select(student_verifications).where(student_verifications.c.id == verification_id))
if not record:
raise HTTPException(404, "认证申请不存在")
if decision == "rejected" and not note:
raise HTTPException(400, "驳回时请填写原因")
await db.execute(update(student_verifications).where(student_verifications.c.id == verification_id).values(
status=decision, review_note=note or None, reviewed_at=now_ms(), reviewed_by=admin["id"],
))
await write_admin_audit(db, request, admin, f"student_verification_{decision}",
record["user_id"], f"审核认证申请 {verification_id}; note={note}")
await db.commit()
return {"ok": True}
@app.get("/api/admin/overview")
async def admin_overview(request: Request) -> dict[str, Any]:
async with SessionLocal() as db:
await admin_required(request, db)
total = await db.scalar(select(func.count()).select_from(users))
pending = await db.scalar(select(func.count()).select_from(student_verifications).where(student_verifications.c.status == "pending"))
approved = await db.scalar(select(func.count()).select_from(student_verifications).where(student_verifications.c.status == "approved"))
rejected = await db.scalar(select(func.count()).select_from(student_verifications).where(student_verifications.c.status == "rejected"))
return {"ok": True, "stats": {"totalUsers": int(total or 0), "pending": int(pending or 0), "approved": int(approved or 0), "rejected": int(rejected or 0)}}
def analytics_date(timestamp: Any) -> date | None:
"""Convert the stored epoch milliseconds to the server's local calendar date."""
if timestamp is None:
return None
try:
return datetime.fromtimestamp(int(timestamp) / 1000).date()
except (OverflowError, TypeError, ValueError, OSError):
return None
@app.get("/api/admin/analytics")
async def admin_analytics(request: Request, days: int = Query(default=7, ge=1, le=30)) -> dict[str, Any]:
async with SessionLocal() as db:
await admin_required(request, db)
# Fetch raw timestamps and bucket in Python so SQLite and MySQL use the
# same server-local calendar-day semantics.
user_rows = await all_rows(db, select(users.c.id, users.c.nickname, users.c.created_at))
invite_rows = await all_rows(db, select(invite_relations.c.created_at))
task_rows = await all_rows(db, select(
tasks.c.user_id, tasks.c.type, tasks.c.reward, tasks.c.created_at, tasks.c.claimed_at,
))
today = datetime.now().date()
yesterday = today - timedelta(days=1)
first_day = today - timedelta(days=days - 1)
date_keys = [(first_day + timedelta(days=offset)).isoformat() for offset in range(days)]
date_key_set = set(date_keys)
registration_days = {key: {"date": key, "count": 0, "viaInvite": 0} for key in date_keys}
registration_dates = [analytics_date(row.get("created_at")) for row in user_rows]
invite_dates = [analytics_date(row.get("created_at")) for row in invite_rows]
for event_date in registration_dates:
if event_date and event_date.isoformat() in date_key_set:
registration_days[event_date.isoformat()]["count"] += 1
for event_date in invite_dates:
if event_date and event_date.isoformat() in date_key_set:
registration_days[event_date.isoformat()]["viaInvite"] += 1
task_days = {
key: {"date": key, "total": 0, "errand": 0, "partner": 0}
for key in date_keys
}
claim_durations: list[float] = []
user_publish_counts: dict[str, int] = {}
bucket_state = [
{"min": 200 + index * 100, "max": 299 + index * 100, "published": 0,
"claimed": 0, "claimDurations": []}
for index in range(13)
]
bucket_state[-1]["max"] = 1500
for row in task_rows:
task_date = analytics_date(row.get("created_at"))
task_type = row.get("type")
if task_date and task_date.isoformat() in date_key_set and task_type in {"errand", "partner"}:
day = task_days[task_date.isoformat()]
day[task_type] += 1
day["total"] += 1
user_id = row.get("user_id")
if user_id:
user_publish_counts[user_id] = user_publish_counts.get(user_id, 0) + 1
created_at = row.get("created_at")
claimed_at = row.get("claimed_at")
duration = None
if claimed_at is not None and created_at is not None:
duration = (int(claimed_at) - int(created_at)) / 60_000
claim_durations.append(duration)
reward = int(row.get("reward") or 0)
if task_type == "errand" and 200 <= reward <= 1500:
bucket_index = min((reward - 200) // 100, 12)
bucket = bucket_state[bucket_index]
bucket["published"] += 1
if claimed_at is not None:
bucket["claimed"] += 1
if duration is not None:
bucket["claimDurations"].append(duration)
price_buckets = []
for bucket in bucket_state:
durations = bucket.pop("claimDurations")
published = bucket["published"]
claimed = bucket["claimed"]
price_buckets.append({
**bucket,
"label": f"{bucket['min']}—{bucket['max']}",
"claimRate": round(claimed / published, 4) if published else 0,
"avgClaimMinutes": round(mean(durations), 2) if durations else 0,
"sampleCount": published,
"insufficient": published < 5,
})
eligible_buckets = [bucket for bucket in price_buckets if bucket["claimed"] and not bucket["insufficient"]]
best_bucket = min(
eligible_buckets,
key=lambda bucket: (bucket["avgClaimMinutes"], -bucket["claimRate"], bucket["min"]),
) if eligible_buckets else None
publisher_count = len(user_publish_counts)
publish_counts = list(user_publish_counts.values())
distribution = [
{"label": str(count), "publishedCount": count,
"userCount": sum(1 for total in publish_counts if total == count)}
for count in range(1, 11)
]
distribution.append({
"label": "10+", "publishedCount": 11,
"userCount": sum(1 for total in publish_counts if total > 10),
})
nickname_by_id = {row["id"]: row["nickname"] for row in user_rows}
top_publishers = [
{"nickname": nickname_by_id.get(user_id) or "未知用户", "count": count}
for user_id, count in sorted(
user_publish_counts.items(), key=lambda item: (-item[1], nickname_by_id.get(item[0], "")),
)[:10]
]
invite_total = len(invite_rows)
total_users = len(user_rows)
today_task = task_days.get(today.isoformat(), {"total": 0, "errand": 0, "partner": 0})
return {
"ok": True,
"days": days,
"registrations": {
"today": sum(1 for event_date in registration_dates if event_date == today),
"yesterday": sum(1 for event_date in registration_dates if event_date == yesterday),
"todayViaInvite": sum(1 for event_date in invite_dates if event_date == today),
"byDay": list(registration_days.values()),
"inviteTotal": invite_total,
"inviteRatio": round(invite_total / total_users, 4) if total_users else 0,
},
"tasks": {
"today": dict(today_task),
"byDay": list(task_days.values()),
"avgClaimMinutes": round(mean(claim_durations), 2) if claim_durations else 0,
"medianClaimMinutes": round(median(claim_durations), 2) if claim_durations else 0,
"priceBuckets": price_buckets,
"bestBucket": best_bucket,
},
"perUser": {
"avgPublished": round(sum(publish_counts) / publisher_count, 2) if publisher_count else 0,
"publisherCount": publisher_count,
"distribution": distribution,
"topPublishers": top_publishers,
},
}
def admin_user_payload(row: dict[str, Any]) -> dict[str, Any]:
commitments = int(row.get("commitments_count") or 0)
return {
"id": row["id"], "name": row["name"], "nickname": row["nickname"], "studentId": row["student_id"],
"school": row["school"], "email": row["email"], "createdAt": row["created_at"],
"creditScore": int(row.get("credit_score") or 70), "pointsBalance": int(row.get("points_balance") or 0),
"breachRate": round(int(row.get("breach_count") or 0) / commitments * 1000) / 10 if commitments else 0,
"status": row.get("status") or "active", "statusUntil": row.get("status_until"),
}
@app.get("/api/admin/users")
async def admin_users(request: Request, q: str = "") -> dict[str, Any]:
async with SessionLocal() as db:
await admin_required(request, db)
stmt = select(
users, user_stats.c.credit_score, user_stats.c.points_balance, user_stats.c.breach_count, user_stats.c.commitments_count,
).select_from(users.outerjoin(user_stats, user_stats.c.user_id == users.c.id)).order_by(users.c.created_at.desc())
rows = await all_rows(db, stmt)
needle = normalize(q).lower()
if needle:
rows = [row for row in rows if needle in f"{row['name']}{row['nickname']}{row['student_id']}{row['school']}{row['email']}".lower()]
for row in rows:
await refresh_account_status(db, row)
await db.commit()
return {"ok": True, "categories": list(CREDIT_CATEGORIES),
"items": [admin_user_payload(row) for row in rows]}
@app.get("/api/admin/credit-adjustments")
async def admin_credit_adjustments(request: Request, userId: str | None = None) -> dict[str, Any]:
async with SessionLocal() as db:
await admin_required(request, db)
admin = users.alias("credit_admin")
stmt = select(
credit_adjustments, users.c.name.label("user_name"), users.c.nickname.label("user_nickname"), admin.c.name.label("admin_name"),
).select_from(
credit_adjustments.join(users, users.c.id == credit_adjustments.c.user_id).outerjoin(admin, admin.c.id == credit_adjustments.c.admin_id)
).where(credit_adjustments.c.user_id == userId if userId else text("1=1"))\
.order_by(credit_adjustments.c.created_at.desc()).limit(100 if userId else 30)
rows = await all_rows(db, stmt)
return {"ok": True, "items": [
{"id": row["id"], "userId": row["user_id"], "delta": row["delta"], "reason": row["reason"], "createdAt": row["created_at"],
"category": row.get("category"), "userName": row["user_name"], "userNickname": row["user_nickname"],
"before": row.get("before_score"), "after": row.get("after_score"), "taskId": row.get("task_id"),
"inviteeId": row.get("invitee_id"), "note": row.get("note"), "ruleKey": row.get("rule_key"), "reversesId": row.get("reverses_id"),
"reversedAt": row.get("reversed_at"), "adminName": row.get("admin_name") or "系统"}
for row in rows
]}
@app.get("/api/admin/credit-options")
async def admin_credit_options(request: Request) -> dict[str, Any]:
async with SessionLocal() as db:
await admin_required(request, db)
return {"ok": True, "items": list(ADMIN_CREDIT_REASONS)}
async def apply_admin_credit(request: Request, user_ids: list[str], db: AsyncSession, body: dict[str, Any] | None = None) -> dict[str, Any]:
admin = await admin_required(request, db)
body = body if body is not None else await request.json()
reason_type = normalize(body.get("reasonType"))
spec = next((item for item in ADMIN_CREDIT_REASONS if item["value"] == reason_type), None)
if not spec:
raise HTTPException(400, "请选择有效的调整原因")
note = normalize(body.get("note") or body.get("reason"))[:400]
if not note:
raise HTTPException(400, "请填写核实依据或调整备注")
if spec.get("noteRequired") and len(note) < 5:
raise HTTPException(400, "“其他”请填写至少 5 字的补充说明")
task_id = normalize(body.get("taskId")) or None
invitee_id = normalize(body.get("inviteeId")) or None
reverses_id = normalize(body.get("reversesId")) or None
if spec.get("taskRequired") and not task_id:
raise HTTPException(400, "该调整原因必须关联任务")
if spec.get("inviteeRequired") and not invitee_id:
raise HTTPException(400, "该调整原因必须关联被邀请用户")
if spec.get("reversalRequired") and not reverses_id:
raise HTTPException(400, "申诉成立必须关联原处罚记录")
if user_ids and len(user_ids) != 1 and (task_id or invitee_id or reverses_id or reason_type != "other"):
raise HTTPException(400, "任务、邀请或申诉调整必须逐个处理")
try:
delta = int(body.get("delta") if body.get("delta") is not None else (spec.get("defaultDelta") or 0))
except (TypeError, ValueError):
raise HTTPException(400, "信用分变动必须是整数")
if len(user_ids) > 100 or (delta and abs(delta) > 100):
raise HTTPException(400, "信用分变动需在 -100 至 100 之间,且一次最多操作 100 人")
if reason_type == "appeal_upheld":
delta = 0 # 由原处罚记录决定恢复值,忽略客户端提交分值。
elif reason_type == "invite_abuse" and delta != -1:
raise HTTPException(400, "邀请违规每次最多扣 1 分")
if not user_ids:
raise HTTPException(400, "请选择调整用户")
results = []
for user_id in list(dict.fromkeys(user_ids)):
target = await one(db, select(users).where(users.c.id == user_id))
if not target:
raise HTTPException(404, "所选用户中包含不存在的账号,请刷新后重试")
if spec.get("taskRequired"):
task = await one(db, select(tasks).where(tasks.c.id == task_id).with_for_update())
if not task:
raise HTTPException(404, "关联任务不存在")
if reason_type in {"task_owner_completion", "task_claimer_completion"} and task["status"] != "done":
raise HTTPException(409, "正常完成奖励只能用于已完成任务")
if reason_type == "task_owner_completion" and task["user_id"] != user_id:
raise HTTPException(400, "所选用户不是该任务发单者")
if reason_type == "task_claimer_completion" and task.get("claimer_id") != user_id:
raise HTTPException(400, "所选用户不是该任务接单者")
if reason_type in {"cancel_early", "cancel_late"} and (task["status"] != "cancelled" or task.get("claimer_id") != user_id):
raise HTTPException(400, "取消调整必须关联该用户接单后取消的任务")
if reason_type in {"cancel_early", "cancel_late"} and task.get("cancelled_at") and task.get("deadline"):
remaining = int(task["deadline"]) - int(task["cancelled_at"])
if reason_type == "cancel_early" and remaining < 2 * 60 * 60_000:
raise HTTPException(400, "该任务取消时距截止时间不足 2 小时")
if reason_type == "cancel_late" and remaining >= 2 * 60 * 60_000:
raise HTTPException(400, "该任务取消时距截止时间至少 2 小时")
if reason_type in {"no_show", "fraud"} and user_id not in {task["user_id"], task.get("claimer_id")}:
raise HTTPException(400, "所选用户不是该任务参与者")
if spec.get("inviteeRequired"):
# Serialize the rolling 90-day cap check (SQLite uses a no-op
# update because it does not implement row-level FOR UPDATE).
await db.execute(update(user_stats).where(user_stats.c.user_id == user_id).values(
updated_at=user_stats.c.updated_at,
))
relation = await one(db, select(invite_relations).where(and_(
invite_relations.c.inviter_id == user_id, invite_relations.c.invitee_id == invitee_id,
)))
if not relation:
raise HTTPException(400, "被邀请用户与该邀请人关系不匹配")
cutoff = now_ms() - 90 * 24 * 60 * 60_000
prior = int(await db.scalar(select(func.coalesce(func.sum(-credit_adjustments.c.delta), 0)).where(and_(
credit_adjustments.c.user_id == user_id,
credit_adjustments.c.rule_key.like("admin:invite_abuse:%"),
credit_adjustments.c.created_at >= cutoff,
credit_adjustments.c.reversed_at.is_(None),
))) or 0)
if prior >= 5:
raise HTTPException(409, "邀请违规近 90 天累计扣分已达 5 分上限")
result: dict[str, Any]
if reason_type == "appeal_upheld":
original = await one(db, select(credit_adjustments).where(and_(
credit_adjustments.c.id == reverses_id, credit_adjustments.c.user_id == user_id,
credit_adjustments.c.delta < 0, credit_adjustments.c.reversed_at.is_(None),
)).with_for_update())
if not original:
raise HTTPException(400, "原处罚记录无效、已撤销或不属于该用户")
result = await record_credit_change(
db, user_id, -int(original["delta"]), "更正", spec["label"],
actor_id=admin["id"], task_id=original.get("task_id"), note=note,
reverses_id=original["id"], rule_key=f"appeal:{original['id']}",
)
await db.execute(update(credit_adjustments).where(credit_adjustments.c.id == original["id"]).values(
reversed_by=admin["id"], reversed_at=now_ms(),
))
confirmed_breach = await db.scalar(select(reliability_events.c.id).where(and_(
reliability_events.c.adjustment_id == original["id"],
reliability_events.c.kind == "breach", reliability_events.c.status == "confirmed",
)).limit(1))
if confirmed_breach:
await db.execute(update(user_stats).where(and_(
user_stats.c.user_id == user_id, user_stats.c.breach_count > 0,
)).values(breach_count=user_stats.c.breach_count - 1))
await db.execute(update(reliability_events).where(reliability_events.c.adjustment_id == original["id"]).values(
status="reversed", reversed_at=now_ms(), reviewed_by=admin["id"],
))
else:
rule_key = None
if reason_type in {"task_owner_completion", "task_claimer_completion"}:
rule_key = f"task-completion:{task_id}:{user_id}"
elif task_id and reason_type in {"cancel_early", "cancel_late", "no_show", "fraud"}:
rule_key = f"admin:{reason_type}:{task_id}:{user_id}"
elif reason_type == "invite_abuse":
rule_key = f"admin:invite_abuse:{user_id}:{invitee_id}:{uuid.uuid4().hex}"
result = await record_credit_change(
db, user_id, delta, spec["category"], spec["label"], actor_id=admin["id"],
task_id=task_id, invitee_id=invitee_id, rule_key=rule_key, note=note,
)
if result["duplicate"]:
raise HTTPException(409, "该任务和调整规则已记账,不能重复调整")
if spec.get("breach"):
if task_id and await db.scalar(select(reliability_events.c.id).where(and_(
reliability_events.c.user_id == user_id, reliability_events.c.task_id == task_id,
reliability_events.c.kind == "breach", reliability_events.c.status == "confirmed",
)).limit(1)):
raise HTTPException(409, "该用户在此任务已有确认失信记录,请先核查并撤销原处罚")
await record_reliability_event(
db, event_key=f"manual-breach:{result['id']}", user_id=user_id,
kind="breach", status="confirmed", task_id=task_id,
adjustment_id=result["id"], reviewed_by=admin["id"], note=note,
)
elif reason_type == "invite_abuse":
await record_reliability_event(
db, event_key=f"manual-invite-abuse:{result['id']}", user_id=user_id,
invitee_id=invitee_id, kind="invite_abuse", status="confirmed",
adjustment_id=result["id"], reviewed_by=admin["id"], note=note,
)
if task_id:
await db.execute(update(reliability_events).where(and_(
reliability_events.c.task_id == task_id,
reliability_events.c.user_id == user_id,
reliability_events.c.kind.in_(["completion_review", "task_review"]),
reliability_events.c.status == "pending",
)).values(status="reviewed", reviewed_by=admin["id"]))
if result["delta"]:
await add_notification(
db, user_id, "credit_adjusted", "校园信用已调整",
f"{spec['label']}:信用分 {result['delta']:+d}(当前 {result['after']} 分)。",
f"task:{task_id}" if task_id else "profile",
)
await write_admin_audit(db, request, admin, "credit_adjust", user_id,
f"reason={spec['label']};delta={result['delta']};task={task_id or ''};note={note}")
results.append({"id": user_id, "nickname": target["nickname"], "applied": result["delta"],
"before": result["before"], "creditScore": result["after"],
"adjustmentId": result["id"]})
await db.commit()
return {"ok": True, "count": len(results), "results": results}
@app.post("/api/admin/users/{user_id}/credit")
async def admin_credit(user_id: str, request: Request) -> dict[str, Any]:
async with SessionLocal() as db:
result = await apply_admin_credit(request, [user_id], db)
item = result["results"][0]
return {"ok": True, "applied": item["applied"], "before": item["before"],
"creditScore": item["creditScore"], "adjustmentId": item["adjustmentId"]}
@app.post("/api/admin/users/batch-credit")
async def admin_batch_credit(request: Request) -> dict[str, Any]:
body = await request.json()
async with SessionLocal() as db:
return await apply_admin_credit(request, [normalize(item) for item in body.get("userIds", [])], db, body)
@app.post("/api/admin/users/{user_id}/points")
async def admin_points(user_id: str, request: Request) -> dict[str, Any]:
async with SessionLocal() as db:
admin = await admin_required(request, db)
body = await request.json()
try:
delta = int(body.get("delta") or 0)
except (TypeError, ValueError):
raise HTTPException(400, "积分变动必须是整数")
reason = normalize(body.get("reason"))[:400]
if not delta or abs(delta) > 1_000_000:
raise HTTPException(400, "积分变动需为 ±1—1000000 的整数")
if not reason:
raise HTTPException(400, "请填写调整原因")
target = await one(db, select(users).where(users.c.id == user_id))
if not target:
raise HTTPException(404, "用户不存在")
stats = await one(db, select(user_stats).where(user_stats.c.user_id == user_id).with_for_update())
if not stats:
timestamp = now_ms()
await db.execute(insert(user_stats).values(user_id=user_id, points_balance=750, credit_score=70, updated_at=timestamp))
stats = {"points_balance": 750}
before = int(stats["points_balance"] or 0)
after = before + delta
if after < 0:
raise HTTPException(400, "积分余额不能低于 0")
timestamp = now_ms()
withdrawable_delta = 0
if delta < 0:
free_part = await deduct_points(db, user_id, -delta, timestamp=timestamp)
if free_part is None:
raise HTTPException(400, "积分余额不能低于 0")
withdrawable_delta = -free_part
else:
await db.execute(update(user_stats).where(user_stats.c.user_id == user_id).values(
points_balance=after, updated_at=timestamp,
))
await db.execute(insert(point_entries).values(
id=new_id(), user_id=user_id, delta=delta, withdrawable_delta=withdrawable_delta,
reason=f"管理员调整:{reason}"[:400], created_at=timestamp,
))
await add_notification(
db, user_id, "points_adjusted", "积分余额已调整",
f"管理员对你的积分进行{('+' if delta > 0 else '')}{delta}分调整:{reason}",
"profile", timestamp,
)
await write_admin_audit(db, request, admin, "points_adjust", user_id, f"delta={delta};reason={reason}")
await db.commit()
return {"ok": True, "delta": delta, "pointsBalance": after, "adminId": admin["id"]}
async def invite_payload(db: AsyncSession, user: dict[str, Any]) -> dict[str, Any]:
stats = await stats_for(db, user["id"])
code = await one(db, select(invite_codes).where(invite_codes.c.owner_id == user["id"]))
return {
"eligible": invite_threshold_reached(stats),
"creditScore": int(stats["credit_score"]),
"withdrawablePoints": int(stats["withdrawable_points"] or 0),
"code": {
"code": code["code"], "usesLeft": int(code["max_uses"]) - int(code["used_count"]),
"maxUses": int(code["max_uses"]),
} if code else None,
}
@app.get("/api/invite-code")
async def get_invite_code(request: Request) -> dict[str, Any]:
async with SessionLocal() as db:
user = await require_user(request, db)
return {"ok": True, **await invite_payload(db, user)}
@app.post("/api/invite-code")
async def create_invite_code(request: Request) -> dict[str, Any]:
async with SessionLocal() as db:
user = await require_user(request, db)
if await one(db, select(invite_codes.c.id).where(invite_codes.c.owner_id == user["id"])):
return {"ok": True, **await invite_payload(db, user)}
await db.rollback()
async with db.begin():
stats = await one(db, select(user_stats).where(user_stats.c.user_id == user["id"]).with_for_update())
existing = await one(db, select(invite_codes).where(invite_codes.c.owner_id == user["id"]))
# Existing codes are permanent; eligibility only controls first issuance.
if not existing:
if not invite_threshold_reached(stats or {}):
raise HTTPException(403, f"可提现积分满 {INVITE_WITHDRAWABLE_THRESHOLD} 才可生成邀请码")
existing = {"id": new_id(), "owner_id": user["id"], "code": secrets.token_urlsafe(6).replace("-", "").replace("_", "").upper()[:10], "max_uses": 2, "used_count": 0, "created_at": now_ms()}
await db.execute(insert(invite_codes).values(**existing))
return {"ok": True, **await invite_payload(db, user)}
@app.get("/api/config")
async def runtime_config() -> dict[str, Any]:
return {"ok": True, "runtime": "fastapi", "database": DB_DRIVER, "workers": WORKERS}
FRONTEND_VIEW_FILES = (
"views/home.html",
"views/express.html",
"views/partner.html",
"views/profile.html",
"views/task.html",
)
FRONTEND_DIALOG_FILES = (
"components/dialogs/task.html",
"components/dialogs/publish.html",
"components/dialogs/auth.html",
"components/dialogs/verification.html",
"components/dialogs/account.html",
"components/dialogs/notifications.html",
"components/dialogs/privacy.html",
"components/dialogs/social.html",
"components/dialogs/official-tasks.html",
)
def render_frontend_shell() -> str:
"""Compose the maintainable multi-file frontend into one browser document."""
template = (FRONTEND_DIR / "base.html").read_text(encoding="utf-8")
views = "\n".join((FRONTEND_DIR / name).read_text(encoding="utf-8") for name in FRONTEND_VIEW_FILES)
dialogs = "\n".join((FRONTEND_DIR / name).read_text(encoding="utf-8") for name in FRONTEND_DIALOG_FILES)
toast = (FRONTEND_DIR / "components/toast.html").read_text(encoding="utf-8")
return (
template
.replace("<!-- LINKUP_VIEWS -->", views)
.replace("<!-- LINKUP_DIALOGS -->", dialogs)
.replace("<!-- LINKUP_TOAST -->", toast)
)
@app.get("/", response_class=HTMLResponse, include_in_schema=False)
@app.get("/index.html", response_class=HTMLResponse, include_in_schema=False)
@app.get("/base.html", response_class=HTMLResponse, include_in_schema=False)
async def frontend_shell() -> HTMLResponse:
return HTMLResponse(render_frontend_shell(), headers={"Cache-Control": "no-cache"})
if FRONTEND_DIR.exists():
app.mount("/", StaticFiles(directory=str(FRONTEND_DIR), html=True), name="static")
if __name__ == "__main__":
import uvicorn
if DB_DRIVER == "sqlite" and WORKERS > 1:
raise RuntimeError("SQLite 仅支持单 worker;多 worker 请使用 MySQL 或 PostgreSQL")
uvicorn.run("main:app", host=HOST, port=PORT, workers=WORKERS)