commit 155058f0f38f47ba62871bfa16c4af9d14f4a93a Author: azzz <811446351@qq.com> Date: Thu Oct 29 16:27:16 2026 +0800 LinkUp initial import diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b6bde21 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +.env +data/ +__pycache__/ +*.pyc diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..095c928 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,23 @@ +FROM python:3.11-slim + +WORKDIR /app + +COPY backend/requirements.txt /app/backend/requirements.txt +RUN pip install --no-cache-dir -r /app/backend/requirements.txt + +COPY backend /app/backend +COPY dist /app/dist + +WORKDIR /app/backend + +ENV PORT=34173 \ + HOST=0.0.0.0 \ + APP_WORKERS=1 \ + DATABASE_DRIVER=sqlite \ + DATABASE_PATH=./data/linkup.db + +EXPOSE 34173 + +VOLUME /app/backend/data + +CMD ["python", "-m", "uvicorn", "main:app", "--host", "0.0.0.0", "--port", "34173", "--workers", "1"] diff --git a/assets/linkup-campus-hero.png b/assets/linkup-campus-hero.png new file mode 100644 index 0000000..d78b05c Binary files /dev/null and b/assets/linkup-campus-hero.png differ diff --git a/backend/.env.example b/backend/.env.example new file mode 100644 index 0000000..1833012 --- /dev/null +++ b/backend/.env.example @@ -0,0 +1,18 @@ +LINKUP_CONFIG=./config.toml +PORT=34173 +HOST=0.0.0.0 +APP_WORKERS=2 +DATABASE_DRIVER=sqlite +DATABASE_PATH=./data/linkup.db +# MySQL: mysql+asyncmy://user:password@127.0.0.1:3306/linkup +DATABASE_URL= +DB_POOL_SIZE=10 +DB_MAX_OVERFLOW=10 +SMTP_HOST=smtp.163.com +SMTP_PORT=465 +SMTP_USER=your_account@163.com +SMTP_PASS=replace_with_a_new_smtp_authorization_code +OTP_PEPPER=replace_with_a_long_random_secret +ADMIN_EMAILS=admin@example.com +FRONTEND_ORIGIN= +TRUST_PROXY_HEADERS=true diff --git a/backend/README.md b/backend/README.md new file mode 100644 index 0000000..3164a30 --- /dev/null +++ b/backend/README.md @@ -0,0 +1,104 @@ +# LinkUp FastAPI 后端 + +后端已从 Node.js 切换为 FastAPI + SQLAlchemy 异步数据库访问。前端 API 路径保持兼容,默认同端口托管 dist 静态文件。 + +## 本地启动 + +需要 Python 3.11+: + +~~~bash +cd backend +python -m venv .venv +source .venv/bin/activate +python -m pip install -r requirements.txt +cp .env.example .env +python main.py +~~~ + +Windows PowerShell: + +~~~powershell +cd backend +py -3.11 -m venv .venv +.\.venv\Scripts\python.exe -m pip install -r requirements.txt +Copy-Item .env.example .env +.\.venv\Scripts\python.exe main.py +~~~ + +`python main.py` 与项目根目录的 start.sh 都会读取 backend/config.toml、backend/.env,并按 `APP_WORKERS` 启动。SQLite 仅使用单 worker;MySQL/PostgreSQL 可按 CPU 与数据库连接预算设置多个 worker。MySQL 多 worker 启动时会使用数据库命名锁串行执行建表与兼容迁移。 + +## 配置切换数据库 + +默认配置文件为 backend/config.toml,也可以用 LINKUP_CONFIG 指定其他 TOML 文件。环境变量优先级高于 TOML。 + +SQLite: + +~~~toml +[database] +driver = "sqlite" +path = "./data/linkup.db" +~~~ + +MySQL: + +~~~toml +[database] +driver = "mysql" +url = "mysql://linkup:密码@127.0.0.1:3306/linkup" +pool_size = 10 +max_overflow = 10 +~~~ + +生产环境建议使用环境变量 DATABASE_DRIVER=mysql、DATABASE_URL=mysql+asyncmy://...,密码不要提交到仓库。PostgreSQL 也支持 driver=postgresql 和 postgresql:// 连接串。连接池是每个 worker 独立创建的,总连接上限约为 `workers × (pool_size + max_overflow)`,不得超过数据库的 `max_connections`。 + +## SQLite ↔ MySQL 双向迁移 + +迁移脚本为 backend/tools/migrate_db.py,按主键幂等合并,不会重复创建用户、任务或流水。首次导入空库可直接运行;覆盖目标库前才使用 --truncate。 + +~~~bash +# SQLite -> MySQL +python backend/tools/migrate_db.py sqlite-to-mysql \ + --sqlite backend/data/linkup.db \ + --mysql-url mysql+pymysql://linkup:密码@127.0.0.1:3306/linkup + +# MySQL -> SQLite +python backend/tools/migrate_db.py mysql-to-sqlite \ + --mysql-url mysql+pymysql://linkup:密码@127.0.0.1:3306/linkup \ + --sqlite backend/data/linkup-copy.db +~~~ + +MySQL 迁移依赖 pymysql;FastAPI 在线访问 MySQL 使用 asyncmy。迁移按 users、积分、认证、任务、举报等外键相关顺序处理,旧 SQLite 缺少 claimer_id 时会自动补空值。 + +## 接口 + +保留原有 /api/auth、/api/tasks、/api/my/tasks、/api/reports、/api/student-verification、/api/invite-code 和 /api/admin 路径;新增 GET /api/health 返回 runtime=fastapi 和当前数据库驱动。 + +- `GET /api/tasks` 不传 `school` 时保留默认范围:普通登录用户本校,管理员和访客全部学校;登录用户仍包含原有的相关进行中任务。 +- `GET /api/tasks?school=学校名` 返回该学校的公开待接任务;`school=all` 返回全部学校的公开待接任务。学校必须来自 `GET /api/schools` 的 `items`(预设学校与已注册学校的并集),非法值返回 400。本人发布的任务仍在「我的任务」中管理。 +- 登录用户可查看同校用户,以及拥有公开待接任务的跨校发布者的公开主页。管理员和访客的原有主页访问规则保持不变。 +- `POST /api/tasks` 跑腿任务使用 `type=errand` + `category` 枚举(`快递代取` / `带饭代买` / `代排队` / `代打印/文件取送`,静态注册表 `ERRAND_CATEGORIES`);旧 `type=express` 请求在写入时归一为 errand/快递代取,存量数据由启动迁移一次性回填。各类目必填字段见注册表,积分统一 200—1500;涉及垫付的类目仅在表单与详情提示线下当面结算,平台不做资金托管。 +- `GET /api/task-defaults?category=类目` 与发布后保存的常用字段按用户 + 类目分别读写(表结构为 `(user_id, category)` 复合主键,旧数据自动迁移)。 +- `POST /api/tasks/{id}/claim` 要求 L2 及以上认证,对全部 errand 类目生效。当前有效的学信网认证可达到 L2;人脸识别与双重认证 L3 即将上线,`faceVerified` 暂为 `false`。未提交、审核中、驳回或报告过期会回落 L1,并在锁任务前返回 403,响应包含 `error`、`code: "VERIFICATION_REQUIRED"` 和当前 `verification`;未登录仍返回 401,已被接单仍返回 409。 + +权限与学校筛选回归测试(在仓库根目录执行,使用隔离的内存数据库): + +```bash +python -m pip install -r backend/tests/requirements.txt +python -m unittest discover -s backend/tests -v +``` + +## 学校分区、常用发布信息与通知 + +- 每个用户绑定注册学校,任务表单会记录独立的 `school` 分区字段。登录后任务广场只返回本校任务,发布任务只能选择自己的学校;管理员可以跨学校查看。 +- 代取任务成功发布后,手机号、学校、校内取件点、校内送达位置写入 `task_defaults`。下次打开发布代取表单时通过 `GET /api/task-defaults` 自动回填,用户仍可修改。 +- 站内通知存储在 `notifications`,发布任务、被接单、任务完成会生成通知。用户端通过 `GET /api/notifications` 查看,使用 `POST /api/notifications/{id}/read` 或 `POST /api/notifications/read-all` 标记已读。 +- 每位用户同时存在的未完成任务(自己发布或自己接取)最多 10 条;`POST /api/tasks` 和接单接口都会校验上限。`GET /api/my/tasks` 返回全部未完成任务,以及按时间倒序保留的最近 20 条已完成任务,并附带 `activeCount`、`activeLimit`、`completedLimit`。 +- 管理员在管理端“用户信用管理”中可分别调整信用分和积分余额。积分调整接口为 `POST /api/admin/users/{user_id}/points`,请求体为 `{ "delta": 100, "reason": "补发活动奖励" }`;调整会写入积分明细并向用户发送站内通知。信用调整同样会发送通知。 +- 积分余额和校园信用卡片已移动到用户端“我的”页面,任务列表上方会显示当前未完成任务配额。 +- 注册前必须勾选并同意当前隐私政策(当前版本 `v1.0`)。用户的同意版本与时间记录在 `users.privacy_policy_version`、`users.privacy_policy_accepted_at`,政策内容可通过 `GET /api/privacy-policy` 获取;旧数据库启动时会自动补充字段。 +- 认证支持密码注册与密码登录:密码使用 PBKDF2-SHA256 单向散列保存;新设备或异常登录会要求邮箱验证码二次验证。旧账号的 `password_hash` 为空时仍可使用原邮箱验证码登录。忘记密码流程为 `POST /api/auth/send-reset-code` + `POST /api/auth/reset-password`,重置成功会撤销该账号已有会话。 +- 快递接单人需通过 `POST /api/tasks/{task_id}/proofs/pickup` 和 `POST /api/tasks/{task_id}/proofs/delivery` 分别上传取件照、送达照(multipart 字段名 `photo`)。两张照片齐全后 `POST /api/tasks/{task_id}/complete` 才会完成结算,并使用 SMTP 将照片作为附件发送给发布者注册邮箱。照片默认保存在 `backend/data/task-proofs/`,单张上限可通过 `[storage] max_proof_mb` 或 `TASK_PROOF_MAX_MB` 调整。 +- `users.password_hash`、`password_resets`、`user_known_ips` 会在启动时自动创建/补列;反向代理部署时可通过 `TRUST_PROXY_HEADERS`(或 `[security] trust_proxy_headers`)控制客户端 IP 透传解析。 +- `task_defaults` 和 `notifications` 是新增表,旧数据库迁移时允许暂不存在,目标库启动时会自动建表。 + +部署包不包含 backend/data 下的 SQLite 数据库文件。切换数据库前请先备份并用迁移脚本验证行数。 diff --git a/backend/config.toml b/backend/config.toml new file mode 100644 index 0000000..206c06b --- /dev/null +++ b/backend/config.toml @@ -0,0 +1,37 @@ +[app] +host = "0.0.0.0" +port = 34173 +workers = 2 +frontend_dir = "../dist" +environment = "production" + +[database] +# sqlite / mysql / postgresql +driver = "sqlite" +path = "./data/linkup.db" +# MySQL 示例:mysql://linkup:password@127.0.0.1:3306/linkup +url = "" +# 连接池按 worker 独立创建;4 workers 时最多使用 80 个连接。 +pool_size = 10 +max_overflow = 10 +pool_recycle = 1800 + +[smtp] +host = "smtp.163.com" +port = 465 +user = "" +password = "" + +[storage] +# 任务凭证保存在运行数据目录,部署打包不会包含这些用户照片。 +proof_dir = "./data/task-proofs" +max_proof_mb = 8 + +[security] +otp_pepper = "" +admin_emails = "" +frontend_origin = "" +# Only enable when the service is behind a trusted reverse proxy. +trust_proxy = false +# Set the administrator WeChat/QQ contact before deployment; blank uses a visible placeholder. +sanction_contact = "" diff --git a/backend/db_schema.py b/backend/db_schema.py new file mode 100644 index 0000000..e2c707b --- /dev/null +++ b/backend/db_schema.py @@ -0,0 +1,393 @@ +"""Shared SQLAlchemy schema for FastAPI and the SQLite/MySQL migration tool.""" + +from sqlalchemy import BigInteger, Boolean, Column, Index, Integer, MetaData, String, Table, Text, UniqueConstraint + +metadata = MetaData() + +email_verifications = Table( + "email_verifications", metadata, + Column("email", String(254), primary_key=True), + Column("code_hash", String(128), nullable=False), + Column("expires_at", BigInteger, nullable=False), + Column("sent_at", BigInteger, nullable=False), + Column("attempts", Integer, nullable=False, default=0), + Column("consumed_at", BigInteger), +) + +users = Table( + "users", metadata, + Column("id", String(64), primary_key=True), + Column("name", String(80), nullable=False), + Column("nickname", String(80), nullable=False), + Column("student_id", String(64), nullable=False, unique=True), + Column("school", String(160), nullable=False), + Column("email", String(254), nullable=False, unique=True), + Column("email_verified_at", BigInteger, nullable=False), + # 密码可为空以兼容已注册的旧账号;旧账号可继续使用邮箱验证码登录。 + Column("password_hash", String(256)), + # 注册时记录用户同意的隐私政策版本与时间,便于合规审计。 + Column("privacy_policy_version", String(32)), + Column("privacy_policy_accepted_at", BigInteger), + Column("status", String(16), nullable=False, default="active"), + Column("status_until", BigInteger), + Column("created_at", BigInteger, nullable=False), +) + +user_stats = Table( + "user_stats", metadata, + Column("user_id", String(64), primary_key=True), + Column("points_balance", Integer, nullable=False, default=750), + Column("withdrawable_points", Integer, nullable=False, default=0), + Column("credit_score", Integer, nullable=False, default=70), + Column("breach_count", Integer, nullable=False, default=0), + Column("commitments_count", Integer, nullable=False, default=0), + Column("completed_tasks", Integer, nullable=False, default=0), + Column("current_streak", Integer, nullable=False, default=0), + Column("claim_restricted_until", BigInteger), + Column("publish_restricted_until", BigInteger), + Column("updated_at", BigInteger, nullable=False), +) + +login_verifications = Table( + "login_verifications", metadata, + Column("email", String(254), primary_key=True), + Column("code_hash", String(128), nullable=False), + Column("expires_at", BigInteger, nullable=False), + Column("sent_at", BigInteger, nullable=False), + Column("attempts", Integer, nullable=False, default=0), + Column("consumed_at", BigInteger), +) + +password_resets = Table( + "password_resets", metadata, + Column("email", String(254), primary_key=True), + Column("code_hash", String(128), nullable=False), + Column("expires_at", BigInteger, nullable=False), + Column("sent_at", BigInteger, nullable=False), + Column("attempts", Integer, nullable=False, default=0), + Column("consumed_at", BigInteger), +) + +user_known_ips = Table( + "user_known_ips", metadata, + Column("user_id", String(64), primary_key=True), + Column("ip", String(64), primary_key=True), + Column("first_seen", BigInteger, nullable=False), + Column("last_seen", BigInteger, nullable=False), +) + +sessions = Table( + "sessions", metadata, + Column("id", String(64), primary_key=True), + Column("user_id", String(64), nullable=False), + Column("token_hash", String(128), nullable=False, unique=True), + Column("expires_at", BigInteger, nullable=False), + Column("created_at", BigInteger, nullable=False), + Column("ip", String(64)), + Column("user_agent", String(400)), +) + +login_logs = Table( + "login_logs", metadata, + Column("id", String(64), primary_key=True), + Column("user_id", String(64)), + Column("email_attempted", String(254)), + Column("success", Boolean, nullable=False), + Column("method", String(16), nullable=False), + Column("ip", String(64)), + Column("user_agent", String(400)), + Column("created_at", BigInteger, nullable=False), +) + +admin_audit_logs = Table( + "admin_audit_logs", metadata, + Column("id", String(64), primary_key=True), + Column("admin_id", String(64), nullable=False), + Column("action", String(80), nullable=False), + Column("target_user_id", String(64)), + Column("detail", String(400)), + Column("ip", String(64)), + Column("created_at", BigInteger, nullable=False), +) + +account_sanctions = Table( + "account_sanctions", metadata, + Column("id", String(64), primary_key=True), + Column("user_id", String(64), nullable=False), + Column("admin_id", String(64), nullable=False), + Column("action", String(16), nullable=False), + Column("scope", String(16), nullable=False), + Column("category", String(32)), + Column("reason", String(400), nullable=False), + Column("created_at", BigInteger, nullable=False), + Column("expires_at", BigInteger), + Column("lifted_at", BigInteger), + Column("lifted_by", String(64)), +) + +student_verifications = Table( + "student_verifications", metadata, + Column("id", String(64), primary_key=True), + Column("user_id", String(64), nullable=False, unique=True), + Column("online_code_cipher", Text, nullable=False), + Column("online_code_iv", String(128), nullable=False), + Column("online_code_tag", String(128), nullable=False), + Column("online_code_last4", String(4), nullable=False), + Column("report_expires_on", String(10), nullable=False), + Column("status", String(16), nullable=False, default="pending"), + Column("review_note", String(400)), + Column("submitted_at", BigInteger, nullable=False), + Column("reviewed_at", BigInteger), + Column("reviewed_by", String(64)), +) + +invite_codes = Table( + "invite_codes", metadata, + Column("id", String(64), primary_key=True), + Column("code", String(32), nullable=False, unique=True), + Column("owner_id", String(64), nullable=False), + Column("max_uses", Integer, nullable=False, default=2), + Column("used_count", Integer, nullable=False, default=0), + Column("created_at", BigInteger, nullable=False), + UniqueConstraint("owner_id", name="uq_invite_codes_owner"), +) + +invite_relations = Table( + "invite_relations", metadata, + Column("invitee_id", String(64), primary_key=True), + Column("inviter_id", String(64), nullable=False), + Column("created_at", BigInteger, nullable=False), +) + +credit_adjustments = Table( + "credit_adjustments", metadata, + Column("id", String(64), primary_key=True), + Column("user_id", String(64), nullable=False), + Column("admin_id", String(64), nullable=False), + Column("delta", Integer, nullable=False), + Column("reason", String(400), nullable=False), + # NULL preserves old free-text entries without guessing a public category. + Column("category", String(16)), + Column("before_score", Integer), + Column("after_score", Integer), + Column("task_id", String(64)), + Column("invitee_id", String(64)), + Column("rule_key", String(128)), + Column("note", String(400)), + Column("reverses_id", String(64)), + Column("reversed_by", String(64)), + Column("reversed_at", BigInteger), + Column("created_at", BigInteger, nullable=False), + UniqueConstraint("rule_key", name="uq_credit_adjustments_rule_key"), + UniqueConstraint("reverses_id", name="uq_credit_adjustments_reverses"), +) + +reliability_events = Table( + "reliability_events", metadata, + Column("id", String(64), primary_key=True), + Column("event_key", String(128), nullable=False, unique=True), + Column("user_id", String(64), nullable=False), + Column("task_id", String(64)), + Column("invitee_id", String(64)), + Column("kind", String(32), nullable=False), + Column("status", String(16), nullable=False), + Column("adjustment_id", String(64)), + Column("created_at", BigInteger, nullable=False), + Column("reviewed_by", String(64)), + Column("reversed_at", BigInteger), + Column("note", String(400)), +) + +public_credit_history_audits = Table( + "public_credit_history_audits", metadata, + Column("id", String(64), primary_key=True), + Column("viewer_id", String(64)), + Column("target_id", String(64), nullable=False), + Column("ts", BigInteger, nullable=False), +) + +conversations = Table( + "conversations", metadata, + Column("id", String(64), primary_key=True), + Column("user_a", String(64), nullable=False), + Column("user_b", String(64), nullable=False), + Column("created_at", BigInteger, nullable=False), + Column("last_message_at", BigInteger, nullable=False), + UniqueConstraint("user_a", "user_b", name="uq_conversations_users"), +) + +messages = Table( + "messages", metadata, + Column("id", String(64), primary_key=True), + Column("conversation_id", String(64), nullable=False), + Column("sender_id", String(64), nullable=False), + Column("content", Text, nullable=False), + Column("created_at", BigInteger, nullable=False), + Column("read_at", BigInteger), +) + +# Serializes send checks across a user's conversations on MySQL and obtains a +# SQLite write lock before checking the rolling hourly message limit. +chat_send_limits = Table( + "chat_send_limits", metadata, + Column("user_id", String(64), primary_key=True), + Column("locked_at", BigInteger, nullable=False), +) + +point_entries = Table( + "point_entries", metadata, + Column("id", String(64), primary_key=True), + Column("user_id", String(64), nullable=False), + Column("delta", Integer, nullable=False), + Column("withdrawable_delta", Integer, nullable=False, default=0), + Column("reason", String(400), nullable=False), + Column("created_at", BigInteger, nullable=False), +) + +official_tasks = Table( + "official_tasks", metadata, + Column("id", String(64), primary_key=True), + Column("admin_id", String(64), nullable=False), + Column("title", String(60), nullable=False), + Column("detail", String(500), nullable=False, default=""), + Column("reward", Integer, nullable=False), + Column("per_account_limit", Integer, nullable=False), + Column("total_quota", Integer, nullable=False, default=0), + Column("status", String(16), nullable=False, default="active"), + Column("deadline", BigInteger), + Column("created_at", BigInteger, nullable=False), +) + +official_task_claims = Table( + "official_task_claims", metadata, + Column("id", String(64), primary_key=True), + Column("task_id", String(64), nullable=False), + Column("user_id", String(64), nullable=False), + Column("reward", Integer, nullable=False), + Column("created_at", BigInteger, nullable=False), +) + +tasks = Table( + "tasks", metadata, + Column("id", String(64), primary_key=True), + Column("user_id", String(64), nullable=False), + Column("type", String(16), nullable=False), + Column("title", String(240), nullable=False), + Column("detail", Text, nullable=False), + Column("place", String(240), nullable=False), + # 独立的学校分区字段;旧任务可由启动迁移从 place 回填。 + Column("school", String(160)), + Column("deadline", BigInteger), + Column("reward", Integer, nullable=False, default=0), + Column("note", Text), + Column("contact", String(160)), + Column("pickup_codes", Text), + Column("category", String(80)), + Column("slots", Integer), + Column("status", String(16), nullable=False, default="open"), + Column("claimer_id", String(64)), + Column("created_at", BigInteger, nullable=False), + Column("claimed_at", BigInteger), + Column("cancelled_at", BigInteger), + Column("cancelled_by", String(64)), + Column("completed_at", BigInteger), +) + +# 快递代取交付凭证:接单人分别提交取件照与送达照。 +task_proofs = Table( + "task_proofs", metadata, + Column("task_id", String(64), primary_key=True), + Column("kind", String(16), primary_key=True), + Column("uploader_id", String(64), nullable=False), + Column("file_path", String(500), nullable=False), + Column("original_name", String(240), nullable=False), + Column("mime_type", String(80), nullable=False), + Column("file_size", Integer, nullable=False), + Column("created_at", BigInteger, nullable=False), +) + +# 用户最近一次发布跑腿任务时使用的常用信息,按类目分别保存,供发布表单自动回填。 +task_defaults = Table( + "task_defaults", metadata, + Column("user_id", String(64), primary_key=True), + Column("category", String(32), primary_key=True, default="快递代取"), + Column("school", String(160), nullable=False), + Column("phone", String(32), nullable=False), + Column("pickup_place", String(240)), + Column("destination", String(240)), + Column("updated_at", BigInteger, nullable=False), +) + +notifications = Table( + "notifications", metadata, + Column("id", String(64), primary_key=True), + Column("user_id", String(64), nullable=False), + Column("kind", String(32), nullable=False), + Column("title", String(120), nullable=False), + Column("content", String(400), nullable=False), + Column("link", String(240)), + Column("read_at", BigInteger), + Column("created_at", BigInteger, nullable=False), +) + +# 组队任务申请人:join 功能的名额计数与 joinedByMe 依据。 +task_participants = Table( + "task_participants", metadata, + Column("task_id", String(64), primary_key=True), + Column("user_id", String(64), primary_key=True), + Column("created_at", BigInteger, nullable=False), +) + +reports = Table( + "reports", metadata, + Column("id", String(64), primary_key=True), + Column("reporter_id", String(64), nullable=False), + Column("target_type", String(32), nullable=False), + Column("target_id", String(64), nullable=False), + Column("target_user_id", String(64)), + Column("conversation_id", String(64)), + Column("message_snapshot", Text), + Column("reason", String(400), nullable=False), + Column("status", String(16), nullable=False, default="open"), + Column("handled_by", String(64)), + Column("handling_note", String(400)), + Column("created_at", BigInteger, nullable=False), + Column("handled_at", BigInteger), +) + +Index("idx_sessions_user_id", sessions.c.user_id) +Index("idx_sessions_expires", sessions.c.expires_at) +Index("idx_user_known_ips_last_seen", user_known_ips.c.user_id, user_known_ips.c.last_seen) +Index("idx_users_school", users.c.school) +Index("idx_tasks_status_created", tasks.c.status, tasks.c.created_at) +Index("idx_tasks_school_status_created", tasks.c.school, tasks.c.status, tasks.c.created_at) +Index("idx_task_proofs_uploader_created", task_proofs.c.uploader_id, task_proofs.c.created_at) +Index("idx_reports_status_created", reports.c.status, reports.c.created_at) +Index("idx_point_entries_user", point_entries.c.user_id, point_entries.c.created_at) +Index("idx_official_task_claims_task", official_task_claims.c.task_id, official_task_claims.c.created_at) +Index("idx_official_task_claims_user", official_task_claims.c.task_id, official_task_claims.c.user_id) +Index("idx_credit_adjustments_user", credit_adjustments.c.user_id, credit_adjustments.c.created_at) +Index("idx_credit_history_audits_target_ts", public_credit_history_audits.c.target_id, public_credit_history_audits.c.ts) +Index("idx_conversations_user_a", conversations.c.user_a, conversations.c.last_message_at) +Index("idx_conversations_user_b", conversations.c.user_b, conversations.c.last_message_at) +Index("idx_messages_conversation_created", messages.c.conversation_id, messages.c.created_at) +Index("idx_messages_sender_created", messages.c.sender_id, messages.c.created_at) +Index("idx_student_verifications_status_submitted", student_verifications.c.status, student_verifications.c.submitted_at) +Index("idx_task_defaults_updated", task_defaults.c.updated_at) +Index("idx_notifications_user_created", notifications.c.user_id, notifications.c.created_at) +Index("idx_notifications_user_read", notifications.c.user_id, notifications.c.read_at) +Index("idx_task_participants_user_task", task_participants.c.user_id, task_participants.c.task_id) +Index("idx_login_logs_user_created", login_logs.c.user_id, login_logs.c.created_at) +Index("idx_login_logs_ip_created", login_logs.c.ip, login_logs.c.created_at) +Index("idx_admin_audit_created", admin_audit_logs.c.created_at) +Index("idx_admin_audit_admin_created", admin_audit_logs.c.admin_id, admin_audit_logs.c.created_at) +Index("idx_account_sanctions_user_created", account_sanctions.c.user_id, account_sanctions.c.created_at) + +TABLES = [ + email_verifications, users, user_stats, login_verifications, password_resets, + user_known_ips, sessions, login_logs, admin_audit_logs, account_sanctions, + student_verifications, invite_codes, invite_relations, credit_adjustments, reliability_events, + public_credit_history_audits, conversations, messages, chat_send_limits, + point_entries, official_tasks, official_task_claims, tasks, task_proofs, task_defaults, notifications, reports, + task_participants, +] diff --git a/backend/main.py b/backend/main.py new file mode 100644 index 0000000..d822f42 --- /dev/null +++ b/backend/main.py @@ -0,0 +1,3851 @@ +"""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("", views) + .replace("", dialogs) + .replace("", 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) diff --git a/backend/package-lock.json b/backend/package-lock.json new file mode 100644 index 0000000..4c12028 --- /dev/null +++ b/backend/package-lock.json @@ -0,0 +1,24 @@ +{ + "name": "linkup-registration-api", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "linkup-registration-api", + "version": "0.1.0", + "dependencies": { + "nodemailer": "latest" + } + }, + "node_modules/nodemailer": { + "version": "10.0.10", + "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.0.10.tgz", + "integrity": "sha512-He9XskOFms62SyAKkLu8CcGcYHAo+BSHSsORI8s4PJH8qZgZY4L4lDfvyN0twvmbpyG+eGrxpyBlskj9d9rJ8A==", + "license": "MIT-0", + "engines": { + "node": ">=20.0.0" + } + } + } +} diff --git a/backend/package.json b/backend/package.json new file mode 100644 index 0000000..afdff31 --- /dev/null +++ b/backend/package.json @@ -0,0 +1,13 @@ +{ + "name": "linkup-fastapi-backend", + "version": "0.2.0", + "private": true, + "description": "LinkUp FastAPI backend; use requirements.txt and uvicorn", + "scripts": { + "start": "python main.py", + "migrate": "python tools/migrate_db.py" + }, + "engines": { + "python": ">=3.11" + } +} diff --git a/backend/requirements.txt b/backend/requirements.txt new file mode 100644 index 0000000..1f1d7b1 --- /dev/null +++ b/backend/requirements.txt @@ -0,0 +1,11 @@ +fastapi>=0.115,<1 +uvicorn[standard]>=0.30,<1 +SQLAlchemy>=2.0.36,<3 +aiosqlite>=0.20,<1 +asyncmy>=0.2.9,<1 +asyncpg>=0.30,<1 +pymysql>=1.1,<2 +cryptography>=43,<46 +aiosmtplib>=3.0,<4 +python-multipart>=0.0.12,<1 +tomli-w>=1.0,<2 diff --git a/backend/server.mjs b/backend/server.mjs new file mode 100644 index 0000000..cfeef9e --- /dev/null +++ b/backend/server.mjs @@ -0,0 +1,1085 @@ +import http from "node:http"; +import { mkdirSync, createReadStream, statSync } from "node:fs"; +import { dirname, resolve, join, normalize as normalizePath, extname, sep } from "node:path"; +import { fileURLToPath } from "node:url"; +import { randomInt, randomUUID, randomBytes, createHash, createCipheriv, createDecipheriv, timingSafeEqual } from "node:crypto"; +import { DatabaseSync } from "node:sqlite"; +import nodemailer from "nodemailer"; + +try { process.loadEnvFile?.(); } catch {} + +const PORT = Number(process.env.PORT || 34173); +const FRONTEND_ORIGIN = process.env.FRONTEND_ORIGIN || `http://127.0.0.1:${PORT}`; +const SMTP_HOST = process.env.SMTP_HOST || "smtp.163.com"; +const SMTP_PORT = Number(process.env.SMTP_PORT || 465); +const SMTP_USER = process.env.SMTP_USER || ""; +const SMTP_PASS = process.env.SMTP_PASS || ""; +const OTP_PEPPER = process.env.OTP_PEPPER || ""; +const ADMIN_EMAILS = new Set(String(process.env.ADMIN_EMAILS || SMTP_USER).split(",").map(value => value.trim().toLowerCase()).filter(Boolean)); +const DATABASE_PATH = resolve(process.env.DATABASE_PATH || "./data/linkup.db"); +const TEST_MODE = process.env.NODE_ENV === "test"; + +if (!SMTP_USER || !SMTP_PASS || !OTP_PEPPER) { + console.error("Missing SMTP_USER, SMTP_PASS or OTP_PEPPER. Copy .env.example to .env and configure server secrets."); + process.exit(1); +} + +mkdirSync(dirname(DATABASE_PATH), { recursive: true }); +const STATIC_ROOT = fileURLToPath(new URL("../dist", import.meta.url)); +const STATIC_TYPES = { + ".html": "text/html; charset=utf-8", + ".js": "text/javascript; charset=utf-8", + ".css": "text/css; charset=utf-8", + ".svg": "image/svg+xml", + ".png": "image/png", + ".jpg": "image/jpeg", + ".ico": "image/x-icon", + ".json": "application/json; charset=utf-8", + ".woff2": "font/woff2", +}; + +function serveStatic(res, pathname) { + let path = decodeURIComponent(pathname); + if (path.endsWith("/")) path += "index.html"; + const file = normalizePath(join(STATIC_ROOT, path)); + if (file !== STATIC_ROOT && !file.startsWith(STATIC_ROOT + sep)) { + res.writeHead(403, { "Content-Type": "text/plain; charset=utf-8" }); + return res.end("Forbidden"); + } + let target = file; + try { + if (!statSync(target).isFile()) target = join(STATIC_ROOT, "index.html"); + } catch { + const last = path.split("/").pop() || ""; + if (extname(last) || last.startsWith(".")) { + res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" }); + return res.end("Not Found"); + } + target = join(STATIC_ROOT, "index.html"); + } + res.writeHead(200, { "Content-Type": STATIC_TYPES[extname(target).toLowerCase()] || "application/octet-stream", "Cache-Control": "no-cache" }); + createReadStream(target).on("error", () => res.end()).pipe(res); +} +const db = new DatabaseSync(DATABASE_PATH); +db.exec(` + PRAGMA journal_mode = WAL; + PRAGMA foreign_keys = ON; + CREATE TABLE IF NOT EXISTS email_verifications ( + email TEXT PRIMARY KEY, + code_hash TEXT NOT NULL, + expires_at INTEGER NOT NULL, + sent_at INTEGER NOT NULL, + attempts INTEGER NOT NULL DEFAULT 0, + consumed_at INTEGER + ); + CREATE TABLE IF NOT EXISTS users ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + nickname TEXT NOT NULL, + student_id TEXT NOT NULL UNIQUE, + school TEXT NOT NULL, + email TEXT NOT NULL UNIQUE, + email_verified_at INTEGER NOT NULL, + created_at INTEGER NOT NULL + ); + CREATE TABLE IF NOT EXISTS user_stats ( + user_id TEXT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, + points_balance INTEGER NOT NULL DEFAULT 750, + withdrawable_points INTEGER NOT NULL DEFAULT 0, + credit_score INTEGER NOT NULL DEFAULT 70, + breach_count INTEGER NOT NULL DEFAULT 0, + commitments_count INTEGER NOT NULL DEFAULT 0, + completed_tasks INTEGER NOT NULL DEFAULT 0, + current_streak INTEGER NOT NULL DEFAULT 0, + updated_at INTEGER NOT NULL + ); + CREATE TABLE IF NOT EXISTS login_verifications ( + email TEXT PRIMARY KEY, + code_hash TEXT NOT NULL, + expires_at INTEGER NOT NULL, + sent_at INTEGER NOT NULL, + attempts INTEGER NOT NULL DEFAULT 0, + consumed_at INTEGER + ); + CREATE TABLE IF NOT EXISTS sessions ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + token_hash TEXT NOT NULL UNIQUE, + expires_at INTEGER NOT NULL, + created_at INTEGER NOT NULL + ); + CREATE TABLE IF NOT EXISTS student_verifications ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL UNIQUE REFERENCES users(id) ON DELETE CASCADE, + online_code_cipher TEXT NOT NULL, + online_code_iv TEXT NOT NULL, + online_code_tag TEXT NOT NULL, + online_code_last4 TEXT NOT NULL, + report_expires_on TEXT NOT NULL, + status TEXT NOT NULL CHECK(status IN ('pending', 'approved', 'rejected')), + review_note TEXT, + submitted_at INTEGER NOT NULL, + reviewed_at INTEGER, + reviewed_by TEXT REFERENCES users(id) + ); + CREATE INDEX IF NOT EXISTS idx_verifications_expires ON email_verifications(expires_at); + CREATE INDEX IF NOT EXISTS idx_login_verifications_expires ON login_verifications(expires_at); + CREATE INDEX IF NOT EXISTS idx_sessions_user_id ON sessions(user_id); + CREATE INDEX IF NOT EXISTS idx_sessions_expires ON sessions(expires_at); + CREATE INDEX IF NOT EXISTS idx_student_verifications_status_submitted ON student_verifications(status, submitted_at); + CREATE TABLE IF NOT EXISTS invite_codes ( + id TEXT PRIMARY KEY, + code TEXT NOT NULL UNIQUE, + owner_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + max_uses INTEGER NOT NULL DEFAULT 2, + used_count INTEGER NOT NULL DEFAULT 0, + created_at INTEGER NOT NULL + ); + CREATE TABLE IF NOT EXISTS invite_relations ( + invitee_id TEXT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, + inviter_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + created_at INTEGER NOT NULL + ); + CREATE INDEX IF NOT EXISTS idx_invite_codes_owner ON invite_codes(owner_id); + CREATE INDEX IF NOT EXISTS idx_invite_relations_inviter ON invite_relations(inviter_id); + CREATE TABLE IF NOT EXISTS credit_adjustments ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + admin_id TEXT NOT NULL REFERENCES users(id), + delta INTEGER NOT NULL, + reason TEXT NOT NULL, + created_at INTEGER NOT NULL + ); + CREATE INDEX IF NOT EXISTS idx_credit_adjustments_user ON credit_adjustments(user_id, created_at); + CREATE TABLE IF NOT EXISTS point_entries ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + delta INTEGER NOT NULL, + withdrawable_delta INTEGER NOT NULL DEFAULT 0, + reason TEXT NOT NULL, + created_at INTEGER NOT NULL + ); + CREATE INDEX IF NOT EXISTS idx_point_entries_user ON point_entries(user_id, created_at); + CREATE TABLE IF NOT EXISTS tasks ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + type TEXT NOT NULL CHECK(type IN ('express','partner')), + title TEXT NOT NULL, + detail TEXT NOT NULL, + place TEXT NOT NULL, + deadline INTEGER, + reward INTEGER NOT NULL DEFAULT 0, + note TEXT, + contact TEXT, + pickup_codes TEXT, + category TEXT, + slots INTEGER, + status TEXT NOT NULL DEFAULT 'open' CHECK(status IN ('open','claimed','done','cancelled')), + claimer_id TEXT REFERENCES users(id) ON DELETE SET NULL, + created_at INTEGER NOT NULL + ); + CREATE INDEX IF NOT EXISTS idx_tasks_status_created ON tasks(status, created_at); + CREATE TABLE IF NOT EXISTS reports ( + id TEXT PRIMARY KEY, + reporter_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + target_type TEXT NOT NULL CHECK(target_type IN ('task')), + target_id TEXT NOT NULL, + reason TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'open' CHECK(status IN ('open','reviewed','dismissed')), + handled_by TEXT REFERENCES users(id), + handling_note TEXT, + created_at INTEGER NOT NULL, + handled_at INTEGER + ); + CREATE INDEX IF NOT EXISTS idx_reports_status_created ON reports(status, created_at); +`); +db.prepare(`INSERT OR IGNORE INTO user_stats(user_id, points_balance, withdrawable_points, credit_score, breach_count, commitments_count, completed_tasks, current_streak, updated_at) + SELECT id, 750, 0, 70, 0, 0, 0, 0, created_at FROM users`).run(); +for (const row of db.prepare(`SELECT u.id, u.created_at FROM users u + WHERE NOT EXISTS (SELECT 1 FROM point_entries p WHERE p.user_id = u.id AND p.reason = '注册赠送')`).all()) { + db.prepare("INSERT INTO point_entries(id, user_id, delta, withdrawable_delta, reason, created_at) VALUES (?, ?, 750, 0, '注册赠送', ?)").run(randomUUID(), row.id, Number(row.created_at)); +} +for (const row of db.prepare(`SELECT r.inviter_id, r.created_at FROM invite_relations r + WHERE NOT EXISTS (SELECT 1 FROM point_entries p WHERE p.user_id = r.inviter_id AND p.reason = '邀请奖励' AND p.created_at = r.created_at)`).all()) { + db.prepare("INSERT INTO point_entries(id, user_id, delta, withdrawable_delta, reason, created_at) VALUES (?, ?, 300, 300, '邀请奖励', ?)").run(randomUUID(), row.inviter_id, Number(row.created_at)); +} +for (const alter of ["ALTER TABLE tasks ADD COLUMN claimer_id TEXT REFERENCES users(id) ON DELETE SET NULL", "CREATE INDEX IF NOT EXISTS idx_tasks_claimer ON tasks(claimer_id)"]) { + try { db.exec(alter); } catch {} +} +db.exec("PRAGMA optimize"); + +const mailer = nodemailer.createTransport(TEST_MODE ? { jsonTransport: true } : { + host: SMTP_HOST, + port: SMTP_PORT, + secure: SMTP_PORT === 465, + auth: { user: SMTP_USER, pass: SMTP_PASS }, + pool: true, + maxConnections: 3, +}); + +const statements = { + verification: db.prepare("SELECT * FROM email_verifications WHERE email = ?"), + saveCode: db.prepare(`INSERT INTO email_verifications(email, code_hash, expires_at, sent_at, attempts, consumed_at) + VALUES (?, ?, ?, ?, 0, NULL) + ON CONFLICT(email) DO UPDATE SET code_hash=excluded.code_hash, expires_at=excluded.expires_at, + sent_at=excluded.sent_at, attempts=0, consumed_at=NULL`), + failAttempt: db.prepare("UPDATE email_verifications SET attempts = attempts + 1 WHERE email = ?"), + consumeCode: db.prepare("UPDATE email_verifications SET consumed_at = ? WHERE email = ?"), + deleteCode: db.prepare("DELETE FROM email_verifications WHERE email = ?"), + findStudent: db.prepare("SELECT id FROM users WHERE student_id = ?"), + findEmail: db.prepare("SELECT * FROM users WHERE email = ?"), + createUser: db.prepare(`INSERT INTO users(id, name, nickname, student_id, school, email, email_verified_at, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)`), + createUserStats: db.prepare(`INSERT INTO user_stats(user_id, points_balance, withdrawable_points, credit_score, breach_count, commitments_count, completed_tasks, current_streak, updated_at) + VALUES (?, 750, 0, ?, 0, 0, 0, 0, ?)`), + findUserStats: db.prepare("SELECT * FROM user_stats WHERE user_id = ?"), + loginVerification: db.prepare("SELECT * FROM login_verifications WHERE email = ?"), + saveLoginCode: db.prepare(`INSERT INTO login_verifications(email, code_hash, expires_at, sent_at, attempts, consumed_at) + VALUES (?, ?, ?, ?, 0, NULL) + ON CONFLICT(email) DO UPDATE SET code_hash=excluded.code_hash, expires_at=excluded.expires_at, + sent_at=excluded.sent_at, attempts=0, consumed_at=NULL`), + failLoginAttempt: db.prepare("UPDATE login_verifications SET attempts = attempts + 1 WHERE email = ?"), + consumeLoginCode: db.prepare("UPDATE login_verifications SET consumed_at = ? WHERE email = ?"), + deleteLoginCode: db.prepare("DELETE FROM login_verifications WHERE email = ?"), + createSession: db.prepare("INSERT INTO sessions(id, user_id, token_hash, expires_at, created_at) VALUES (?, ?, ?, ?, ?)"), + findSession: db.prepare(`SELECT s.id AS session_id, s.expires_at, u.* FROM sessions s JOIN users u ON u.id = s.user_id WHERE s.token_hash = ?`), + deleteSession: db.prepare("DELETE FROM sessions WHERE token_hash = ?"), + deleteExpiredSessions: db.prepare("DELETE FROM sessions WHERE expires_at < ?"), + findStudentVerification: db.prepare("SELECT * FROM student_verifications WHERE user_id = ?"), + saveStudentVerification: db.prepare(`INSERT INTO student_verifications(id, user_id, online_code_cipher, online_code_iv, online_code_tag, online_code_last4, report_expires_on, status, review_note, submitted_at, reviewed_at, reviewed_by) + VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', NULL, ?, NULL, NULL) + ON CONFLICT(user_id) DO UPDATE SET online_code_cipher=excluded.online_code_cipher, online_code_iv=excluded.online_code_iv, + online_code_tag=excluded.online_code_tag, online_code_last4=excluded.online_code_last4, report_expires_on=excluded.report_expires_on, + status='pending', review_note=NULL, submitted_at=excluded.submitted_at, reviewed_at=NULL, reviewed_by=NULL`), + listStudentVerifications: db.prepare(`SELECT v.*, u.name, u.nickname, u.student_id, u.school, u.email + FROM student_verifications v JOIN users u ON u.id = v.user_id WHERE v.status = ? ORDER BY v.submitted_at ASC`), + reviewStudentVerification: db.prepare("UPDATE student_verifications SET status = ?, review_note = ?, reviewed_at = ?, reviewed_by = ? WHERE id = ?"), + findStudentVerificationById: db.prepare("SELECT * FROM student_verifications WHERE id = ?"), + findInviteCodeByOwner: db.prepare("SELECT * FROM invite_codes WHERE owner_id = ?"), + findInviteCode: db.prepare("SELECT * FROM invite_codes WHERE code = ?"), + createInviteCode: db.prepare("INSERT INTO invite_codes(id, code, owner_id, max_uses, used_count, created_at) VALUES (?, ?, ?, 2, 0, ?)"), + incrementInviteUse: db.prepare("UPDATE invite_codes SET used_count = used_count + 1 WHERE id = ?"), + insertInviteRelation: db.prepare("INSERT INTO invite_relations(invitee_id, inviter_id, created_at) VALUES (?, ?, ?)"), + findInviterId: db.prepare("SELECT inviter_id FROM invite_relations WHERE invitee_id = ?"), + addEarnedPoints: db.prepare("UPDATE user_stats SET points_balance = points_balance + ?, withdrawable_points = withdrawable_points + ?, updated_at = ? WHERE user_id = ?"), + changeCreditScore: db.prepare("UPDATE user_stats SET credit_score = MAX(0, MIN(100, credit_score + ?)), updated_at = ? WHERE user_id = ?"), + findUserById: db.prepare("SELECT * FROM users WHERE id = ?"), + listUsersWithStats: db.prepare(`SELECT u.id, u.name, u.nickname, u.student_id, u.school, u.email, u.created_at, + s.credit_score, s.points_balance, s.breach_count, s.commitments_count + FROM users u LEFT JOIN user_stats s ON s.user_id = u.id ORDER BY u.created_at DESC`), + insertCreditAdjustment: db.prepare("INSERT INTO credit_adjustments(id, user_id, admin_id, delta, reason, created_at) VALUES (?, ?, ?, ?, ?, ?)"), + listCreditAdjustments: db.prepare(`SELECT a.id, a.user_id, a.delta, a.reason, a.created_at, + u.name AS user_name, u.nickname AS user_nickname, admin.name AS admin_name + FROM credit_adjustments a JOIN users u ON u.id = a.user_id JOIN users admin ON admin.id = a.admin_id + ORDER BY a.created_at DESC LIMIT 30`), + insertPointEntry: db.prepare("INSERT INTO point_entries(id, user_id, delta, withdrawable_delta, reason, created_at) VALUES (?, ?, ?, ?, ?, ?)"), + listPointEntries: db.prepare("SELECT delta, reason, created_at FROM point_entries WHERE user_id = ? ORDER BY created_at DESC LIMIT 50"), + createTask: db.prepare(`INSERT INTO tasks(id, user_id, type, title, detail, place, deadline, reward, note, contact, pickup_codes, category, slots, status, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'open', ?)`), + listOpenTasks: db.prepare(`SELECT t.id, t.user_id, t.type, t.title, t.detail, t.place, t.deadline, t.reward, t.note, t.category, t.slots, t.status, t.contact, t.pickup_codes, t.claimer_id, t.created_at, + u.nickname, u.name, s.credit_score FROM tasks t JOIN users u ON u.id = t.user_id + LEFT JOIN user_stats s ON s.user_id = t.user_id WHERE t.status = 'open' ORDER BY t.created_at DESC`), + listRelatedTasks: db.prepare(`SELECT t.id, t.user_id, t.type, t.title, t.detail, t.place, t.deadline, t.reward, t.note, t.category, t.slots, t.status, t.contact, t.pickup_codes, t.claimer_id, t.created_at, + u.nickname, u.name, s.credit_score FROM tasks t JOIN users u ON u.id = t.user_id + LEFT JOIN user_stats s ON s.user_id = t.user_id WHERE t.status = 'claimed' AND (t.claimer_id = ? OR t.user_id = ?) ORDER BY t.created_at DESC`), + claimTask: db.prepare("UPDATE tasks SET status = 'claimed', claimer_id = ? WHERE id = ? AND type = 'express' AND status = 'open'"), + addPoints: db.prepare("UPDATE user_stats SET points_balance = points_balance + ?, updated_at = ? WHERE user_id = ?"), + addPointsWithdrawable: db.prepare("UPDATE user_stats SET points_balance = points_balance + ?, withdrawable_points = withdrawable_points + ?, updated_at = ? WHERE user_id = ?"), + completeTask: db.prepare("UPDATE tasks SET status = 'done' WHERE id = ? AND status = 'claimed'"), + findTaskById: db.prepare("SELECT * FROM tasks WHERE id = ?"), + cancelTask: db.prepare("UPDATE tasks SET status = 'cancelled' WHERE id = ?"), + insertReport: db.prepare("INSERT INTO reports(id, reporter_id, target_type, target_id, reason, status, created_at) VALUES (?, ?, ?, ?, ?, 'open', ?)"), + findOpenReport: db.prepare("SELECT id FROM reports WHERE reporter_id = ? AND target_type = ? AND target_id = ? AND status = 'open'"), + listReportsByStatus: db.prepare(`SELECT r.id, r.reporter_id, r.target_type, r.target_id, r.reason, r.status, r.handling_note, r.created_at, r.handled_at, + u.name AS reporter_name, u.nickname AS reporter_nickname, u.email AS reporter_email, + t.title AS task_title, t.detail AS task_detail, t.status AS task_status, t.type AS task_type, t.reward AS task_reward, + tu.name AS task_owner_name, tu.nickname AS task_owner_nickname, tu.student_id AS task_owner_student_id + FROM reports r JOIN users u ON u.id = r.reporter_id + LEFT JOIN tasks t ON t.id = r.target_id + LEFT JOIN users tu ON tu.id = t.user_id + WHERE r.status = ? ORDER BY r.created_at DESC LIMIT 100`), + findReportById: db.prepare("SELECT * FROM reports WHERE id = ?"), + handleReport: db.prepare("UPDATE reports SET status = ?, handling_note = ?, handled_by = ?, handled_at = ? WHERE id = ?"), + listMyTasks: db.prepare(`SELECT id, user_id, claimer_id, type, title, place, deadline, reward, status, contact, created_at FROM tasks + WHERE (user_id = ? OR claimer_id = ?) AND status IN ('open','claimed','done') + ORDER BY CASE status WHEN 'open' THEN 0 WHEN 'claimed' THEN 1 ELSE 2 END, created_at DESC`), + adminOverview: db.prepare(`SELECT + (SELECT COUNT(*) FROM users) AS total_users, + (SELECT COUNT(*) FROM student_verifications WHERE status = 'pending') AS pending, + (SELECT COUNT(*) FROM student_verifications WHERE status = 'approved') AS approved, + (SELECT COUNT(*) FROM student_verifications WHERE status = 'rejected') AS rejected`), +}; +const sendWindows = new Map(); + +function canSendFromIp(ip) { + const now = Date.now(); + const recent = (sendWindows.get(ip) || []).filter(time => now - time < 60 * 60_000); + if (recent.length >= 10) return false; + recent.push(now); + sendWindows.set(ip, recent); + return true; +} + +const normalize = value => String(value ?? "").trim(); +const normalizeEmail = value => normalize(value).toLowerCase(); +const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; +const studentIdPattern = /^[A-Za-z0-9_-]{4,32}$/; +const hashCode = (email, code) => createHash("sha256").update(`${email}:${code}:${OTP_PEPPER}`).digest(); +const hashToken = token => createHash("sha256").update(token).digest("hex"); +const safeEqual = (left, right) => left.length === right.length && timingSafeEqual(left, right); +const verificationKey = createHash("sha256").update(`${OTP_PEPPER}:student-verification`).digest(); +const isAdmin = user => ADMIN_EMAILS.has(normalizeEmail(user.email)); +function verificationSummary(userId) { + const record = statements.findStudentVerification.get(userId); + if (!record) return { level: 1, status: "unsubmitted", label: "邮箱已验证" }; + const expired = record.status === "approved" && record.report_expires_on < new Date().toISOString().slice(0, 10); + return { + level: record.status === "approved" && !expired ? 2 : 1, + status: expired ? "expired" : record.status, + label: record.status === "approved" && !expired ? "学信网已认证" : "邮箱已验证", + reportExpiresOn: record.report_expires_on, + submittedAt: record.submitted_at, + reviewNote: record.status === "rejected" ? record.review_note : undefined, + codeLast4: record.online_code_last4, + }; +} +function accountStats(userId) { + const stats = statements.findUserStats.get(userId) || {}; + const commitments = Number(stats.commitments_count || 0); + const breaches = Number(stats.breach_count || 0); + return { + pointsBalance: Number(stats.points_balance || 0), + withdrawablePoints: Number(stats.withdrawable_points || 0), + creditScore: Number(stats.credit_score ?? 70), + breachRate: commitments ? Math.round((breaches / commitments) * 1000) / 10 : 0, + completedTasks: Number(stats.completed_tasks || 0), + currentStreak: Number(stats.current_streak || 0), + }; +} +const publicUser = user => ({ id:user.id, name:user.name, nickname:user.nickname, studentId:user.student_id, school:user.school, email:user.email, createdAt:user.created_at, stats:accountStats(user.id), verification:verificationSummary(user.id), isAdmin:isAdmin(user) }); + +const INVITE_ALPHABET = "23456789ABCDEFGHJKMNPQRSTUVWXYZ"; +const generateInviteCode = () => Array.from(randomBytes(8), byte => INVITE_ALPHABET[byte % INVITE_ALPHABET.length]).join(""); +const inviteEligible = credit => credit > 90; +function applyCreditChange(userId, delta) { + if (!delta) return { applied: 0 }; + const before = Number(statements.findUserStats.get(userId)?.credit_score ?? 0); + statements.changeCreditScore.run(delta, Date.now(), userId); + const after = Number(statements.findUserStats.get(userId)?.credit_score ?? 0); + const applied = after - before; + if (delta >= 0 || applied >= 0) return { applied }; + const relation = statements.findInviterId.get(userId); + const inviterStats = relation && statements.findUserStats.get(relation.inviter_id); + if (!inviterStats) return { applied }; + const inviterBefore = Number(inviterStats.credit_score); + statements.changeCreditScore.run(-Math.ceil(-applied / 2), Date.now(), relation.inviter_id); + const inviterDelta = Number(statements.findUserStats.get(relation.inviter_id).credit_score) - inviterBefore; + return { applied, inviterId: relation.inviter_id, inviterDelta }; +} + +function encryptVerificationCode(value) { + const iv = randomBytes(12); + const cipher = createCipheriv("aes-256-gcm", verificationKey, iv); + const encrypted = Buffer.concat([cipher.update(value, "utf8"), cipher.final()]); + return { cipher: encrypted.toString("base64url"), iv: iv.toString("base64url"), tag: cipher.getAuthTag().toString("base64url") }; +} + +function decryptVerificationCode(record) { + const decipher = createDecipheriv("aes-256-gcm", verificationKey, Buffer.from(record.online_code_iv, "base64url")); + decipher.setAuthTag(Buffer.from(record.online_code_tag, "base64url")); + return Buffer.concat([decipher.update(Buffer.from(record.online_code_cipher, "base64url")), decipher.final()]).toString("utf8"); +} + +function issueSession(userId) { + const token = randomBytes(32).toString("base64url"); + const now = Date.now(); + statements.deleteExpiredSessions.run(now); + statements.createSession.run(randomUUID(), userId, hashToken(token), now + 30 * 24 * 60 * 60_000, now); + return token; +} + +function bearerToken(req) { + const value = String(req.headers.authorization || ""); + return value.startsWith("Bearer ") ? value.slice(7).trim() : ""; +} + +function authenticatedUser(req) { + const token = bearerToken(req); + if (!token) return null; + const session = statements.findSession.get(hashToken(token)); + if (!session || session.expires_at < Date.now()) return null; + return session; +} + +function headers(origin) { + const allowed = origin === FRONTEND_ORIGIN || /^http:\/\/(127\.0\.0\.1|localhost)(:\d+)?$/.test(origin || ""); + return { + "Content-Type": "application/json; charset=utf-8", + "Access-Control-Allow-Origin": allowed ? origin : FRONTEND_ORIGIN, + "Access-Control-Allow-Headers": "Content-Type, Authorization", + "Access-Control-Allow-Methods": "GET, POST, OPTIONS", + "Vary": "Origin", + "X-Content-Type-Options": "nosniff", + "Cache-Control": "no-store", + }; +} + +function send(res, status, body, origin) { + res.writeHead(status, headers(origin)); + res.end(JSON.stringify(body)); +} + +async function readJson(req) { + const chunks = []; + let size = 0; + for await (const chunk of req) { + size += chunk.length; + if (size > 16_384) throw Object.assign(new Error("请求内容过大"), { status: 413 }); + chunks.push(chunk); + } + try { return JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}"); } + catch { throw Object.assign(new Error("请求格式错误"), { status: 400 }); } +} + +async function sendCode(req, res, origin) { + const body = await readJson(req); + const email = normalizeEmail(body.email); + if (!emailPattern.test(email) || email.length > 254) return send(res, 400, { error: "请输入有效邮箱" }, origin); + if (statements.findEmail.get(email)) return send(res, 409, { error: "该邮箱已注册" }, origin); + if (!canSendFromIp(req.socket.remoteAddress || "unknown")) return send(res, 429, { error: "验证码发送过于频繁,请稍后再试" }, origin); + + const now = Date.now(); + const previous = statements.verification.get(email); + if (previous && now - previous.sent_at < 60_000) { + return send(res, 429, { error: `请在 ${Math.ceil((60_000 - (now - previous.sent_at)) / 1000)} 秒后重试` }, origin); + } + + const code = String(randomInt(0, 1_000_000)).padStart(6, "0"); + statements.saveCode.run(email, hashCode(email, code).toString("hex"), now + 10 * 60_000, now); + try { + await mailer.sendMail({ + from: `"LinkUp 校园互助" <${SMTP_USER}>`, + to: email, + subject: "LinkUp 注册验证码", + text: `你的 LinkUp 注册验证码是:${code}。验证码 10 分钟内有效,请勿转发给他人。`, + html: `

LinkUp 校园互助

你的注册验证码是:

${code}

验证码 10 分钟内有效,请勿转发给他人。

`, + }); + return send(res, 200, { ok: true, expiresIn: 600, ...(TEST_MODE ? { testCode: code } : {}) }, origin); + } catch (error) { + statements.deleteCode.run(email); + console.error("SMTP delivery failed:", error?.code || error?.message || "unknown error"); + return send(res, 502, { error: "验证码暂时无法发送,请稍后重试" }, origin); + } +} + +async function sendLoginCode(req, res, origin) { + const body = await readJson(req); + const email = normalizeEmail(body.email); + if (!emailPattern.test(email) || email.length > 254) return send(res, 400, { error: "请输入有效邮箱" }, origin); + if (!statements.findEmail.get(email)) return send(res, 404, { error: "该邮箱尚未注册" }, origin); + if (!canSendFromIp(req.socket.remoteAddress || "unknown")) return send(res, 429, { error: "验证码发送过于频繁,请稍后再试" }, origin); + + const now = Date.now(); + const previous = statements.loginVerification.get(email); + if (previous && now - previous.sent_at < 60_000) { + return send(res, 429, { error: `请在 ${Math.ceil((60_000 - (now - previous.sent_at)) / 1000)} 秒后重试` }, origin); + } + + const code = String(randomInt(0, 1_000_000)).padStart(6, "0"); + statements.saveLoginCode.run(email, hashCode(email, code).toString("hex"), now + 10 * 60_000, now); + try { + await mailer.sendMail({ + from: `"LinkUp 校园互助" <${SMTP_USER}>`, + to: email, + subject: "LinkUp 登录验证码", + text: `你的 LinkUp 登录验证码是:${code}。验证码 10 分钟内有效,请勿转发给他人。`, + html: `

LinkUp 校园互助

你的登录验证码是:

${code}

验证码 10 分钟内有效,请勿转发给他人。

`, + }); + return send(res, 200, { ok: true, expiresIn: 600, ...(TEST_MODE ? { testCode: code } : {}) }, origin); + } catch (error) { + statements.deleteLoginCode.run(email); + console.error("SMTP login delivery failed:", error?.code || error?.message || "unknown error"); + return send(res, 502, { error: "验证码暂时无法发送,请稍后重试" }, origin); + } +} + +async function loginUser(req, res, origin) { + const body = await readJson(req); + const email = normalizeEmail(body.email); + const code = normalize(body.code); + if (!emailPattern.test(email)) return send(res, 400, { error: "请输入有效邮箱" }, origin); + if (!/^\d{6}$/.test(code)) return send(res, 400, { error: "请输入 6 位验证码" }, origin); + const user = statements.findEmail.get(email); + if (!user) return send(res, 404, { error: "该邮箱尚未注册" }, origin); + + const verification = statements.loginVerification.get(email); + const now = Date.now(); + if (!verification || verification.consumed_at) return send(res, 400, { error: "请先获取登录验证码" }, origin); + if (verification.expires_at < now) return send(res, 400, { error: "验证码已过期,请重新获取" }, origin); + if (verification.attempts >= 5) return send(res, 429, { error: "验证码错误次数过多,请重新获取" }, origin); + if (!safeEqual(hashCode(email, code), Buffer.from(verification.code_hash, "hex"))) { + statements.failLoginAttempt.run(email); + return send(res, 400, { error: "验证码不正确" }, origin); + } + + statements.consumeLoginCode.run(now, email); + const token = issueSession(user.id); + return send(res, 200, { ok: true, token, user: publicUser(user) }, origin); +} + +function currentUser(req, res, origin) { + const session = authenticatedUser(req); + if (!session) return send(res, 401, { error: "登录已过期,请重新登录" }, origin); + return send(res, 200, { ok: true, user: publicUser(session) }, origin); +} + +function listPointEntriesHandler(req, res, origin) { + const user = authenticatedUser(req); + if (!user) return send(res, 401, { error: "请先登录" }, origin); + const entries = statements.listPointEntries.all(user.id).map(row => ({ + delta: Number(row.delta), + reason: row.reason, + createdAt: Number(row.created_at), + })); + const stats = statements.findUserStats.get(user.id); + return send(res, 200, { + ok: true, + entries, + balance: Number(stats?.points_balance ?? 0), + withdrawable: Number(stats?.withdrawable_points ?? 0), + }, origin); +} + +function taskItem(row, viewerId) { + const owner = viewerId != null && viewerId === row.user_id; + const claimer = viewerId != null && row.claimer_id != null && viewerId === row.claimer_id; + let pickupCodes = null; + if (claimer && row.pickup_codes) { + try { pickupCodes = JSON.parse(row.pickup_codes); } catch {} + } + return { + id: row.id, + type: row.type, + title: row.title, + route: row.detail, + place: row.place, + deadline: row.deadline, + reward: Number(row.reward), + note: row.note, + category: row.category, + joined: row.slots ? `0/${row.slots}` : null, + user: row.nickname || row.name, + credit: Number(row.credit_score ?? 70), + createdAt: row.created_at, + status: row.status, + mine: owner, + claimedByMe: claimer, + phone: owner || claimer ? row.contact : undefined, + pickupCodes, + }; +} + +function listTasks(req, res, origin) { + const session = authenticatedUser(req); + const viewerId = session ? session.id : null; + const items = statements.listOpenTasks.all().map(row => taskItem(row, viewerId)); + if (viewerId) { + for (const row of statements.listRelatedTasks.all(viewerId, viewerId)) items.push(taskItem(row, viewerId)); + } + return send(res, 200, { ok: true, items }, origin); +} + +async function createTask(req, res, origin) { + const user = authenticatedUser(req); + if (!user) return send(res, 401, { error: "请先登录后发布" }, origin); + const body = await readJson(req); + const type = normalize(body.type); + if (!["express", "partner"].includes(type)) return send(res, 400, { error: "任务类型无效" }, origin); + const now = Date.now(); + const deadline = Number(body.deadline); + if (!Number.isFinite(deadline) || deadline < now || deadline > now + 30 * 24 * 60 * 60_000) return send(res, 400, { error: "请选择有效的截止时间(今天至未来 30 天内)" }, origin); + const id = randomUUID(); + let title, detail, place, reward, note, contact = null, pickupCodes = null, category = null, slots = null; + if (type === "express") { + const phone = normalize(body.phone); + const pickupPlace = normalize(body.pickupPlace); + const destination = normalize(body.destination); + pickupCodes = Array.isArray(body.pickupCodes) ? body.pickupCodes.map(value => normalize(value)).filter(Boolean) : []; + if (!/^[\d\-+ ]{6,20}$/.test(phone)) return send(res, 400, { error: "请填写有效手机号" }, origin); + if (!pickupPlace || pickupPlace.length > 60) return send(res, 400, { error: "请填写取件地点" }, origin); + if (!destination || destination.length > 60) return send(res, 400, { error: "请填写送达位置" }, origin); + if (!pickupCodes.length) return send(res, 400, { error: "请至少填写一个取件码" }, origin); + reward = Number(body.reward); + if (!Number.isInteger(reward) || reward < 200 || reward > 1500) return send(res, 400, { error: "任务积分需为 200—1500 的整数" }, origin); + const publisherStats = statements.findUserStats.get(user.id); + if (!publisherStats || Number(publisherStats.points_balance) < reward) return send(res, 400, { error: `积分余额不足,发布任务至少需要 ${reward} 积分` }, origin); + title = `${pickupPlace} → ${destination}`; + detail = `送到 ${destination}`; + place = pickupPlace; + contact = phone; + const desc = normalize(body.sizeDesc); + const remark = normalize(body.note).slice(0, 200); + note = [desc && `快递描述:${desc}`, pickupCodes.length > 1 ? `共 ${pickupCodes.length} 个取件码` : null, remark].filter(Boolean).join(";") || null; + } else { + title = normalize(body.title); + contact = normalize(body.contact); + category = normalize(body.category); + slots = Number(body.slots); + const experience = normalize(body.experience).slice(0, 300); + const link = normalize(body.link); + if (!title || title.length > 60) return send(res, 400, { error: "请填写任务标题" }, origin); + if (!contact || contact.length > 40) return send(res, 400, { error: "请填写联系方式" }, origin); + if (!["考研自习", "竞赛组队", "运动健身", "兴趣社交"].includes(category)) return send(res, 400, { error: "请选择任务类型" }, origin); + if (!Number.isInteger(slots) || slots < 1 || slots > 20) return send(res, 400, { error: "所需人数需为 1—20 的整数" }, origin); + if (link && !/^https?:\/\/.{4,200}$/.test(link)) return send(res, 400, { error: "链接格式不正确" }, origin); + reward = 0; + place = "待商定"; + detail = experience || "期待你的加入"; + note = link ? `组队链接(待人工审核后展示):${link}` : null; + } + statements.createTask.run(id, user.id, type, title, detail, place, deadline, reward, note, contact, pickupCodes ? JSON.stringify(pickupCodes) : null, category, slots, now); + return send(res, 201, { ok: true, id }, origin); +} + +function cancelTaskHandler(req, res, origin, taskId) { + const user = authenticatedUser(req); + if (!user) return send(res, 401, { error: "请先登录" }, origin); + const task = statements.findTaskById.get(taskId); + if (!task || task.status === "cancelled") return send(res, 404, { error: "任务不存在" }, origin); + if (task.status !== "open") return send(res, 409, { error: "已被接单的任务不能取消" }, origin); + if (task.user_id !== user.id) return send(res, 403, { error: "只能取消自己发布的任务" }, origin); + statements.cancelTask.run(taskId); + return send(res, 200, { ok: true }, origin); +} + +function claimTaskHandler(req, res, origin, taskId) { + const user = authenticatedUser(req); + if (!user) return send(res, 401, { error: "请先登录后接单" }, origin); + const task = statements.findTaskById.get(taskId); + if (!task || task.status === "cancelled") return send(res, 404, { error: "任务不存在" }, origin); + if (task.type !== "express") return send(res, 400, { error: "组队任务请在详情内申请加入" }, origin); + if (task.user_id === user.id) return send(res, 400, { error: "不能接自己发布的任务" }, origin); + const reward = Number(task.reward); + const now = Date.now(); + db.exec("BEGIN IMMEDIATE"); + try { + const claimed = statements.claimTask.run(user.id, taskId); + if (!claimed.changes) throw Object.assign(new Error("该任务已被他人接单"), { code: "RACE" }); + if (reward > 0) { + const publisherStats = statements.findUserStats.get(task.user_id); + if (!publisherStats || Number(publisherStats.points_balance) < reward) throw Object.assign(new Error("发布者积分余额不足,无法接单"), { code: "BALANCE" }); + statements.addPoints.run(-reward, now, task.user_id); + statements.insertPointEntry.run(randomUUID(), task.user_id, -reward, 0, `任务被接单 · ${task.title}`.slice(0, 60), now); + } + db.exec("COMMIT"); + } catch (error) { + try { db.exec("ROLLBACK"); } catch {} + if (error.code === "BALANCE") return send(res, 409, { error: "发布者积分余额不足,无法接单" }, origin); + if (error.code === "RACE") return send(res, 409, { error: "该任务已被他人接单" }, origin); + throw error; + } + return send(res, 200, { ok: true, phone: task.contact, pickupCodes: task.pickup_codes ? JSON.parse(task.pickup_codes) : [] }, origin); +} + +function completeTaskHandler(req, res, origin, taskId) { + const user = authenticatedUser(req); + if (!user) return send(res, 401, { error: "请先登录" }, origin); + const task = statements.findTaskById.get(taskId); + if (!task) return send(res, 404, { error: "任务不存在" }, origin); + if (task.status !== "claimed") return send(res, 409, { error: "任务不在进行中" }, origin); + if (task.user_id !== user.id && task.claimer_id !== user.id) return send(res, 403, { error: "仅任务双方可以确认完成" }, origin); + const reward = Number(task.reward); + const now = Date.now(); + db.exec("BEGIN IMMEDIATE"); + try { + const done = statements.completeTask.run(taskId); + if (!done.changes) throw new Error("RACE"); + if (reward > 0 && task.claimer_id) { + statements.addPointsWithdrawable.run(reward, reward, now, task.claimer_id); + statements.insertPointEntry.run(randomUUID(), task.claimer_id, reward, reward, `任务完成 · ${task.title}`.slice(0, 60), now); + } + db.exec("COMMIT"); + } catch (error) { + try { db.exec("ROLLBACK"); } catch {} + return send(res, 409, { error: "任务状态已变化,请刷新后重试" }, origin); + } + return send(res, 200, { ok: true, reward }, origin); +} + +function listMyTasksHandler(req, res, origin) { + const user = authenticatedUser(req); + if (!user) return send(res, 401, { error: "请先登录" }, origin); + const items = statements.listMyTasks.all(user.id, user.id).map(row => { + const claimed = row.claimer_id === user.id; + return { + id: row.id, + type: row.type, + title: row.title, + place: row.place, + deadline: row.deadline, + reward: Number(row.reward), + status: row.status, + role: claimed ? "claimed" : "published", + phone: claimed ? row.contact : undefined, + createdAt: row.created_at, + }; + }); + return send(res, 200, { ok: true, items }, origin); +} + +function reportItem(row) { + return { + 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: row.task_title ? { + title: row.task_title, + detail: row.task_detail, + type: row.task_type, + reward: Number(row.task_reward || 0), + status: row.task_status, + owner: { name: row.task_owner_name, nickname: row.task_owner_nickname, studentId: row.task_owner_student_id }, + } : null, + reason: row.reason, + status: row.status, + handlingNote: row.handling_note, + createdAt: row.created_at, + handledAt: row.handled_at, + }; +} + +async function createReport(req, res, origin) { + const user = authenticatedUser(req); + if (!user) return send(res, 401, { error: "请先登录后举报" }, origin); + const body = await readJson(req); + const targetType = normalize(body.targetType); + const targetId = normalize(body.targetId); + const reason = normalize(body.reason).slice(0, 200); + if (targetType !== "task" || !targetId) return send(res, 400, { error: "举报对象无效" }, origin); + if (reason.length < 5) return send(res, 400, { error: "请填写举报理由(5—200 字)" }, origin); + if (!statements.findTaskById.get(targetId)) return send(res, 404, { error: "被举报的任务不存在" }, origin); + if (statements.findOpenReport.get(user.id, targetType, targetId)) return send(res, 409, { error: "你已举报过该内容,请等待处理" }, origin); + const id = randomUUID(); + statements.insertReport.run(id, user.id, targetType, targetId, reason, Date.now()); + return send(res, 201, { ok: true, id }, origin); +} + +function adminListReports(req, res, origin, url) { + const user = authenticatedUser(req); + if (!user) return send(res, 401, { error: "请先登录" }, origin); + if (!isAdmin(user)) return send(res, 403, { error: "无管理权限" }, origin); + const requested = normalize(url.searchParams.get("status") || "open"); + const status = ["open", "reviewed", "dismissed"].includes(requested) ? requested : "open"; + const items = statements.listReportsByStatus.all(status).map(reportItem); + return send(res, 200, { ok: true, items }, origin); +} + +async function adminHandleReport(req, res, origin, reportId) { + const admin = authenticatedUser(req); + if (!admin) return send(res, 401, { error: "请先登录" }, origin); + if (!isAdmin(admin)) return send(res, 403, { error: "无管理权限" }, origin); + const report = statements.findReportById.get(reportId); + if (!report) return send(res, 404, { error: "举报记录不存在" }, origin); + const body = await readJson(req); + const decision = normalize(body.decision); + const note = normalize(body.note).slice(0, 200); + if (!["reviewed", "dismissed"].includes(decision)) return send(res, 400, { error: "处理结果无效" }, origin); + statements.handleReport.run(decision, note || null, admin.id, Date.now(), reportId); + return send(res, 200, { ok: true }, origin); +} + +function logoutUser(req, res, origin) { + const token = bearerToken(req); + if (token) statements.deleteSession.run(hashToken(token)); + return send(res, 200, { ok: true }, origin); +} + +async function submitStudentVerification(req, res, origin) { + const user = authenticatedUser(req); + if (!user) return send(res, 401, { error: "请先登录" }, origin); + const body = await readJson(req); + const onlineCode = normalize(body.onlineCode).replace(/\s+/g, "").toUpperCase(); + const reportExpiresOn = normalize(body.reportExpiresOn); + if (!/^[A-Z0-9-]{8,32}$/.test(onlineCode)) return send(res, 400, { error: "请输入有效的学信网在线验证码" }, origin); + if (!/^\d{4}-\d{2}-\d{2}$/.test(reportExpiresOn)) return send(res, 400, { error: "请选择验证报告有效期" }, origin); + const expiresAt = Date.parse(`${reportExpiresOn}T23:59:59+08:00`); + if (!Number.isFinite(expiresAt) || expiresAt < Date.now()) return send(res, 400, { error: "验证报告已过期,请先在学信网延长有效期" }, origin); + if (expiresAt > Date.now() + 2 * 365 * 24 * 60 * 60_000) return send(res, 400, { error: "验证报告有效期不正确" }, origin); + const encrypted = encryptVerificationCode(onlineCode); + const existing = statements.findStudentVerification.get(user.id); + statements.saveStudentVerification.run(existing?.id || randomUUID(), user.id, encrypted.cipher, encrypted.iv, encrypted.tag, onlineCode.slice(-4), reportExpiresOn, Date.now()); + return send(res, 200, { ok: true, verification: verificationSummary(user.id) }, origin); +} + +function getStudentVerification(req, res, origin) { + const user = authenticatedUser(req); + if (!user) return send(res, 401, { error: "请先登录" }, origin); + return send(res, 200, { ok: true, verification: verificationSummary(user.id) }, origin); +} + +function listStudentVerifications(req, res, origin, url) { + const user = authenticatedUser(req); + if (!user) return send(res, 401, { error: "请先登录" }, origin); + if (!isAdmin(user)) return send(res, 403, { error: "无审核权限" }, origin); + const requestedStatus = normalize(url.searchParams.get("status") || "pending"); + const status = ["pending", "approved", "rejected"].includes(requestedStatus) ? requestedStatus : "pending"; + const items = statements.listStudentVerifications.all(status).map(record => ({ + id: record.id, + name: record.name, + nickname: record.nickname, + studentId: record.student_id, + school: record.school, + email: record.email, + onlineCode: decryptVerificationCode(record), + codeLast4: record.online_code_last4, + reportExpiresOn: record.report_expires_on, + status: record.status, + reviewNote: record.review_note, + submittedAt: record.submitted_at, + reviewedAt: record.reviewed_at, + })); + return send(res, 200, { ok: true, items }, origin); +} + +function adminOverview(req, res, origin) { + const user = authenticatedUser(req); + if (!user) return send(res, 401, { error: "请先登录" }, origin); + if (!isAdmin(user)) return send(res, 403, { error: "无管理权限" }, origin); + const stats = statements.adminOverview.get(); + return send(res, 200, { ok: true, stats: { totalUsers: stats.total_users, pending: stats.pending, approved: stats.approved, rejected: stats.rejected } }, origin); +} + +function adminUserItem(row) { + const commitments = Number(row.commitments_count || 0); + const breaches = Number(row.breach_count || 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: Number(row.credit_score ?? 70), + pointsBalance: Number(row.points_balance ?? 0), + breachRate: commitments ? Math.round((breaches / commitments) * 1000) / 10 : 0, + }; +} + +function adminListUsers(req, res, origin, url) { + const user = authenticatedUser(req); + if (!user) return send(res, 401, { error: "请先登录" }, origin); + if (!isAdmin(user)) return send(res, 403, { error: "无管理权限" }, origin); + const q = normalize(url.searchParams.get("q")).toLowerCase(); + const items = statements.listUsersWithStats.all() + .map(adminUserItem) + .filter(item => !q || `${item.name}${item.nickname}${item.studentId}${item.school}${item.email}`.toLowerCase().includes(q)); + return send(res, 200, { ok: true, items }, origin); +} + +function adminCreditAdjustments(req, res, origin) { + const user = authenticatedUser(req); + if (!user) return send(res, 401, { error: "请先登录" }, origin); + if (!isAdmin(user)) return send(res, 403, { error: "无管理权限" }, origin); + const items = statements.listCreditAdjustments.all().map(row => ({ + id: row.id, + userId: row.user_id, + userName: row.user_name, + userNickname: row.user_nickname, + delta: Number(row.delta), + reason: row.reason, + adminName: row.admin_name, + createdAt: row.created_at, + })); + return send(res, 200, { ok: true, items }, origin); +} + +async function adminAdjustUserCredit(req, res, origin, userId) { + const admin = authenticatedUser(req); + if (!admin) return send(res, 401, { error: "请先登录" }, origin); + if (!isAdmin(admin)) return send(res, 403, { error: "无管理权限" }, origin); + const target = statements.findUserById.get(userId); + if (!target) return send(res, 404, { error: "用户不存在" }, origin); + const body = await readJson(req); + const delta = Number(body.delta); + const reason = normalize(body.reason).slice(0, 200); + if (!Number.isInteger(delta) || delta === 0 || Math.abs(delta) > 100) return send(res, 400, { error: "信用分变动需为 ±1—100 的整数" }, origin); + if (!reason) return send(res, 400, { error: "请填写调整原因" }, origin); + const result = applyCreditChange(userId, delta); + if (!result.applied) return send(res, 400, { error: delta < 0 ? "该用户信用分已为 0,无法再扣减" : "信用分未变化" }, origin); + statements.insertCreditAdjustment.run(randomUUID(), userId, admin.id, result.applied, reason, Date.now()); + const stats = statements.findUserStats.get(userId); + return send(res, 200, { + ok: true, + applied: result.applied, + creditScore: Number(stats.credit_score), + inviter: result.inviterId ? { id: result.inviterId, delta: result.inviterDelta } : null, + }, origin); +} + +async function reviewStudentVerification(req, res, origin, verificationId) { + const user = authenticatedUser(req); + if (!user) return send(res, 401, { error: "请先登录" }, origin); + if (!isAdmin(user)) return send(res, 403, { error: "无审核权限" }, origin); + const record = statements.findStudentVerificationById.get(verificationId); + if (!record) return send(res, 404, { error: "认证申请不存在" }, origin); + const body = await readJson(req); + const decision = normalize(body.decision); + const note = normalize(body.note).slice(0, 200); + if (!["approved", "rejected"].includes(decision)) return send(res, 400, { error: "审核结果无效" }, origin); + if (decision === "rejected" && !note) return send(res, 400, { error: "驳回时请填写原因" }, origin); + statements.reviewStudentVerification.run(decision, note || null, Date.now(), user.id, verificationId); + return send(res, 200, { ok: true }, origin); +} + +function invitePayload(user) { + const stats = statements.findUserStats.get(user.id); + const creditScore = Number(stats?.credit_score ?? 70); + const record = statements.findInviteCodeByOwner.get(user.id); + return { + eligible: inviteEligible(creditScore), + creditScore, + code: record ? { code: record.code, maxUses: record.max_uses, usesLeft: Math.max(0, record.max_uses - record.used_count) } : null, + }; +} + +function getInviteCode(req, res, origin) { + const user = authenticatedUser(req); + if (!user) return send(res, 401, { error: "请先登录" }, origin); + return send(res, 200, { ok: true, ...invitePayload(user) }, origin); +} + +function createInviteCode(req, res, origin) { + const user = authenticatedUser(req); + if (!user) return send(res, 401, { error: "请先登录" }, origin); + if (!statements.findInviteCodeByOwner.get(user.id)) { + const stats = statements.findUserStats.get(user.id); + if (!inviteEligible(Number(stats?.credit_score ?? 70))) return send(res, 403, { error: "信用分达到 90 以上才能生成邀请码" }, origin); + let created = false; + for (let attempt = 0; attempt < 5 && !created; attempt += 1) { + try { + statements.createInviteCode.run(randomUUID(), generateInviteCode(), user.id, Date.now()); + created = true; + } catch (error) { + if (!String(error.message).includes("invite_codes.code")) throw error; + } + } + if (!created) return send(res, 500, { error: "邀请码生成失败,请稍后重试" }, origin); + } + return send(res, 200, { ok: true, ...invitePayload(user) }, origin); +} + +function registerUser(req, res, origin) { + return readJson(req).then(body => { + const name = normalize(body.name); + const nickname = normalize(body.nickname); + const studentId = normalize(body.studentId); + const school = normalize(body.school); + const email = normalizeEmail(body.email); + const code = normalize(body.code); + const inviteCode = normalize(body.inviteCode).toUpperCase(); + + if (!name || name.length > 40) return send(res, 400, { error: "请填写有效姓名" }, origin); + if (!nickname || nickname.length > 30) return send(res, 400, { error: "请填写有效昵称" }, origin); + if (!studentIdPattern.test(studentId)) return send(res, 400, { error: "学号应为 4—32 位字母、数字、下划线或短横线" }, origin); + if (!school || school.length > 80) return send(res, 400, { error: "请填写学校" }, origin); + if (!emailPattern.test(email)) return send(res, 400, { error: "请输入有效邮箱" }, origin); + if (!/^\d{6}$/.test(code)) return send(res, 400, { error: "请输入 6 位验证码" }, origin); + if (inviteCode && !/^[A-Z0-9]{6,16}$/.test(inviteCode)) return send(res, 400, { error: "邀请码格式不正确" }, origin); + if (statements.findStudent.get(studentId)) return send(res, 409, { error: "该学号已注册,一个学号只能注册一个账号" }, origin); + if (statements.findEmail.get(email)) return send(res, 409, { error: "该邮箱已注册" }, origin); + + const verification = statements.verification.get(email); + const now = Date.now(); + if (!verification || verification.consumed_at) return send(res, 400, { error: "请先获取邮箱验证码" }, origin); + if (verification.expires_at < now) return send(res, 400, { error: "验证码已过期,请重新获取" }, origin); + if (verification.attempts >= 5) return send(res, 429, { error: "验证码错误次数过多,请重新获取" }, origin); + if (!safeEqual(hashCode(email, code), Buffer.from(verification.code_hash, "hex"))) { + statements.failAttempt.run(email); + return send(res, 400, { error: "验证码不正确" }, origin); + } + + try { + db.exec("BEGIN IMMEDIATE"); + if (statements.findStudent.get(studentId)) throw Object.assign(new Error("STUDENT_EXISTS"), { code: "STUDENT_EXISTS" }); + if (statements.findEmail.get(email)) throw Object.assign(new Error("EMAIL_EXISTS"), { code: "EMAIL_EXISTS" }); + let invite = null; + if (inviteCode) { + invite = statements.findInviteCode.get(inviteCode); + if (!invite || invite.used_count >= invite.max_uses) throw Object.assign(new Error("INVALID_INVITE"), { code: "INVALID_INVITE" }); + } + const id = randomUUID(); + statements.createUser.run(id, name, nickname, studentId, school, email, now, now); + statements.createUserStats.run(id, invite ? 80 : 70, now); + statements.insertPointEntry.run(randomUUID(), id, 750, 0, "注册赠送", now); + if (invite) { + statements.insertInviteRelation.run(id, invite.owner_id, now); + statements.incrementInviteUse.run(invite.id); + statements.addEarnedPoints.run(300, 300, now, invite.owner_id); + statements.insertPointEntry.run(randomUUID(), invite.owner_id, 300, 300, "邀请奖励", now); + } + statements.consumeCode.run(now, email); + db.exec("COMMIT"); + const token = issueSession(id); + return send(res, 201, { ok: true, token, user: publicUser(statements.findEmail.get(email)) }, origin); + } catch (error) { + try { db.exec("ROLLBACK"); } catch {} + if (error.code === "INVALID_INVITE") return send(res, 400, { error: "邀请码无效或已被用完" }, origin); + if (error.code === "STUDENT_EXISTS" || String(error.message).includes("users.student_id")) return send(res, 409, { error: "该学号已注册,一个学号只能注册一个账号" }, origin); + if (error.code === "EMAIL_EXISTS" || String(error.message).includes("users.email")) return send(res, 409, { error: "该邮箱已注册" }, origin); + console.error("Registration failed:", error?.code || error?.message || "unknown error"); + return send(res, 500, { error: "注册失败,请稍后重试" }, origin); + } + }); +} + +const server = http.createServer(async (req, res) => { + const origin = req.headers.origin || ""; + if (req.method === "OPTIONS") { res.writeHead(204, headers(origin)); return res.end(); } + try { + const url = new URL(req.url || "/", `http://${req.headers.host || "localhost"}`); + if (req.method === "GET" && url.pathname === "/api/health") return send(res, 200, { ok: true }, origin); + if (req.method === "GET" && url.pathname === "/api/auth/me") return currentUser(req, res, origin); + if (req.method === "GET" && url.pathname === "/api/points/entries") return listPointEntriesHandler(req, res, origin); + if (req.method === "GET" && url.pathname === "/api/tasks") return listTasks(req, res, origin); + if (req.method === "POST" && url.pathname === "/api/tasks") return await createTask(req, res, origin); + const taskCancelMatch = url.pathname.match(/^\/api\/tasks\/([0-9a-f-]+)\/cancel$/i); + if (req.method === "POST" && taskCancelMatch) return cancelTaskHandler(req, res, origin, taskCancelMatch[1]); + const taskClaimMatch = url.pathname.match(/^\/api\/tasks\/([0-9a-f-]+)\/claim$/i); + if (req.method === "POST" && taskClaimMatch) return claimTaskHandler(req, res, origin, taskClaimMatch[1]); + const taskCompleteMatch = url.pathname.match(/^\/api\/tasks\/([0-9a-f-]+)\/complete$/i); + if (req.method === "POST" && taskCompleteMatch) return completeTaskHandler(req, res, origin, taskCompleteMatch[1]); + if (req.method === "GET" && url.pathname === "/api/my/tasks") return listMyTasksHandler(req, res, origin); + if (req.method === "POST" && url.pathname === "/api/reports") return await createReport(req, res, origin); + if (req.method === "GET" && url.pathname === "/api/admin/reports") return adminListReports(req, res, origin, url); + const reportHandleMatch = url.pathname.match(/^\/api\/admin\/reports\/([0-9a-f-]+)\/handle$/i); + if (req.method === "POST" && reportHandleMatch) return await adminHandleReport(req, res, origin, reportHandleMatch[1]); + if (req.method === "POST" && url.pathname === "/api/auth/send-code") return await sendCode(req, res, origin); + if (req.method === "POST" && url.pathname === "/api/auth/send-login-code") return await sendLoginCode(req, res, origin); + if (req.method === "POST" && url.pathname === "/api/auth/register") return await registerUser(req, res, origin); + if (req.method === "POST" && url.pathname === "/api/auth/login") return await loginUser(req, res, origin); + if (req.method === "POST" && url.pathname === "/api/auth/logout") return logoutUser(req, res, origin); + if (req.method === "GET" && url.pathname === "/api/student-verification") return getStudentVerification(req, res, origin); + if (req.method === "POST" && url.pathname === "/api/student-verification") return await submitStudentVerification(req, res, origin); + if (req.method === "GET" && url.pathname === "/api/invite-code") return getInviteCode(req, res, origin); + if (req.method === "POST" && url.pathname === "/api/invite-code") return createInviteCode(req, res, origin); + if (req.method === "GET" && url.pathname === "/api/admin/student-verifications") return listStudentVerifications(req, res, origin, url); + if (req.method === "GET" && url.pathname === "/api/admin/overview") return adminOverview(req, res, origin); + if (req.method === "GET" && url.pathname === "/api/admin/users") return adminListUsers(req, res, origin, url); + if (req.method === "GET" && url.pathname === "/api/admin/credit-adjustments") return adminCreditAdjustments(req, res, origin); + const creditMatch = url.pathname.match(/^\/api\/admin\/users\/([0-9a-f-]+)\/credit$/i); + if (req.method === "POST" && creditMatch) return await adminAdjustUserCredit(req, res, origin, creditMatch[1]); + const reviewMatch = url.pathname.match(/^\/api\/admin\/student-verifications\/([0-9a-f-]+)\/review$/i); + if (req.method === "POST" && reviewMatch) return await reviewStudentVerification(req, res, origin, reviewMatch[1]); + if ((req.method === "GET" || req.method === "HEAD") && !url.pathname.startsWith("/api/")) return serveStatic(res, url.pathname); + return send(res, 404, { error: "接口不存在" }, origin); + } catch (error) { + return send(res, error.status || 500, { error: error.status ? error.message : "服务器错误" }, origin); + } +}); + +const HOST = process.env.HOST || "0.0.0.0"; +server.listen(PORT, HOST, () => { + console.log(`LinkUp registration API listening on http://${HOST}:${PORT}`); +}); diff --git a/backend/tests/requirements.txt b/backend/tests/requirements.txt new file mode 100644 index 0000000..51e177d --- /dev/null +++ b/backend/tests/requirements.txt @@ -0,0 +1,2 @@ +-r ../requirements.txt +httpx>=0.27,<1 diff --git a/backend/tests/test_admin_analytics.py b/backend/tests/test_admin_analytics.py new file mode 100644 index 0000000..ffcfaeb --- /dev/null +++ b/backend/tests/test_admin_analytics.py @@ -0,0 +1,217 @@ +"""API regressions for the admin operations analytics endpoint.""" +import importlib +import os +import tempfile +import unittest +from datetime import datetime, time, timedelta +from pathlib import Path +from time import perf_counter +from unittest.mock import patch +from uuid import uuid4 + +import httpx +from sqlalchemy import insert +from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine + + +class AdminAnalyticsTests(unittest.IsolatedAsyncioTestCase): + @classmethod + def setUpClass(cls): + cls.temp_root = Path(tempfile.gettempdir()) / f"linkup-admin-analytics-{uuid4().hex}" + cls.temp_root.mkdir() + with patch.dict(os.environ, { + "DATABASE_DRIVER": "sqlite", "DATABASE_PATH": str(cls.temp_root / "unused.db"), + "TASK_PROOF_DIR": str(cls.temp_root / "proofs"), "NODE_ENV": "test", + }): + cls.m = importlib.import_module("backend.main") + + async def asyncSetUp(self): + self.m = type(self).m + self.engine = create_async_engine("sqlite+aiosqlite:///:memory:") + self.sessions = async_sessionmaker(self.engine, expire_on_commit=False) + self.patch_session = patch.object(self.m, "SessionLocal", self.sessions) + self.patch_session.start() + self.patch_admin = patch.object(self.m, "ADMIN_EMAILS", {"admin@example.test"}) + self.patch_admin.start() + async with self.engine.begin() as db: + await db.run_sync(self.m.metadata.create_all) + for user_id, email in [("admin", "admin@example.test"), ("viewer", "viewer@example.test")]: + await db.execute(insert(self.m.users).values( + id=user_id, name=user_id, nickname=user_id, student_id=user_id, + school="示例学校", email=email, email_verified_at=1, created_at=1, + )) + await db.execute(insert(self.m.sessions).values( + id=user_id, user_id=user_id, token_hash=self.m.hash_token(user_id), + expires_at=self.m.now_ms() + 3_600_000, created_at=1, + )) + self.client = httpx.AsyncClient( + transport=httpx.ASGITransport(app=self.m.app), base_url="http://test", + ) + + async def asyncTearDown(self): + await self.client.aclose() + self.patch_session.stop() + self.patch_admin.stop() + await self.engine.dispose() + + @staticmethod + def auth(user_id="admin"): + return {"Authorization": f"Bearer {user_id}"} if user_id else {} + + async def add_user(self, db, user_id, created_at, nickname=None): + await db.execute(insert(self.m.users).values( + id=user_id, name=user_id, nickname=nickname or user_id, student_id=user_id, + school="示例学校", email=f"{user_id}@example.test", email_verified_at=1, + created_at=created_at, + )) + + async def add_task(self, db, task_id, user_id, task_type, created_at, reward=0, claimed_at=None, status="open"): + await db.execute(insert(self.m.tasks).values( + id=task_id, user_id=user_id, type=task_type, title=task_id, detail="测试任务", + place="示例学校", school="示例学校", category="快递代取" if task_type == "errand" else "竞赛组队", + deadline=created_at + 86_400_000, reward=reward, status=status, + created_at=created_at, claimed_at=claimed_at, + )) + + async def test_daily_trends_price_buckets_claim_durations_and_user_distribution(self): + today = datetime.now().date() + noon = int(datetime.combine(today, time(hour=12)).timestamp() * 1000) + yesterday = today - timedelta(days=1) + yesterday_noon = int(datetime.combine(yesterday, time(hour=12)).timestamp() * 1000) + old = int(datetime.combine(today - timedelta(days=31), time(hour=12)).timestamp() * 1000) + async with self.sessions() as db: + await self.add_user(db, "publisher-a", noon, "发布者甲") + await self.add_user(db, "publisher-b", yesterday_noon, "发布者乙") + await self.add_user(db, "invitee", noon, "被邀请用户") + await self.add_user(db, "old-user", old, "窗口外用户") + await db.execute(insert(self.m.invite_relations).values( + invitee_id="invitee", inviter_id="admin", created_at=noon, + )) + for index, duration in enumerate([5, 30, 120, 15, 25]): + await self.add_task( + db, f"fast-{index}", "publisher-a", "errand", + noon - duration * 60_000, reward=250, claimed_at=noon, + status="done" if index % 2 else "claimed", + ) + for index in range(5): + await self.add_task( + db, f"slow-{index}", "publisher-b", "errand", + noon - 60 * 60_000, reward=350, claimed_at=noon, status="claimed", + ) + await self.add_task(db, "open-max-price", "publisher-a", "errand", noon, reward=1500) + await self.add_task(db, "partner-today", "publisher-a", "partner", noon) + await self.add_task(db, "cancelled-yesterday", "publisher-a", "errand", yesterday_noon, + reward=200, status="cancelled") + await db.commit() + + started = perf_counter() + response = await self.client.get("/api/admin/analytics?days=7", headers=self.auth()) + self.assertLess(perf_counter() - started, 0.5, "analytics endpoint exceeded the 500ms target") + self.assertEqual(response.status_code, 200, response.text) + body = response.json() + self.assertEqual(body["registrations"]["today"], 2) + self.assertEqual(body["registrations"]["yesterday"], 1) + self.assertEqual(body["registrations"]["todayViaInvite"], 1) + self.assertEqual(body["registrations"]["inviteTotal"], 1) + self.assertEqual(body["registrations"]["inviteRatio"], 0.1667) + self.assertEqual(len(body["registrations"]["byDay"]), 7) + today_registrations = next(item for item in body["registrations"]["byDay"] if item["date"] == today.isoformat()) + self.assertEqual((today_registrations["count"], today_registrations["viaInvite"]), (2, 1)) + yesterday_tasks = next(item for item in body["tasks"]["byDay"] if item["date"] == yesterday.isoformat()) + self.assertEqual((yesterday_tasks["total"], yesterday_tasks["errand"], yesterday_tasks["partner"]), (1, 1, 0)) + self.assertEqual(body["tasks"]["today"], {"date": today.isoformat(), "total": 12, "errand": 11, "partner": 1}) + self.assertEqual(body["tasks"]["avgClaimMinutes"], 49.5) + self.assertEqual(body["tasks"]["medianClaimMinutes"], 60) + first_bucket = next(item for item in body["tasks"]["priceBuckets"] if item["label"] == "200—299") + self.assertEqual((first_bucket["published"], first_bucket["claimed"]), (6, 5)) + self.assertEqual(first_bucket["claimRate"], 0.8333) + self.assertEqual(first_bucket["avgClaimMinutes"], 39) + self.assertFalse(first_bucket["insufficient"]) + max_bucket = next(item for item in body["tasks"]["priceBuckets"] if item["label"] == "1400—1500") + self.assertEqual(max_bucket["published"], 1) + self.assertTrue(max_bucket["insufficient"]) + self.assertEqual(body["tasks"]["bestBucket"]["label"], "200—299") + self.assertEqual(body["perUser"]["avgPublished"], 6.5) + self.assertEqual(body["perUser"]["publisherCount"], 2) + distribution = {item["label"]: item["userCount"] for item in body["perUser"]["distribution"]} + self.assertEqual(distribution["5"], 1) + self.assertEqual(distribution["8"], 1) + self.assertEqual(distribution["10"], 0) + self.assertEqual(distribution["10+"], 0) + self.assertEqual(body["perUser"]["topPublishers"][0], {"nickname": "发布者甲", "count": 8}) + self.assertNotIn("id", body["perUser"]["topPublishers"][0]) + + async def test_days_bounds_and_authorization(self): + self.assertEqual((await self.client.get("/api/admin/analytics")).status_code, 401) + self.assertEqual((await self.client.get("/api/admin/analytics", headers=self.auth("viewer"))).status_code, 403) + one_day = await self.client.get("/api/admin/analytics?days=1", headers=self.auth()) + thirty_days = await self.client.get("/api/admin/analytics?days=30", headers=self.auth()) + self.assertEqual((one_day.status_code, len(one_day.json()["tasks"]["byDay"])), (200, 1)) + self.assertEqual((thirty_days.status_code, len(thirty_days.json()["tasks"]["byDay"])), (200, 30)) + self.assertEqual((await self.client.get("/api/admin/analytics?days=0", headers=self.auth())).status_code, 422) + self.assertEqual((await self.client.get("/api/admin/analytics?days=31", headers=self.auth())).status_code, 422) + + async def test_local_midnight_events_are_bucketed_on_their_calendar_day(self): + today = datetime.now().date() + yesterday = today - timedelta(days=1) + yesterday_2359 = int(datetime.combine(yesterday, time(hour=23, minute=59)).timestamp() * 1000) + today_0001 = int(datetime.combine(today, time(hour=0, minute=1)).timestamp() * 1000) + async with self.sessions() as db: + await self.add_user(db, "edge-yesterday", yesterday_2359) + await self.add_user(db, "edge-today", today_0001) + await db.execute(insert(self.m.invite_relations).values( + invitee_id="edge-yesterday", inviter_id="admin", created_at=yesterday_2359, + )) + await self.add_task(db, "edge-task-yesterday", "edge-yesterday", "errand", + yesterday_2359, reward=200) + await self.add_task(db, "edge-task-today", "edge-today", "partner", today_0001) + await db.commit() + + response = await self.client.get("/api/admin/analytics?days=2", headers=self.auth()) + self.assertEqual(response.status_code, 200, response.text) + body = response.json() + self.assertEqual(body["registrations"]["today"], 1) + self.assertEqual(body["registrations"]["yesterday"], 1) + self.assertEqual(body["registrations"]["todayViaInvite"], 0) + yesterday_registration = next(item for item in body["registrations"]["byDay"] if item["date"] == yesterday.isoformat()) + self.assertEqual((yesterday_registration["count"], yesterday_registration["viaInvite"]), (1, 1)) + yesterday_task = next(item for item in body["tasks"]["byDay"] if item["date"] == yesterday.isoformat()) + today_task = next(item for item in body["tasks"]["byDay"] if item["date"] == today.isoformat()) + self.assertEqual((yesterday_task["errand"], yesterday_task["partner"]), (1, 0)) + self.assertEqual((today_task["errand"], today_task["partner"]), (0, 1)) + + async def test_ten_or_more_publications_share_the_top_distribution_bucket(self): + old = int(datetime.combine(datetime.now().date() - timedelta(days=31), time(hour=12)).timestamp() * 1000) + async with self.sessions() as db: + await self.add_user(db, "heavy-publisher", old, "高频发布者") + await self.add_user(db, "exact-ten-publisher", old, "十次发布者") + for index in range(11): + await self.add_task(db, f"heavy-task-{index}", "heavy-publisher", "partner", old, + status="cancelled") + for index in range(10): + await self.add_task(db, f"exact-ten-task-{index}", "exact-ten-publisher", "partner", old, + status="cancelled") + await db.commit() + response = await self.client.get("/api/admin/analytics?days=1", headers=self.auth()) + self.assertEqual(response.status_code, 200, response.text) + body = response.json() + ten_plus = next(item for item in body["perUser"]["distribution"] if item["label"] == "10+") + exactly_ten = next(item for item in body["perUser"]["distribution"] if item["label"] == "10") + self.assertEqual(ten_plus["userCount"], 1) + self.assertEqual(exactly_ten["userCount"], 1) + self.assertEqual(body["perUser"]["avgPublished"], 10.5) + self.assertEqual(body["perUser"]["topPublishers"][0], {"nickname": "高频发布者", "count": 11}) + + async def test_empty_analytics_returns_zeroes(self): + response = await self.client.get("/api/admin/analytics?days=1", headers=self.auth()) + self.assertEqual(response.status_code, 200, response.text) + body = response.json() + self.assertEqual((body["registrations"]["today"], body["registrations"]["yesterday"]), (0, 0)) + self.assertEqual(body["registrations"]["inviteRatio"], 0) + self.assertEqual(body["registrations"]["todayViaInvite"], 0) + self.assertEqual(body["tasks"]["today"]["total"], 0) + self.assertEqual((body["tasks"]["avgClaimMinutes"], body["tasks"]["medianClaimMinutes"]), (0, 0)) + self.assertIsNone(body["tasks"]["bestBucket"]) + self.assertEqual(len(body["tasks"]["priceBuckets"]), 13) + self.assertEqual(body["perUser"]["avgPublished"], 0) + self.assertEqual(body["perUser"]["topPublishers"], []) diff --git a/backend/tests/test_official_tasks.py b/backend/tests/test_official_tasks.py new file mode 100644 index 0000000..7a79d80 --- /dev/null +++ b/backend/tests/test_official_tasks.py @@ -0,0 +1,222 @@ +"""Regressions for the standalone official-task reward flow.""" +import asyncio +import importlib +import os +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch +from uuid import uuid4 + +import httpx +from sqlalchemy import func, insert, select +from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine + + +class OfficialTaskTests(unittest.IsolatedAsyncioTestCase): + @classmethod + def setUpClass(cls): + cls.temp_root = Path(tempfile.gettempdir()) / f"linkup-official-tasks-{uuid4().hex}" + cls.temp_root.mkdir() + with patch.dict(os.environ, { + "DATABASE_DRIVER": "sqlite", "DATABASE_PATH": str(cls.temp_root / "unused.db"), + "TASK_PROOF_DIR": str(cls.temp_root / "proofs"), "NODE_ENV": "test", + }): + cls.m = importlib.import_module("backend.main") + + async def asyncSetUp(self): + self.m = type(self).m + self.engine = create_async_engine("sqlite+aiosqlite:///:memory:") + self.sessions = async_sessionmaker(self.engine, expire_on_commit=False) + self.patch_session = patch.object(self.m, "SessionLocal", self.sessions) + self.patch_session.start() + self.patch_admin = patch.object(self.m, "ADMIN_EMAILS", {"admin@example.test"}) + self.patch_admin.start() + async with self.engine.begin() as db: + await db.run_sync(self.m.metadata.create_all) + now = self.m.now_ms() + for user_id, email in [ + ("admin", "admin@example.test"), ("alpha", "alpha@example.test"), + ("beta", "beta@example.test"), ("viewer", "viewer@example.test"), + ]: + await db.execute(insert(self.m.users).values( + id=user_id, name=user_id, nickname=user_id, student_id=user_id, + school="示例学校", email=email, email_verified_at=now, created_at=now, + )) + await db.execute(insert(self.m.user_stats).values( + user_id=user_id, points_balance=1000, withdrawable_points=7, + credit_score=70, breach_count=0, commitments_count=0, + completed_tasks=0, current_streak=0, updated_at=now, + )) + await db.execute(insert(self.m.sessions).values( + id=user_id, user_id=user_id, token_hash=self.m.hash_token(user_id), + expires_at=now + 3_600_000, created_at=now, + )) + self.client = httpx.AsyncClient( + transport=httpx.ASGITransport(app=self.m.app), base_url="http://test", + ) + + async def asyncTearDown(self): + await self.client.aclose() + self.patch_session.stop() + self.patch_admin.stop() + await self.engine.dispose() + + @staticmethod + def auth(user_id="admin"): + return {"Authorization": f"Bearer {user_id}"} if user_id else {} + + async def create_task(self, **payload): + data = {"title": "官方问卷", "detail": "填写活动反馈", "reward": 25, + "perAccountLimit": 2, "totalQuota": 0, "deadline": None} + data.update(payload) + response = await self.client.post("/api/admin/official-tasks", json=data, headers=self.auth()) + self.assertEqual(response.status_code, 201, response.text) + return response.json()["task"]["id"] + + async def test_permissions_limits_ledger_balance_and_square_isolation(self): + self.assertEqual((await self.client.post("/api/admin/official-tasks", json={}, headers=self.auth("viewer"))).status_code, 403) + self.assertEqual((await self.client.post("/api/admin/official-tasks", json={})).status_code, 401) + self.assertEqual((await self.client.get("/api/admin/official-tasks", headers=self.auth("viewer"))).status_code, 403) + before_square = await self.client.get("/api/tasks", headers=self.auth("alpha")) + self.assertEqual(before_square.status_code, 200, before_square.text) + + task_id = await self.create_task(title="", reward=25) + listed = await self.client.get("/api/official-tasks", headers=self.auth("alpha")) + self.assertEqual(listed.status_code, 200, listed.text) + task = next(item for item in listed.json()["items"] if item["id"] == task_id) + self.assertEqual(task["title"], "") + self.assertEqual((task["myClaimCount"], task["remainingClaims"]), (0, 2)) + shell = await self.client.get("/") + self.assertEqual(shell.status_code, 200) + self.assertIn('id="officialTasksDialog"', shell.text) + self.assertIn('data-action="official-tasks"', shell.text) + + first = await self.client.post(f"/api/official-tasks/{task_id}/claim", json={}, headers=self.auth("alpha")) + second = await self.client.post(f"/api/official-tasks/{task_id}/claim", json={}, headers=self.auth("alpha")) + third = await self.client.post(f"/api/official-tasks/{task_id}/claim", json={}, headers=self.auth("alpha")) + self.assertEqual((first.status_code, second.status_code, third.status_code), (200, 200, 409)) + self.assertEqual(third.json()["error"], "您已达到领取上限") + self.assertEqual((await self.client.post(f"/api/official-tasks/{task_id}/claim", json={})).status_code, 401) + other = await self.client.post(f"/api/official-tasks/{task_id}/claim", json={}, headers=self.auth("beta")) + self.assertEqual(other.status_code, 200, other.text) + admin_list = await self.client.get("/api/admin/official-tasks", headers=self.auth()) + admin_task = next(item for item in admin_list.json()["items"] if item["id"] == task_id) + self.assertEqual((admin_task["claimCount"], admin_task["claimedUsers"]), (3, 2)) + alpha_state = await self.client.get("/api/official-tasks", headers=self.auth("alpha")) + alpha_task = next(item for item in alpha_state.json()["items"] if item["id"] == task_id) + self.assertEqual((alpha_task["myClaimCount"], alpha_task["remainingClaims"]), (2, 0)) + + after_square = await self.client.get("/api/tasks", headers=self.auth("alpha")) + self.assertEqual(after_square.json(), before_square.json(), "官方任务不得进入或改变任务广场响应") + async with self.sessions() as db: + balance = await db.scalar(select(self.m.user_stats.c.points_balance).where(self.m.user_stats.c.user_id == "alpha")) + beta_balance = await db.scalar(select(self.m.user_stats.c.points_balance).where(self.m.user_stats.c.user_id == "beta")) + withdrawable = await db.scalar(select(self.m.user_stats.c.withdrawable_points).where(self.m.user_stats.c.user_id == "alpha")) + entries = (await db.execute(select(self.m.point_entries).where(self.m.point_entries.c.user_id == "alpha"))).mappings().all() + claims = (await db.execute(select(self.m.official_task_claims).where(self.m.official_task_claims.c.user_id == "alpha"))).mappings().all() + self.assertEqual((balance, beta_balance, withdrawable), (1050, 1025, 7)) + self.assertEqual(len(entries), 2) + self.assertTrue(all((row["delta"], row["withdrawable_delta"], row["reason"]) == + (25, 0, "官方任务 · ") for row in entries)) + self.assertEqual([(row["reward"], row["task_id"]) for row in claims], [(25, task_id), (25, task_id)]) + self.assertIn("escapeHtml(task.title)", self._app_source()) + self.assertIn("escapeHtml(task.detail", self._app_source()) + admin_source = (Path(__file__).resolve().parents[2] / "dist" / "admin.js").read_text(encoding="utf-8") + self.assertIn("escapeHtml(item.title)", admin_source) + self.assertIn("escapeHtml(item.detail", admin_source) + + async def test_total_quota_close_deadline_and_claim_restriction(self): + total_task = await self.create_task(title="限总量", perAccountLimit=3, totalQuota=1) + self.assertEqual((await self.client.post(f"/api/official-tasks/{total_task}/claim", json={}, headers=self.auth("alpha"))).status_code, 200) + full_listing = await self.client.get("/api/official-tasks", headers=self.auth("beta")) + self.assertNotIn(total_task, [item["id"] for item in full_listing.json()["items"]]) + full = await self.client.post(f"/api/official-tasks/{total_task}/claim", json={}, headers=self.auth("beta")) + self.assertEqual((full.status_code, full.json()["error"]), (409, "名额已领完")) + + close_task = await self.create_task(title="下线任务") + closed = await self.client.post(f"/api/admin/official-tasks/{close_task}/close", json={}, headers=self.auth()) + self.assertEqual(closed.status_code, 200, closed.text) + self.assertNotIn(close_task, [item["id"] for item in (await self.client.get("/api/official-tasks")).json()["items"]]) + late_task = await self.create_task(title="已过期", deadline=self.m.now_ms() - 1) + late_claim = await self.client.post(f"/api/official-tasks/{late_task}/claim", json={}, headers=self.auth("alpha")) + self.assertEqual((late_claim.status_code, late_claim.json()["error"]), (409, "官方任务已下线")) + + restricted_task = await self.create_task(title="受限制账号不可领") + async with self.sessions() as db: + await db.execute(insert(self.m.account_sanctions).values( + id="claim-restriction", user_id="alpha", admin_id="admin", action="restrict", + scope="claim", category="其他违规", reason="test", created_at=self.m.now_ms(), + expires_at=self.m.now_ms() + 3_600_000, + )) + await db.commit() + rejected = await self.client.post(f"/api/official-tasks/{restricted_task}/claim", json={}, headers=self.auth("alpha")) + self.assertEqual(rejected.status_code, 403, rejected.text) + self.assertIn("已被限制", rejected.json()["error"]) + + banned_task = await self.create_task(title="封禁账号不可领") + async with self.sessions() as db: + await db.execute(insert(self.m.account_sanctions).values( + id="full-ban", user_id="beta", admin_id="admin", action="ban", + scope="all", category="其他违规", reason="test", created_at=self.m.now_ms(), + expires_at=self.m.now_ms() + 3_600_000, + )) + await db.commit() + banned = await self.client.post(f"/api/official-tasks/{banned_task}/claim", json={}, headers=self.auth("beta")) + self.assertEqual((banned.status_code, banned.json()["error"]), (403, "账号当前不可领取官方任务")) + + async def test_concurrent_claims_for_last_per_account_slot_have_one_winner(self): + database = self.temp_root / f"race-{uuid4().hex}.db" + engine = create_async_engine("sqlite+aiosqlite:///" + str(database), connect_args={"timeout": 10}) + sessions = async_sessionmaker(engine, expire_on_commit=False) + now = self.m.now_ms() + try: + async with engine.begin() as db: + await db.run_sync(self.m.metadata.create_all) + for user_id in ("admin", "alpha"): + await db.execute(insert(self.m.users).values( + id=user_id, name=user_id, nickname=user_id, student_id=user_id, + school="示例学校", email=f"{user_id}@example.test", email_verified_at=now, created_at=now, + )) + await db.execute(insert(self.m.user_stats).values( + user_id=user_id, points_balance=1000, 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(self.m.sessions).values( + id=user_id, user_id=user_id, token_hash=self.m.hash_token(user_id), + expires_at=now + 3_600_000, created_at=now, + )) + await db.execute(insert(self.m.official_tasks).values( + id="race-official", admin_id="admin", title="并发任务", detail="", reward=11, + per_account_limit=1, total_quota=0, status="active", deadline=None, created_at=now, + )) + with patch.object(self.m, "SessionLocal", sessions): + responses = await asyncio.gather(*[ + self.client.post("/api/official-tasks/race-official/claim", json={}, headers=self.auth("alpha")) + for _ in range(2) + ]) + self.assertEqual(sorted(response.status_code for response in responses), [200, 409], + [response.text for response in responses]) + async with sessions() as db: + claims = await db.scalar(select(self.m.official_task_claims.c.id).where( + self.m.official_task_claims.c.task_id == "race-official", + )) + balance = await db.scalar(select(self.m.user_stats.c.points_balance).where( + self.m.user_stats.c.user_id == "alpha", + )) + ledger_count = await db.scalar(select(func.count()).select_from(self.m.point_entries).where( + self.m.point_entries.c.user_id == "alpha", + )) + self.assertIsNotNone(claims) + self.assertEqual((balance, ledger_count), (1011, 1)) + finally: + await engine.dispose() + + @staticmethod + def _app_source(): + return (Path(__file__).resolve().parents[2] / "dist" / "app.js").read_text(encoding="utf-8") + + +if __name__ == "__main__": + unittest.main() diff --git a/backend/tests/test_task_access.py b/backend/tests/test_task_access.py new file mode 100644 index 0000000..9b26cd1 --- /dev/null +++ b/backend/tests/test_task_access.py @@ -0,0 +1,662 @@ +"""Run with: python -m unittest discover -s backend/tests -v + +These API regressions use an isolated in-memory database and never start the +production lifespan or connect to the configured application database. +""" +import asyncio +import importlib +import os +import shutil +import tempfile +import unittest +from datetime import datetime, timedelta +from pathlib import Path +from unittest.mock import AsyncMock, patch +from uuid import uuid4 + +import httpx +from sqlalchemy import event, func, insert, inspect, select, text, update +from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine + + +class TaskAccessTests(unittest.IsolatedAsyncioTestCase): + @classmethod + def setUpClass(cls): + # Python 3.13 creates TemporaryDirectory with a Windows ACL that a + # restricted test runner cannot enter; a regular unique directory works. + cls.directory = Path(tempfile.gettempdir()) / f"linkup-task-access-{uuid4().hex}" + cls.directory.mkdir() + with patch.dict(os.environ, { + "DATABASE_DRIVER": "sqlite", "DATABASE_PATH": str(cls.directory / "unused.db"), + "TASK_PROOF_DIR": str(cls.directory / "proofs"), "NODE_ENV": "test", + }): + cls.m = importlib.import_module("backend.main") + + @classmethod + def tearDownClass(cls): + if cls.directory.resolve().parent != Path(tempfile.gettempdir()).resolve(): + raise RuntimeError("Refusing to remove a test directory outside the temp root") + shutil.rmtree(cls.directory) + + async def asyncSetUp(self): + m = self.m + self.engine = create_async_engine("sqlite+aiosqlite:///:memory:") + self.sessions = async_sessionmaker(self.engine, expire_on_commit=False) + self.patch_session = patch.object(m, "SessionLocal", self.sessions) + self.patch_session.start() + self.patch_admin = patch.object(m, "ADMIN_EMAILS", {"admin@example.test"}) + self.patch_admin.start() + self.locks = [] + event.listen(self.engine.sync_engine, "before_execute", self.record_lock) + async with self.engine.begin() as db: + await db.run_sync(m.metadata.create_all) + for uid, school in [("viewer", "山东管理学院"), ("local", "山东管理学院"), + ("remote", "中国石油大学(华东)"), ("private", "注册学校"), + ("admin", "山东管理学院")]: + await db.execute(insert(m.users).values( + id=uid, name=uid, nickname=uid, student_id=uid, school=school, + email=uid + "@example.test", email_verified_at=1, created_at=1, + )) + await db.execute(insert(m.user_stats).values(user_id=uid, points_balance=1000, updated_at=1)) + await db.execute(insert(m.sessions).values( + id=uid, user_id=uid, token_hash=m.hash_token(uid), + expires_at=m.now_ms() + 3600000, created_at=1, + )) + for tid, owner, school, status, claimer in [ + ("local-open", "local", "山东管理学院", "open", None), + ("remote-open", "remote", "中国石油大学(华东)", "open", None), + ("registered-open", "remote", "注册学校", "open", None), + ("own-open", "viewer", "山东管理学院", "open", None), + ("related", "local", "山东管理学院", "claimed", "viewer"), + ("public-claimed", "local", "山东管理学院", "claimed", "remote"), + ("own-claimed", "viewer", "山东管理学院", "claimed", "remote"), + ("private-done", "private", "注册学校", "done", "local"), + ("private-cancelled", "private", "注册学校", "cancelled", None), + ]: + await db.execute(insert(m.tasks).values( + id=tid, user_id=owner, school=school, type="errand", category="快递代取", title=tid, + detail="送达宿舍", place=school, status=status, claimer_id=claimer, + reward=300, created_at=1, contact="13000000000", pickup_codes='["123"]', + )) + self.client = httpx.AsyncClient(transport=httpx.ASGITransport(app=m.app), base_url="http://test") + + def record_lock(self, connection, clause, multiparams, params, options): + if getattr(clause, "_for_update_arg", None) is not None: + self.locks.append(clause) + + async def asyncTearDown(self): + await self.client.aclose() + self.patch_session.stop() + self.patch_admin.stop() + await self.engine.dispose() + + def auth(self, uid="viewer"): + return {"Authorization": "Bearer " + uid} if uid else {} + + async def ids(self, school=None, uid="viewer"): + response = await self.client.get("/api/tasks", params={} if school is None else {"school": school}, headers=self.auth(uid)) + self.assertEqual(response.status_code, 200, response.text) + return {item["id"] for item in response.json()["items"]} + + async def test_default_behavior_and_explicit_school_filters(self): + local = {"local-open", "related", "public-claimed", "own-claimed"} + self.assertEqual(await self.ids(), local) + self.assertEqual(await self.ids("山东管理学院"), local) + self.assertEqual(await self.ids("中国石油大学(华东)"), {"remote-open"}) + self.assertEqual(await self.ids("注册学校"), {"registered-open", "private-done"}) + self.assertEqual(await self.ids("all"), local | {"remote-open", "registered-open", "private-done"}) + + async def test_guest_admin_and_validation(self): + all_visible = {"local-open", "remote-open", "registered-open", "own-open", + "related", "public-claimed", "own-claimed", "private-done"} + for uid in (None, "admin"): + with self.subTest(uid=uid): + self.assertEqual(await self.ids(uid=uid), all_visible) + self.assertEqual(await self.ids("all", uid), all_visible) + self.assertEqual(await self.ids("中国石油大学(华东)", uid), {"remote-open"}) + for uid in (None, "viewer", "admin"): + for value in ("不存在学校", "", " all "): + response = await self.client.get("/api/tasks", params={"school": value}, headers=self.auth(uid)) + self.assertEqual(response.status_code, 400) + self.assertIsInstance(response.json()["error"], str) + response = await self.client.get("/api/schools", headers=self.auth()) + self.assertEqual(response.json()["preferred"], "山东管理学院") + self.assertIn("注册学校", response.json()["items"]) + self.assertTrue(set(self.m.SCHOOL_OPTIONS).issubset(response.json()["items"])) + + async def test_cross_school_profile_requires_public_task(self): + for uid, viewer, status in [("remote", "viewer", 200), ("private", "viewer", 404), + ("local", "viewer", 200), ("private", "admin", 200), + ("private", None, 200)]: + with self.subTest(uid=uid, viewer=viewer): + response = await self.client.get(f"/api/users/{uid}/profile", headers=self.auth(viewer)) + self.assertEqual(response.status_code, status) + + async def test_public_statuses_and_private_fields(self): + response = await self.client.get("/api/tasks", headers=self.auth()) + items = {item["id"]: item for item in response.json()["items"]} + self.assertEqual(items["public-claimed"]["status"], "claimed") + self.assertEqual(items["own-claimed"]["status"], "claimed") + self.assertNotIn("phone", items["public-claimed"]) + self.assertNotIn("pickupCodes", items["public-claimed"]) + self.assertEqual(items["related"]["phone"], "13000000000") + self.assertEqual(items["related"]["pickupCodes"], ["123"]) + self.assertEqual(items["own-claimed"]["phone"], "13000000000") + self.assertNotIn("pickupCodes", items["own-claimed"]) + done = (await self.client.get("/api/tasks", params={"school": "注册学校"}, + headers=self.auth())).json()["items"] + completed = next(item for item in done if item["id"] == "private-done") + self.assertEqual(completed["status"], "done") + self.assertNotIn("phone", completed) + self.assertNotIn("pickupCodes", completed) + owner_items = (await self.client.get("/api/tasks", params={"school": "注册学校"}, + headers=self.auth("private"))).json()["items"] + owner_completed = next(item for item in owner_items if item["id"] == "private-done") + self.assertEqual(owner_completed["phone"], "13000000000") + self.assertNotIn("pickupCodes", owner_completed) + claimer_items = (await self.client.get("/api/tasks", params={"school": "注册学校"}, + headers=self.auth("local"))).json()["items"] + claimer_completed = next(item for item in claimer_items if item["id"] == "private-done") + self.assertEqual(claimer_completed["phone"], "13000000000") + self.assertEqual(claimer_completed["pickupCodes"], ["123"]) + for task_id in ("related", "private-done"): + response = await self.client.post(f"/api/tasks/{task_id}/claim", headers=self.auth()) + self.assertEqual(response.status_code, 409, response.text) + async with self.sessions() as db: + await db.execute(insert(self.m.tasks).values( + id="claimed-partner", user_id="local", school="山东管理学院", type="partner", + title="组队", detail="自习", place="山东管理学院", status="claimed", + reward=0, created_at=1, + )) + await db.commit() + response = await self.client.post("/api/tasks/claimed-partner/claim", headers=self.auth()) + self.assertEqual(response.status_code, 409, response.text) + + async def test_completed_tasks_are_sql_limited_and_ordered_by_completion(self): + m = self.m + async with self.sessions() as db: + for index in range(12): + await db.execute(insert(m.tasks).values( + id=f"done-{index}", user_id="local", school="山东管理学院", + type="errand", category="快递代取", title=f"done-{index}", detail="送达宿舍", + place="山东管理学院", status="done", reward=300, + created_at=1000-index, completed_at=100+index, + )) + await db.commit() + response = await self.client.get("/api/tasks", headers=self.auth()) + self.assertEqual(response.status_code, 200, response.text) + completed = [item for item in response.json()["items"] if item["status"] == "done"] + self.assertEqual([item["id"] for item in completed], [f"done-{index}" for index in range(11, 1, -1)]) + async with self.sessions() as db: + await db.execute(update(m.tasks).where(m.tasks.c.id == "done-0").values(completed_at=200)) + await db.commit() + response = await self.client.get("/api/tasks", headers=self.auth()) + completed = [item["id"] for item in response.json()["items"] if item["status"] == "done"] + self.assertEqual(completed[0], "done-0") + self.assertNotIn("done-2", completed) + + async def test_legacy_done_rows_receive_completed_at_on_startup(self): + m = self.m + legacy_engine = create_async_engine("sqlite+aiosqlite:///" + str(self.directory / "legacy.db")) + legacy_sessions = async_sessionmaker(legacy_engine, expire_on_commit=False) + try: + async with legacy_engine.begin() as db: + await db.execute(text( + "CREATE TABLE tasks (id VARCHAR(64) PRIMARY KEY, status VARCHAR(16) NOT NULL, " + "created_at BIGINT NOT NULL, place VARCHAR(240), school VARCHAR(160), " + "claimer_id VARCHAR(64))" + )) + await db.execute(text( + "INSERT INTO tasks (id, status, created_at, place, school) " + "VALUES ('old-done', 'done', 1234, '山东管理学院', '山东管理学院')" + )) + with patch.object(m, "engine", legacy_engine), patch.object(m, "SessionLocal", legacy_sessions): + await m._init_database_unlocked() + await m._init_database_unlocked() # 迁移可重复启动。 + async with legacy_engine.connect() as db: + columns = await db.run_sync( + lambda connection: {column["name"] for column in inspect(connection).get_columns("tasks")} + ) + completed_at = await db.scalar(text("SELECT completed_at FROM tasks WHERE id='old-done'")) + self.assertIn("completed_at", columns) + self.assertEqual(completed_at, 1234) + finally: + await legacy_engine.dispose() + + async def verification(self, status, expired=False): + m = self.m + async with self.sessions() as db: + await db.execute(m.student_verifications.delete()) + if status: + await db.execute(insert(m.student_verifications).values( + id="verification", user_id="viewer", status=status, + report_expires_on=(datetime.now() - timedelta(days=int(expired))).strftime("%Y-%m-%d"), + online_code_cipher="test", online_code_iv="test", online_code_tag="test", + online_code_last4="1234", submitted_at=1, + )) + await db.commit() + + async def test_verification_summary_levels_and_expiry(self): + for status, expired, expected_status, level in [ + (None, False, "unsubmitted", 1), + ("pending", False, "pending", 1), + ("rejected", False, "rejected", 1), + ("approved", False, "approved", 2), + ("approved", True, "expired", 1), + ]: + with self.subTest(status=status, expired=expired): + await self.verification(status, expired) + response = await self.client.get("/api/student-verification", headers=self.auth()) + self.assertEqual(response.status_code, 200, response.text) + summary = response.json()["verification"] + self.assertEqual(summary["status"], expected_status) + self.assertEqual(summary["level"], level) + self.assertIs(summary["faceVerified"], False) + + async def test_unverified_claim_is_rejected_before_any_row_lock(self): + for status, expired, expected in [(None, False, "unsubmitted"), ("pending", False, "pending"), + ("rejected", False, "rejected"), ("approved", True, "expired")]: + with self.subTest(status=status, expired=expired): + await self.verification(status, expired) + self.locks.clear() + response = await self.client.post("/api/tasks/local-open/claim", headers=self.auth()) + self.assertEqual(response.status_code, 403) + self.assertEqual(response.json()["code"], "VERIFICATION_REQUIRED") + self.assertEqual(response.json()["verification"]["status"], expected) + self.assertEqual(response.json()["verification"]["level"], 1) + self.assertIs(response.json()["verification"]["faceVerified"], False) + self.assertIn("L2 及以上认证", response.json()["error"]) + self.assertEqual(len(self.locks), 0) + async with self.sessions() as db: + self.assertEqual(await db.scalar(select(self.m.tasks.c.status).where(self.m.tasks.c.id == "local-open")), "open") + self.assertEqual(await db.scalar(select(self.m.user_stats.c.points_balance).where(self.m.user_stats.c.user_id == "local")), 1000) + + async def test_approved_claim_and_distinct_login_conflict_errors(self): + response = await self.client.post("/api/tasks/local-open/claim") + self.assertEqual(response.status_code, 401) + self.assertEqual(response.json()["error"], "请先登录") + await self.verification("approved") # Reports expiring today remain valid. + response = await self.client.post("/api/tasks/local-open/claim", headers=self.auth()) + self.assertEqual(response.status_code, 200, response.text) + self.assertEqual(response.json()["pickupCodes"], ["123"]) + response = await self.client.post("/api/tasks/local-open/claim", headers=self.auth()) + self.assertEqual(response.status_code, 409) + self.assertNotIn("code", response.json()) + async with self.sessions() as db: + self.assertEqual(await db.scalar(select(self.m.user_stats.c.points_balance).where(self.m.user_stats.c.user_id == "local")), 700) + entries = (await db.execute(select(self.m.point_entries).where( + self.m.point_entries.c.user_id == "local", + ))).mappings().all() + self.assertEqual(len(entries), 1) + self.assertEqual((entries[0]["delta"], entries[0]["withdrawable_delta"], entries[0]["reason"]), + (-300, 0, "任务被接单 · local-open")) + + async def test_claim_rolls_back_when_conditional_publisher_debit_fails(self): + await self.verification("approved") + async with self.sessions() as db: + await db.execute(update(self.m.user_stats).where(self.m.user_stats.c.user_id == "local").values( + points_balance=299, + )) + await db.commit() + response = await self.client.post("/api/tasks/local-open/claim", headers=self.auth()) + self.assertEqual(response.status_code, 409) + self.assertEqual(response.json()["error"], "发布者积分余额不足,任务已暂不可接") + async with self.sessions() as db: + status = await db.scalar(select(self.m.tasks.c.status).where(self.m.tasks.c.id == "local-open")) + balance = await db.scalar(select(self.m.user_stats.c.points_balance).where(self.m.user_stats.c.user_id == "local")) + entries = await db.scalar(select(func.count()).select_from(self.m.point_entries).where( + self.m.point_entries.c.user_id == "local", + )) + self.assertEqual((status, balance, entries), ("open", 299, 0)) + + async def test_cancellation_refunds_only_claimed_tasks_and_records_money_movement(self): + m = self.m + await self.verification("approved") + # Posting uses the current model: no reserve is held until a task is claimed. + open_cancel = await self.client.post("/api/tasks/remote-open/cancel", headers=self.auth("remote")) + self.assertEqual(open_cancel.status_code, 200, open_cancel.text) + self.assertFalse(open_cancel.json()["refunded"]) + async with self.sessions() as db: + remote_balance = await db.scalar(select(m.user_stats.c.points_balance).where(m.user_stats.c.user_id == "remote")) + remote_entries = await db.scalar(select(func.count()).select_from(m.point_entries).where( + m.point_entries.c.user_id == "remote", + )) + self.assertEqual(remote_balance, 1000) + self.assertEqual(remote_entries, 0) + + claim = await self.client.post("/api/tasks/local-open/claim", headers=self.auth()) + self.assertEqual(claim.status_code, 200, claim.text) + # This test covers refund accounting; the separate cooldown regression + # verifies that a newly accepted task cannot be cancelled immediately. + async with self.sessions() as db: + await db.execute(update(m.tasks).where(m.tasks.c.id == "local-open").values( + claimed_at=m.now_ms() - m.RIDER_CANCELLATION_COOLDOWN_MS - 1, + )) + await db.commit() + cancelled = await self.client.post("/api/tasks/local-open/cancel", headers=self.auth()) + self.assertEqual(cancelled.status_code, 200, cancelled.text) + self.assertTrue(cancelled.json()["refunded"]) + async with self.sessions() as db: + local_balance = await db.scalar(select(m.user_stats.c.points_balance).where(m.user_stats.c.user_id == "local")) + entries = (await db.execute(select(m.point_entries).where( + m.point_entries.c.user_id == "local", + ).order_by(m.point_entries.c.created_at))).mappings().all() + notice_users = set((await db.execute(select(m.notifications.c.user_id).where( + m.notifications.c.kind == "task_cancelled", + m.notifications.c.link == "task:local-open", + ))).scalars().all()) + self.assertEqual(local_balance, 1000) + self.assertEqual([(row["delta"], row["reason"]) for row in entries], [ + (-300, "任务被接单 · local-open"), (300, "任务取消退款 · local-open"), + ]) + self.assertEqual(notice_users, {"local", "viewer"}) + + async def test_parallel_sqlite_claims_have_one_winner_and_one_ledger_entry(self): + m = self.m + database = self.directory / "parallel-claims.db" + database.unlink(missing_ok=True) + engine = create_async_engine("sqlite+aiosqlite:///" + str(database), connect_args={"timeout": 10}) + sessions = async_sessionmaker(engine, expire_on_commit=False) + client = httpx.AsyncClient(transport=httpx.ASGITransport(app=m.app), base_url="http://test") + now = m.now_ms() + try: + async with engine.begin() as db: + await db.run_sync(m.metadata.create_all) + for uid in ("race-owner", "race-a", "race-b"): + await db.execute(insert(m.users).values( + id=uid, name=uid, nickname=uid, student_id=uid, + school="山东管理学院", email=f"{uid}@example.test", + email_verified_at=now, created_at=now, + )) + await db.execute(insert(m.user_stats).values( + user_id=uid, points_balance=1000, 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(m.sessions).values( + id=uid, user_id=uid, token_hash=m.hash_token(uid), + expires_at=now + 3_600_000, created_at=now, + )) + for uid in ("race-a", "race-b"): + await db.execute(insert(m.student_verifications).values( + id=f"verification-{uid}", user_id=uid, + online_code_cipher="test", online_code_iv="test", online_code_tag="test", + online_code_last4="1234", report_expires_on=(datetime.now()+timedelta(days=1)).strftime("%Y-%m-%d"), + status="approved", submitted_at=now, + )) + await db.execute(insert(m.tasks).values( + id="race-task", user_id="race-owner", type="errand", category="快递代取", + title="并发抢单", detail="送至宿舍", place="山东管理学院", school="山东管理学院", + status="open", reward=300, deadline=now + 86_400_000, + contact="13900000000", pickup_codes='["123"]', created_at=now, + )) + with patch.object(m, "SessionLocal", sessions): + responses = await asyncio.gather(*[ + client.post("/api/tasks/race-task/claim", headers={"Authorization": f"Bearer race-{suffix}"}) + for suffix in ("a", "b") + ]) + self.assertEqual(sorted(response.status_code for response in responses), [200, 409], + [response.text for response in responses]) + async with sessions() as db: + owner_balance = await db.scalar(select(m.user_stats.c.points_balance).where( + m.user_stats.c.user_id == "race-owner", + )) + owner_entries = (await db.execute(select(m.point_entries).where( + m.point_entries.c.user_id == "race-owner", + ))).mappings().all() + task = await m.one(db, select(m.tasks).where(m.tasks.c.id == "race-task")) + self.assertEqual(owner_balance, 700) + self.assertEqual(len(owner_entries), 1) + self.assertEqual((owner_entries[0]["delta"], owner_entries[0]["withdrawable_delta"]), (-300, 0)) + self.assertEqual(task["status"], "claimed") + self.assertIn(task["claimer_id"], {"race-a", "race-b"}) + finally: + await client.aclose() + await engine.dispose() + + async def test_claim_consumes_locked_points_before_free_points(self): + await self.verification("approved") + async with self.sessions() as db: + await db.execute(update(self.m.user_stats).where( + self.m.user_stats.c.user_id == "local", + ).values(points_balance=1000, withdrawable_points=200)) + await db.execute(update(self.m.tasks).where( + self.m.tasks.c.id == "local-open", + ).values(reward=900)) + await db.commit() + + response = await self.client.post("/api/tasks/local-open/claim", headers=self.auth()) + self.assertEqual(response.status_code, 200, response.text) + async with self.sessions() as db: + stats = await self.m.one(db, select(self.m.user_stats).where( + self.m.user_stats.c.user_id == "local", + )) + entry = await self.m.one(db, select(self.m.point_entries).where( + self.m.point_entries.c.user_id == "local", + )) + self.assertEqual((stats["points_balance"], stats["withdrawable_points"]), (100, 100)) + self.assertEqual((entry["delta"], entry["withdrawable_delta"]), (-900, -100)) + + async def test_admin_point_deduction_preserves_the_free_balance_after_locked_points(self): + async with self.sessions() as db: + await db.execute(update(self.m.user_stats).where( + self.m.user_stats.c.user_id == "local", + ).values(points_balance=1000, withdrawable_points=200)) + await db.commit() + + response = await self.client.post("/api/admin/users/local/points", json={ + "delta": -900, "reason": "points-layer-test", + }, headers=self.auth("admin")) + self.assertEqual(response.status_code, 200, response.text) + async with self.sessions() as db: + stats = await self.m.one(db, select(self.m.user_stats).where( + self.m.user_stats.c.user_id == "local", + )) + entry = await self.m.one(db, select(self.m.point_entries).where( + self.m.point_entries.c.user_id == "local", + )) + self.assertEqual((stats["points_balance"], stats["withdrawable_points"]), (100, 100)) + self.assertEqual((entry["delta"], entry["withdrawable_delta"]), (-900, -100)) + + async def test_simulated_level_three_user_can_claim(self): + # Face verification is not live; simulate a future trusted summary to + # guard the minimum-level claim rule without exposing an upgrade path. + level_three = {"level": 3, "status": "approved", "label": "双重认证", "faceVerified": True} + with patch.object(self.m, "verification_summary", new_callable=AsyncMock, return_value=level_three) as summary: + response = await self.client.post("/api/tasks/local-open/claim", headers=self.auth()) + summary.assert_awaited_once() + self.assertEqual(response.status_code, 200, response.text) + self.assertEqual(response.json()["pickupCodes"], ["123"]) + + async def test_task_defaults_category_migration(self): + m = self.m + legacy_engine = create_async_engine("sqlite+aiosqlite:///" + str(self.directory / "legacy-defaults.db")) + legacy_sessions = async_sessionmaker(legacy_engine, expire_on_commit=False) + try: + async with legacy_engine.begin() as db: + await db.execute(text( + "CREATE TABLE task_defaults (user_id VARCHAR(64) PRIMARY KEY, school VARCHAR(160) NOT NULL," + " phone VARCHAR(32) NOT NULL, pickup_place VARCHAR(240) NOT NULL," + " destination VARCHAR(240) NOT NULL, updated_at BIGINT NOT NULL)" + )) + await db.execute(text( + "INSERT INTO task_defaults (user_id, school, phone, pickup_place, destination, updated_at)" + " VALUES ('local', '山东管理学院', '13000000000', '菜鸟驿站', 'C12-518', 1)" + )) + await db.execute(text( + "CREATE TABLE account_sanctions (id VARCHAR(64) PRIMARY KEY, user_id VARCHAR(64) NOT NULL," + " admin_id VARCHAR(64) NOT NULL, action VARCHAR(16) NOT NULL, scope VARCHAR(16) NOT NULL," + " reason VARCHAR(400) NOT NULL, created_at BIGINT NOT NULL, expires_at BIGINT," + " lifted_at BIGINT, lifted_by VARCHAR(64))" + )) + await db.execute(text( + "INSERT INTO account_sanctions (id, user_id, admin_id, action, scope, reason, created_at)" + " VALUES ('old-sanction', 'local', 'admin', 'ban', 'all', 'legacy internal reason', 2)" + )) + with patch.object(m, "engine", legacy_engine), patch.object(m, "SessionLocal", legacy_sessions): + await m._init_database_unlocked() + async with legacy_engine.connect() as db: + columns = await db.run_sync( + lambda connection: {column["name"] for column in inspect(connection).get_columns("task_defaults")} + ) + row = (await db.execute(text( + "SELECT user_id, category, school, phone, pickup_place, destination" + " FROM task_defaults" + ))).all() + sanction_columns = await db.run_sync( + lambda connection: {column["name"] for column in inspect(connection).get_columns("account_sanctions")} + ) + sanction_row = (await db.execute(text( + "SELECT id, category, reason FROM account_sanctions WHERE id='old-sanction'" + ))).one() + self.assertIn("category", columns) + self.assertEqual(row, [("local", "快递代取", "山东管理学院", "13000000000", "菜鸟驿站", "C12-518")]) + self.assertIn("category", sanction_columns) + self.assertEqual(sanction_row, ("old-sanction", None, "legacy internal reason")) + finally: + await legacy_engine.dispose() + + async def publish_errand(self, category, payload): + body = {"type": "errand", "category": category, "school": "山东管理学院", + "deadline": self.m.now_ms() + 86400000, "reward": 300, + "phone": "13900000000", **payload} + response = await self.client.post("/api/tasks", json=body, headers=self.auth("local")) + self.assertEqual(response.status_code, 201, response.text) + return response.json()["id"] + + async def test_errand_categories_claim_pipeline_end_to_end(self): + m = self.m + cases = [ + ("快递代取", {"pickupPlace": "菜鸟驿站", "destination": "C12-518", + "pickupCodes": ["5-12-3041"], "sizeDesc": "小件"}), + ("带饭代买", {"shop": "二食堂麻辣烫", "destination": "C12-518", "items": "微辣,不要香菜"}), + ("代排队", {"queuePlace": "校医院", "matter": "代排队打印体检表", "timeSlot": "明早 8 点"}), + ("代打印/文件取送", {"pickupPlace": "打印店", "destination": "C12-518", "requirement": "双面 A4 3 份"}), + ] + async with self.sessions() as db: + await db.execute(update(m.user_stats).where(m.user_stats.c.user_id == "local").values(points_balance=5000)) + await db.commit() + await self.verification("approved") + for index, (category, payload) in enumerate(cases): + with self.subTest(category=category): + task_id = await self.publish_errand(category, payload) + async with self.sessions() as db: + row = (await db.execute(select(m.tasks).where(m.tasks.c.id == task_id))).mappings().one() + self.assertEqual(row["type"], "errand") + self.assertEqual(row["category"], category) + self.assertEqual(row["school"], "山东管理学院") + self.assertEqual(row["contact"], "13900000000") + self.assertEqual(int(row["reward"]), 300) + # 发布只校验余额不扣分;接单时才扣发布者积分。 + expected_balance = 5000 - 300 * index + self.assertEqual(await self.scalar_user_points("local"), expected_balance) + claim = await self.client.post(f"/api/tasks/{task_id}/claim", headers=self.auth()) + self.assertEqual(claim.status_code, 200, claim.text) + self.assertEqual(claim.json()["contact"], "13900000000") + self.assertEqual(await self.scalar_user_points("local"), expected_balance - 300) + png = b"\x89PNG\r\n\x1a\n" + b"0" * 16 + for kind in ("pickup", "delivery"): + upload = await self.client.post( + f"/api/tasks/{task_id}/proofs/{kind}", + files={"photo": (f"{kind}.png", png, "image/png")}, headers=self.auth()) + self.assertEqual(upload.status_code, 200, upload.text) + detail = (await self.client.get(f"/api/my/tasks/{task_id}", headers=self.auth())).json()["task"] + self.assertTrue(detail["proofs"]["ready"]) + completed = await self.client.post(f"/api/tasks/{task_id}/complete", headers=self.auth("local")) + self.assertEqual(completed.status_code, 200, completed.text) + self.assertEqual(await self.scalar_user_points("viewer"), 1000 + 300 * (index + 1)) + duplicate = await self.client.post(f"/api/tasks/{task_id}/complete", headers=self.auth("local")) + self.assertEqual(duplicate.status_code, 409, duplicate.text) + async with self.sessions() as db: + reasons = (await db.execute(select(m.point_entries.c.reason).where( + m.point_entries.c.user_id == "viewer"))).scalars().all() + status = await db.scalar(select(m.tasks.c.status).where(m.tasks.c.id == task_id)) + self.assertTrue(any(reason.startswith(f"完成{category} · ") for reason in reasons), + sorted(reasons)) + self.assertEqual(status, "done") + + async def test_publish_boundaries_and_invalid_phone_across_errand_categories(self): + m = self.m + await self.verification("approved") + async with self.sessions() as db: + await db.execute(update(m.user_stats).where(m.user_stats.c.user_id == "local").values(points_balance=2000)) + await db.commit() + common = {"type":"errand", "school":"山东管理学院", "deadline":m.now_ms()+86_400_000, + "phone":"13900000000"} + category_fields = [ + ("快递代取", {"pickupPlace":"菜鸟驿站", "destination":"C12-518", "pickupCodes":["5-12-3041"]}), + ("带饭代买", {"shop":"二食堂", "destination":"C12-518", "items":"不加辣"}), + ("代排队", {"queuePlace":"校医院", "matter":"办理事项", "timeSlot":"明早"}), + ("代打印/文件取送", {"pickupPlace":"打印店", "destination":"C12-518", "requirement":"A4 双面"}), + ] + for reward, expected in [(199, 400), (200, 201), (1500, 201), (1501, 400)]: + response = await self.client.post("/api/tasks", json={ + **common, **category_fields[0][1], "category":category_fields[0][0], "reward":reward, + }, headers=self.auth("local")) + self.assertEqual(response.status_code, expected, (reward, response.text)) + for category, fields in category_fields: + response = await self.client.post("/api/tasks", json={ + **common, **fields, "category":category, "reward":200, "phone":"not-a-phone", + }, headers=self.auth("local")) + self.assertEqual(response.status_code, 400, (category, response.text)) + self.assertEqual(await self.scalar_user_points("local"), 2000) + + async def scalar_user_points(self, uid): + async with self.sessions() as db: + return int(await db.scalar(select(self.m.user_stats.c.points_balance).where( + self.m.user_stats.c.user_id == uid))) + + async def test_errand_validation_alias_and_partner_guard(self): + m = self.m + base = {"type": "errand", "school": "山东管理学院", + "deadline": m.now_ms() + 86400000, "reward": 300, "phone": "13900000000"} + async with self.sessions() as db: + await db.execute(insert(m.tasks).values( + id="open-partner", user_id="local", school="山东管理学院", type="partner", + title="组队", detail="自习", place="山东管理学院", status="open", + reward=0, created_at=1, slots=3, + )) + await db.commit() + invalid = [ + ({**base, "category": "代遛狗"}, 400), + ({**base, "category": "带饭代买"}, 400), # 缺 shop/destination + ({**base, "category": "带饭代买", "shop": "二食堂"}, 400), + ({**base, "category": "快递代取", "pickupPlace": "驿站", + "destination": "C12", "pickupCodes": ["1"], "reward": 100}, 400), + ({**base, "category": "代排队", "queuePlace": "校医院", + "matter": "代排队", "reward": 2000}, 400), + ] + for payload, expected in invalid: + response = await self.client.post("/api/tasks", json=payload, headers=self.auth("local")) + self.assertEqual(response.status_code, expected, payload) + # 旧客户端 express 别名:写入即归一为 errand + 快递代取。 + alias = await self.client.post("/api/tasks", json={ + "type": "express", "school": "山东管理学院", "deadline": m.now_ms() + 86400000, + "reward": 300, "phone": "13900000000", "pickupPlace": "菜鸟驿站", + "destination": "C12-518", "pickupCodes": ["5-12-3041"], + }, headers=self.auth("local")) + self.assertEqual(alias.status_code, 201, alias.text) + async with self.sessions() as db: + row = (await db.execute(select(m.tasks).where(m.tasks.c.id == alias.json()["id"]))).mappings().one() + self.assertEqual((row["type"], row["category"]), ("errand", "快递代取")) + # task_defaults 按类目分别保存:快递类目记录别名发布的数据,带饭类目记录带饭的数据,互不串。 + food = await self.client.post("/api/tasks", json={ + **base, "category": "带饭代买", "shop": "二食堂", "destination": "C12-518", "items": "微辣", + }, headers=self.auth("local")) + self.assertEqual(food.status_code, 201, food.text) + food_defaults = (await self.client.get("/api/task-defaults", params={"category": "带饭代买"}, + headers=self.auth("local"))).json()["defaults"] + self.assertEqual(food_defaults["phone"], "13900000000") + self.assertEqual(food_defaults["pickupPlace"], "二食堂") + express_defaults = (await self.client.get("/api/task-defaults", params={"category": "快递代取"}, + headers=self.auth("local"))).json()["defaults"] + self.assertEqual(express_defaults["pickupPlace"], "菜鸟驿站") + # 开放中的组队任务直接 claim 仍返回 400。 + await self.verification("approved") + response = await self.client.post("/api/tasks/open-partner/claim", headers=self.auth()) + self.assertEqual(response.status_code, 400, response.text) + self.assertIn("组队任务", response.json()["error"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/backend/tests/test_v1_social_credit.py b/backend/tests/test_v1_social_credit.py new file mode 100644 index 0000000..8a82710 --- /dev/null +++ b/backend/tests/test_v1_social_credit.py @@ -0,0 +1,716 @@ +"""Isolated API regressions for V1 credit rules, invite eligibility and social flows.""" +import importlib +import os +import tempfile +import unittest +from datetime import timedelta +from pathlib import Path +from unittest.mock import AsyncMock, patch +from uuid import uuid4 + +import httpx +from sqlalchemy import and_, insert, select, update +from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine + + +class V1SocialCreditTests(unittest.IsolatedAsyncioTestCase): + @classmethod + def setUpClass(cls): + cls.temp_root = Path(tempfile.gettempdir()) / f"linkup-v1-tests-{uuid4().hex}" + cls.temp_root.mkdir() + with patch.dict(os.environ, { + "DATABASE_DRIVER": "sqlite", "DATABASE_PATH": str(cls.temp_root / "unused.db"), + "TASK_PROOF_DIR": str(cls.temp_root / "module-proofs"), "NODE_ENV": "test", + }): + cls.m = importlib.import_module("backend.main") + + async def asyncSetUp(self): + m = self.m + self.engine = create_async_engine("sqlite+aiosqlite:///:memory:") + self.sessions = async_sessionmaker(self.engine, expire_on_commit=False) + self.patch_session = patch.object(m, "SessionLocal", self.sessions); self.patch_session.start() + self.patch_admin = patch.object(m, "ADMIN_EMAILS", {"admin@example.test"}); self.patch_admin.start() + self.proof_dir = self.temp_root / f"proofs-{uuid4().hex}"; self.proof_dir.mkdir() + self.patch_proof_dir = patch.object(m, "PROOF_DIR", self.proof_dir); self.patch_proof_dir.start() + async with self.engine.begin() as db: + await db.run_sync(m.metadata.create_all) + for uid, school in [ + ("viewer", "山东管理学院"), ("peer", "山东管理学院"), + ("owner", "山东管理学院"), ("claimer", "山东管理学院"), + ("admin", "山东管理学院"), ("remote", "中国石油大学(华东)"), + ]: + await db.execute(insert(m.users).values( + id=uid, name=uid, nickname=uid, student_id=uid, school=school, + email=f"{uid}@example.test", email_verified_at=1, created_at=1, + )) + await db.execute(insert(m.user_stats).values( + user_id=uid, points_balance=1000, withdrawable_points=0, + credit_score=70, breach_count=0, commitments_count=0, + completed_tasks=0, current_streak=0, updated_at=1, + )) + await db.execute(insert(m.sessions).values( + id=uid, user_id=uid, token_hash=m.hash_token(uid), + expires_at=m.now_ms() + 3_600_000, created_at=1, + )) + self.client = httpx.AsyncClient(transport=httpx.ASGITransport(app=m.app), base_url="http://test") + + async def asyncTearDown(self): + await self.client.aclose() + self.patch_session.stop(); self.patch_admin.stop(); self.patch_proof_dir.stop() + await self.engine.dispose() + + def auth(self, user="viewer"): + return {"Authorization": "Bearer " + user} if user else {} + + async def test_invites_require_withdrawable_points_and_keep_issued_code(self): + m = self.m + async with self.sessions() as db: + await db.execute(update(m.user_stats).where(m.user_stats.c.user_id == "viewer").values( + credit_score=95, withdrawable_points=79, + )) + await db.commit() + response = await self.client.get("/api/invite-code", headers=self.auth()) + self.assertFalse(response.json()["eligible"]) + self.assertEqual(response.json()["withdrawablePoints"], 79) + denied = await self.client.post("/api/invite-code", json={}, headers=self.auth()) + self.assertEqual(denied.status_code, 403) + self.assertIn("可提现积分满 80", denied.text) + + async with self.sessions() as db: + await db.execute(update(m.user_stats).where(m.user_stats.c.user_id == "viewer").values( + credit_score=70, withdrawable_points=80, + )) + await db.commit() + issued = await self.client.post("/api/invite-code", json={}, headers=self.auth()) + self.assertEqual(issued.status_code, 200, issued.text) + code = issued.json()["code"] + self.assertEqual(code["maxUses"], 2) + self.assertEqual(issued.json()["creditScore"], 70) + + async with self.sessions() as db: + await db.execute(update(m.user_stats).where(m.user_stats.c.user_id == "viewer").values(withdrawable_points=0)) + await db.commit() + existing = await self.client.post("/api/invite-code", json={}, headers=self.auth()) + self.assertEqual(existing.status_code, 200, existing.text) + self.assertEqual(existing.json()["code"], code) + + async def test_registration_inviter_credit_gate_remains_90(self): + m = self.m + async with self.sessions() as db: + await db.execute(update(m.user_stats).where(m.user_stats.c.user_id == "owner").values(credit_score=89)) + await db.execute(insert(m.invite_codes).values( + id="code-row", code="INVITE123", owner_id="owner", max_uses=2, used_count=0, created_at=m.now_ms(), + )) + email = "new-user@example.test" + await db.execute(insert(m.email_verifications).values( + email=email, code_hash=m.hash_code(email, "123456"), expires_at=m.now_ms()+600_000, + sent_at=m.now_ms(), attempts=0, + )) + await db.commit() + response = await self.client.post("/api/auth/register", json={ + "name":"新同学", "nickname":"新同学", "studentId":"NEW_12345", "school":"山东管理学院", + "email":"new-user@example.test", "code":"123456", "password":"password123", + "passwordConfirm":"password123", "privacyConsent":True, "privacyPolicyVersion":m.PRIVACY_POLICY_VERSION, + "inviteCode":"INVITE123", + }) + self.assertEqual(response.status_code, 400) + self.assertIn("邀请码拥有者信用分需达到 90 分", response.text) + + async def test_registration_accepts_current_privacy_policy_version(self): + m = self.m + email = "current-policy@example.test" + async with self.sessions() as db: + await db.execute(insert(m.email_verifications).values( + email=email, code_hash=m.hash_code(email, "123456"), + expires_at=m.now_ms()+600_000, sent_at=m.now_ms(), attempts=0, + )) + await db.commit() + response = await self.client.post("/api/auth/register", json={ + "name":"新同学", "nickname":"版本验证", "studentId":"CURRENT_123", + "school":"山东管理学院", "email":email, "code":"123456", + "password":"password123", "passwordConfirm":"password123", + "privacyConsent":True, "privacyPolicyVersion":m.PRIVACY_POLICY_VERSION, + }) + self.assertEqual(response.status_code, 201, response.text) + self.assertEqual((response.json()["user"]["stats"]["pointsBalance"], + response.json()["user"]["stats"]["creditScore"]), (750, 70)) + + async def test_recharge_and_withdraw_use_withdrawable_points_and_write_ledgers(self): + m = self.m + rejected = await self.client.post("/api/points/withdraw", json={"points":100}, headers=self.auth()) + self.assertEqual(rejected.status_code, 400) + self.assertIn("可提现积分不足", rejected.text) + zero = await self.client.post("/api/points/withdraw", json={"points":0}, headers=self.auth()) + self.assertEqual(zero.status_code, 400) + + recharge = await self.client.post("/api/points/recharge", json={"amount":1}, headers=self.auth()) + self.assertEqual(recharge.status_code, 200, recharge.text) + self.assertEqual((recharge.json()["points"], recharge.json()["balance"], recharge.json()["withdrawable"]), + (100, 1100, 100)) + withdraw = await self.client.post("/api/points/withdraw", json={"points":100}, headers=self.auth()) + self.assertEqual(withdraw.status_code, 200, withdraw.text) + self.assertEqual((withdraw.json()["amountCents"], withdraw.json()["amountYuan"]), (75, 0.75)) + async with self.sessions() as db: + stats = await m.one(db, select(m.user_stats).where(m.user_stats.c.user_id == "viewer")) + entries = (await db.execute(select(m.point_entries).where( + m.point_entries.c.user_id == "viewer", + ))).mappings().all() + self.assertEqual((stats["points_balance"], stats["withdrawable_points"]), (1000, 0)) + self.assertEqual(sorted((row["delta"], row["withdrawable_delta"]) for row in entries), [ + (-100, -100), (100, 100), + ]) + self.assertTrue(any(row["reason"] == "充值 1 元" for row in entries)) + self.assertTrue(any(row["reason"].startswith("提现 100 积分") for row in entries)) + + async def test_credit_ledger_appeal_and_redacted_public_history(self): + m = self.m; now = m.now_ms() + async with self.sessions() as db: + await db.execute(insert(m.tasks).values( + id="no-show-task", user_id="owner", claimer_id="claimer", type="errand", category="快递代取", + title="未履约", detail="送达", place="山东管理学院", school="山东管理学院", + status="claimed", reward=0, deadline=now+86_400_000, claimed_at=now-60_000, created_at=now-120_000, + )) + await db.execute(insert(m.reliability_events).values( + id="pending-review", event_key="pending-review", user_id="claimer", task_id="no-show-task", + kind="task_review", status="pending", created_at=now-30_000, + )) + await db.execute(insert(m.credit_adjustments).values( + id="legacy-adjustment", user_id="viewer", admin_id="admin", delta=-2, + reason="legacy detailed reason must never leak", category=None, + before_score=70, after_score=68, created_at=now-20, + )) + await db.execute(insert(m.credit_adjustments).values( + id="public-adjustment", user_id="viewer", admin_id="admin", delta=3, + reason="private reason does not appear in public responses", category="奖励", + before_score=68, after_score=71, created_at=now-10, + )) + await db.commit() + unauthorized = await self.client.post("/api/admin/users/claimer/credit", json={ + "reasonType":"no_show", "taskId":"no-show-task", "note":"核实记录存在", + }, headers=self.auth("viewer")) + self.assertEqual(unauthorized.status_code, 403) + no_admin = await self.client.post("/api/admin/users/claimer/credit", json={ + "reasonType":"no_show", "taskId":"no-show-task", "note":"核实记录存在", + }) + self.assertEqual(no_admin.status_code, 401) + + options = await self.client.get("/api/admin/credit-options", headers=self.auth("admin")) + self.assertEqual(options.status_code, 200) + self.assertIn("appeal_upheld", [item["value"] for item in options.json()["items"]]) + self.assertEqual(len((await self.client.get("/api/credit/summary", headers=self.auth("claimer"))).json()["pendingCases"]), 1) + penalty = await self.client.post("/api/admin/users/claimer/credit", json={ + "reasonType":"no_show", "taskId":"no-show-task", "note":"确认未履约且联系无回应", + }, headers=self.auth("admin")) + self.assertEqual(penalty.status_code, 200, penalty.text) + self.assertEqual(penalty.json()["applied"], -8) + penalized_summary = (await self.client.get("/api/credit/summary", headers=self.auth("claimer"))).json() + self.assertEqual(penalized_summary["breachCount90d"], 1) + self.assertEqual(penalized_summary["pendingCases"], []) + + rows = await self.client.get("/api/admin/credit-adjustments?userId=claimer", headers=self.auth("admin")) + original = rows.json()["items"][0] + self.assertEqual((original["before"], original["after"], original["adminName"]), (70, 62, "admin")) + appeal = await self.client.post("/api/admin/users/claimer/credit", json={ + "reasonType":"appeal_upheld", "reversesId":original["id"], "note":"申诉证据证明已按时履约", + }, headers=self.auth("admin")) + self.assertEqual(appeal.status_code, 200, appeal.text) + self.assertEqual((appeal.json()["applied"], appeal.json()["creditScore"]), (8, 70)) + summary = (await self.client.get("/api/credit/summary", headers=self.auth("claimer"))).json() + self.assertEqual(summary["breachCount90d"], 0) + self.assertEqual(summary["breachRateLabel"], "记录较少") + + public = await self.client.get("/api/users/viewer/credit-history", headers=self.auth("peer")) + self.assertEqual(public.status_code, 200, public.text) + body = public.json() + self.assertEqual(body["hiddenCount"], 1) + self.assertEqual(set(body["items"][0]), {"delta", "category", "date"}) + self.assertNotIn("legacy detailed reason", public.text) + self.assertNotIn("admin_id", public.text) + async with self.sessions() as db: + audit_count = await db.scalar(select(m.func.count()).select_from(m.public_credit_history_audits)) + self.assertEqual(audit_count, 1) + + async with self.sessions() as db: + await db.execute(insert(m.invite_relations).values(invitee_id="peer", inviter_id="viewer", created_at=m.now_ms())) + await db.commit() + for index in range(5): + adjusted = await self.client.post("/api/admin/users/viewer/credit", json={ + "reasonType":"invite_abuse", "inviteeId":"peer", "note":f"串通刷分核实记录 {index}", + }, headers=self.auth("admin")) + self.assertEqual(adjusted.status_code, 200, adjusted.text) + self.assertEqual(adjusted.json()["applied"], -1) + capped = await self.client.post("/api/admin/users/viewer/credit", json={ + "reasonType":"invite_abuse", "inviteeId":"peer", "note":"超过累计上限测试", + }, headers=self.auth("admin")) + self.assertEqual(capped.status_code, 409) + abuse_history = await self.client.get("/api/admin/credit-adjustments?userId=viewer", headers=self.auth("admin")) + abuse_items = [item for item in abuse_history.json()["items"] if item["reason"] == "查实恶意邀请或串通违规"] + self.assertEqual(len(abuse_items), 5) + self.assertTrue(all(item["inviteeId"] == "peer" for item in abuse_items)) + + async def test_cancel_rules_and_idempotent_completion_credit_cap(self): + m = self.m; now = m.now_ms() + async with self.sessions() as db: + await db.execute(insert(m.invite_relations).values(invitee_id="viewer", inviter_id="owner", created_at=now-100_000)) + for task_id, status, claimer, deadline in [ + ("cancel-open", "open", None, now+3_600_000), + ("cancel-early", "claimed", "viewer", now+3*3_600_000), + ("cancel-short", "claimed", "viewer", now+3_600_000), + ]: + await db.execute(insert(m.tasks).values( + id=task_id, user_id="owner", claimer_id=claimer, type="errand", category="快递代取", + title=task_id, detail="送达", place="山东管理学院", school="山东管理学院", + status=status, reward=0, deadline=deadline, + claimed_at=now-m.RIDER_CANCELLATION_COOLDOWN_MS-1 if claimer else None, created_at=now-20_000, + )) + await db.commit() + self.assertEqual((await self.client.post("/api/tasks/cancel-open/cancel", headers=self.auth("owner"))).status_code, 200) + self.assertEqual((await self.client.post("/api/tasks/cancel-early/cancel", headers=self.auth())).status_code, 200) + self.assertEqual((await self.client.post("/api/tasks/cancel-short/cancel", headers=self.auth())).status_code, 200) + async with self.sessions() as db: + viewer_stats = await m.one(db, select(m.user_stats).where(m.user_stats.c.user_id == "viewer")) + inviter_stats = await m.one(db, select(m.user_stats).where(m.user_stats.c.user_id == "owner")) + self.assertEqual(viewer_stats["credit_score"], 67) + self.assertEqual(inviter_stats["credit_score"], 70) + summary = (await self.client.get("/api/credit/summary", headers=self.auth())).json() + self.assertEqual(summary["breachCount90d"], 1) + self.assertEqual(summary["commitments90d"], 2) + + proof_file = self.proof_dir / "proof.jpg"; proof_file.write_bytes(b"jpeg") + async with self.sessions() as db: + for index in range(6): + task_id = f"done-{index}" + await db.execute(insert(m.tasks).values( + id=task_id, user_id="owner", claimer_id="claimer", type="errand", category="快递代取", + title=task_id, detail="送达", place="山东管理学院", school="山东管理学院", + status="claimed", reward=10, deadline=now+86_400_000, claimed_at=now-30_000, created_at=now-40_000, + )) + for kind in m.PROOF_KINDS: + await db.execute(insert(m.task_proofs).values( + task_id=task_id, kind=kind, uploader_id="claimer", file_path="proof.jpg", + original_name="proof.jpg", mime_type="image/jpeg", file_size=4, created_at=now-10_000, + )) + await db.commit() + with patch.object(m, "send_task_proof_email", new=AsyncMock()): + for index in range(6): + response = await self.client.post(f"/api/tasks/done-{index}/complete", headers=self.auth("owner")) + self.assertEqual(response.status_code, 200, response.text) + async with self.sessions() as db: + owner_stats = await m.one(db, select(m.user_stats).where(m.user_stats.c.user_id == "owner")) + claimer_stats = await m.one(db, select(m.user_stats).where(m.user_stats.c.user_id == "claimer")) + first_task = await m.one(db, select(m.tasks).where(m.tasks.c.id == "done-0")) + before_notifications = await db.scalar(select(m.func.count()).select_from(m.notifications).where(m.notifications.c.kind == "credit_adjusted")) + async with self.sessions() as db: + async with db.begin(): + await m.settle_task_completion_credit(db, dict(first_task)) + async with self.sessions() as db: + after_notifications = await db.scalar(select(m.func.count()).select_from(m.notifications).where(m.notifications.c.kind == "credit_adjusted")) + self.assertEqual(owner_stats["credit_score"], 75) + self.assertEqual(claimer_stats["credit_score"], 75) + self.assertEqual(claimer_stats["withdrawable_points"], 60) + self.assertEqual(before_notifications, after_notifications) + for uid in ("owner", "claimer"): + async with self.sessions() as db: + count = await db.scalar(select(m.func.count()).select_from(m.credit_adjustments).where( + m.credit_adjustments.c.user_id == uid, + m.credit_adjustments.c.rule_key.like("task-completion:%"), + )) + self.assertEqual(count, 6) + + async def test_rider_cooldown_and_cancellation_frequency_restrict_claiming(self): + m = self.m + now = m.now_ms() + async with self.sessions() as db: + for index in range(3): + await db.execute(insert(m.tasks).values( + id=f"rider-cancel-{index}", user_id="owner", claimer_id="viewer", + type="errand", category="快递代取", title=f"rider-cancel-{index}", + detail="送达", place="山东管理学院", school="山东管理学院", status="claimed", + reward=0, deadline=now + 3 * 60 * 60_000, + claimed_at=now - m.RIDER_CANCELLATION_COOLDOWN_MS - 1, created_at=now - 60_000, + )) + await db.execute(insert(m.tasks).values( + id="cooldown-task", user_id="owner", claimer_id="claimer", type="errand", + category="快递代取", title="冷静期任务", detail="送达", place="山东管理学院", + school="山东管理学院", status="claimed", reward=0, + deadline=now + 3 * 60 * 60_000, claimed_at=now, created_at=now, + )) + await db.execute(insert(m.tasks).values( + id="restricted-claim-target", user_id="owner", type="errand", category="快递代取", + title="待接任务", detail="送达", place="山东管理学院", school="山东管理学院", + status="open", reward=0, deadline=now + 3 * 60 * 60_000, created_at=now, + )) + await db.commit() + + cooldown = await self.client.post("/api/tasks/cooldown-task/cancel", headers=self.auth("claimer")) + self.assertEqual(cooldown.status_code, 409, cooldown.text) + self.assertIn("30 分钟", cooldown.json()["error"]) + for index in range(3): + cancelled = await self.client.post(f"/api/tasks/rider-cancel-{index}/cancel", headers=self.auth()) + self.assertEqual(cancelled.status_code, 200, cancelled.text) + async with self.sessions() as db: + stats = await m.one(db, select(m.user_stats).where(m.user_stats.c.user_id == "viewer")) + self.assertGreater(stats["claim_restricted_until"], m.now_ms()) + self.assertEqual(stats["credit_score"], 70) + self.assertEqual(stats["breach_count"], 0) + + with patch.object(m, "verification_summary", new_callable=AsyncMock, return_value={"level": 2}): + claim = await self.client.post("/api/tasks/restricted-claim-target/claim", headers=self.auth()) + self.assertEqual(claim.status_code, 403, claim.text) + self.assertIn("暂时限制接单", claim.json()["error"]) + + async def test_publisher_cancel_bands_and_delivered_proof_guard(self): + m = self.m + now = m.now_ms() + proof_file = self.proof_dir / "cancel-proof.jpg" + proof_file.write_bytes(b"jpeg") + async with self.sessions() as db: + for task_id, age, proof_kinds in [ + ("publisher-grace", 9 * 60_000, ()), + ("publisher-empty-late", 11 * 60_000, ()), + ("publisher-picked", 11 * 60_000, ("pickup",)), + ("publisher-delivered", 11 * 60_000, ("pickup", "delivery")), + ("publisher-reported", 11 * 60_000, ("pickup",)), + ]: + await db.execute(insert(m.tasks).values( + id=task_id, user_id="owner", claimer_id="claimer", type="errand", + category="快递代取", title=task_id, detail="送达", place="山东管理学院", + school="山东管理学院", status="claimed", reward=1000, + deadline=now + 3 * 60 * 60_000, claimed_at=now - age, created_at=now - 1_000, + )) + for kind in proof_kinds: + await db.execute(insert(m.task_proofs).values( + task_id=task_id, kind=kind, uploader_id="claimer", file_path=proof_file.name, + original_name=proof_file.name, mime_type="image/jpeg", file_size=4, created_at=now - 1_000, + )) + await db.execute(insert(m.reports).values( + id="publisher-cancel-report", reporter_id="viewer", target_type="task", + target_id="publisher-reported", target_user_id="owner", reason="情况待查", + status="open", created_at=now, + )) + await db.execute(update(m.user_stats).where(m.user_stats.c.user_id == "owner").values( + credit_score=70, breach_count=0, + )) + await db.commit() + + expected = { + "publisher-grace": ("grace", 1000, 0), + "publisher-empty-late": ("empty_late", 800, 200), + "publisher-picked": ("picked", 500, 500), + } + for task_id, (band, owner_refund, rider_compensation) in expected.items(): + response = await self.client.post(f"/api/tasks/{task_id}/cancel", headers=self.auth("owner")) + self.assertEqual(response.status_code, 200, response.text) + result = response.json() + self.assertEqual((result["band"], result["ownerRefund"], result["riderCompensation"]), + (band, owner_refund, rider_compensation)) + self.assertEqual(owner_refund + rider_compensation, 1000) + delivered = await self.client.post("/api/tasks/publisher-delivered/cancel", headers=self.auth("owner")) + self.assertEqual(delivered.status_code, 409, delivered.text) + + async with self.sessions() as db: + owner_points = (await db.execute(select(m.point_entries.c.delta).where(and_( + m.point_entries.c.user_id == "owner", + m.point_entries.c.reason.like("任务撤单退款 · publisher-%"), + )))).scalars().all() + rider_points = (await db.execute(select(m.point_entries.c.delta).where(and_( + m.point_entries.c.user_id == "claimer", + m.point_entries.c.reason.like("%补偿 · publisher-%"), + )))).scalars().all() + owner_stats = await m.one(db, select(m.user_stats).where(m.user_stats.c.user_id == "owner")) + picked_events = await m.all_rows(db, select(m.reliability_events).where( + m.reliability_events.c.task_id == "publisher-picked", + )) + picked_adjustment = await m.one(db, select(m.credit_adjustments).where( + m.credit_adjustments.c.rule_key == f"task-publisher-cancel-picked:publisher-picked:owner", + )) + self.assertEqual(owner_points, [1000, 800, 500]) + self.assertEqual(rider_points, [200, 500]) + self.assertEqual(owner_stats["credit_score"], 67) + self.assertEqual(owner_stats["breach_count"], 1) + self.assertEqual({event["kind"]: event["status"] for event in picked_events}, + {"task_review": "pending", "breach": "confirmed"}) + self.assertEqual(picked_adjustment["delta"], -3) + + reported = await self.client.post("/api/tasks/publisher-reported/cancel", headers=self.auth("owner")) + self.assertEqual(reported.status_code, 200, reported.text) + self.assertTrue(reported.json()["creditReviewPending"]) + async with self.sessions() as db: + owner_stats = await m.one(db, select(m.user_stats).where(m.user_stats.c.user_id == "owner")) + pending = await m.one(db, select(m.reliability_events).where( + m.reliability_events.c.event_key == "task-publisher-cancel-review:publisher-reported:owner", + )) + adjustment = await m.one(db, select(m.credit_adjustments).where( + m.credit_adjustments.c.rule_key == "task-publisher-cancel-picked:publisher-reported:owner", + )) + self.assertEqual(owner_stats["credit_score"], 67) + self.assertEqual(owner_stats["breach_count"], 1) + self.assertEqual(pending["status"], "pending") + self.assertIsNone(adjustment) + + async def test_lift_requires_live_sanction_and_does_not_create_empty_history(self): + m = self.m + payload = {"action": "lift", "reason": "测试解除"} + + async def counts(): + async with self.sessions() as db: + values = [] + for table in (m.account_sanctions, m.notifications, m.admin_audit_logs): + values.append(len(await m.all_rows(db, select(table)))) + return tuple(values) + + original = await counts() + empty = await self.client.post("/api/admin/users/viewer/sanctions", json=payload, headers=self.auth("admin")) + self.assertEqual(empty.status_code, 400, empty.text) + self.assertIn("该账号当前没有生效中的处理", empty.text) + self.assertEqual(await counts(), original) + + async with self.sessions() as db: + await db.execute(insert(m.account_sanctions).values( + id="expired", user_id="viewer", admin_id="admin", action="ban", scope="all", + category="其他违规", reason="已到期处罚", created_at=1, expires_at=m.now_ms()-1, + )) + await db.commit() + original = await counts() + expired = await self.client.post("/api/admin/users/viewer/sanctions", json=payload, headers=self.auth("admin")) + self.assertEqual(expired.status_code, 400, expired.text) + self.assertEqual(await counts(), original) + + for action in ("restrict", "ban"): + imposed = await self.client.post("/api/admin/users/viewer/sanctions", json={ + "action": action, "scopes": ["publish"] if action == "restrict" else ["all"], + "duration_days": "permanent" if action == "restrict" else 7, + "category": "其他违规", "reason": "待解除的处罚", + }, headers=self.auth("admin")) + self.assertEqual(imposed.status_code, 200, imposed.text) + before = await counts() + lifted = await self.client.post("/api/admin/users/viewer/sanctions", json=payload, headers=self.auth("admin")) + self.assertEqual(lifted.status_code, 200, lifted.text) + self.assertEqual(lifted.json()["status"], "active") + self.assertEqual((await counts())[0], before[0]+1) + after = await counts() + duplicate = await self.client.post("/api/admin/users/viewer/sanctions", json=payload, headers=self.auth("admin")) + self.assertEqual(duplicate.status_code, 400, duplicate.text) + self.assertEqual(await counts(), after) + history = await self.client.get("/api/admin/users/viewer/sanctions", headers=self.auth("admin")) + self.assertEqual(sum(item["action"] == "lift" for item in history.json()["items"]), 2) + + async def test_sanction_category_privacy_enforcement_and_lift(self): + m = self.m + with patch.object(m, "ADMIN_SANCTION_CONTACT", "微信:linkup-admin"): + restricted = await self.client.post("/api/admin/users/viewer/sanctions", json={ + "action": "restrict", "scopes": ["withdraw"], "duration_days": 7, + "category": "多次失约", "reason": "仅内部可见的核实材料", + }, headers=self.auth("admin")) + self.assertEqual(restricted.status_code, 200, restricted.text) + admin_target = await self.client.post("/api/admin/users/admin/sanctions", json={ + "action": "ban", "duration_days": 7, "category": "其他违规", "reason": "管理员不能被处理", + }, headers=self.auth("admin")) + self.assertEqual(admin_target.status_code, 400, admin_target.text) + denied = await self.client.post("/api/points/withdraw", json={"points": 1}, headers=self.auth()) + self.assertEqual(denied.status_code, 403, denied.text) + self.assertEqual((await self.client.get("/api/auth/me", headers=self.auth())).status_code, 200) + + async with self.sessions() as db: + notice = await m.one(db, select(m.notifications).where(and_( + m.notifications.c.user_id == "viewer", m.notifications.c.kind == "account_sanction", + )).order_by(m.notifications.c.created_at.desc())) + self.assertIn("多次失约", notice["content"]) + self.assertIn("微信:linkup-admin", notice["content"]) + self.assertNotIn("仅内部可见的核实材料", notice["content"]) + + history = await self.client.get("/api/admin/users/viewer/sanctions", headers=self.auth("admin")) + self.assertEqual(history.status_code, 200, history.text) + self.assertEqual(history.json()["items"][0]["category"], "多次失约") + self.assertEqual(history.json()["items"][0]["reason"], "仅内部可见的核实材料") + audit = await self.client.get("/api/admin/audit-logs?action=account_sanction_restrict", + headers=self.auth("admin")) + self.assertEqual(audit.status_code, 200, audit.text) + self.assertEqual(len(audit.json()["items"]), 1) + + async with self.sessions() as db: + await db.execute(update(m.account_sanctions).where(and_( + m.account_sanctions.c.user_id == "viewer", m.account_sanctions.c.action == "restrict", + )).values(expires_at=m.now_ms() - 1)) + await db.commit() + self.assertEqual((await self.client.get("/api/auth/me", headers=self.auth())).status_code, 200) + expired_withdraw = await self.client.post("/api/points/withdraw", json={"points": 1}, headers=self.auth()) + self.assertEqual(expired_withdraw.status_code, 400, expired_withdraw.text) + + lifted = await self.client.post("/api/admin/users/viewer/sanctions", json={ + "action": "lift", "reason": "已核实解除", + }, headers=self.auth("admin")) + self.assertEqual(lifted.status_code, 400, lifted.text) + self.assertIn("该账号当前没有生效中的处理", lifted.text) + self.assertEqual((await self.client.get("/api/auth/me", headers=self.auth())).status_code, 200) + + now = m.now_ms() + async with self.sessions() as db: + await db.execute(insert(m.tasks).values( + id="ban-peer-open", user_id="peer", type="errand", category="快递代取", + title="ban-peer-open", detail="送达", place="山东管理学院", school="山东管理学院", + status="open", reward=200, deadline=now + 86_400_000, created_at=now, + )) + await db.execute(insert(m.tasks).values( + id="ban-peer-publisher", user_id="peer", claimer_id="viewer", type="errand", + category="快递代取", title="ban-peer-publisher", detail="送达", place="山东管理学院", + school="山东管理学院", status="claimed", reward=100, deadline=now + 86_400_000, + claimed_at=now - 3_600_000, created_at=now, + )) + await db.execute(insert(m.tasks).values( + id="ban-peer-claimer", user_id="owner", claimer_id="peer", type="errand", + category="快递代取", title="ban-peer-claimer", detail="送达", place="山东管理学院", + school="山东管理学院", status="claimed", reward=100, deadline=now + 86_400_000, + claimed_at=now - 3_600_000, created_at=now, + )) + await db.execute(update(m.user_stats).where(m.user_stats.c.user_id == "peer").values(points_balance=500)) + await db.commit() + + banned = await self.client.post("/api/admin/users/peer/sanctions", json={ + "action": "ban", "duration_days": 7, "category": "涉嫌欺诈", + "reason": "BAN_INTERNAL_SECRET", + }, headers=self.auth("admin")) + self.assertEqual(banned.status_code, 200, banned.text) + with patch.object(m, "ADMIN_SANCTION_CONTACT", "微信:linkup-admin"): + login = await self.client.post("/api/auth/login", json={ + "email": "peer@example.test", "password": "anything", + }) + self.assertEqual(login.status_code, 403, login.text) + self.assertIn("涉嫌欺诈", login.json()["error"]) + self.assertIn("恢复", login.json()["error"]) + self.assertIn("微信:linkup-admin", login.json()["error"]) + self.assertNotIn("BAN_INTERNAL_SECRET", login.text) + self.assertEqual((await self.client.get("/api/credit/summary", headers=self.auth("peer"))).status_code, 401) + async with self.sessions() as db: + task_states = (await db.execute(select(m.tasks.c.id, m.tasks.c.status, m.tasks.c.claimer_id).where( + m.tasks.c.id.in_(["ban-peer-open", "ban-peer-publisher", "ban-peer-claimer"]), + ))).mappings().all() + refund_rows = await m.all_rows(db, select(m.point_entries).where(and_( + m.point_entries.c.reason.like("%ban-peer-%"), + m.point_entries.c.user_id.in_(["peer", "owner"]), + ))) + peer_sessions = await db.scalar(select(m.func.count()).select_from(m.sessions).where( + m.sessions.c.user_id == "peer", + )) + notices = await m.all_rows(db, select(m.notifications).where(and_( + m.notifications.c.link.in_(["task:ban-peer-publisher", "task:ban-peer-claimer"]), + m.notifications.c.kind == "task_cancelled", + ))) + self.assertEqual({row["id"]: (row["status"], row["claimer_id"]) for row in task_states}, { + "ban-peer-open": ("cancelled", None), + "ban-peer-publisher": ("cancelled", "viewer"), + "ban-peer-claimer": ("open", None), + }) + self.assertEqual(sorted((row["user_id"], row["delta"]) for row in refund_rows), [ + ("owner", 100), ("peer", 100), + ]) + self.assertEqual(peer_sessions, 0) + self.assertEqual(len(notices), 2) + + async def test_login_logs_mask_email_capture_session_and_respect_proxy_trust(self): + m = self.m + trusted_ip = "198.51.100.77" + async with self.sessions() as db: + await db.execute(insert(m.login_verifications).values( + email="viewer@example.test", code_hash=m.hash_code("viewer@example.test", "246810"), + expires_at=m.now_ms() + 600_000, sent_at=m.now_ms(), attempts=0, + )) + await db.execute(update(m.users).where(m.users.c.id == "peer").values(password_hash="stored-hash")) + await db.commit() + headers = {"X-Forwarded-For": f"{trusted_ip}, 10.0.0.2", "User-Agent": "TestBrowser/7.2"} + with patch.object(m, "TRUST_PROXY", True): + login = await self.client.post("/api/auth/login", json={ + "email": "viewer@example.test", "code": "246810", + }, headers=headers) + self.assertEqual(login.status_code, 200, login.text) + async with self.sessions() as db: + await db.execute(insert(m.login_verifications).values( + email="viewer@example.test", code_hash=m.hash_code("viewer@example.test", "135790"), + expires_at=m.now_ms() + 600_000, sent_at=m.now_ms(), attempts=0, + )) + await db.commit() + second_login = await self.client.post("/api/auth/login", json={ + "email": "viewer@example.test", "code": "135790", + }, headers={"X-Real-IP": "203.0.113.88", "User-Agent": "Firefox/130 Windows"}) + self.assertEqual(second_login.status_code, 200, second_login.text) + with patch.object(m, "verify_password", return_value=False): + failed = await self.client.post("/api/auth/login", json={ + "email": "peer@example.test", "password": "wrong", + }, headers=headers) + self.assertEqual(failed.status_code, 401, failed.text) + + async with self.sessions() as db: + logs = await m.all_rows(db, select(m.login_logs).where(m.login_logs.c.ip == trusted_ip) + .order_by(m.login_logs.c.created_at)) + session = await m.one(db, select(m.sessions).where(and_( + m.sessions.c.user_id == "viewer", m.sessions.c.ip == trusted_ip, + )).order_by(m.sessions.c.created_at.desc()).limit(1)) + sessions = await m.all_rows(db, select(m.sessions).where( + and_(m.sessions.c.user_id == "viewer", m.sessions.c.ip.is_not(None)), + ).order_by(m.sessions.c.created_at)) + known = await m.one(db, select(m.user_known_ips).where(and_( + m.user_known_ips.c.user_id == "viewer", m.user_known_ips.c.ip == trusted_ip, + ))) + self.assertEqual([bool(row["success"]) for row in logs], [True, False]) + self.assertEqual(logs[1]["email_attempted"], "pe***@example.test") + self.assertEqual(logs[1]["user_agent"], "TestBrowser/7.2") + self.assertEqual(session["user_agent"], "TestBrowser/7.2") + self.assertIsNotNone(known) + self.assertEqual([(row["ip"], row["user_agent"]) for row in sessions], [ + (trusted_ip, "TestBrowser/7.2"), ("203.0.113.88", "Firefox/130 Windows"), + ]) + filtered = await self.client.get( + f"/api/admin/login-logs?ip={trusted_ip}&success=false&method=password", headers=self.auth("admin"), + ) + self.assertEqual(filtered.status_code, 200, filtered.text) + self.assertEqual(len(filtered.json()["items"]), 1) + + from starlette.requests import Request + forged = Request({ + "type": "http", "headers": [(b"x-real-ip", b"203.0.113.200")], + "client": ("127.0.0.1", 12345), "method": "GET", "path": "/", + "query_string": b"", "server": ("test", 80), + }) + with patch.object(m, "TRUST_PROXY", False): + self.assertEqual(m.client_ip(forged), "127.0.0.1") + + async def test_chat_turn_taking_cross_school_visibility_and_report_snapshot(self): + opened = await self.client.post("/api/chats", json={"userId":"peer"}, headers=self.auth()) + self.assertEqual(opened.status_code, 201, opened.text) + chat_id = opened.json()["id"] + first = await self.client.post(f"/api/chats/{chat_id}/messages", json={"content":""}, headers=self.auth()) + self.assertEqual(first.status_code, 201, first.text) + blocked = await self.client.post(f"/api/chats/{chat_id}/messages", json={"content":"second"}, headers=self.auth()) + self.assertEqual(blocked.status_code, 403) + self.assertIn("对方回复后才能继续发送", blocked.text) + reply = await self.client.post(f"/api/chats/{chat_id}/messages", json={"content":"收到"}, headers=self.auth("peer")) + self.assertEqual(reply.status_code, 201, reply.text) + self.assertEqual((await self.client.post(f"/api/chats/{chat_id}/messages", json={"content":"继续"}, headers=self.auth())).status_code, 201) + + report = await self.client.post("/api/reports", json={ + "targetType":"chat", "targetId":chat_id, "targetUserId":"peer", "reason":"对方发送不当消息", + }, headers=self.auth()) + self.assertEqual(report.status_code, 201, report.text) + reports = await self.client.get("/api/admin/reports?status=open", headers=self.auth("admin")) + snapshot = reports.json()["items"][0]["messageSnapshot"] + self.assertLessEqual(len(snapshot), 20) + self.assertIn("", [message["content"] for message in snapshot]) + self.assertEqual((await self.client.get("/api/chats", headers=self.auth("peer"))).status_code, 200) + + for index in range(28): + incoming = await self.client.post(f"/api/chats/{chat_id}/messages", json={"content":f"reply {index}"}, headers=self.auth("peer")) + self.assertEqual(incoming.status_code, 201, incoming.text) + outgoing = await self.client.post(f"/api/chats/{chat_id}/messages", json={"content":f"message {index}"}, headers=self.auth()) + self.assertEqual(outgoing.status_code, 201, outgoing.text) + self.assertEqual((await self.client.post(f"/api/chats/{chat_id}/messages", json={"content":"final reply"}, headers=self.auth("peer"))).status_code, 201) + rate_limited = await self.client.post(f"/api/chats/{chat_id}/messages", json={"content":"over the hourly cap"}, headers=self.auth()) + self.assertEqual(rate_limited.status_code, 429, rate_limited.text) + + hidden = await self.client.post("/api/chats", json={"userId":"remote"}, headers=self.auth()) + self.assertEqual(hidden.status_code, 404) + social_js = (Path(__file__).parents[2] / "dist" / "social.js").read_text(encoding="utf-8-sig") + self.assertIn("escapeHtml(message.content)", social_js) + + +if __name__ == "__main__": + unittest.main() diff --git a/backend/tools/bench.py b/backend/tools/bench.py new file mode 100644 index 0000000..cc0d37f --- /dev/null +++ b/backend/tools/bench.py @@ -0,0 +1,65 @@ +"""多 worker 多接口压测:python tools/bench.py [并发数] [每场景秒数]""" +import asyncio, json, sys, time +import aiohttp + +BASE = "http://127.0.0.1:34173" +CONC = int(sys.argv[1]) if len(sys.argv) > 1 else 100 +DURATION = float(sys.argv[2]) if len(sys.argv) > 2 else 10 + +SCENARIOS = [ + ("任务·公开 /api/tasks", "/api/tasks", False), + ("任务·登录态 /api/tasks", "/api/tasks", True), + ("会话 /api/auth/me", "/api/auth/me", True), + ("通知 /api/notifications", "/api/notifications", True), + ("积分流水 /api/points/entries", "/api/points/entries", True), + ("信用详情 /api/credit/summary", "/api/credit/summary", True), +] + +TOKEN = None + + +async def login(session): + global TOKEN + if TOKEN: + return {"Authorization": f"Bearer {TOKEN}"} + async with session.post(f"{BASE}/api/auth/login", + json={"email": "localuser@linkup.test", "password": "LinkUp2026!"}) as r: + data = await r.json() + assert data.get("ok"), data + TOKEN = data["token"] + return {"Authorization": f"Bearer {TOKEN}"} + + +async def worker(session, path, headers, stop_at, latencies, errors): + while time.monotonic() < stop_at: + t0 = time.perf_counter() + try: + async with session.get(f"{BASE}{path}", headers=headers) as r: + await r.read() + if r.status != 200: + errors[0] += 1 + except Exception: + errors[0] += 1 + continue + latencies.append((time.perf_counter() - t0) * 1000) + + +async def run_scenario(session, label, path, authed): + headers = await login(session) if authed else {} + latencies, errors = [], [0] + stop_at = time.monotonic() + DURATION + await asyncio.gather(*[worker(session, path, headers, stop_at, latencies, errors) for _ in range(CONC)]) + latencies.sort() + total = len(latencies) + errors[0] + rps = total / DURATION + p = lambda q: latencies[min(len(latencies) - 1, int(len(latencies) * q))] + print(f"{label:<30} {rps:>7.0f} RPS P50 {p(0.5):>6.0f}ms P95 {p(0.95):>6.0f}ms 失败 {errors[0]}") + + +async def main(): + async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(limit=0), + timeout=aiohttp.ClientTimeout(total=30)) as session: + for label, path, authed in SCENARIOS: + await run_scenario(session, label, path, authed) + +asyncio.run(main()) diff --git a/backend/tools/migrate_db.py b/backend/tools/migrate_db.py new file mode 100644 index 0000000..f37a2b9 --- /dev/null +++ b/backend/tools/migrate_db.py @@ -0,0 +1,229 @@ +#!/usr/bin/env python3 +"""Bidirectional SQLite/MySQL migration for LinkUp. + +Examples: + python tools/migrate_db.py sqlite-to-mysql --sqlite ./data/linkup.db \ + --mysql-url mysql+pymysql://linkup:secret@127.0.0.1:3306/linkup + python tools/migrate_db.py mysql-to-sqlite --mysql-url mysql+pymysql://... \ + --sqlite ./data/linkup-copy.db + +The script is deliberately idempotent: rows are merged by their primary key, +so it can be resumed after a network interruption. Use --truncate only when a +fresh target database is intended. +""" + +from __future__ import annotations + +import argparse +import os +import sys +import tomllib +from pathlib import Path +from typing import Any + +from sqlalchemy import create_engine, delete, inspect, insert, select, text, update +from sqlalchemy.engine import Engine +from sqlalchemy.exc import SQLAlchemyError + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from db_schema import TABLES, metadata + + +DEFAULT_CONFIG = Path(__file__).resolve().parents[1] / "config.toml" +TABLE_ORDER = [ + "users", + "user_stats", + "email_verifications", + "login_verifications", + "password_resets", + "user_known_ips", + "sessions", + "student_verifications", + "invite_codes", + "invite_relations", + "credit_adjustments", + "point_entries", + "tasks", + "task_defaults", + "notifications", + "reports", +] +# 新增表允许从旧库迁移时暂不存在;目标库会由 metadata.create_all 自动建表。 +OPTIONAL_SOURCE_TABLES = {"task_defaults", "notifications", "password_resets", "user_known_ips"} +DEFAULTS: dict[str, dict[str, Any]] = { + "email_verifications": {"attempts": 0}, + "login_verifications": {"attempts": 0}, + "user_stats": { + "points_balance": 750, "withdrawable_points": 0, "credit_score": 70, + "breach_count": 0, "commitments_count": 0, "completed_tasks": 0, + "current_streak": 0, + }, + "invite_codes": {"max_uses": 2, "used_count": 0}, + "point_entries": {"withdrawable_delta": 0}, + "tasks": {"reward": 0, "status": "open"}, + "reports": {"status": "open"}, +} + + +def load_config(path: Path) -> dict[str, Any]: + if not path.exists(): + return {} + with path.open("rb") as handle: + return tomllib.load(handle) + + +def sqlite_url(path: str) -> str: + resolved = Path(path).expanduser().resolve() + resolved.parent.mkdir(parents=True, exist_ok=True) + return f"sqlite:///{resolved.as_posix()}" + + +def mysql_url(value: str) -> str: + url = value.strip() + if url.startswith("mysql://"): + return "mysql+pymysql://" + url[len("mysql://"):] + if url.startswith("mysql+pymysql://"): + return url + if url.startswith("mysql+asyncmy://"): + return "mysql+pymysql://" + url[len("mysql+asyncmy://"):] + raise ValueError("MySQL URL 必须以 mysql://、mysql+pymysql:// 或 mysql+asyncmy:// 开头") + + +def make_engine(url: str, label: str) -> Engine: + kwargs: dict[str, Any] = {"future": True, "pool_pre_ping": True} + if url.startswith("sqlite://"): + kwargs["connect_args"] = {"check_same_thread": False, "timeout": 60} + else: + kwargs.update(pool_size=5, max_overflow=10, pool_recycle=1800) + print(f"[LinkUp] 连接{label}: {url.split('@')[-1]}") + return create_engine(url, **kwargs) + + +def table_map() -> dict[str, Any]: + return {table.name: table for table in TABLES} + + +def source_rows(connection, table, available_columns: set[str]) -> list[dict[str, Any]]: + selected = [column for column in table.c if column.name in available_columns] + if not selected: + return [] + result = connection.execute(select(*selected)) + return [dict(row) for row in result.mappings().all()] + + +def normalise_row(table, row: dict[str, Any]) -> dict[str, Any]: + values: dict[str, Any] = {} + defaults = DEFAULTS.get(table.name, {}) + for column in table.c: + if column.name in row: + values[column.name] = row[column.name] + elif column.name in defaults: + values[column.name] = defaults[column.name] + elif column.nullable or column.primary_key: + values[column.name] = None + return values + + +def merge_rows(connection, table, rows: list[dict[str, Any]]) -> tuple[int, int]: + primary_keys = [column.name for column in table.primary_key.columns] + inserted = updated = 0 + for original in rows: + row = normalise_row(table, original) + if any(row.get(key) is None for key in primary_keys): + continue + condition = [table.c[key] == row[key] for key in primary_keys] + exists = connection.execute(select(table).where(*condition).limit(1)).first() + if exists: + connection.execute(update(table).where(*condition).values(**row)) + updated += 1 + else: + connection.execute(insert(table).values(**row)) + inserted += 1 + return inserted, updated + + +def truncate_target(connection, tables: dict[str, Any]) -> None: + for name in reversed(TABLE_ORDER): + connection.execute(delete(tables[name])) + + +def migrate(args: argparse.Namespace) -> None: + config = load_config(Path(args.config).resolve()) + database = config.get("database", {}) + source_is_sqlite = args.direction == "sqlite-to-mysql" + source_sqlite = args.sqlite or database.get("path", "./data/linkup.db") + source_mysql = args.mysql_url or os.getenv("DATABASE_URL") or database.get("url", "") + if source_is_sqlite: + if not source_mysql: + raise SystemExit("缺少目标 MySQL URL,请使用 --mysql-url") + source_engine = make_engine(sqlite_url(source_sqlite), "SQLite 源库") + target_engine = make_engine(mysql_url(source_mysql), "MySQL 目标库") + else: + if not source_mysql: + raise SystemExit("缺少源 MySQL URL,请使用 --mysql-url") + target_sqlite = args.sqlite or "./data/linkup-migrated.db" + source_engine = make_engine(mysql_url(source_mysql), "MySQL 源库") + target_engine = make_engine(sqlite_url(target_sqlite), "SQLite 目标库") + + tables = table_map() + try: + metadata.create_all(target_engine) + # Node 版本的旧 SQLite 数据库可能在 tasks 表中还没有 claimer_id。 + # MySQL 已存在该字段时 ALTER 会失败,安全忽略即可。 + with target_engine.begin() as target_schema: + try: + target_schema.execute(text("ALTER TABLE tasks ADD COLUMN claimer_id VARCHAR(64)")) + except Exception: + pass + try: + target_schema.execute(text("ALTER TABLE tasks ADD COLUMN school VARCHAR(160)")) + except Exception: + pass + try: + target_schema.execute(text("UPDATE tasks SET school = place WHERE school IS NULL")) + except Exception: + pass + source_inspector = inspect(source_engine) + available = {name: {column["name"] for column in source_inspector.get_columns(name)} for name in TABLE_ORDER if source_inspector.has_table(name)} + missing = [name for name in TABLE_ORDER if name not in available and name not in OPTIONAL_SOURCE_TABLES] + if missing: + raise SystemExit(f"源数据库缺少表:{', '.join(missing)}") + + with target_engine.begin() as target: + if args.truncate: + print("[LinkUp] 清空目标表(--truncate)") + truncate_target(target, tables) + with source_engine.connect() as source: + total_inserted = total_updated = 0 + for name in TABLE_ORDER: + if name not in available: + print(f"[LinkUp] {name}: 源库暂无,跳过") + continue + table = tables[name] + rows = source_rows(source, table, available[name]) + inserted, updated = merge_rows(target, table, rows) + total_inserted += inserted + total_updated += updated + print(f"[LinkUp] {name}: {len(rows)} 行,新增 {inserted},更新 {updated}") + print(f"[LinkUp] 迁移完成:新增 {total_inserted} 行,更新 {total_updated} 行") + finally: + source_engine.dispose() + target_engine.dispose() + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description="LinkUp SQLite/MySQL 双向迁移工具") + parser.add_argument("direction", choices=("sqlite-to-mysql", "mysql-to-sqlite")) + parser.add_argument("--sqlite", help="SQLite 文件路径") + parser.add_argument("--mysql-url", help="MySQL 连接串") + parser.add_argument("--config", default=str(DEFAULT_CONFIG), help="配置文件路径(默认 backend/config.toml)") + parser.add_argument("--truncate", action="store_true", help="迁移前清空目标库,危险操作,请确认目标库可重建") + return parser.parse_args() + + +if __name__ == "__main__": + try: + migrate(parse_args()) + except (SQLAlchemyError, ValueError) as error: + print(f"[LinkUp] 迁移失败:{error}", file=sys.stderr) + raise SystemExit(1) diff --git a/dist/README.md b/dist/README.md new file mode 100644 index 0000000..626a3b8 --- /dev/null +++ b/dist/README.md @@ -0,0 +1,12 @@ +# 前端文件组织 + +- `base.html`:页面基础壳,包含图标、顶栏、底栏、移动端导航和资源入口。 +- `views/`:按业务页面拆分的视图片段。 +- `components/dialogs/`:按功能拆分的弹窗片段。 +- `components/toast.html`:Toast 的独立 DOM 结构。 +- `js/toast.js`:Toast 行为及顶层堆叠处理。 +- `styles/toast.css`:Toast 专属样式。 + +`backend/main.py` 中的 `render_frontend_shell()` 会在请求 `/`、`/index.html` 或 +`/base.html` 时将这些固定片段组合成一个完整文档。新增视图或弹窗时,将文件加入 +对应的 `FRONTEND_*_FILES` 列表即可;不要再把大段页面结构写回 `index.html`。 diff --git a/dist/admin-security.js b/dist/admin-security.js new file mode 100644 index 0000000..99d842a --- /dev/null +++ b/dist/admin-security.js @@ -0,0 +1,278 @@ +let loginLogOffset = 0; +let auditLogOffset = 0; + +const adminDate = value => value ? new Date(Number(value)).toLocaleString('zh-CN') : '—'; + +function summarizeAdminUa(ua) { + const value = String(ua || ''); + if (!value) return '未知设备'; + const browser = value.includes('Edg/') ? 'Edge' : value.includes('Firefox/') ? 'Firefox' + : value.includes('Chrome/') ? 'Chrome' : value.includes('Safari/') ? 'Safari' + : value.includes('MSIE') ? 'IE' : ''; + const system = value.includes('Windows') ? 'Windows' : value.includes('Android') ? 'Android' + : value.includes('iPhone') || value.includes('iPad') ? 'iOS' + : value.includes('Mac OS') ? 'macOS' : value.includes('Linux') ? 'Linux' : ''; + return browser && system ? `${browser} · ${system}` : value.length > 90 ? `${value.slice(0, 90)}…` : value; +} + +function statusBadge(item) { + const labels = { active: '正常', banned: '封禁中', restricted: '限制中' }; + const status = item.status || 'active'; + const until = item.statusUntil && status !== 'active' ? new Date(Number(item.statusUntil)) : null; + const date = until && !Number.isNaN(until.getTime()) + ? `${until.getFullYear()}-${String(until.getMonth() + 1).padStart(2, '0')}-${String(until.getDate()).padStart(2, '0')}` : ''; + const style = status === 'banned' ? 'rejected' : status === 'restricted' ? 'restricted' : ''; + return `${labels[status] || '正常'}${date ? ` · 至 ${date}` : ''}`; +} + +const adminGroupTabs = {'review-center':'reviews', 'log-center':'login-logs'}; +const loadedAdminViews = new Set(); +const pendingAdminViews = new Map(); +const adminViewLoaders = { + reviews: () => refreshAll(), reports: () => loadAdminReports(), + credit: async () => { const results = await Promise.allSettled([loadAdminUsers(), loadAdjustLog()]); + const failure = results.find(result => result.status === 'rejected' || result.value?.refreshError); + return failure ? {refreshError:failure.reason || failure.value.refreshError} : undefined; }, + 'login-logs': () => loadLoginLogs(false), 'audit-logs': () => loadAuditLogs(false), + analytics: () => loadAnalytics(), 'official-tasks': () => loadOfficialTasks(), +}; +async function ensureAdminView(view) { + if (loadedAdminViews.has(view)) return; + if (pendingAdminViews.has(view)) return pendingAdminViews.get(view); + const request = Promise.resolve().then(adminViewLoaders[view]).then(result => { + if (result?.refreshError) throw result.refreshError; + if (!result?.feedbackError) loadedAdminViews.add(view); + }).catch(error => toast(error.message)).finally(() => pendingAdminViews.delete(view)); + pendingAdminViews.set(view, request); + return request; +} +function switchAdminView(view) { + let group = ['reviews','reports'].includes(view) ? 'review-center' : ['login-logs','audit-logs'].includes(view) ? 'log-center' : view; + if (group !== view) adminGroupTabs[group] = view; + const panel = adminGroupTabs[group] || group; + $$('[data-view]').forEach(button => button.classList.toggle('active', button.dataset.view === group)); + $$('[data-admin-tab]').forEach(button => { + const selected = button.dataset.adminTab === adminGroupTabs['review-center'] || button.dataset.adminTab === adminGroupTabs['log-center']; + button.classList.toggle('active', selected); button.setAttribute('aria-selected', String(selected)); + }); + $('#reviewCenter').hidden = group !== 'review-center'; $('#logCenter').hidden = group !== 'log-center'; + $('#reviewHeader').hidden = panel !== 'reviews'; $('#reviewStats').hidden = panel !== 'reviews'; + const panels = {reviews:'reviewPanel',reports:'reportsPanel',credit:'creditPanel','login-logs':'loginLogsPanel','audit-logs':'auditLogsPanel',analytics:'analyticsPanel','official-tasks':'officialTasksPanel'}; + Object.entries(panels).forEach(([name,id]) => { $(`#${id}`).hidden = name !== panel; }); + return ensureAdminView(panel); +} + +function loginFilters() { + const params = new URLSearchParams(); + const userId = $('#loginFilterUser').value.trim(); + const ip = $('#loginFilterIp').value.trim(); + const success = $('#loginFilterSuccess').value; + const method = $('#loginFilterMethod').value; + if (userId) params.set('user_id', userId); + if (ip) params.set('ip', ip); + if (success) params.set('success', success); + if (method) params.set('method', method); + return params; +} + +async function loadLoginLogs(more = false) { + const list = $('#loginLogsList'); + if (!more) { + loginLogOffset = 0; + list.innerHTML = '
正在加载登录日志…
'; + } + try { + const params = loginFilters(); + params.set('offset', String(loginLogOffset)); + const result = await api(`/api/admin/login-logs?${params}`); + const rows = result.items.map(item => `
+ ${item.success ? '成功' : '失败'} + ${escapeHtml(item.emailAttempted || '未知账号')} + ${escapeHtml(item.method === 'password' ? '密码' : '验证码')} + ${escapeHtml(item.ip || '—')} + ${escapeHtml(summarizeAdminUa(item.userAgent))} +
`).join(''); + if (!more) list.innerHTML = rows || '
暂无登录日志
'; + else list.insertAdjacentHTML('beforeend', rows); + loginLogOffset = result.nextOffset ?? loginLogOffset; + $('#loginLogsMore').hidden = result.nextOffset === null; + } catch (error) { + if (!more) list.innerHTML = `
${escapeHtml(error.message)}
`; + else if (!activeButtons.has($('#loginLogsMore'))) toast(error.message); + return {refreshError:error}; + } +} + +async function loadAuditLogs(more = false) { + const list = $('#auditLogsList'); + if (!more) { + auditLogOffset = 0; + list.innerHTML = '
正在加载操作日志…
'; + } + try { + const params = new URLSearchParams(); + const adminId = $('#auditFilterAdmin').value.trim(); + const action = $('#auditFilterAction').value.trim(); + if (adminId) params.set('admin_id', adminId); + if (action) params.set('action', action); + params.set('offset', String(auditLogOffset)); + const result = await api(`/api/admin/audit-logs?${params}`); + const rows = result.items.map(item => `
+ ${escapeHtml(item.action)}${escapeHtml(item.adminId)} + ${escapeHtml(item.targetUserId || '—')}${escapeHtml(item.detail || '')} + ${escapeHtml(item.ip || '—')}
`).join(''); + if (!more) list.innerHTML = rows || '
暂无操作日志
'; + else list.insertAdjacentHTML('beforeend', rows); + auditLogOffset = result.nextOffset ?? auditLogOffset; + $('#auditLogsMore').hidden = result.nextOffset === null; + } catch (error) { + if (!more) list.innerHTML = `
${escapeHtml(error.message)}
`; + else if (!activeButtons.has($('#auditLogsMore'))) toast(error.message); + return {refreshError:error}; + } +} + +async function loadAdminUsers() { + const list = $('#userList'); + const query = $('#userSearch').value.trim(); + list.innerHTML = '
正在加载用户…
'; + try { + const result = await api(`/api/admin/users?q=${encodeURIComponent(query)}`); + if (!result.items.length) { + list.innerHTML = '
没有匹配的用户
'; + updateBulkSelection(); + return; + } + list.innerHTML = result.items.map(item => `
+ +
${escapeHtml(item.name)} · @${escapeHtml(item.nickname)} +
学号 ${escapeHtml(item.studentId)} · ${escapeHtml(item.school)} · ${escapeHtml(item.email)}
+
+ + +
+
+
信用分 ${item.creditScore}积分余额 ${item.pointsBalance}${statusBadge(item)}
+
+
信用
+
积分
+
`).join(''); + list.querySelectorAll('.adjustment-form').forEach(form => form.onsubmit = event => form.dataset.kind === 'points' ? submitPointsAdjust(event, form) : submitCreditAdjust(event, form)); + list.querySelectorAll('[data-security-user]').forEach(button => button.onclick = () => openAdminUserDetail(button.dataset.securityUser)); + list.querySelectorAll('[data-sanction-user]').forEach(button => button.onclick = () => openSanctionDialog(button.dataset.uid, button.dataset.sanctionUser)); + bindBulkUserSelection(); + } catch (error) { + list.innerHTML = `
${escapeHtml(error.message)}
`; + updateBulkSelection(); + return {refreshError:error}; + } +} + +function openSanctionDialog(userId, action) { + const form = $('#sanctionForm'); + form.reset(); + form.elements.userId.value = userId; + form.elements.action.value = action; + $('[data-sanction-category]').hidden = action === 'lift'; + $('#sanctionCategory').required = action !== 'lift'; + $('[data-sanction-scopes]').hidden = action !== 'restrict'; + $('[data-sanction-duration]').hidden = action === 'lift'; + $('#sanctionTitle').textContent = action === 'ban' ? '封禁账号' : action === 'restrict' ? '限制账号功能' : '解除账号处理'; + showSanctionCustomDays(); + $('#sanctionDialog').showModal(); +} + +function showSanctionCustomDays() { + const custom = $('#sanctionForm').elements.action.value !== 'lift' && $('#sanctionDuration').value === 'custom'; + $('#sanctionCustomDays').hidden = !custom; + $('#sanctionCustomDays').required = custom; +} + +async function submitSanction(event) { + event.preventDefault(); + const form = event.currentTarget; + if (!form.reportValidity()) return; + const action = form.elements.action.value; + const payload = { action, reason: form.elements.reason.value.trim() }; + if (action !== 'lift') { + payload.category = form.elements.category.value; + const duration = $('#sanctionDuration').value; + payload.duration_days = duration === 'custom' ? $('#sanctionCustomDays').value : duration; + } + if (action === 'ban') payload.scope = 'all'; + if (action === 'restrict') { + payload.scopes = [...form.querySelectorAll('input[name="scope"]:checked')].map(input => input.value); + if (!payload.scopes.length) { toast('请至少选择一项限制维度'); return; } + } + const button = $('#sanctionSubmit'); + return withButtonFeedback(button, async () => { + await api(`/api/admin/users/${encodeURIComponent(form.elements.userId.value)}/sanctions`, payload); + $('#sanctionDialog').close(); + toast(action === 'lift' ? '已解除账号处理' : action === 'ban' ? '账号已封禁' : '账号功能已限制'); + await loadAdminUsers(); + }); +} + +function scopeLabel(scope) { return ({ all: '全站', publish: '发单', claim: '接单', withdraw: '提现' })[scope] || scope; } + +async function openAdminUserDetail(userId) { + const body = $('#userDetailBody'); + body.innerHTML = '
正在读取安全信息与处理历史…
'; + $('#userDetailDialog').showModal(); + try { + const [security, sanctions] = await Promise.all([ + api(`/api/admin/users/${encodeURIComponent(userId)}/security`), + api(`/api/admin/users/${encodeURIComponent(userId)}/sanctions`), + ]); + const ips = security.knownIps.length ? security.knownIps.map(item => `${escapeHtml(item.ip)}${adminDate(item.firstSeen)}${adminDate(item.lastSeen)}`).join('') : '暂无已知 IP'; + const activeSessions = security.sessions.length ? security.sessions.map(item => `${escapeHtml(summarizeAdminUa(item.userAgent))}${escapeHtml(item.ip || '—')}${escapeHtml(item.userAgent || '未知设备')}${adminDate(item.createdAt)}`).join('') : '暂无活跃会话'; + const logins = security.loginLogs.length ? security.loginLogs.map(item => `${item.success ? '成功' : '失败'}${escapeHtml(item.emailAttempted || '—')}${escapeHtml(item.method)}${escapeHtml(item.ip || '—')}${escapeHtml(summarizeAdminUa(item.userAgent))}${adminDate(item.createdAt)}`).join('') : '暂无登录记录'; + const history = sanctions.items.length ? sanctions.items.map(item => `${escapeHtml(({ ban: '封禁', restrict: '限制', lift: '解除' })[item.action] || item.action)} · ${escapeHtml(scopeLabel(item.scope))}${item.active ? ' · 生效中' : ''}${item.liftedAt ? ' · 已解除' : ''}${escapeHtml(item.category || '—')}${escapeHtml(item.reason)}${escapeHtml(item.adminName)} · ${adminDate(item.createdAt)}${item.expiresAt ? adminDate(item.expiresAt) : item.action === 'lift' ? '—' : '永久'}${item.liftedAt ? `
解除:${escapeHtml(item.liftedByName || '管理员')} · ${adminDate(item.liftedAt)}` : ''}`).join('') : '暂无制裁处理记录'; + body.innerHTML = `

用户安全信息

+

已知登录 IP

${ips}
IP首次出现最近出现
+

活跃会话

${activeSessions}
设备摘要IP浏览器信息创建时间
+

近期登录记录(最多 20 条)

${logins}
结果邮箱方式IP设备时间
+

账号处理历史

${history}
动作用户可见分类内部理由操作人 / 时间期限与解除
`; + } catch (error) { body.innerHTML = `
${escapeHtml(error.message)}
`; toast(error.message); } +} + +$$('[data-view]').forEach(button => button.onclick = () => switchAdminView(button.dataset.view)); +$$('[data-admin-tab]').forEach(button => button.onclick = () => switchAdminView(button.dataset.adminTab)); +$('#loginLogsRefresh').onclick = () => loadLoginLogs(false); +$('#loginLogsMore').onclick = () => withButtonFeedback($('#loginLogsMore'), () => loadLoginLogs(true), {label:'加载中…'}); +$('#auditLogsRefresh').onclick = () => loadAuditLogs(false); +$('#auditLogsMore').onclick = () => withButtonFeedback($('#auditLogsMore'), () => loadAuditLogs(true), {label:'加载中…'}); +$('#sanctionForm').onsubmit = submitSanction; +$('#sanctionDuration').onchange = showSanctionCustomDays; +$$('[data-sanction-close]').forEach(button => button.onclick = () => $('#sanctionDialog').close()); +$$('[data-detail-close]').forEach(button => button.onclick = () => $('#userDetailDialog').close()); +let adminFilterTimer; +['#loginFilterUser', '#loginFilterIp', '#auditFilterAdmin', '#auditFilterAction'].forEach(selector => $(selector).addEventListener('input', () => { + clearTimeout(adminFilterTimer); + adminFilterTimer = setTimeout(() => { + if (!$('#loginLogsPanel').hidden) showAdminLoadError(loadLoginLogs(false)); + if (!$('#auditLogsPanel').hidden) showAdminLoadError(loadAuditLogs(false)); + }, 350); +})); +$('#loginFilterSuccess').onchange = () => showAdminLoadError(loadLoginLogs(false)); +$('#loginFilterMethod').onchange = () => showAdminLoadError(loadLoginLogs(false)); + +// Bind after extension scripts have replaced loaders; always use current implementations. +const adminRefreshLoaders = { + reportsRefresh: () => loadAdminReports(), + adjustRefresh: () => loadAdjustLog(), + officialTasksRefresh: () => loadOfficialTasks(), + analyticsRefresh: () => loadAnalytics(), + loginLogsRefresh: () => loadLoginLogs(false), + auditLogsRefresh: () => loadAuditLogs(false), +}; +Object.entries(adminRefreshLoaders).forEach(([id, loader]) => { + const button = $(`#${id}`); + button.onclick = () => withRefreshFeedback(button, loader); +}); +$('#loginLogsRefresh').refreshState = { + capture: () => loginLogOffset, restore: value => { loginLogOffset = value; }, +}; +$('#auditLogsRefresh').refreshState = { + capture: () => auditLogOffset, restore: value => { auditLogOffset = value; }, +}; diff --git a/dist/admin-social.js b/dist/admin-social.js new file mode 100644 index 0000000..07c0399 --- /dev/null +++ b/dist/admin-social.js @@ -0,0 +1,154 @@ +let adjustmentReasons = []; +let adjustmentReasonsPromise = null; +async function loadAdjustmentReasons() { + if (!adjustmentReasonsPromise) { + adjustmentReasonsPromise = api('/api/admin/credit-options') + .then(result => { adjustmentReasons = result.items || []; return adjustmentReasons; }) + .catch(error => { adjustmentReasonsPromise = null; throw error; }); + } + return adjustmentReasonsPromise; +} +function reasonOptionHtml() { + return '' + adjustmentReasons.map(item => { + const delta = item.defaultDelta === null ? '按原处罚' : (item.defaultDelta > 0 ? '+' : '') + item.defaultDelta; + return ''; + }).join(''); +} +function findCreditReason(value) { return adjustmentReasons.find(item => item.value === value); } + +const baseLoadAdminUsersV1 = loadAdminUsers; +loadAdminUsers = async function () { + await loadAdjustmentReasons(); + const result = await baseLoadAdminUsersV1(); + if (result?.refreshError) return result; + $$('.adjustment-form[data-kind="credit"]').forEach(form => { + if (form.querySelector('.reason-type-input')) return; + const row = form.closest('[data-uid]'); + const selector = document.createElement('select'); + selector.className = 'reason-type-input'; selector.required = true; + selector.setAttribute('aria-label', '信用调整原因'); selector.innerHTML = reasonOptionHtml(); + const reasonFields = form.querySelector('.adjust-reason-fields'); + reasonFields.prepend(selector); + const delta = form.querySelector('.delta-input'); + delta.value = ''; + delta.setAttribute('aria-label', '调整分值'); + const note = form.querySelector('.reason-input'); + note.placeholder = '核实依据/管理员备注(必填)'; + note.setAttribute('aria-label', '核实依据与管理员备注'); + const task = document.createElement('input'); task.className = 'task-id-input'; task.placeholder = '关联任务 ID'; task.hidden = true; + const invitee = document.createElement('input'); invitee.className = 'invitee-id-input'; invitee.placeholder = '被邀请用户 ID'; invitee.hidden = true; + const reversal = document.createElement('select'); reversal.className = 'reverses-id-input'; reversal.innerHTML = ''; reversal.hidden = true; + const preview = document.createElement('small'); preview.className = 'credit-preview'; + const id = document.createElement('small'); id.className = 'admin-user-id'; id.textContent = '账号 ID:' + row.dataset.uid; + reasonFields.append(task, invitee, reversal); + form.insertBefore(preview, form.querySelector('button')); + row.querySelector('.credit-now').append(id); + const updatePreview = () => { + const current = Number(row.querySelector('.credit-now b')?.textContent || 0); + const amount = Number(delta.value) || 0; + preview.textContent = '调整后信用分:' + Math.max(0, Math.min(100, current + amount)); + }; + const updateReason = async () => { + const spec = findCreditReason(selector.value); + task.hidden = !spec?.taskRequired; task.required = !!spec?.taskRequired; + invitee.hidden = !spec?.inviteeRequired; invitee.required = !!spec?.inviteeRequired; + reversal.hidden = !spec?.reversalRequired; reversal.required = !!spec?.reversalRequired; + delta.value = spec?.defaultDelta === null ? '' : String(spec?.defaultDelta ?? ''); + delta.disabled = spec?.value === 'appeal_upheld' || spec?.value === 'invite_abuse'; + if (spec?.reversalRequired) { + reversal.innerHTML = ''; + try { + const result = await api('/api/admin/credit-adjustments?userId=' + encodeURIComponent(row.dataset.uid)); + const eligible = (result.items || []).filter(item => Number(item.delta) < 0 && !item.reversedAt && !item.reversesId); + reversal.innerHTML = '' + eligible.map(item => + '' + ).join(''); + if (!eligible.length) reversal.innerHTML = ''; + } catch (error) { + reversal.innerHTML = ''; + toast(error.message); + } + } + updatePreview(); + }; + selector.addEventListener('change', updateReason); + delta.addEventListener('input', updatePreview); + }); + const bulkReason = $('#bulkCreditReasonType'); + if (bulkReason) bulkReason.innerHTML = '' + adjustmentReasons.map(item => + '' + ).join(''); +}; +submitCreditAdjust = async function (event, form) { + event.preventDefault(); + const row = form.closest('[data-uid]'); + const spec = findCreditReason(form.querySelector('.reason-type-input')?.value); + const note = form.querySelector('.reason-input').value.trim(); + const delta = Number(form.querySelector('.delta-input').value || 0); + if (!spec) { toast('请选择信用调整原因'); return; } + if (!note) { toast('请填写核实依据或管理员备注'); return; } + const payload = { + reasonType: spec.value, delta, note, + taskId: form.querySelector('.task-id-input').value.trim(), + inviteeId: form.querySelector('.invitee-id-input').value.trim(), + reversesId: form.querySelector('.reverses-id-input').value + }; + const button = form.querySelector('button'); button.disabled = true; + try { + const result = await api('/api/admin/users/' + encodeURIComponent(row.dataset.uid) + '/credit', payload); + toast('已调整 ' + (result.applied > 0 ? '+' : '') + result.applied + ',信用分 ' + result.before + ' → ' + result.creditScore); + await loadAdminUsers(); await loadAdjustLog(); + } catch (error) { toast(error.message); } + finally { button.disabled = false; } +}; +submitBulkCredit = async function () { + const userIds = [...selectedUserIds]; + const delta = Number($('#bulkCreditDelta').value); + const note = $('#bulkCreditReason').value.trim(); + const reasonType = $('#bulkCreditReasonType').value; + if (!userIds.length) { toast('请先选择用户'); return; } + if (!Number.isInteger(delta) || delta === 0 || Math.abs(delta) > 100) { toast('请输入 ±1—100 的整数信用分变动'); return; } + if (reasonType !== 'other') { toast('批量调整仅支持“其他”,有任务或申诉关联的原因请逐人处理'); return; } + if (!note) { toast('请填写批量调整依据与备注'); return; } + const button = $('#bulkCreditBtn'); button.disabled = true; + try { + const result = await api('/api/admin/users/batch-credit', {userIds, delta, reasonType, note}); + toast('已批量调整 ' + result.count + ' 个用户'); + selectedUserIds.clear(); $('#bulkCreditDelta').value = ''; $('#bulkCreditReason').value = ''; + $('#bulkCreditReasonType').value = ''; + await loadAdminUsers(); await loadAdjustLog(); + } catch (error) { toast(error.message); } + finally { button.disabled = false; } +}; +$('#bulkCreditBtn').onclick = submitBulkCredit; + +const previousLoadAdjustLog = loadAdjustLog; +loadAdjustLog = async function () { + const log = $('#adjustLog'); log.innerHTML = '
正在加载记录…
'; + try { + const result = await api('/api/admin/credit-adjustments'); + if (!result.items.length) { log.innerHTML = '
暂无调整记录
'; return; } + log.innerHTML = result.items.map(item => '
' + escapeHtml(item.userName) + ' · @' + escapeHtml(item.userNickname) + '' + (item.delta > 0 ? '+' : '') + item.delta + '' + escapeHtml(item.category || '未分类') + '' + escapeHtml(item.reason) + '' + escapeHtml(item.adminName || '系统') + ' · ' + escapeHtml(new Date(Number(item.createdAt)).toLocaleString('zh-CN')) + (item.reversedAt ? ' · 已撤销' : '') + '
').join(''); + } catch (error) { log.innerHTML = '
' + escapeHtml(error.message) + '
'; return {refreshError:error}; } +}; +const previousLoadAdminReports = loadAdminReports; +loadAdminReports = async function () { + const list = $('#reportsList'); + const status = $$('[data-rstatus]').find(button => button.classList.contains('active'))?.dataset.rstatus || 'open'; + list.innerHTML = '
正在加载举报记录…
'; + const statusText = {open:'待处理', reviewed:'已核实', dismissed:'已驳回'}; + try { + const result = await api(`/api/admin/reports?status=${status}`); + if (!result.items.length) { list.innerHTML = `
暂无${statusText[status]||''}的举报
`; return; } + list.innerHTML = result.items.map(item => { + const isChat = item.targetType === 'chat'; + const title = isChat ? `举报了私聊 · @${item.targetUser?.nickname||'用户'}` : item.task ? `举报了任务「${item.task.title}」` : '举报了已删除的任务'; + const taskInfo = item.task ? `
被举报任务${escapeHtml(item.task.title)}
发布者${escapeHtml(item.task.owner.name)} · ${escapeHtml(item.task.owner.studentId)}
任务状态${escapeHtml(item.task.status)}
任务积分${item.task.reward}
` : ''; + const snapshot = (item.messageSnapshot||[]).length ? `
举报会话 · 最近 ${(item.messageSnapshot||[]).length} 条消息${item.messageSnapshot.map(message => `
${escapeHtml(message.senderId===item.reporter.id?item.reporter.nickname:(item.targetUser?.nickname||'对方'))}${escapeHtml(message.content)}
`).join('')}
` : ''; + const actions = item.status === 'open' ? '
' : ''; + return `

${escapeHtml(item.reporter.name)} · @${escapeHtml(item.reporter.nickname)} ${escapeHtml(title)}

举报人邮箱 ${escapeHtml(item.reporter.email)} · ${new Date(item.createdAt).toLocaleString('zh-CN')}
${statusText[item.status]||escapeHtml(item.status)}
举报理由

${escapeHtml(item.reason)}

${taskInfo}${snapshot}${!item.task&&!isChat?'
任务已被删除
':''}${item.handlingNote?`

处理备注:${escapeHtml(item.handlingNote)}

`:''}${actions}
`; + }).join(''); + list.querySelectorAll('[data-rhandle]').forEach(button => button.onclick = () => handleReport(button)); + } catch (error) { list.innerHTML = `
${escapeHtml(error.message)}
`; return {refreshError:error}; } +}; diff --git a/dist/admin.css b/dist/admin.css new file mode 100644 index 0000000..56efb24 --- /dev/null +++ b/dist/admin.css @@ -0,0 +1,135 @@ +[hidden]{display:none!important}:root{--text:#10231f;--ink:#10231f;--ink2:#19453b;--lime:#dfff46;--bg:#f4f7f4;--white:#fff;--muted:#697a74;--line:#dce4e0;--red:#b84432;--amber:#a26800}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--text);font-family:Manrope,"PingFang SC","Microsoft YaHei",sans-serif}button,input,textarea{font:inherit}button,a{transition:.18s}.admin-shell{min-height:100vh;display:grid;grid-template-columns:260px 1fr}.sidebar{position:sticky;top:0;height:100vh;padding:28px 20px;background:var(--ink);color:white;display:flex;flex-direction:column}.brand{display:flex;align-items:center;gap:12px;color:white;text-decoration:none;font-size:21px}.brand>span,.login-mark{width:42px;height:42px;border-radius:13px;background:var(--lime);color:var(--ink);display:grid;place-items:center;font-weight:900}.side-label{margin:45px 12px 12px;color:#93aaa3;font-size:12px;font-weight:800;letter-spacing:.12em}.side-item{width:100%;display:flex;align-items:center;gap:11px;padding:12px 14px;border:0;border-radius:11px;background:transparent;color:#bfd0cb;text-decoration:none;text-align:left;font-weight:700}.side-item.active{background:#24423b;color:white}.side-item:hover{background:#1c3932}.side-bottom{margin-top:auto;border-top:1px solid #29473f;padding:20px 10px 0;display:flex;flex-direction:column;gap:5px}.side-bottom small,.side-bottom span{color:#93aaa3;font-size:12px}.side-bottom button{margin-top:12px;border:1px solid #46635c;background:transparent;color:white;border-radius:9px;padding:8px}main{min-width:0}.login-view{min-height:100vh;display:grid;place-items:center;padding:24px}.login-card{width:min(440px,100%);background:var(--white);border:1px solid var(--line);border-radius:24px;padding:38px;box-shadow:0 18px 55px rgba(16,35,31,.08)}.login-mark{margin-bottom:24px}.eyebrow{margin:0 0 6px;color:#547168;font-size:12px;font-weight:800;letter-spacing:.13em}.login-card h1,.dashboard h1{margin:0;font-size:30px}.login-card>p:not(.eyebrow),header>div>p:last-child{color:var(--muted);line-height:1.6}.login-card form{margin-top:26px;display:grid;gap:17px}.login-card label{display:grid;gap:8px;font-size:14px;font-weight:750}.login-card input{width:100%;height:46px;border:1px solid var(--line);border-radius:11px;padding:0 13px;outline:none}.login-card input:focus{border-color:var(--ink2);box-shadow:0 0 0 3px rgba(25,69,59,.1)}.code-row{display:grid;grid-template-columns:1fr 118px;gap:8px}.code-row button{border:1px solid var(--ink);border-radius:11px;background:var(--ink);color:white;font-weight:750}.code-row button:disabled{opacity:.5}.primary{border:0;border-radius:11px;background:var(--ink);color:white;padding:13px 18px;font-weight:800}.full{width:100%}.form-error{min-height:20px;margin:0;color:var(--red);font-size:13px}.dashboard{padding:38px 42px}.dashboard header{display:flex;align-items:flex-start;justify-content:space-between;gap:20px}.refresh{border:1px solid var(--line);background:var(--white);border-radius:10px;padding:10px 15px;font-weight:750}.stats-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:14px;margin:28px 0}.stats-grid article{background:var(--white);border:1px solid var(--line);border-radius:17px;padding:20px}.stats-grid span,.stats-grid small{display:block;color:var(--muted);font-size:13px}.stats-grid strong{display:block;margin:8px 0 3px;font-size:31px}.review-panel{background:var(--white);border:1px solid var(--line);border-radius:19px;overflow:hidden}.panel-head{padding:17px 20px;border-bottom:1px solid var(--line);display:flex;justify-content:space-between;align-items:center;gap:18px}.panel-head>a{color:var(--ink2);font-size:13px;font-weight:750}.tabs{display:flex;gap:5px;background:#f0f4f1;padding:4px;border-radius:10px}.tabs button{border:0;background:transparent;border-radius:8px;padding:8px 13px;color:var(--muted);font-weight:750}.tabs button.active{background:var(--white);color:var(--text);box-shadow:0 2px 8px rgba(16,35,31,.08)}.review-list{padding:18px;display:grid;gap:12px}.review-card{border:1px solid var(--line);border-radius:15px;padding:18px}.review-top{display:flex;justify-content:space-between;gap:16px}.review-top h3{margin:0 0 5px;font-size:16px}.review-meta,.review-time{color:var(--muted);font-size:12px}.review-data{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin:15px 0}.data-box{background:#f3f6f4;border-radius:11px;padding:12px}.data-box span{display:block;color:var(--muted);font-size:12px;margin-bottom:5px}.data-box code{font-size:15px;font-weight:800;letter-spacing:.06em}.review-card textarea{width:100%;min-height:72px;border:1px solid var(--line);border-radius:10px;padding:10px;resize:vertical}.review-actions{display:flex;justify-content:flex-end;gap:8px;margin-top:10px}.review-actions button{border:1px solid var(--line);background:var(--white);border-radius:9px;padding:9px 14px;font-weight:750}.review-actions .approve{background:var(--ink);border-color:var(--text);color:white}.status-pill{display:inline-flex;border-radius:999px;padding:5px 9px;font-size:12px;font-weight:750;background:#eef3f1}.status-pill.approved{background:#eaf6df;color:#356217}.status-pill.rejected{background:#fff0ec;color:var(--red)}.review-note{margin:12px 0 0;color:var(--muted);font-size:13px}.loading,.empty{padding:70px 20px;text-align:center;color:var(--muted)}.toast{position:fixed;right:24px;bottom:24px;max-width:340px;background:var(--ink);color:white;border-radius:11px;padding:12px 16px;opacity:0;transform:translateY(10px);pointer-events:none}.toast.show{opacity:1;transform:none}@media(max-width:900px){.admin-shell{grid-template-columns:1fr}.sidebar{position:relative;height:auto;padding:12px 16px;flex-direction:row;flex-wrap:wrap;align-items:center;gap:10px}.side-label{display:none}.side-item{display:inline-flex;width:auto;padding:8px 12px;font-size:13px;border-radius:9px}.side-bottom{display:flex;flex-direction:row;align-items:center;gap:10px;margin:0;border:0;padding:0}.side-bottom small,.side-bottom strong,.side-bottom span{display:none}.side-bottom button{margin:0;padding:8px 12px;font-size:13px}.dashboard{padding:25px 18px}.stats-grid{grid-template-columns:1fr 1fr}}@media(max-width:560px){.login-card{padding:28px 20px}.stats-grid{grid-template-columns:1fr 1fr}.dashboard header,.panel-head,.review-top{flex-direction:column;align-items:stretch}.review-data{grid-template-columns:1fr}.tabs{overflow:auto}.panel-head>a{align-self:flex-start}} + +.panel-note{color:var(--muted);font-size:12px;line-height:1.5}.user-search{display:flex;align-items:center;gap:8px;font-size:13px;font-weight:750;color:var(--muted)}.user-search input{width:230px;max-width:52vw;height:36px;border:1px solid var(--line);border-radius:9px;padding:0 11px;outline:none}.user-search input:focus{border-color:var(--ink2)}.user-list{padding:4px 18px}.user-row{display:flex;flex-wrap:wrap;align-items:center;gap:6px 14px;padding:14px 0;border-bottom:1px solid var(--line)}.user-row:last-child{border-bottom:0}.user-info{flex:1 1 240px;min-width:0}.user-info strong{display:block;font-size:15px;margin-bottom:3px}.credit-now{font-size:12px;color:var(--muted);font-weight:750;text-align:right}.credit-now b{display:block;font-size:19px;color:var(--text)}.credit-form{display:flex;gap:8px;flex:1 1 320px}.credit-form input{height:38px;border:1px solid var(--line);border-radius:9px;padding:0 11px;outline:none}.credit-form input:focus{border-color:var(--ink2)}.delta-input{width:100px}.reason-input{flex:1;min-width:130px}.credit-form button{border:0;border-radius:9px;background:var(--ink);color:white;font-weight:750;padding:0 18px}.credit-form button:disabled{opacity:.5}.log-title{font-size:14px}.adjust-log{padding:14px 18px;display:grid;gap:9px}.log-row{display:flex;flex-wrap:wrap;align-items:baseline;gap:4px 10px;font-size:13px}.log-row .pos{color:#356217;font-weight:800}.log-row .neg{color:var(--red);font-weight:800}.log-row em{margin-left:auto;color:var(--muted);font-style:normal;font-size:12px}@media(max-width:560px){.credit-form{flex-basis:100.panel-note{color:var(--muted);font-size:12px;line-height:1.5}.user-search{display:flex;align-items:center;gap:8px;font-size:13px;font-weight:750;color:var(--muted)}.user-search input{width:230px;max-width:52vw;height:36px;border:1px solid var(--line);border-radius:9px;padding:0 11px;outline:none}.user-search input:focus{border-color:var(--ink2)}.user-list{padding:4px 18px}.user-row{display:flex;flex-wrap:wrap;align-items:center;gap:6px 14px;padding:14px 0;border-bottom:1px solid var(--line)}.user-row:last-child{border-bottom:0}.user-info{flex:1 1 240px;min-width:0}.user-info strong{display:block;font-size:15px;margin-bottom:3px}.credit-now{font-size:12px;color:var(--muted);font-weight:750;text-align:right}.credit-now b{display:block;font-size:19px;color:var(--text)}.credit-form{display:flex;gap:8px;flex:1 1 320px}.credit-form input{height:38px;border:1px solid var(--line);border-radius:9px;padding:0 11px;outline:none}.credit-form input:focus{border-color:var(--ink2)}.delta-input{width:100px}.reason-input{flex:1;min-width:130px}.credit-form button{border:0;border-radius:9px;background:var(--ink);color:white;font-weight:750;padding:0 18px}.credit-form button:disabled{opacity:.5}.log-title{font-size:14px}.adjust-log{padding:14px 18px;display:grid;gap:9px}.log-row{display:flex;flex-wrap:wrap;align-items:baseline;gap:4px 10px;font-size:13px}.log-row .pos{color:#356217;font-weight:800}.log-row .neg{color:var(--red);font-weight:800}.log-row em{margin-left:auto;color:var(--muted);font-style:normal;font-size:12px}@media(max-width:560px){.credit-form{flex-basis:100%;flex-direction:column;align-items:stretch}.delta-input{width:100%}.log-row em{margin-left:0;flex-basis:100%}} +}} +@media(prefers-color-scheme:dark){:root{color-scheme:dark;--text:#e7ede9;--bg:#0e1512;--white:#15201b;--line:#243830;--muted:#8ba39a;--red:#e08a72;--amber:#d9b03c}.login-card input,.login-card textarea,.review-card textarea,.user-search input,.credit-form input{background:#18241f;color:var(--text);border-color:var(--line)}.tabs{background:#1a2723}.tabs button.active{color:var(--text)}.data-box{background:#18241f}.user-row{border-bottom-color:var(--line)}.toast{background:#2a423a}.credit-form button:disabled{opacity:.45}} +@media(prefers-color-scheme:dark){.status-pill.approved{background:#17251a;color:#7fb069}.status-pill.rejected{background:#2b1712;color:#e08a72}} +.status-pill.open{background:#fff0ec;color:var(--red)}.status-pill.reviewed{background:#eaf6df;color:#356217}.status-pill.dismissed{background:#eef3f1;color:var(--muted)}.report-reason{margin:14px 0;padding:12px 14px;background:#fdf0ec;border-radius:11px}.report-reason span{display:block;font-size:12px;font-weight:750;color:var(--red);margin-bottom:4px}.report-reason p{margin:0;font-size:14px} +@media(prefers-color-scheme:dark){.status-pill.open{background:#2b1712;color:#e08a72}.status-pill.reviewed{background:#17251a;color:#7fb069}.status-pill.dismissed{background:#1d2b25;color:var(--muted)}.report-reason{background:#2b1c16}.report-reason p{color:#d8a899}} + .bulk-toolbar{display:flex;align-items:center;gap:9px;flex-wrap:wrap;padding:14px 18px;background:#f3f6f4;border-bottom:1px solid var(--line)}.bulk-toolbar input{height:36px;border:1px solid var(--line);border-radius:9px;padding:0 10px;background:var(--white);color:var(--text)}.bulk-toolbar input[type=number]{width:120px}.bulk-toolbar input[type=text]{flex:1;min-width:180px}.bulk-toolbar button{height:36px;border:0;border-radius:9px;background:var(--ink);color:white;padding:0 14px;font-weight:750}.select-all{display:flex;align-items:center;gap:6px;font-size:13px;font-weight:750}.bulk-toolbar>span{color:var(--muted);font-size:13px}.user-select-wrap{display:flex;align-items:center;justify-content:center;width:24px}.user-select{width:17px;height:17px;accent-color:var(--ink2)}@media(max-width:560px){.bulk-toolbar input[type=text]{min-width:100%;flex-basis:100%}.bulk-toolbar button{width:100%}} +.adjust-actions{display:flex;flex:1 1 100%;flex-direction:column;gap:7px}.adjustment-form{display:flex;align-items:center;gap:8px;flex-basis:auto}.adjustment-form .adjust-label{width:32px;color:var(--muted);font-size:12px;font-weight:800}.points-form button{background:#315d14}.points-form .delta-input{min-width:110px}.points-form .reason-input{min-width:180px}@media(max-width:560px){.adjustment-form{flex-wrap:wrap}.adjustment-form .adjust-label{width:100%}.adjustment-form .delta-input,.adjustment-form .reason-input{width:100%;min-width:0}} +.credit-form{flex-wrap:wrap;align-items:center}.credit-form select,.credit-form input,.credit-form textarea{min-width:130px;flex:1 1 150px;height:38px;border:1px solid var(--line);border-radius:9px;padding:0 10px;background:var(--white);color:var(--text)}.credit-form .delta-input{flex:0 1 100px;min-width:85px}.credit-form [hidden]{display:none!important}.credit-preview,.admin-user-id{flex-basis:100%;color:var(--muted);font-size:11px}.bulk-toolbar select{height:36px;border:1px solid var(--line);border-radius:9px;padding:0 10px;background:var(--white);color:var(--text)} +.account-status{display:inline-flex;margin-top:7px;padding:4px 9px;border-radius:99px;background:#eaf6df;color:#356217;font-size:11px;font-weight:800}.account-status.banned{background:#fff0ec;color:#b84432}.account-status.restricted{background:#fff5df;color:#936300}.user-admin-actions{display:flex;flex-wrap:wrap;gap:6px;margin-top:9px}.user-admin-actions button{border:1px solid var(--line);border-radius:8px;background:var(--white);color:var(--text);padding:6px 9px;font-size:11px;font-weight:750}.user-admin-actions button:hover{border-color:var(--ink2)}.log-filters{display:flex;align-items:center;flex-wrap:wrap;gap:7px}.log-filters input,.log-filters select{height:36px;min-width:100px;max-width:180px;border:1px solid var(--line);border-radius:9px;padding:0 9px;background:var(--white);color:var(--text)}.security-log-table{padding:12px 18px;display:grid;gap:7px;overflow-x:auto}.security-log-row{min-width:800px;display:grid;grid-template-columns:70px 1.1fr 75px 130px 1fr 155px;align-items:center;gap:10px;padding:10px 12px;border:1px solid var(--line);border-radius:10px;font-size:12px}.security-log-row.audit{min-width:920px;grid-template-columns:150px 130px 130px minmax(240px,1fr) 130px 155px}.security-log-row .success{color:#356217;font-weight:800}.security-log-row .failure{color:var(--red);font-weight:800}.security-log-row time{color:var(--muted);white-space:nowrap}.load-more{display:block;margin:0 auto 16px}.admin-modal{max-height:90vh;overflow:auto}.admin-modal form{display:grid;gap:14px}.admin-modal h2{margin:0 42px 16px 0}.sanction-scopes{display:flex;flex-wrap:wrap;gap:12px;border:1px solid var(--line);border-radius:11px;padding:12px}.sanction-scopes legend{padding:0 5px;font-size:13px;font-weight:750}.sanction-scopes label{display:flex;align-items:center;gap:6px;font-size:13px}.sanction-scopes input{accent-color:var(--ink2)}.user-detail-modal{width:min(1060px,calc(100vw - 28px));padding:28px}.user-detail-modal section{margin-top:23px}.user-detail-modal h3{font-size:15px;margin:0 0 9px}.security-table-wrap{width:100%;overflow:auto;border:1px solid var(--line);border-radius:10px}.security-table-wrap table{width:100%;min-width:650px;border-collapse:collapse;font-size:12px}.security-table-wrap th,.security-table-wrap td{padding:9px 10px;text-align:left;vertical-align:top;border-bottom:1px solid var(--line);overflow-wrap:anywhere}.security-table-wrap th{background:#f3f6f4;font-weight:800;white-space:nowrap}.security-table-wrap tr:last-child td{border-bottom:0}.user-detail-modal .modal-close,.admin-modal .modal-close{position:sticky;float:right;top:0;right:0;z-index:4;width:36px;height:36px;border:0;border-radius:50%;background:var(--bg);font-size:22px;cursor:pointer}.admin-modal textarea{width:100%;resize:vertical;border:1px solid var(--line);border-radius:10px;padding:10px;background:var(--white);color:var(--text)} +@media(max-width:850px){.log-filters{width:100%}.log-filters input,.log-filters select{flex:1;max-width:none}.user-admin-actions button{padding:7px}.user-detail-modal{padding:20px}} +@media(prefers-color-scheme:dark){.account-status{background:#17251a;color:#9acb70}.account-status.banned{background:#2b1712;color:#e08a72}.account-status.restricted{background:#2b2410;color:#d9b03c}.security-table-wrap th{background:#18241f}.user-admin-actions button{background:#18241f;color:var(--text)}} +.analytics-panel{margin-top:0}.analytics-toolbar label{display:flex;align-items:center;gap:7px;color:var(--muted);font-size:13px;font-weight:750}.analytics-toolbar select{height:38px;border:1px solid var(--line);border-radius:9px;padding:0 28px 0 10px;background:var(--white);color:var(--text);font:inherit}.analytics-note,.analytics-section-heading p{margin:5px 0 0;color:var(--muted);font-size:12px;line-height:1.5}.analytics-kpis{margin:0;padding:18px 20px 0}.analytics-section{padding:20px;border-top:1px solid var(--line)}.analytics-section-heading{display:flex;align-items:flex-start;justify-content:space-between;gap:14px;margin-bottom:15px}.analytics-section-heading h2{margin:0;font-size:17px}.analytics-section h3{margin:0 0 10px;font-size:14px}.analytics-legend{display:flex;gap:13px;color:var(--muted);font-size:12px}.analytics-legend span{display:flex;align-items:center;gap:6px;white-space:nowrap}.analytics-legend i{width:9px;height:9px;border-radius:3px}.registration-key,.registration-bar{background:#6b7ce5}.task-key,.task-bar{background:#67b88a}.analytics-chart-scroll{width:100%;overflow-x:auto}.analytics-chart{display:grid;grid-auto-columns:minmax(28px,1fr);grid-auto-flow:column;gap:7px;min-width:max(100%,560px);height:178px;padding:8px 2px 0}.analytics-day{display:flex;flex-direction:column;justify-content:flex-end;align-items:center;gap:8px;min-width:0}.analytics-bars{height:145px;width:100%;display:flex;align-items:flex-end;justify-content:center;gap:3px}.analytics-bar{width:min(15px,42%);min-height:0;border-radius:4px 4px 0 0;transition:opacity .15s}.analytics-bar:hover{opacity:.68}.analytics-day time{color:var(--muted);font-size:10px;white-space:nowrap}.analytics-table-wrap{width:100%;overflow-x:auto;border:1px solid var(--line);border-radius:11px}.analytics-table-wrap table{width:100%;min-width:600px;border-collapse:collapse;font-size:12px}.analytics-table-wrap th,.analytics-table-wrap td{padding:10px 12px;text-align:left;border-bottom:1px solid var(--line);white-space:nowrap}.analytics-table-wrap th{background:#f3f6f4;font-weight:800}.analytics-table-wrap tr:last-child td{border-bottom:0}.analytics-table-wrap tr.insufficient{background:#f5f6f5;color:#8b9691}.analytics-table-wrap tr.best-bucket{background:#edf7df;color:#294b21;font-weight:750}.analytics-table-wrap td small{margin-left:5px;color:#8b9691;font-size:10px}.best-tag{display:inline-block;margin-left:5px;color:#477a25;font-size:10px}.analytics-best,.analytics-average{margin:10px 0 0;color:var(--muted);font-size:12px}.analytics-columns{display:grid;grid-template-columns:1fr 1fr;gap:20px}.analytics-columns>div{min-width:0}.analytics-columns .analytics-table-wrap table{min-width:260px}.table-empty{text-align:center!important;color:var(--muted)}.analytics-top{margin:0;padding:0;list-style:none;border:1px solid var(--line);border-radius:11px;overflow:hidden}.analytics-top li{display:flex;justify-content:space-between;gap:12px;padding:10px 12px;border-bottom:1px solid var(--line);font-size:13px}.analytics-top li:last-child{border-bottom:0}.analytics-top li strong{white-space:nowrap}.analytics-top .table-empty{display:block;text-align:center!important}@media(max-width:560px){.analytics-toolbar{display:grid;grid-template-columns:1fr auto;gap:10px}.analytics-toolbar>div{grid-column:1/-1}.analytics-toolbar .refresh{grid-column:1/-1;width:100%}.analytics-kpis{padding:12px}.analytics-section{padding:15px 12px}.analytics-section-heading{flex-direction:column}.analytics-legend{align-self:flex-start}.analytics-columns{grid-template-columns:1fr;gap:22px}.analytics-table-wrap table{min-width:540px}} +@media(prefers-color-scheme:dark){.registration-key,.registration-bar{background:#93a0ff}.task-key,.task-bar{background:#75d19b}.analytics-table-wrap th{background:#18241f}.analytics-table-wrap tr.insufficient{background:#18201c;color:#82928a}.analytics-table-wrap tr.best-bucket{background:#1a2a17;color:#b7e399}.best-tag{color:#b7e399}} +.official-task-form{display:block;padding:0;background:#f3f6f4;border-bottom:1px solid var(--line)}.official-form-group{padding:16px 20px;border-bottom:1px solid var(--line)}.official-form-group h2,.official-list-heading strong{margin:0;font-size:12px;font-weight:800;line-height:1.4}.official-form-group h2{margin-bottom:12px}.official-field-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:13px}.official-field-grid label{display:grid;align-content:start;gap:6px;min-width:0;color:var(--muted);font-size:12px;font-weight:750}.official-task-form input,.official-task-form textarea{width:100%;min-width:0;border:1px solid var(--line);border-radius:9px;padding:10px;background:var(--white);color:var(--text);font:inherit}.official-task-form textarea{resize:vertical}.official-task-form small{color:var(--muted);font-size:11px;font-weight:500;line-height:1.45}.official-field-grid .full{grid-column:1/-1}.official-reward-grid{grid-template-columns:repeat(3,minmax(0,1fr))}.official-input-unit{display:flex;align-items:center;min-width:0;gap:8px}.official-input-unit input{flex:1}.official-input-unit>span{flex:none;color:var(--muted);font-size:12px;font-weight:700}.official-form-actions{display:flex;justify-content:flex-end;padding:14px 20px}.official-form-actions .primary{justify-self:end}.official-list-heading{padding:16px 20px 10px;border-bottom:1px solid var(--line)}.official-task-list{display:grid;gap:10px;padding:18px}.official-admin-card{min-width:0;padding:15px;border:1px solid var(--line);border-radius:12px;background:var(--white)}.official-admin-card h3{display:flex;align-items:center;gap:9px;min-width:0;margin:0;font-size:16px}.official-admin-title{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.official-admin-card .status-pill{flex:none;margin-left:auto}.official-admin-card p{margin:7px 0;color:var(--muted);font-size:12px;line-height:1.5;overflow-wrap:anywhere}.official-admin-meta{display:flex;flex-wrap:wrap;gap:8px 14px;color:var(--muted);font-size:11px}.official-quota{display:grid;gap:6px;margin-top:12px}.official-quota-copy{display:flex;justify-content:space-between;gap:12px;color:var(--muted);font-size:11px;line-height:1.4}.official-quota-copy strong{flex:none;color:var(--text);font-size:11px}.official-quota-track{height:6px;overflow:hidden;border-radius:999px;background:var(--line)}.official-quota-track span{display:block;height:100%;border-radius:inherit;background:var(--ink2)}.official-admin-card .refresh{margin-top:12px}@media(max-width:900px){.official-reward-grid{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(max-width:560px){.official-form-group{padding:14px}.official-field-grid,.official-reward-grid{grid-template-columns:1fr}.official-field-grid .full{grid-column:auto}.official-form-actions{padding:14px}.official-form-actions .primary{width:100%}.official-list-heading{padding:14px 14px 10px}.official-task-list{padding:13px}.official-admin-card h3{align-items:flex-start}.official-admin-card .status-pill{margin-top:1px}} +@media(prefers-color-scheme:dark){.official-task-form{background:#18241f}.official-form-group{border-bottom-color:var(--line)}.official-list-heading{border-bottom-color:var(--line)}.official-input-unit>span,.official-quota-copy{color:var(--muted)}} + +/* Operations analytics dashboard */ +.analytics-panel{overflow:hidden;border-color:#e2e9e5;border-radius:22px;background:#f7f9f7;box-shadow:0 12px 35px rgba(22,48,39,.055)} +.analytics-toolbar{min-height:166px;padding:27px 30px;border:0;background:radial-gradient(circle at 82% 4%,rgba(215,255,96,.16),transparent 27%),linear-gradient(115deg,#102b25 0%,#19483d 62%,#236052 100%);color:#fff} +.analytics-title-group{max-width:620px}.analytics-eyebrow{margin:0 0 8px;color:#c9e9b5;font-size:10px;font-weight:850;letter-spacing:.19em}.analytics-title-group>strong{display:block;font-size:26px;letter-spacing:.01em}.analytics-title-group .analytics-note{max-width:590px;margin-top:8px;color:#c0d4cc;font-size:12px;line-height:1.65} +.analytics-controls{display:flex;align-items:flex-end;gap:9px;flex-shrink:0}.analytics-toolbar label{display:grid;gap:6px;color:#bfd5cb;font-size:11px;font-weight:750}.analytics-toolbar label span{padding-left:3px}.analytics-toolbar select{height:40px;min-width:122px;border:1px solid rgba(255,255,255,.22);border-radius:11px;padding:0 11px;background:rgba(255,255,255,.1);color:#fff;font-weight:750;outline:none}.analytics-toolbar select option{background:#fff;color:#10231f}.analytics-toolbar .refresh{height:40px;border:1px solid rgba(255,255,255,.25);border-radius:11px;background:rgba(255,255,255,.1);color:#fff;font-size:12px;font-weight:800}.analytics-toolbar .refresh:hover{background:rgba(255,255,255,.19);border-color:rgba(255,255,255,.45)} +.analytics-kpis{grid-template-columns:repeat(4,minmax(0,1fr));gap:12px;margin:0;padding:17px 20px 4px}.analytics-kpis article.analytics-kpi{position:relative;min-width:0;overflow:hidden;margin:0;padding:17px 18px 16px;border:1px solid #e5ebe7;border-radius:15px;background:#fff;box-shadow:0 4px 12px rgba(18,44,35,.035)}.analytics-kpi:before{position:absolute;top:0;left:0;width:3px;height:100%;content:"";background:var(--kpi-accent,#317261)}.kpi-registration{--kpi-accent:#6e7de0}.kpi-publish{--kpi-accent:#49a982}.kpi-invite{--kpi-accent:#d5a844}.kpi-claim{--kpi-accent:#418b8a}.analytics-kpi-heading{display:flex;align-items:center;justify-content:space-between;gap:8px;color:#74847d;font-size:12px;font-weight:750}.analytics-kpi-heading i{display:grid;width:32px;height:32px;place-items:center;border-radius:10px;background:color-mix(in srgb,var(--kpi-accent) 11%,white);color:var(--kpi-accent);font-style:normal}.analytics-kpi-heading svg{width:17px;height:17px;fill:none;stroke:currentColor;stroke-linecap:round;stroke-linejoin:round;stroke-width:1.7}.analytics-kpi strong{display:block;margin:10px 0 4px;color:#172e27;font-size:29px;line-height:1.15;letter-spacing:-.035em}.analytics-kpi small{display:block;min-height:18px;color:#87948e;font-size:10px;line-height:1.5} +.analytics-section{margin:14px 20px 0;padding:20px 21px;border:1px solid #e5ebe7;border-radius:16px;background:#fff;box-shadow:0 4px 14px rgba(18,44,35,.03)}.analytics-user-section{margin-bottom:20px}.analytics-section-heading{align-items:center;margin-bottom:16px}.analytics-section-heading h2{color:#19382e;font-size:16px;letter-spacing:-.01em}.analytics-section-heading p{color:#8a9791;font-size:11px}.analytics-section h3{margin-bottom:10px;color:#385247;font-size:12px;font-weight:800} +.analytics-legend{gap:14px;font-size:11px}.analytics-legend span{gap:7px}.analytics-legend i{width:8px;height:8px;border-radius:3px}.registration-key,.registration-bar{background:#7180e8}.task-key,.task-bar{background:#4db287}.analytics-chart-scroll{overflow-x:auto;border:1px solid #edf1ee;border-radius:13px;background:repeating-linear-gradient(to bottom,#fff 0,#fff 38px,#f0f4f1 39px,#fff 40px)}.analytics-chart{height:202px;min-width:max(100%,560px);grid-auto-columns:minmax(34px,1fr);gap:6px;padding:10px 10px 0}.analytics-bars{height:163px;gap:4px;align-items:flex-end}.analytics-bar{width:min(17px,42%);min-height:2px;border-radius:5px 5px 2px 2px;box-shadow:0 2px 5px rgba(20,53,42,.11);transition:filter .15s,transform .15s}.analytics-bar:hover{opacity:1;filter:brightness(.92);transform:translateY(-2px)}.analytics-day time{color:#84928b;font-size:10px;font-weight:700} +.analytics-table-wrap{border-color:#e7ede9;border-radius:12px}.analytics-table-wrap table{min-width:600px;font-size:12px}.analytics-table-wrap th,.analytics-table-wrap td{padding:11px 14px;border-bottom-color:#edf1ee}.analytics-table-wrap th{background:#f5f8f6;color:#75857d;font-size:10px;font-weight:800;letter-spacing:.025em}.analytics-table-wrap tbody tr:not(.best-bucket):not(.insufficient):hover{background:#f8faf8}.analytics-table-wrap tr.insufficient{background:#f7f8f7;color:#a2aca7}.analytics-table-wrap tr.best-bucket{background:#f0f7e8;color:#294b21}.analytics-table-wrap tr:last-child td{border-bottom:0}.analytics-table-wrap td:first-child{font-weight:750}.analytics-table-wrap td small{display:inline-block;margin-left:7px;padding:3px 6px;border-radius:5px;background:#f0f2f1;color:#929d97;font-size:9px}.best-tag{display:inline-block;margin-left:7px;padding:3px 7px;border-radius:99px;background:#dceecb;color:#477a25;font-size:9px;font-weight:850}.analytics-best{margin:12px 0 0;padding:10px 12px;border-radius:10px;background:#f5f8f2;color:#59734d;font-size:11px;line-height:1.5}.analytics-columns{gap:18px}.analytics-average{margin-top:9px;font-size:10px}.analytics-top{counter-reset:publish-rank;border-color:#e7ede9;border-radius:12px}.analytics-top li{align-items:center;min-height:43px;padding:9px 13px;border-bottom-color:#edf1ee;color:#354c41;font-size:12px}.analytics-top li:not(.table-empty):before{display:grid;width:23px;height:23px;flex:0 0 23px;place-items:center;counter-increment:publish-rank;content:counter(publish-rank);border-radius:8px;background:#f1f5f2;color:#72857b;font-size:10px;font-weight:850}.analytics-top li:nth-child(-n+3):not(.table-empty):before{background:#e9f2df;color:#477a25}.analytics-top li span{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.analytics-top li strong{padding:5px 8px;border-radius:8px;background:#f2f6f3;color:#315b4a;font-size:10px}.analytics-top li.table-empty{padding:24px;color:#8a9791} +@media(max-width:900px){.analytics-toolbar{align-items:flex-start}.analytics-controls{align-self:center}.analytics-kpis{grid-template-columns:repeat(2,minmax(0,1fr))}} +@media(max-width:560px){.analytics-toolbar{display:flex;flex-direction:column;align-items:stretch;gap:17px;padding:22px 17px}.analytics-title-group>strong{font-size:23px}.analytics-title-group .analytics-note{max-width:none;font-size:11px}.analytics-controls{width:100%;align-items:flex-end}.analytics-controls label{flex:1}.analytics-toolbar select{width:100%;min-width:0}.analytics-toolbar .refresh{padding:0 12px;white-space:nowrap}.analytics-kpis{grid-template-columns:repeat(2,minmax(0,1fr));gap:8px;padding:12px 10px 0}.analytics-kpis article.analytics-kpi{padding:13px 11px 12px;border-radius:12px}.analytics-kpi-heading{font-size:10px}.analytics-kpi-heading i{width:28px;height:28px}.analytics-kpi-heading svg{width:15px;height:15px}.analytics-kpi strong{margin-top:8px;font-size:24px}.analytics-kpi small{font-size:9px}.analytics-section{margin:10px 10px 0;padding:15px 12px;border-radius:13px}.analytics-user-section{margin-bottom:10px}.analytics-section-heading{align-items:flex-start;gap:8px}.analytics-section-heading h2{font-size:15px}.analytics-section-heading p{font-size:10px}.analytics-legend{font-size:10px}.analytics-chart{min-width:max(100%,520px);height:184px;grid-auto-columns:33px}.analytics-bars{height:147px}.analytics-columns{grid-template-columns:1fr;gap:18px}.analytics-table-wrap table{min-width:520px}.analytics-columns .analytics-table-wrap table{min-width:250px}.analytics-top li{padding:8px 10px}} +@media(prefers-color-scheme:dark){.analytics-panel{border-color:#263a31;background:#101a15}.analytics-toolbar{background:radial-gradient(circle at 82% 4%,rgba(215,255,96,.1),transparent 27%),linear-gradient(115deg,#0e211c 0%,#153a30 62%,#1a493d 100%)}.analytics-kpis article.analytics-kpi,.analytics-section{border-color:#273b32;background:#15221c;box-shadow:none}.analytics-kpi-heading{color:#91a59b}.analytics-kpi-heading i{background:color-mix(in srgb,var(--kpi-accent) 16%,#15221c)}.analytics-kpi strong{color:#e7eee9}.analytics-kpi small{color:#91a198}.analytics-section-heading h2,.analytics-section h3{color:#d9e7df}.analytics-section-heading p{color:#91a198}.analytics-chart-scroll{border-color:#263a31;background:repeating-linear-gradient(to bottom,#14211b 0,#14211b 38px,#1d2a24 39px,#14211b 40px)}.analytics-day time{color:#92a59b}.analytics-table-wrap{border-color:#273b32}.analytics-table-wrap th{background:#1b2a23;color:#9aada3}.analytics-table-wrap th,.analytics-table-wrap td,.analytics-top li{border-bottom-color:#273b32}.analytics-table-wrap tbody tr:not(.best-bucket):not(.insufficient):hover{background:#1a2a22}.analytics-table-wrap tr.insufficient{background:#18231d;color:#82928a}.analytics-table-wrap tr.best-bucket{background:#1b2b1d;color:#c0e6a0}.analytics-table-wrap td small{background:#25312b;color:#9aa69f}.best-tag{background:#293c26;color:#b7e399}.analytics-best{background:#1a2a20;color:#b7cda8}.analytics-top{border-color:#273b32}.analytics-top li{color:#d5e0d9}.analytics-top li:not(.table-empty):before{background:#23332b;color:#a1b5aa}.analytics-top li:nth-child(-n+3):not(.table-empty):before{background:#293c26;color:#b7e399}.analytics-top li strong{background:#23332b;color:#c4d7cc}} +[data-updated]{display:block;min-height:18px;color:var(--muted);font-size:12px;font-weight:400;line-height:1.5;white-space:nowrap} +.admin-group{min-width:0} +.group-heading{margin-bottom:20px;border:1px solid var(--line);border-radius:15px;background:var(--white);gap:14px} +.group-heading>strong{font-size:16px} +.group-heading .tabs{min-width:0} +.group-heading .tabs button{white-space:nowrap} +button[aria-busy="true"]{cursor:wait;opacity:.6;white-space:nowrap} +.user-admin-actions button:disabled{cursor:not-allowed;opacity:.6} +@media(max-width:560px){.group-heading{align-items:stretch;gap:12px;padding:14px}.group-heading .tabs{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:7px}.group-heading .tabs button{min-width:0;padding:9px 7px}} +.refresh-actions{display:flex;align-items:center;justify-content:flex-end;gap:12px;min-width:0} +.refresh-actions a{color:var(--ink2);font-size:13px;font-weight:750;text-decoration:none} +.refresh{white-space:nowrap;flex-shrink:0;color:var(--text);min-width:100px} +.refresh:disabled{cursor:wait;opacity:.6} +.refresh-error{margin:0;padding:12px 20px;color:var(--red);background:var(--bg);font-size:12px;border-bottom:1px solid var(--line);overflow-wrap:anywhere} +.analytics-title-group [data-updated]{color:#c0d4cc;margin-top:8px} + +/* Credit management: reuse panel headings, surfaces, pills and control styles. */ +#creditPanel .credit-panel-heading{align-items:center} +#creditPanel .credit-panel-heading strong{font-size:16px} +#creditPanel .panel-note{margin:6px 0 0} +#creditPanel .user-search{display:grid;gap:6px;font-size:12px} +#creditPanel .user-search input{width:280px;max-width:100%;height:38px;background:var(--white);color:var(--text)} +#creditPanel .credit-bulk-toolbar{display:grid;gap:14px;padding:18px 20px;background:#f3f6f4} +#creditPanel .bulk-selection{display:flex;align-items:center;flex-wrap:wrap;gap:10px 18px} +#creditPanel .bulk-selection>strong{font-size:13px;margin-right:auto} +#creditPanel #selectedUserCount{color:var(--text);font-size:12px;font-weight:800;white-space:nowrap} +#creditPanel .bulk-fields{display:grid;grid-template-columns:120px minmax(0,1fr) minmax(0,1.5fr);align-items:end;gap:10px} +#creditPanel .bulk-fields label{display:grid;gap:7px;min-width:0;font-size:12px;color:var(--muted);font-weight:750} +#creditPanel .bulk-fields input,#creditPanel .bulk-fields select{width:100%;min-width:0;height:38px} +#creditPanel .bulk-fields button{grid-column:1/-1;justify-self:end;min-height:38px;height:auto;white-space:nowrap;border-radius:11px;padding:10px 15px} +#creditPanel .user-list{display:grid;gap:14px;padding:20px} +#creditPanel .user-row{display:grid;grid-template-columns:24px minmax(0,1fr) auto;gap:16px;padding:18px;border:1px solid var(--line);border-radius:15px;background:var(--white);align-items:start} +#creditPanel .user-select-wrap{padding-top:3px} +#creditPanel .user-info{min-width:0} +#creditPanel .user-info strong{font-size:16px;margin-bottom:6px;overflow-wrap:anywhere} +#creditPanel .review-meta{line-height:1.5;overflow-wrap:anywhere} +#creditPanel .credit-now{display:grid;justify-items:end;gap:6px;min-width:130px;line-height:1.5} +#creditPanel .credit-score{display:flex;align-items:baseline;justify-content:flex-end;gap:8px} +#creditPanel .credit-now b{font-size:26px;line-height:1.2} +#creditPanel .credit-now small{font-size:12px} +#creditPanel .account-status{margin:0;padding:5px 9px;border-radius:999px;font-size:12px;font-weight:750;background:#eef3f1;color:var(--muted);border:1px solid transparent} +#creditPanel .account-status.banned{background:#fff0ec;color:var(--red)} +#creditPanel .account-status.restricted{background:var(--bg);color:var(--text);border-color:var(--line)} +#creditPanel .admin-user-id{overflow-wrap:anywhere;max-width:200px;font-weight:400} +#creditPanel .user-admin-actions{gap:7px;margin-top:12px} +#creditPanel .user-admin-actions button{padding:7px 10px} +#creditPanel .adjust-actions{grid-column:1/-1;display:grid;grid-template-columns:minmax(0,1fr);gap:12px;border-top:1px solid var(--line);padding-top:16px;min-width:0} +#creditPanel .adjustment-form{display:grid;grid-template-columns:32px 100px minmax(0,1fr) 100px;gap:8px;min-width:0;flex-basis:auto;padding:12px;background:var(--bg);border-radius:11px;align-items:start} +#creditPanel .adjustment-form .adjust-label{grid-column:1;grid-row:1;width:auto;font-size:12px;color:var(--text);line-height:38px} +#creditPanel .adjustment-form select,#creditPanel .adjustment-form input{width:100%;min-width:0;height:38px;font-size:12px} +#creditPanel .adjustment-form .delta-input{grid-column:2;grid-row:1} +#creditPanel .adjust-reason-fields{grid-column:3;grid-row:1;display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:8px;min-width:0} +#creditPanel .points-form .adjust-reason-fields{grid-template-columns:minmax(0,1fr)} +#creditPanel .task-id-input,#creditPanel .invitee-id-input,#creditPanel .reverses-id-input{grid-column:1/-1} +#creditPanel .adjustment-form button{grid-column:4;grid-row:1;height:38px;padding:0 15px;min-width:0;white-space:nowrap} +#creditPanel .adjustment-form .primary{background:var(--ink);color:white;border:0;border-radius:11px;font-weight:800} +#creditPanel .adjustment-form .refresh{background:var(--white);color:var(--text);border:1px solid var(--line);border-radius:10px;font-weight:750} +#creditPanel .credit-preview{grid-column:3/-1;font-size:11px;line-height:1.5} +#creditPanel .credit-preview:empty{display:none} +#creditPanel .adjust-log{padding:18px 20px;gap:0} +#creditPanel .log-row{display:grid;grid-template-columns:minmax(0,1fr) 50px 90px minmax(0,1.5fr) minmax(0,1fr);align-items:baseline;padding:12px;border-bottom:1px solid var(--line);line-height:1.5;gap:10px} +#creditPanel .log-row:nth-child(even){background:#f3f6f4} +#creditPanel .log-row>*{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +#creditPanel .log-row:last-child{border-bottom:0} +#creditPanel .log-row em{margin:0;text-align:right} +#creditPanel .log-category{padding:3px 9px;border-radius:999px;background:var(--bg);font-size:11px;color:var(--muted)} +#creditPanel input:focus-visible,#creditPanel select:focus-visible{outline:2px solid var(--ink2);outline-offset:2px} +@media(max-width:900px){ + #creditPanel .bulk-fields{grid-template-columns:120px minmax(0,1fr)} + #creditPanel .bulk-fields .bulk-note{grid-column:1/-1} + #creditPanel .user-info{grid-column:2/-1} + #creditPanel .credit-now{grid-column:2/-1;justify-items:start;text-align:left;min-width:0} + #creditPanel .credit-score{justify-content:flex-start} + #creditPanel .adjust-actions{grid-template-columns:minmax(0,1fr)} + #creditPanel .log-row{grid-template-columns:minmax(0,1fr) 50px 90px minmax(0,1.5fr)} + #creditPanel .log-row em{grid-column:1/-1;text-align:left} +} +@media(max-width:560px){ + .refresh-actions{justify-content:space-between;gap:8px} + #reviewHeader .refresh-actions{justify-content:flex-end} + #creditPanel .credit-panel-heading{align-items:stretch;gap:14px} + #creditPanel .user-search input{width:100%} + #creditPanel .credit-bulk-toolbar{padding:14px} + #creditPanel .bulk-selection>strong{flex-basis:100%;margin:0} + #creditPanel .bulk-fields{grid-template-columns:minmax(0,1fr)} + #creditPanel .bulk-fields button{width:100%;justify-self:stretch} + #creditPanel .user-list{padding:14px;gap:12px} + #creditPanel .user-row{grid-template-columns:24px minmax(0,1fr);padding:14px;gap:10px} + #creditPanel .admin-user-id{max-width:100%} + #creditPanel .adjustment-form{grid-template-columns:minmax(0,1fr);padding:10px} + #creditPanel .adjustment-form .adjust-label,#creditPanel .adjustment-form .delta-input,#creditPanel .adjustment-form .adjust-reason-fields,#creditPanel .adjustment-form .credit-preview,#creditPanel .adjustment-form button{grid-column:1/-1;grid-row:auto} + #creditPanel .adjustment-form .adjust-reason-fields{grid-template-columns:minmax(0,1fr)} + #creditPanel .adjustment-form .adjust-label{line-height:1.5} + #creditPanel .adjustment-form button{width:100%} + #creditPanel .adjust-log{padding:14px} + #creditPanel .log-row{grid-template-columns:minmax(0,1fr) 50px;gap:8px} + #creditPanel .log-row .log-category,#creditPanel .log-row>span:not(.pos):not(.neg):not(.log-category),#creditPanel .log-row em{grid-column:1/-1} +} +@media(prefers-color-scheme:dark){ + #creditPanel .credit-bulk-toolbar,#creditPanel .log-row:nth-child(even){background:#18241f} + #creditPanel .account-status{background:#1d2b25;color:var(--muted)} + #creditPanel .account-status.banned{background:#2b1712;color:var(--red)} + #creditPanel .account-status.restricted{background:var(--bg);color:var(--text);border-color:var(--line)} +} diff --git a/dist/admin.html b/dist/admin.html new file mode 100644 index 0000000..6875b12 --- /dev/null +++ b/dist/admin.html @@ -0,0 +1,160 @@ + + + + + + + LinkUp 管理端 + + + + + + +
+ + +
+ + + +
+
+
+ + +

账号处理

+
+
限制功能(可多选)
+
+
+

面向用户只展示原因分类;内部理由不会出现在被处理账号可见的通知或登录响应中。

+
+
+
+ + + + + + diff --git a/dist/admin.js b/dist/admin.js new file mode 100644 index 0000000..4bd62d4 --- /dev/null +++ b/dist/admin.js @@ -0,0 +1,138 @@ +const API_BASE=window.LINKUP_API_BASE||''; +const $=selector=>document.querySelector(selector),$$=selector=>[...document.querySelectorAll(selector)]; +const token=()=>localStorage.getItem('linkup_session')||''; +const escapeHtml=value=>String(value??'').replace(/[&<>'"]/g,char=>({'&':'&','<':'<','>':'>',"'":''','"':'"'}[char])); +let currentStatus='pending';let toastTimer; +// Feedback is separate from loaders: keep their loading/empty/error rendering. +const refreshTargets = { + refreshBtn: '#pendingCount,#approvedCount,#rejectedCount,#userCount,#reviewList', + reportsRefresh: '#reportsList', + adjustRefresh: '#adjustLog', + officialTasksRefresh: '#officialTaskList', + analyticsRefresh: '#analyticsTodayRegistrations,#analyticsInviteRatio,#analyticsTodayTasks,#analyticsTodayTaskTypes,#analyticsTodayInvites,#analyticsAvgClaim,#analyticsMedianClaim,#analyticsTrend,#analyticsPriceBuckets,#analyticsBestBucket,#analyticsDistribution,#analyticsAvgPublished,#analyticsTopPublishers', + loginLogsRefresh: '#loginLogsList', + auditLogsRefresh: '#auditLogsList', +}; +const activeRefreshes = new WeakSet(); +async function showAdminLoadError(request) { + try { const result = await request; if (result?.refreshError) throw result.refreshError; return result; } + catch (error) { toast(error.message); return {feedbackError:error}; } +} +const activeButtons = new WeakSet(); +async function withButtonFeedback(button, asyncFn, options = {}) { + if (!button || button.disabled || activeButtons.has(button)) return; + activeButtons.add(button); + const original = {nodes:[...button.childNodes], width:button.style.width, height:button.style.height}; + const size = button.getBoundingClientRect(); + button.style.width = `${size.width}px`; button.style.height = `${size.height}px`; + button.disabled = true; button.setAttribute('aria-busy', 'true'); + button.textContent = options.label || '处理中…'; + try { + const result = await asyncFn(); + if (result?.refreshError) throw result.refreshError; + return result; + } catch (error) { + options.onError?.(error); + if (options.toastError !== false) toast(error.message); + return {feedbackError:error}; + } finally { + button.replaceChildren(...original.nodes); + button.style.width = original.width; button.style.height = original.height; + activeButtons.delete(button); button.removeAttribute('aria-busy'); + button.disabled = options.disabledAfter?.() || false; + } +} +async function withRefreshFeedback(button, loaderFn) { + if (!button || button.disabled || activeRefreshes.has(button)) return; + activeRefreshes.add(button); + const head = button.closest('.panel-head') || $('#reviewPanel .panel-head'); + const updated = $$(`[data-updated="${button.id}"]`); + const previousError = head.parentElement.querySelector(`[data-refresh-error="${button.id}"]`); + previousError?.remove(); + // Keep original nodes, not HTML strings, so restored cards retain their handlers. + const previous = $$(refreshTargets[button.id]).map(element => ({ + element, nodes: [...element.childNodes], + usable: !element.querySelector('.loading') && element.textContent.trim() !== '' && !element.textContent.trim().startsWith('正在加载'), + })); + const savedState = button.refreshState?.capture(); + return withButtonFeedback(button, async () => { + try { + const result = await loaderFn(); + if (result?.refreshError) throw result.refreshError; + if (updated.length) { + const now = new Date(); + updated.forEach(note => { + note.textContent = `更新于 ${[now.getHours(), now.getMinutes(), now.getSeconds()].map(value => String(value).padStart(2, '0')).join(':')}`; + note.dateTime = now.toISOString(); + }); + } + } catch (error) { + previous.filter(item => item.usable).forEach(({ element, nodes }) => element.replaceChildren(...nodes)); + button.refreshState?.restore(savedState); + const notice = document.createElement('p'); + notice.className = 'refresh-error'; + notice.dataset.refreshError = button.id; + notice.setAttribute('role', 'alert'); + notice.textContent = error.message; + head.insertAdjacentElement('afterend', notice); + throw error; + } finally { + activeRefreshes.delete(button); + } + }, {label:'刷新中…'}); +} +function toast(message){clearTimeout(toastTimer);$('#adminToast').textContent=message;$('#adminToast').classList.add('show');toastTimer=setTimeout(()=>$('#adminToast').classList.remove('show'),2500)} +async function api(path,payload=null,auth=true){const headers={'Content-Type':'application/json'};if(auth&&token())headers.Authorization=`Bearer ${token()}`;let response;try{response=await fetch(`${API_BASE}${path}`,{method:payload?'POST':'GET',headers,...(payload?{body:JSON.stringify(payload)}:{})})}catch{throw new Error('无法连接管理服务')}let data={};try{data=await response.json()}catch{}if(!response.ok)throw new Error(data.error||'请求失败');return data} +function showLogin(message=''){$('#loginView').hidden=false;$('#dashboard').hidden=true;$('#logoutBtn').hidden=true;$('#loginError').textContent=message} +function showDashboard(user){$('#loginView').hidden=true;$('#dashboard').hidden=false;$('#logoutBtn').hidden=false;$('#adminName').textContent=user.name;$('#adminEmail').textContent=user.email;loadedAdminViews.clear();switchAdminView('review-center')} +async function checkAccess(){if(!token())return showLogin();try{const result=await api('/api/auth/me');if(!result.user.isAdmin)return showLogin('当前账号没有管理权限,请使用管理员邮箱登录');showDashboard(result.user)}catch{showLogin()}} +async function sendCode(){ + const email=$('#adminLoginEmail');if(!email.reportValidity())return;const button=$('#sendAdminCode'); + const sent=await withButtonFeedback(button,async()=>{ + await api('/api/auth/send-login-code',{email:email.value},false);toast('验证码已发送');return true; + },{label:'发送中…',onError:error=>{$('#loginError').textContent=error.message}}); + if(!sent||sent.feedbackError)return; + let seconds=60;button.disabled=true;button.textContent=`${seconds}s`; + const timer=setInterval(()=>{seconds-=1;if(seconds<=0){clearInterval(timer);button.disabled=false;button.textContent='获取验证码'}else button.textContent=`${seconds}s`},1000); +} +async function login(event){ + event.preventDefault();const form=event.currentTarget;if(!form.reportValidity())return;$('#loginError').textContent=''; + return withButtonFeedback($('#adminLoginSubmit'),async()=>{ + const result=await api('/api/auth/login',Object.fromEntries(new FormData(form)),false); + if(!result.user.isAdmin){await fetch(`${API_BASE}/api/auth/logout`,{method:'POST',headers:{'Content-Type':'application/json','Authorization':`Bearer ${result.token}`}});throw new Error('该账号没有管理权限')} + localStorage.setItem('linkup_session',result.token);localStorage.setItem('linkup_profile',JSON.stringify(result.user));showDashboard(result.user);form.reset(); + },{label:'正在登录…',onError:error=>{$('#loginError').textContent=error.message}}); +} +async function loadOverview(){const result=await api('/api/admin/overview');$('#pendingCount').textContent=result.stats.pending;$('#approvedCount').textContent=result.stats.approved;$('#rejectedCount').textContent=result.stats.rejected;$('#userCount').textContent=result.stats.totalUsers} +const analyticsNumber=value=>Number(value||0).toLocaleString('zh-CN',{maximumFractionDigits:2}); +async function loadAnalytics(){const days=Number($('#analyticsDays').value||7);try{const result=await api(`/api/admin/analytics?days=${days}`);const registrations=result.registrations;const tasks=result.tasks;const todayTasks=tasks.today;const inviteToday=registrations.todayViaInvite||0;$('#analyticsTodayRegistrations').textContent=analyticsNumber(registrations.today);$('#analyticsInviteRatio').textContent=`累计邀请注册 ${analyticsNumber(registrations.inviteTotal)},邀请占比 ${(registrations.inviteRatio*100).toFixed(1)}%`; +$('#analyticsTodayTasks').textContent=analyticsNumber(todayTasks.total);$('#analyticsTodayTaskTypes').textContent=`代取 ${analyticsNumber(todayTasks.errand)} · 组队 ${analyticsNumber(todayTasks.partner)}`;$('#analyticsTodayInvites').textContent=analyticsNumber(inviteToday);$('#analyticsAvgClaim').textContent=`${analyticsNumber(tasks.avgClaimMinutes)} 分钟`; +$('#analyticsMedianClaim').textContent=`中位数 ${analyticsNumber(tasks.medianClaimMinutes)} 分钟`; +const daysData=registrations.byDay.map(item=>({date:item.date,registrations:item.count,tasks:tasks.byDay.find(task=>task.date===item.date)?.total||0}));const maxValue=Math.max(1,...daysData.flatMap(item=>[item.registrations,item.tasks]));$('#analyticsTrend').innerHTML=daysData.map(item=>{const regHeight=item.registrations?Math.max(3,item.registrations/maxValue*100):0;const taskHeight=item.tasks?Math.max(3,item.tasks/maxValue*100):0;return `
`}).join(''); +$('#analyticsPriceBuckets').innerHTML=tasks.priceBuckets.map(bucket=>`${escapeHtml(bucket.label)} ${bucket.insufficient?'样本不足':''} ${tasks.bestBucket?.label===bucket.label?'最易被接取':''}${analyticsNumber(bucket.published)}${analyticsNumber(bucket.claimed)}${(bucket.claimRate*100).toFixed(1)}%${analyticsNumber(bucket.avgClaimMinutes)} 分钟`).join('')||'暂无悬赏任务'; +$('#analyticsBestBucket').textContent=tasks.bestBucket?`最易被接取:${tasks.bestBucket.label} 积分,平均 ${analyticsNumber(tasks.bestBucket.avgClaimMinutes)} 分钟接单,接单率 ${(tasks.bestBucket.claimRate*100).toFixed(1)}%。`:'暂无达到 5 个发布样本且已被接取的悬赏区间,暂不标注最易被接取档。'; +$('#analyticsDistribution').innerHTML=result.perUser.distribution.map(item=>`${item.label==='10+'?'10+(超过 10 个)':`${escapeHtml(item.label)} 个`}${analyticsNumber(item.userCount)}`).join('')||'暂无发布记录'; +$('#analyticsAvgPublished').textContent=`平均每位发布者 ${analyticsNumber(result.perUser.avgPublished)} 个任务(${analyticsNumber(result.perUser.publisherCount)} 位发布者)`; +$('#analyticsTopPublishers').innerHTML=result.perUser.topPublishers.length?result.perUser.topPublishers.map(item=>`
  • ${escapeHtml(item.nickname)}${analyticsNumber(item.count)} 个
  • `).join(''):'
  • 暂无发布记录
  • '; +}catch(error){$('#analyticsTrend').innerHTML=`
    ${escapeHtml(error.message)}
    `;$('#analyticsPriceBuckets').innerHTML=`${escapeHtml(error.message)}`;$('#analyticsDistribution').innerHTML=`${escapeHtml(error.message)}`;$('#analyticsTopPublishers').innerHTML=`
  • ${escapeHtml(error.message)}
  • `;$('#analyticsBestBucket').textContent='';if(!activeRefreshes.has($('#analyticsRefresh')))toast(error.message);return {refreshError:error}}} +function statusText(status){return {pending:'待审核',approved:'已通过',rejected:'已驳回'}[status]||status} +async function loadList(){const list=$('#reviewList');list.innerHTML='
    正在加载认证申请…
    ';try{const result=await api(`/api/admin/student-verifications?status=${currentStatus}`);if(!result.items.length){list.innerHTML=`
    暂无${statusText(currentStatus)}申请
    `;return}list.innerHTML=result.items.map(item=>`

    ${escapeHtml(item.name)} · ${escapeHtml(item.school)}

    学号 ${escapeHtml(item.studentId)} · ${escapeHtml(item.email)}
    ${statusText(item.status)}
    ${new Date(item.submittedAt).toLocaleString('zh-CN')}
    学信网在线验证码${escapeHtml(item.onlineCode)}
    报告有效期${escapeHtml(item.reportExpiresOn)}
    ${item.status==='pending'?'
    ':`

    审核备注:${escapeHtml(item.reviewNote||'无')}

    `}
    `).join('');$$('[data-decision]').forEach(button=>button.onclick=()=>review(button))}catch(error){list.innerHTML=`
    ${escapeHtml(error.message)}
    `;return {refreshError:error}}} +async function refreshAll(){return withRefreshFeedback($('#refreshBtn'),async()=>{const results=await Promise.all([loadOverview(),loadList()].map(request=>request.catch(error=>({refreshError:error}))));return results.find(result=>result?.refreshError)})} +async function review(button){const card=button.closest('[data-id]');const decision=button.dataset.decision;const note=card.querySelector('textarea').value.trim();if(decision==='rejected'&&!note){toast('驳回时请填写原因');return}card.querySelectorAll('button').forEach(item=>item.disabled=true);try{await api(`/api/admin/student-verifications/${card.dataset.id}/review`,{decision,note});toast(decision==='approved'?'认证已通过':'申请已驳回');await refreshAll()}catch(error){card.querySelectorAll('button').forEach(item=>item.disabled=false);toast(error.message)}} +function logout(){localStorage.removeItem('linkup_session');localStorage.removeItem('linkup_profile');showLogin()} +function switchAdminView(view){$$('[data-view]').forEach(b=>b.classList.toggle('active',b.dataset.view===view));$('#reviewPanel').hidden=view!=='reviews';$('#creditPanel').hidden=view!=='credit';$('#reportsPanel').hidden=view!=='reports';if(view==='credit'){loadAdminUsers();loadAdjustLog()}if(view==='reports')loadAdminReports()} +async function loadAdminReports(){const list=$('#reportsList');const status=$$('[data-rstatus]').find(b=>b.classList.contains('active'))?.dataset.rstatus||'open';list.innerHTML='
    正在加载举报记录…
    ';try{const result=await api(`/api/admin/reports?status=${status}`);if(!result.items.length){list.innerHTML=`
    暂无${{open:'待处理',reviewed:'已核实',dismissed:'已驳回'}[status]||''}的举报
    `;return}list.innerHTML=result.items.map(item=>`

    ${escapeHtml(item.reporter.name)} · @${escapeHtml(item.reporter.nickname)} 举报了任务

    举报人邮箱 ${escapeHtml(item.reporter.email)} · ${new Date(item.createdAt).toLocaleString('zh-CN')}
    ${{open:'待处理',reviewed:'已核实',dismissed:'已驳回'}[item.status]||item.status}
    举报理由

    ${escapeHtml(item.reason)}

    ${item.task?`
    被举报任务${escapeHtml(item.task.title)}
    发布者${escapeHtml(item.task.owner.name)} · ${escapeHtml(item.task.owner.studentId)}
    任务状态${escapeHtml(item.task.status)}
    任务积分${item.task.reward}
    `:'
    任务已被删除
    '}${item.handlingNote?`

    处理备注:${escapeHtml(item.handlingNote)}

    `:''}${item.status==='open'&&item.task?`
    `:item.status==='open'?'
    ':''}
    `).join('');list.querySelectorAll('[data-rhandle]').forEach(button=>button.onclick=()=>handleReport(button))}catch(error){list.innerHTML=`
    ${escapeHtml(error.message)}
    `;return {refreshError:error}}} +async function handleReport(button){const card=button.closest('[data-rid]');const decision=button.dataset.rhandle;const note=card.querySelector('textarea')?.value.trim()||'';card.querySelectorAll('button,textarea').forEach(el=>el.disabled=true);try{await api(`/api/admin/reports/${card.dataset.rid}/handle`,{decision,note});toast(decision==='reviewed'?'已标记为核实违规':'已驳回该举报');loadAdminReports();loadOverview()}catch(error){toast(error.message);card.querySelectorAll('button,textarea').forEach(el=>el.disabled=false)}} +let rptStatus='open'; +async function submitCreditAdjust(event,form){event.preventDefault();const row=form.closest('[data-uid]');const delta=Number(form.querySelector('.delta-input').value);const reason=form.querySelector('.reason-input').value.trim();const button=form.querySelector('button');button.disabled=true;try{const result=await api(`/api/admin/users/${row.dataset.uid}/credit`,{delta,reason});const extra=result.inviter?`,其邀请人信用 ${result.inviter.delta>0?'+':''}${result.inviter.delta}`:'';toast(`已调整 ${result.applied>0?'+':''}${result.applied},当前信用 ${result.creditScore}${extra}`);form.reset();loadAdminUsers();loadAdjustLog()}catch(error){toast(error.message)}finally{button.disabled=false}} +async function loadAdjustLog(){const log=$('#adjustLog');log.innerHTML='
    正在加载记录…
    ';try{const result=await api('/api/admin/credit-adjustments');if(!result.items.length){log.innerHTML='
    暂无调整记录
    ';return}log.innerHTML=result.items.map(item=>`
    ${escapeHtml(item.userName)} · @${escapeHtml(item.userNickname)}${item.delta>0?'+':''}${item.delta}${escapeHtml(item.reason)}${escapeHtml(item.adminName)} · ${new Date(item.createdAt).toLocaleString('zh-CN')}
    `).join('')}catch(error){log.innerHTML=`
    ${escapeHtml(error.message)}
    `;return {refreshError:error}}} +$('#sendAdminCode').onclick=sendCode;$('#adminLoginForm').onsubmit=login;$('#refreshBtn').onclick=refreshAll;$('#logoutBtn').onclick=logout;$$('[data-status]').forEach(button=>button.onclick=()=>{currentStatus=button.dataset.status;$$('[data-status]').forEach(item=>item.classList.toggle('active',item===button));showAdminLoadError(loadList())});$$('[data-rstatus]').forEach(button=>button.onclick=()=>{rptStatus=button.dataset.rstatus;$$('[data-rstatus]').forEach(item=>item.classList.toggle('active',item===button));showAdminLoadError(loadAdminReports())});$('#reportsRefresh').onclick=loadAdminReports;$('#analyticsDays').onchange=()=>showAdminLoadError(loadAnalytics());$('#analyticsRefresh').onclick=loadAnalytics;let userSearchTimer;$('#userSearch').addEventListener('input',()=>{clearTimeout(userSearchTimer);userSearchTimer=setTimeout(()=>loadAdminUsers().then(result=>{if(result?.refreshError)toast(result.refreshError.message)}).catch(error=>toast(error.message)),250)});$('#adjustRefresh').onclick=loadAdjustLog;checkAccess(); +const selectedUserIds=new Set();function updateBulkSelection(){const count=$$('.user-select:checked').length;$('#selectedUserCount').textContent=`已选 ${count} 人`;const visible=$$('.user-select');$('#selectAllUsers').checked=visible.length>0&&visible.every(input=>input.checked)}function bindBulkUserSelection(){ $$('.user-select').forEach(input=>input.onchange=()=>{if(input.checked)selectedUserIds.add(input.dataset.userId);else selectedUserIds.delete(input.dataset.userId);updateBulkSelection()});updateBulkSelection() }async function loadAdminUsers(){const list=$('#userList');const q=$('#userSearch').value.trim();list.innerHTML='
    正在加载用户…
    ';try{const result=await api(`/api/admin/users?q=${encodeURIComponent(q)}`);if(!result.items.length){list.innerHTML='
    没有匹配的用户
    ';updateBulkSelection();return}list.innerHTML=result.items.map(item=>`
    ${escapeHtml(item.name)} · @${escapeHtml(item.nickname)}
    学号 ${escapeHtml(item.studentId)} · ${escapeHtml(item.school)} · ${escapeHtml(item.email)}
    信用 ${item.creditScore}积分 ${item.pointsBalance}
    `).join('');list.querySelectorAll('.credit-form').forEach(form=>form.onsubmit=event=>submitCreditAdjust(event,form));bindBulkUserSelection()}catch(error){list.innerHTML=`
    ${escapeHtml(error.message)}
    `;updateBulkSelection()}}async function submitBulkCredit(){const userIds=[...selectedUserIds];const delta=Number($('#bulkCreditDelta').value);const reason=$('#bulkCreditReason').value.trim();if(!userIds.length){toast('请先选择用户');return}if(!Number.isInteger(delta)||delta===0||Math.abs(delta)>100){toast('请输入 ±1—100 的整数信用分变动');return}if(!reason){toast('请填写批量调整原因');return}const button=$('#bulkCreditBtn');button.disabled=true;try{const result=await api('/api/admin/users/batch-credit',{userIds,delta,reason});toast(`已批量调整 ${result.count} 个用户`);selectedUserIds.clear();$('#bulkCreditDelta').value='';$('#bulkCreditReason').value='';await loadAdminUsers();await loadAdjustLog()}catch(error){toast(error.message)}finally{button.disabled=false}}$('#selectAllUsers').onchange=()=>{$$('.user-select').forEach(input=>{input.checked=$('#selectAllUsers').checked;if(input.checked)selectedUserIds.add(input.dataset.userId);else selectedUserIds.delete(input.dataset.userId)});updateBulkSelection()};$('#bulkCreditBtn').onclick=submitBulkCredit; + +async function submitPointsAdjust(event,form){event.preventDefault();const row=form.closest('[data-uid]');const delta=Number(form.querySelector('.delta-input').value);const reason=form.querySelector('.reason-input').value.trim();const button=form.querySelector('button');if(!Number.isInteger(delta)||delta===0||Math.abs(delta)>1000000){toast('请输入 ±1—1000000 的整数积分变动');return}if(!reason){toast('请填写调整原因');return}button.disabled=true;try{const result=await api(`/api/admin/users/${row.dataset.uid}/points`,{delta,reason});toast(`已调整积分 ${delta>0?'+':''}${delta},当前余额 ${result.pointsBalance}`);form.reset();await loadAdminUsers()}catch(error){toast(error.message)}finally{button.disabled=false}} +async function loadAdminUsers(){const list=$('#userList');const q=$('#userSearch').value.trim();list.innerHTML='
    正在加载用户…
    ';try{const result=await api(`/api/admin/users?q=${encodeURIComponent(q)}`);if(!result.items.length){list.innerHTML='
    没有匹配的用户
    ';updateBulkSelection();return}list.innerHTML=result.items.map(item=>`
    ${escapeHtml(item.name)} · @${escapeHtml(item.nickname)}
    学号 ${escapeHtml(item.studentId)} · ${escapeHtml(item.school)} · ${escapeHtml(item.email)}
    信用 ${item.creditScore}积分余额 ${item.pointsBalance}
    信用
    积分
    `).join('');list.querySelectorAll('.adjustment-form').forEach(form=>form.onsubmit=event=>form.dataset.kind==='points'?submitPointsAdjust(event,form):submitCreditAdjust(event,form));bindBulkUserSelection()}catch(error){list.innerHTML=`
    ${escapeHtml(error.message)}
    `;updateBulkSelection()}} + +async function loadOfficialTasks(){const list=$('#officialTaskList');list.innerHTML='
    正在加载官方任务…
    ';try{const result=await api('/api/admin/official-tasks');if(!result.items.length){list.innerHTML='
    暂无官方任务
    ';return}list.innerHTML=result.items.map(item=>{const expired=item.status==='active'&&item.deadline&&Number(item.deadline)<=Date.now();const quota=Number(item.totalQuota)||0;const claimCount=Number(item.claimCount)||0;const soldOut=item.status==='active'&"a>0&&claimCount>=quota;const status=expired?'已过期':item.status==='closed'?'已下线':soldOut?'名额已领完':'进行中';const statusClass=expired||soldOut?'rejected':item.status==='closed'?'dismissed':'';const remaining=item.remainingTotal===null?'不限':Number(item.remainingTotal);const progress=quota>0?Math.min(100,Math.round(claimCount/quota*100)):0;const quotaProgress=quota>0?`
    已领 ${claimCount} / 总量 ${quota}${progress}%
    `:'';return `

    ${escapeHtml(item.title)}${status}

    ${escapeHtml(item.detail||'无详情')}

    单次奖励 ${Number(item.reward)} 积分每账号限领 ${Number(item.perAccountLimit)} 次已领取 ${claimCount} 次领取人数 ${Number(item.claimedUsers)} 人剩余总名额 ${remaining}下架时间 ${item.deadline?adminDate(item.deadline):'不限'}
    ${quotaProgress}${item.status==='active'?'':''}
    `}).join('');list.querySelectorAll('[data-close-official-task]').forEach(button=>button.onclick=()=>closeOfficialTask(button))}catch(error){list.innerHTML=`
    ${escapeHtml(error.message)}
    `;return {refreshError:error}}} +async function createOfficialTask(event){event.preventDefault();const form=event.currentTarget;if(!form.reportValidity())return;const values=Object.fromEntries(new FormData(form));const payload={title:values.title.trim(),detail:values.detail.trim(),reward:Number(values.reward),perAccountLimit:Number(values.perAccountLimit),totalQuota:Number(values.totalQuota),deadline:values.deadline?new Date(values.deadline).getTime():null};if(!Number.isInteger(payload.reward)||payload.reward<1||payload.reward>5000||!Number.isInteger(payload.perAccountLimit)||payload.perAccountLimit<1||payload.perAccountLimit>99||!Number.isInteger(payload.totalQuota)||payload.totalQuota<0){toast('请检查奖励、单账号限次和总名额设置');return}const button=form.querySelector('button[type="submit"]');button.disabled=true;try{await api('/api/admin/official-tasks',payload);toast('官方任务已创建并上线');form.reset();await loadOfficialTasks()}catch(error){toast(error.message)}finally{button.disabled=false}} +async function closeOfficialTask(button){const card=button.closest('[data-official-admin-id]');button.disabled=true;try{await api(`/api/admin/official-tasks/${encodeURIComponent(card.dataset.officialAdminId)}/close`,{});toast('官方任务已下线');await loadOfficialTasks()}catch(error){toast(error.message);button.disabled=false}} +$('#officialTaskForm').onsubmit=createOfficialTask;$('#officialTasksRefresh').onclick=loadOfficialTasks; diff --git a/dist/app.js b/dist/app.js new file mode 100644 index 0000000..7391663 --- /dev/null +++ b/dist/app.js @@ -0,0 +1,709 @@ +let tasks=[]; +const fmtDeadline=ts=>{if(!ts)return'时间待定';const d=new Date(ts);const sameDay=new Date().toDateString()===d.toDateString();return `${sameDay?'今天':`${d.getMonth()+1}/${d.getDate()}`} ${String(d.getHours()).padStart(2,'0')}:${String(d.getMinutes()).padStart(2,'0')} 前`}; +function fmtPublishedAt(ts){ + if(ts===null||ts===undefined||ts==='')return '未知'; + const d=new Date(Number(ts)); + if(!Number.isFinite(d.getTime()))return '未知'; + const pad=n=>String(n).padStart(2,'0'); + return `${d.getFullYear()}/${pad(d.getMonth()+1)}/${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`; +} +let taskLoadSequence=0; +let schoolFilterState={key:null,promise:null}; +function fitSchoolSelect(select){ + const text=select.selectedOptions[0]?.textContent||''; + const style=getComputedStyle(select); + const ctx=fitSchoolSelect.ctx||(fitSchoolSelect.ctx=document.createElement('canvas').getContext('2d')); + ctx.font=`${style.fontSize} ${style.fontFamily}`; + select.style.width=`${Math.min(160,Math.ceil(ctx.measureText(text).width)+2)}px`; +} +window.addEventListener('resize',()=>{ + const select=document.getElementById('schoolFilter'); + if(select?.selectedOptions.length)fitSchoolSelect(select); +},{passive:true}); +async function loadSchoolFilter(){ + const select=$('#schoolFilter'); + if(!select)return ''; + const key=`${sessionToken()||''}:${signedInUser?.id||''}:${!!signedInUser?.isAdmin}`; + if(schoolFilterState.key===key&&schoolFilterState.promise)return schoolFilterState.promise; + const state={key,promise:null}; + schoolFilterState=state; + select.disabled=true; + state.promise=(async()=>{ + const result=await apiRequest('/api/schools',null,{auth:true}); + if(schoolFilterState!==state)return ''; + const schools=result.items||[]; + let saved=''; + try{saved=localStorage.getItem('linkup_school_filter')||''}catch{} + const valid=value=>value==='all'||schools.includes(value); + const preferred=signedInUser?.isAdmin?'all':(result.preferred||'all'); + const selected=valid(saved)?saved:(valid(preferred)?preferred:'all'); + if(saved&&!valid(saved)){try{localStorage.removeItem('linkup_school_filter')}catch{}} + select.innerHTML=''+schools.map(school=>``).join(''); + select.value=selected; + fitSchoolSelect(select); + select.title=selected==='all'?'全部学校':selected; + select.disabled=false; + select.onchange=()=>{ + select.title=select.value==='all'?'全部学校':select.value; + fitSchoolSelect(select); + try{localStorage.setItem('linkup_school_filter',select.value)}catch{} + loadTasks(); + }; + return selected; + })(); + try{return await state.promise}catch(error){ + if(schoolFilterState===state){schoolFilterState.promise=null;select.innerHTML=''} + throw error; + } +} +async function loadTasks(){ + const sequence=++taskLoadSequence; + try{ + await loadSchoolFilter(); + if(sequence!==taskLoadSequence)return; + const school=$('#schoolFilter')?.value||''; + const result=await apiRequest(`/api/tasks${school?`?school=${encodeURIComponent(school)}`:''}`,null,{auth:true}); + if(sequence!==taskLoadSequence)return; + tasks=(result.items||[]).map(it=>({id:String(it.id),userId:String(it.userId||''),deadline:Number(it.deadline)||0,type:it.type,title:escapeHtml(it.title),route:escapeHtml(it.route||''),place:escapeHtml(it.place||''),time:fmtDeadline(it.deadline),reward:it.reward,urgent:it.type!=='partner'&&!!it.deadline&&it.deadline-Date.now()<3*3600e3,note:escapeHtml(it.note||''),category:escapeHtml(it.category||'找搭子'),joined:it.joined?escapeHtml(it.joined):'',user:escapeHtml(it.user||'同学'),credit:it.credit,registeredAt:it.userCreatedAt,breachRate:it.userBreachRate,mine:!!it.mine,status:it.status,claimedByMe:!!it.claimedByMe,joinedByMe:!!it.joinedByMe,createdAt:it.createdAt,completedAt:it.completedAt,phone:it.phone?escapeHtml(String(it.phone)):null,pickupCodes:Array.isArray(it.pickupCodes)?it.pickupCodes.map(c=>escapeHtml(String(c))):null})) + }catch(error){if(sequence!==taskLoadSequence)return;tasks=[];toast(error.message)} + render();loadMyTasks(); +} +let currentFilter='all'; +let currentPartnerTopic='all'; +let currentSort='combined'; +// 筛选值泛化为 type+category:all / partner / errand:类目名 +function matchFilter(t,filter){if(filter==='all')return true;if(filter==='partner')return t.type==='partner';if(filter.startsWith('errand:'))return isErrandTask(t)&&errandCategory(t)===filter.slice(7);return false} +const SORT_LABELS={combined:'综合排序',latest:'最新发布',urgent:'最紧急',reward:'积分最高','open-first':'未接取优先'}; +function compareCombinedTasks(a,b){const created=(Number(b.createdAt)||0)-(Number(a.createdAt)||0);const ad=Number(a.deadline)||Number.MAX_SAFE_INTEGER,bd=Number(b.deadline)||Number.MAX_SAFE_INTEGER;const aUrgent=ad-Date.now()<3*3600e3,bUrgent=bd-Date.now()<3*3600e3;return Number(bUrgent)-Number(aUrgent)||(Number(b.credit)||0)-(Number(a.credit)||0)||created} +function sortTasks(items){const completed=items.filter(task=>task.status==='done').sort((a,b)=>(Number(b.completedAt)||0)-(Number(a.completedAt)||0)||(Number(b.createdAt)||0)-(Number(a.createdAt)||0));if(currentSort==='open-first'){const open=items.filter(task=>task.status==='open').sort(compareCombinedTasks);const claimed=items.filter(task=>task.status==='claimed').sort((a,b)=>(Number(b.createdAt)||0)-(Number(a.createdAt)||0));const other=items.filter(task=>task.status!=='open'&&task.status!=='claimed'&&task.status!=='done').sort((a,b)=>(Number(b.createdAt)||0)-(Number(a.createdAt)||0));return [...open,...claimed,...other,...completed]}const active=items.filter(task=>task.status!=='done');active.sort((a,b)=>{const created=(Number(b.createdAt)||0)-(Number(a.createdAt)||0);if(currentSort==='latest')return created;if(currentSort==='urgent'){const ad=Number(a.deadline)||Number.MAX_SAFE_INTEGER,bd=Number(b.deadline)||Number.MAX_SAFE_INTEGER;return ad-bd||created}if(currentSort==='reward')return (Number(b.reward)||0)-(Number(a.reward)||0)||created;return compareCombinedTasks(a,b)});return [...active,...completed]} +function updateSortMenu(){const button=$('#sortBtn'),menu=$('#sortMenu');if(!button||!menu)return;button.innerHTML=`${SORT_LABELS[currentSort]||SORT_LABELS.combined} `;menu.querySelectorAll('[data-sort]').forEach(option=>{const selected=option.dataset.sort===currentSort;option.setAttribute('aria-selected',String(selected));option.classList.toggle('active',selected)})} +function toggleSortMenu(force){const button=$('#sortBtn'),menu=$('#sortMenu');if(!button||!menu)return;const open=typeof force==='boolean'?force:menu.hidden;menu.hidden=!open;button.setAttribute('aria-expanded',String(open));if(open)menu.querySelector(`[data-sort="${currentSort}"]`)?.focus()} +const $=s=>document.querySelector(s),$$=s=>[...document.querySelectorAll(s)]; +const icon=id=>``; +function taskCard(t){const meta=isErrandTask(t)?errandMeta(t):null;const cat=isErrandTask(t)?errandCategory(t):'';return `
    ${icon(t.type==='partner'?'i-people':meta.icon)}
    ${t.title}${statusLabel[t.status]||statusLabel.open}${t.type==='partner'?(t.category||'找搭子'):(cat==='快递代取'?(t.urgent?'较紧急':'普通件'):cat)}

    ${t.route}

    ${icon('i-pin')}${t.place}${icon('i-clock')}${t.time}${icon('i-shield')}信用 ${t.credit}

    发布于 ${fmtPublishedAt(t.createdAt)}

    ${t.reward||t.joined||'组队'}${t.reward?'积分':'组队中'}
    `} +const emptyBoard=(title,hint)=>`
    ${title}

    ${hint}

    `; + +const bump=el=>{if(!el)return;el.classList.remove('fade-swap');void el.offsetWidth;el.classList.add('fade-swap')}; +function render(){const q=$('#searchInput')?.value.trim().toLowerCase()||'';const list=sortTasks(tasks.filter(t=>(currentFilter==='all'||matchFilter(t,currentFilter))&&`${t.title}${t.route}${t.place}`.toLowerCase().includes(q)));$('#taskList').innerHTML=list.map(taskCard).join('');$('#emptyState').hidden=!!list.length;$('#nearbyCount').textContent=tasks.filter(t=>t.status==='open').length;const errands=sortTasks(tasks.filter(isErrandTask));$('#expressList').innerHTML=errands.length?errands.map(taskCard).join(''):emptyBoard('暂无可接的跑腿任务','成为第一个发布跑腿需求的人。');const partners=sortTasks(tasks.filter(t=>t.type==='partner'));$('#partnerGrid').innerHTML=partners.length?partners.map(t=>`
    ${t.category}${statusLabel[t.status]||statusLabel.open}

    ${t.title}

    ${t.route}

    发布于 ${fmtPublishedAt(t.createdAt)}

    `).join(''):emptyBoard('还没有组队活动','发起一个搭子,等同学来加入。');bindTaskCards()} +function bindTaskCards(){$$('[data-task]').forEach(el=>{el.onclick=()=>openTask(el.dataset.task);el.onkeydown=e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();openTask(el.dataset.task)}}})} +function publisherMeta(t){const date=t.registeredAt?new Date(t.registeredAt).toLocaleDateString('zh-CN',{year:'numeric',month:'2-digit',day:'2-digit'}):'—';const breach=Number.isFinite(Number(t.breachRate))?`${Number(t.breachRate)}%`:'—';return `注册于 ${date} · 失信率 ${breach}`} +function openTask(id){const t=tasks.find(x=>x.id===id);if(!t)return;const errand=isErrandTask(t),meta=errandMeta(t),cat=errandCategory(t);const claimBox=t.claimedByMe&&errand?`
    已接单 · 联系发布者${t.phone?`${t.phone}`:`

    该任务发布于旧版本,未留存手机号,请按任务信息交接或联系平台协助

    `}${cat==='快递代取'?(t.pickupCodes&&t.pickupCodes.length?`

    取件码:${t.pickupCodes.join(' / ')}

    `:'

    取件码见备注或与发布者确认'):''}

    `:'';let actions;if(t.status==='done')actions='已完成';else if(t.status==='claimed')actions=(errand&&(t.claimedByMe||t.mine))?'':'进行中';else if(errand){if(t.mine)actions='';else actions=``}else if(t.joinedByMe)actions='';else actions='';$('#taskDetail').innerHTML=`${icon(t.type==='partner'?'i-people':meta.icon)}${t.type==='partner'?(t.category||'找搭子'):cat}${statusLabel[t.status]||statusLabel.open}

    ${t.title}

    ${t.route}

    发布于 ${fmtPublishedAt(t.createdAt)}

    ${t.type==='partner'?'活动地点':'所在学校'}${t.place}
    ${t.type==='partner'?'时间':(cat==='快递代取'?'最晚送达':'最晚完成')}${t.time}
    任务积分${t.reward?`${t.reward} 积分`:'组队互助'}
    ${t.type==='partner'?'当前人数':(meta.fourth||'任务说明')}${t.type==='partner'?(t.joined||'—'):'详见下方备注'}
    ${claimBox}${errand&&meta.notice?`

    ${meta.notice}

    `:''}

    ${t.note||''}

    ${t.user[0]}
    ${t.user}${publisherMeta(t)}
    信用 ${t.credit}
    ${actions}
    `;$('#taskDialog').showModal();const manageTaskBtn=$('[data-manage-task]');if(manageTaskBtn)manageTaskBtn.onclick=()=>{closeDialogs();openMyTask(t.id)};const cancelBtn=$('[data-cancel-task]');if(cancelBtn)cancelBtn.onclick=async()=>{cancelBtn.disabled=true;try{await apiRequest(`/api/tasks/${t.id}/cancel`,{},{auth:true});closeDialogs();toast('已取消发布');loadTasks()}catch(error){cancelBtn.disabled=false;toast(error.message)}};const acceptBtn=$('[data-accept]');if(acceptBtn&&errand&&!t.mine&&!t.claimedByMe)acceptBtn.onclick=async()=>{if(!signedInUser){toast('请先登录');openLogin();return}if(Number(signedInUser.verification?.level||1)<2){openClaimVerification();return}acceptBtn.disabled=true;try{await apiRequest(`/api/tasks/${t.id}/claim`,{},{auth:true});await loadTasks();closeDialogs();toast(`接单成功,请在“我的任务”中上传${meta.pickupLabel.replace(/^\d+\.\s*/,'')}和${meta.deliveryLabel.replace(/^\d+\.\s*/,'')}`);const nt=tasks.find(x=>x.id===t.id);if(nt)openTask(nt.id)}catch(error){acceptBtn.disabled=false;if(error.code==='VERIFICATION_REQUIRED'||error.status===403){openClaimVerification(error.verification)}else{toast(error.message);if(error.status===401)openLogin()}}};if(acceptBtn&&t.type==='partner')acceptBtn.onclick=async()=>{if(!signedInUser){toast('请先登录后申请加入');openLogin();return}if(t.joinedByMe)return;acceptBtn.disabled=true;try{const result=await apiRequest(`/api/tasks/${t.id}/join`,{},{auth:true});await loadTasks();closeDialogs();toast(`申请成功(${result.joined||'已记录'}),等待发起人确认`)}catch(error){acceptBtn.disabled=false;toast(error.message);if(String(error.message).includes('登录'))openLogin()}};const reportBtn=$('[data-report]');if(reportBtn)reportBtn.onclick=()=>{if(!signedInUser){toast('请先登录后举报');openLogin();return}reportTargetId=t.id;$('#reportError').textContent='';$('#reportDialog').showModal()}} +function navigate(name){$$('.view').forEach(v=>v.classList.toggle('active',v.id===`view-${name}`));$$('[data-nav]').forEach(n=>{const active=n.dataset.nav===name;n.classList.toggle('active',active);if(n.matches('button'))n.setAttribute('aria-current',active?'page':'false')});window.scrollTo({top:0,behavior:'auto'})} +const PUBLISH_TOKEN_EXPRESS='errand:快递代取'; +function normalizePublishToken(token){if(!token||token==='express')return PUBLISH_TOKEN_EXPRESS;return token} +function publishCategoryOf(token){return normalizePublishToken(token).startsWith('errand:')?normalizePublishToken(token).slice(7):null} +const deadlineField=label=>`
    `; +const rewardField='

    单次任务 200—1500 积分

    '; +const noteField=placeholder=>`
    `; +const advanceNotice=category=>{const notice=ERRAND_META[category]?.notice;return notice?`

    ${notice}

    `:''}; +function schoolSelectField(hint){return '

    '+hint+'

    '} +function errandFields(category){ + if(category==='带饭代买')return `
    `; + if(category==='代排队')return `
    `; + if(category==='代打印/文件取送')return `
    `; + return `
    ${deadlineField('最晚送达时间')}${rewardField}
    ${noteField('重量、易碎提醒或交接说明')}`; +} +function formTemplate(token){const normalized=normalizePublishToken(token);if(normalized==='partner')return `
    ${schoolSelectField('组队范围限校内,优先显示你的已认证学校。')}
    ${deadlineField('最晚组队时间')}

    外部链接将在人工审核后展示

    `;const category=publishCategoryOf(normalized),phoneField='
    ';if(category==='快递代取')return `
    ${schoolSelectField('互助范围限校内,优先显示你的已认证学校。')}${errandFields(category)}
    `;if(category==='代排队')return `
    ${schoolSelectField('互助范围限校内,优先显示你的已认证学校。')}${phoneField}${errandFields(category)}${deadlineField('最晚完成时间')}${rewardField}${noteField('补充说明或交接要求')}
    ${advanceNotice(category)}`;return `
    ${schoolSelectField('互助范围限校内,优先显示你的已认证学校。')}${phoneField}${errandFields(category)}${deadlineField(category==='带饭代买'?'最晚送达时间':'最晚完成时间')}${rewardField}${noteField('补充说明或交接要求')}
    ${advanceNotice(category)}`} +function openPublish(type='express'){setPublishType(type);$('#publishDialog').showModal()} +function bindPickupCodeControls(){const list=$('[data-pickup-codes]');if(!list)return;list.addEventListener('click',e=>{const add=e.target.closest('[data-add-code]');const remove=e.target.closest('[data-remove-code]');if(add){const index=list.querySelectorAll('.pickup-code-row').length+1;const row=document.createElement('div');row.className='pickup-code-row';row.innerHTML=``;list.appendChild(row);row.querySelector('input').focus()}else if(remove){remove.closest('.pickup-code-row').remove();[...list.querySelectorAll('input')].forEach((input,i)=>input.setAttribute('aria-label',`取件码 ${i+1}`))}})} +function setPublishType(token){const normalized=normalizePublishToken(token),type=normalized==='partner'?'partner':'errand',category=publishCategoryOf(normalized);$('#publishTitle').textContent=type==='partner'?'发布找搭子':`发布${category}`;$$('[data-publish-cat]').forEach(b=>b.classList.toggle('active',b.dataset.publishCat===normalized));$('#publishForm').innerHTML=formTemplate(normalized);bindPickupCodeControls();$('#publishForm').onsubmit=async e=>{e.preventDefault();if(!signedInUser){toast('请先登录后再发布');openLogin();return}const form=e.currentTarget;if(!form.reportValidity())return;const formData=new FormData(form);const values=Object.fromEntries(formData);values.pickupCodes=formData.getAll('pickupCode[]').map(v=>String(v).trim()).filter(Boolean);values.deadline=values.deadline?Date.parse(values.deadline):NaN;const payload={...values,type};if(type==='errand')payload.category=category;const button=form.querySelector('.submit-publish');button.disabled=true;try{await apiRequest('/api/tasks',payload,{auth:true});closeDialogs();form.reset();toast(type==='errand'?`${category}发布成功,已进入附近任务池`:'组队发布成功,等待同学加入');loadTasks()}catch(error){toast(error.message)}finally{button.disabled=false}}} +function animateCloseDialog(dialog){if(!dialog.open||dialog.classList.contains('closing'))return;dialog.classList.add('closing');const done=()=>{if(!dialog.classList.contains('closing'))return;dialog.classList.remove('closing');dialog.removeEventListener('animationend',done);dialog.close()};dialog.addEventListener('animationend',done);setTimeout(done,320)} +function closeDialogs(){$$('dialog[open]').forEach(d=>animateCloseDialog(d))} +function toast(msg){window.LinkUpToast.show(msg)} +const activeButtons = new WeakSet(); +async function withButtonFeedback(button, asyncFn, options = {}) { + if (!button || button.disabled || activeButtons.has(button)) return; + activeButtons.add(button); + const display = options.display || button; + const original = {nodes:[...display.childNodes], width:display.style.width, height:display.style.height}; + const size = display.getBoundingClientRect(); + display.style.width = `${size.width}px`; display.style.height = `${size.height}px`; + button.disabled = true; button.setAttribute('aria-busy', 'true'); + display.textContent = options.label || '处理中…'; + options.onBusy?.(true); + try { return await asyncFn(); } + catch (error) { options.onError?.(error); toast(error.message); return {feedbackError:error}; } + finally { + display.replaceChildren(...original.nodes); + display.style.width = original.width; display.style.height = original.height; + activeButtons.delete(button); button.removeAttribute('aria-busy'); + button.disabled = options.disabledAfter?.() || false; + options.onBusy?.(false); + } +} +const API_BASE=window.LINKUP_API_BASE||''; +let signedInUser=null; +let reportTargetId=null; +let myTasks=[],myTab='published'; +async function loadMyTasks(){if(!sessionToken()){myTasks=[];renderMyTasks();return}try{const result=await apiRequest('/api/my/tasks',null,{auth:true});myTasks=result.items||[]}catch{myTasks=[]}renderMyTasks()} +function renderMyTasks(){const body=$('#myTasksBody');if(!body)return;if(!signedInUser){body.innerHTML='
    登录后查看你的任务

    发布或接下的任务会集中显示在这里。

    ';return}const list=myTasks.filter(t=>myTab==='published'?t.role==='published':t.role==='claimed');if(!list.length){body.innerHTML=`
    ${myTab==='published'?'还没有发布过任务':'还没有接受的任务'}

    ${myTab==='published'?'发布的任务可以在这里管理或取消。':'接下的任务会显示在这里。'}

    `;return}body.innerHTML=list.map(t=>`
    ${escapeHtml(t.title)}${fmtDeadline(t.deadline)}${t.role==='claimed'&&t.phone?` · ${escapeHtml(String(t.phone))}`:''}${t.reward?` · ${t.reward} 积分`:''}发布于 ${fmtPublishedAt(t.createdAt)}
    ${t.status==='done'?'已完成':t.status==='claimed'?'进行中':'待接单'}
    `).join('');body.querySelectorAll('[data-my-task]').forEach(el=>{el.onclick=()=>openMyTask(el.dataset.myTask);el.onkeydown=e=>{if(e.key==='Enter')openMyTask(el.dataset.myTask)}})} +const statusLabel={open:'待接单',claimed:'进行中',done:'已完成',cancelled:'已取消'}; +// 跑腿代办类目元数据:与后端 ERRAND_CATEGORIES 的类目名保持一致。 +// 凭证内部 kind 仍是 pickup/delivery,仅展示文案按类目取名。 +const ERRAND_META={ + '快递代取':{icon:'i-box',cls:'cat-express',fourth:'快递描述',pickupLabel:'1. 取件照片',pickupHelp:'在快递站取件前拍摄,需看清单号与包裹外观。',deliveryLabel:'2. 送达照片',deliveryHelp:'送到指定位置后拍摄,需看清位置与包裹完好情况。',proofIntro:'取件时拍清快递单号和包裹外观;送到宿舍楼下后拍清送达位置和包裹完好情况。任务完成后,两张照片会通过邮件发送给发布者。'}, + '带饭代买':{icon:'i-meal',cls:'cat-food',fourth:'物品描述',notice:'物品费用请线下当面结算,平台不提供资金托管',pickupLabel:'1. 取餐照片',pickupHelp:'在店铺取餐时拍摄,需看清店铺名与物品外观。',deliveryLabel:'2. 送达照片',deliveryHelp:'送达后拍摄,需看清交付位置与餐品完好。',proofIntro:'取餐后拍清店铺名和物品外观;送达后拍清交付位置和餐品完好情况。任务完成后,两张照片会通过邮件发送给发布者。'}, + '代排队':{icon:'i-clock',cls:'cat-queue',fourth:'事项描述',pickupLabel:'1. 排队现场照片',pickupHelp:'排到后拍摄现场叫号或所在位置。',deliveryLabel:'2. 办理完成照片',deliveryHelp:'办理完成后拍摄,需看清办理结果。',proofIntro:'排到后拍清现场叫号或所在位置;办理完成后拍清办理结果。任务完成后,两张照片会通过邮件发送给发布者。'}, + '代打印/文件取送':{icon:'i-print',cls:'cat-print',fourth:'打印要求',notice:'打印材料等费用请线下当面结算,平台不提供资金托管',pickupLabel:'1. 取件照片',pickupHelp:'取件时拍摄,需看清文件包装与份数。',deliveryLabel:'2. 送达照片',deliveryHelp:'送达后拍摄,需看清交付位置与文件完好。',proofIntro:'取件时拍清文件包装和份数;送达后拍清交付位置和文件完好情况。任务完成后,两张照片会通过邮件发送给发布者。'} +}; +const isErrandTask=t=>t.type==='errand'||t.type==='express'; +const errandCategory=t=>t.category||'快递代取'; +const errandMeta=t=>ERRAND_META[errandCategory(t)]||ERRAND_META['快递代取']; +async function openMyTask(id){const body=$('#taskManageBody');if(!body)return;body.innerHTML='
    正在加载任务详情…
    ';navigate('task'); +try{const result=await apiRequest(`/api/my/tasks/${id}`,null,{auth:true});renderTaskManage(result.task)} +catch(error){toast(error.message);body.innerHTML=`
    加载失败

    ${escapeHtml(error.message)}

    `}} +async function uploadTaskProof(taskId,kind,file){ + const form=new FormData();form.append('photo',file); + const headers={};if(sessionToken())headers.Authorization=`Bearer ${sessionToken()}`; + let response;try{response=await fetch(`${API_BASE}/api/tasks/${encodeURIComponent(taskId)}/proofs/${encodeURIComponent(kind)}`,{method:'POST',headers,body:form})} + catch{throw new Error('照片上传失败,请检查网络后重试')} + let data={};try{data=await response.json()}catch{} + if(!response.ok)throw new Error(data.error||'照片上传失败,请稍后重试');return data +} +function proofCard(kind,label,help,proof,canUpload){ + const uploaded=Boolean(proof?.uploaded),filename=uploaded?escapeHtml(proof.filename||'已上传'):''; + return `
    ${uploaded?'✓ ':''}${label}

    ${help}

    ${uploaded?`${filename}`:''}
    ${canUpload?``:`${uploaded?'已上传':'等待接单人上传'}`}
    ` +} +function renderTaskManage(t){ + const body=$('#taskManageBody');if(!body)return; + const owner=t.role==='owner',errand=isErrandTask(t),meta=errandMeta(t),canUpload=errand&&t.status==='claimed'&&!owner; + const proofItems=t.proofs?.items||{},proofReady=Boolean(t.proofs?.ready),pickupUploaded=Boolean(proofItems.pickup?.uploaded),deliveryUploaded=Boolean(proofItems.delivery?.uploaded); + const publisherCannotCancel=owner&&t.status==='claimed'&&pickupUploaded&&deliveryUploaded; + const publisherCancelBand=pickupUploaded?'picked':Date.now()-(Number(t.claimedAt)||0)<=10*60_000?'grace':'empty_late'; + const publisherCompensation=publisherCancelBand==='picked'?Math.floor((Number(t.reward)||0)*.5):publisherCancelBand==='empty_late'?Math.floor((Number(t.reward)||0)*.2):0; + let actions=''; + if(owner&&errand&&t.status==='open')actions=''; + if(errand&&t.status==='claimed'){ + const label=owner?'确认完成 · 积分转给接单同学':'确认送达 · 完成任务'; + actions=`${owner&&!publisherCannotCancel?``:''}`; + } + const codes=t.pickupCodes&&t.pickupCodes.length?`
    取件码

    ${t.pickupCodes.map(escapeHtml).join(' / ')}

    `:''; + const proofBlock=errand&&['claimed','done'].includes(t.status)?`
    交付凭证

    两张照片缺一不可

    ${Number(Boolean(proofItems.pickup?.uploaded))+Number(Boolean(proofItems.delivery?.uploaded))}/2

    ${meta.proofIntro}

    ${proofCard('pickup',meta.pickupLabel,meta.pickupHelp,proofItems.pickup,canUpload)}${proofCard('delivery',meta.deliveryLabel,meta.deliveryHelp,proofItems.delivery,canUpload)}
    `:''; + const partnerBlock=t.type==='partner'&&owner?`

    申请加入的同学(${(t.participants||[]).length})

    ${t.participants&&t.participants.length?`
    ${t.participants.map(p=>`
    ${escapeHtml(p.nickname)}${escapeHtml(p.school||'')} · 信用 ${p.credit} · ${new Date(p.joinedAt).toLocaleString('zh-CN')}
    `).join('')}
    `:'

    还没有同学申请,等待中。

    '}`:''; + body.innerHTML=`
    ${statusLabel[t.status]||t.status}
    ${icon(errand?(meta.icon):'i-people')}${errand?errandCategory(t):(t.category||'找搭子')}

    ${escapeHtml(t.title)}

    ${t.deadline?fmtDeadline(t.deadline):'时间待定'} · 发布于 ${fmtPublishedAt(t.createdAt)}

    ${errand?'所在学校':'活动学校'}${escapeHtml(t.place)}
    任务积分${t.reward?`${t.reward} 积分`:'组队互助'}
    ${errand?`
    联系方式${escapeHtml(t.contact||'—')}
    `:`
    当前名额${t.slots?`${(t.participants||[]).length}/${t.slots} 人`:'不限'}
    `}
    ${codes}

    ${t.note?escapeHtml(t.note):escapeHtml(t.detail||'')}

    ${owner&&errand&&t.status!=='done'?'

    接单人上传两张凭证后才能完成任务并结算积分。

    ':''}${publisherCannotCancel?'

    已上传送达照,任务不可撤销;请通过完成确认或举报处理。

    ':''}${proofBlock}${partnerBlock}${actions?`
    ${actions}
    `:''}`; + body.querySelector('[data-manage-cancel]')?.addEventListener('click',async e=>{e.target.disabled=true; + try{await apiRequest(`/api/tasks/${t.id}/cancel`,{},{auth:true});toast('已取消发布,冻结积分已退还');loadMyTasks();loadTasks();openMyTask(t.id)} + catch(error){e.target.disabled=false;toast(error.message)}}); + body.querySelector('[data-manage-owner-cancel]')?.addEventListener('click',async e=>{ + let confirmation=''; + if(publisherCancelBand==='empty_late')confirmation=`将补偿骑手 ${publisherCompensation} 积分,其余 ${Number(t.reward)-publisherCompensation} 积分退回给你。确认取消任务?`; + if(publisherCancelBand==='picked')confirmation=`将补偿骑手 ${publisherCompensation} 积分,信用分 -3 并计一次失信;若任务有未处理举报,信用责任会转管理员核实。包裹仍在骑手处,请双方协商取回,纠纷走举报。确认取消任务?`; + if(confirmation&&!window.confirm(confirmation))return; + e.currentTarget.disabled=true; + try{const result=await apiRequest(`/api/tasks/${t.id}/cancel`,{},{auth:true});toast(`任务已取消,退回 ${result.ownerRefund} 积分${result.riderCompensation?`,骑手获补偿 ${result.riderCompensation} 积分`:''}${result.creditReviewPending?',信用责任转管理员核实':''}`);loadMyTasks();loadTasks();openMyTask(t.id)} + catch(error){e.currentTarget.disabled=false;toast(error.message)} + }); + body.querySelectorAll('[data-proof-upload]').forEach(input=>input.addEventListener('change',async()=>{ + const file=input.files?.[0];if(!file)return; + if(file.size>8*1024*1024){toast('单张照片不能超过 8MB');input.value='';return} + await withButtonFeedback(input,async()=>{ + await uploadTaskProof(t.id,input.dataset.proofUpload,file);toast('照片上传成功'); + await openMyTask(t.id);if(typeof loadNotificationSummary==='function')loadNotificationSummary(); + },{label:'上传中…',display:input.parentElement.querySelector('span'), + onBusy:busy=>input.closest('.proof-card')?.classList.toggle('uploading',busy), + onError:()=>{input.value='';}}); + })); + body.querySelectorAll('[data-manage-complete]').forEach(b=>b.addEventListener('click',async()=>{b.disabled=true; + try{await apiRequest(`/api/tasks/${t.id}/complete`,{},{auth:true});toast('任务完成,凭证照片已发送至发布者邮箱');loadMyTasks();loadTasks();if(typeof loadNotificationSummary==='function')loadNotificationSummary();openMyTask(t.id)} + catch(error){b.disabled=false;toast(error.message)}})); + body.querySelectorAll('[data-manage-back],[data-manage-back2]').forEach(b=>b.addEventListener('click',()=>navigate('profile'))) +} +let cachedNotifications=[]; + +const sessionToken=()=>localStorage.getItem('linkup_session')||''; +async function apiRequest(path,payload=null,options={}){const method=options.method||(payload?'POST':'GET');const headers={'Content-Type':'application/json'};if(options.auth&&sessionToken())headers.Authorization=`Bearer ${sessionToken()}`;let response;try{response=await fetch(`${API_BASE}${path}`,{method,headers,...(payload?{body:JSON.stringify(payload)}:{})})}catch{throw new Error('暂时无法连接用户服务,请稍后再试')}let data={};try{data=await response.json()}catch{}if(!response.ok){const error=new Error(data.error||'请求失败,请稍后重试');error.status=response.status;error.code=data.code;error.verification=data.verification;throw error}return data} +const escapeHtml=value=>String(value??'').replace(/[&<>'"]/g,char=>({'&':'&','<':'<','>':'>',"'":''','"':'"'}[char])); +async function copyText(text){try{if(navigator.clipboard&&window.isSecureContext){await navigator.clipboard.writeText(text);return true}}catch{}try{const handler=e=>{e.clipboardData.setData('text/plain',text);e.preventDefault()};document.addEventListener('copy',handler,{once:true});const ok=document.execCommand('copy');document.removeEventListener('copy',handler);if(ok)return true}catch{}try{const ta=document.createElement('textarea');ta.value=text;ta.setAttribute('readonly','');ta.style.cssText='position:fixed;top:-999px;left:-999px;opacity:0';document.body.appendChild(ta);ta.focus();ta.select();ta.setSelectionRange(0,text.length);const ok=document.execCommand('copy');ta.remove();if(ok)return true}catch{}return false} +const VERIFICATION_LEVELS=Object.freeze([ + Object.freeze({level:1,name:'注册会员',condition:'注册账号',permission:'可发布任务,不可接单'}), + Object.freeze({level:2,name:'校园认证',condition:'学信网认证通过,或人脸识别通过(人脸识别即将上线)',permission:'可发布任务、接单'}), + Object.freeze({level:3,name:'双重认证',condition:'学信网认证与人脸识别同时通过(人脸识别即将上线)',permission:'可发布任务、接单',benefit:'专属标识与更多权益,敬请期待',upcoming:true}) +]); +let pendingVerificationLevelsAfterLogin=false; +function resumeVerificationLevelsAfterLogin(){ + if(!pendingVerificationLevelsAfterLogin||!signedInUser)return; + pendingVerificationLevelsAfterLogin=false; + // Let the login dialog finish its close animation before opening the next modal. + setTimeout(()=>{if(signedInUser)openVerificationLevels()},350); +} +function verificationLevelInfo(verification){return VERIFICATION_LEVELS.find(item=>item.level===Number(verification?.level))||VERIFICATION_LEVELS[0]} +function verificationStatusText(verification){ + const current=verificationLevelInfo(verification),status=verification?.status||'unsubmitted',prefix=`当前为 L${current.level} ${current.name}。`; + if(status==='pending')return `${prefix}学信网认证审核中,通过后可升级至 L${Math.min(3,current.level+1)}。`; + if(status==='rejected')return `${prefix}学信网认证未通过:${verification.reviewNote||'请重新提交有效报告'}。`; + if(status==='expired')return `${prefix}学信网报告已过期,等级已按仍有效的凭证调整;请延长报告有效期后重新认证。`; + if(status==='approved')return `${prefix}学信网认证已通过,有效期至 ${verification.reportExpiresOn||'—'}。`; + return current.level===1?`${prefix}满足 L2 ${VERIFICATION_LEVELS[1].name}条件后即可接单。`:`${prefix}${current.permission}。${current.benefit||''}`; +} +function renderVerificationLevels(verification){ + const current=verificationLevelInfo(verification),status=verification?.status||'unsubmitted'; + $('#verificationLevelStatus').textContent=verificationStatusText(verification); + $('#verificationLevelsList').innerHTML=VERIFICATION_LEVELS.map(item=>{ + const active=item.level===current.level; + return `

    L${item.level} ${escapeHtml(item.name)}

    ${item.upcoming?'即将上线':''}${active?'当前等级':''}

    解锁条件${escapeHtml(item.condition)}

    对应权限${escapeHtml(item.permission)}

    ${item.benefit?`

    更多权益${escapeHtml(item.benefit)}

    `:''}
    `; + }).join(''); + const action=$('#verificationLevelAction'); + if(current.level===1){action.innerHTML='';action.querySelector('button').onclick=()=>{const dialog=$('#verificationLevelsDialog');dialog.close();if(status==='pending')openClaimVerification(verification);else openVerification()}}; + if(current.level===2)action.innerHTML=''; + if(current.level===3)action.innerHTML='

    '+escapeHtml(current.benefit)+'

    '; +} +async function openVerificationLevels(){ + if(!signedInUser){pendingVerificationLevelsAfterLogin=true;openLogin();return} + const dialog=$('#verificationLevelsDialog');renderVerificationLevels(signedInUser.verification);if(!dialog.open)dialog.showModal(); + try{const result=await apiRequest('/api/auth/me',null,{auth:true});if(!dialog.open||!result.user||result.user.id!==signedInUser?.id)return;signedInUser=result.user;localStorage.setItem('linkup_profile',JSON.stringify(result.user));renderVerification(result.user.verification)}catch{} +} +function renderVerification(verification={level:1,status:'unsubmitted',label:'邮箱已验证'}){const status=verification.status||'unsubmitted',level=verificationLevelInfo(verification);const descriptions={unsubmitted:level.level===1?`升级为 L2 ${VERIFICATION_LEVELS[1].name}:${VERIFICATION_LEVELS[1].condition};${VERIFICATION_LEVELS[1].permission}。`:`当前为 L${level.level} ${level.name}。完成学信网认证后可升级为 L3 ${VERIFICATION_LEVELS[2].name}。`,pending:`申请审核中 · 验证码尾号 ${verification.codeLast4||'—'} · 当前 L${level.level} ${level.name}`,approved:`已通过学信网核验 · 有效期至 ${verification.reportExpiresOn||'—'} · ${level.permission}${level.benefit?` · ${level.benefit}`:''}`,rejected:`审核未通过:${verification.reviewNote||'请重新提交有效报告'} · 当前 L${level.level} ${level.name}`,expired:`认证报告已过期,请延长有效期后重新提交 · 当前 L${level.level} ${level.name}`};const actions={unsubmitted:'开始认证',pending:'审核中',approved:'更新报告',rejected:'重新提交',expired:'重新认证'};const badge=$('[data-verification-badge]');badge.classList.remove('pending','approved','rejected','expired');if(status!=='unsubmitted')badge.classList.add(status);$('[data-verification-label]').textContent=verification.label||'邮箱已验证';$('[data-verification-level]').textContent=`L${level.level}`;$('[data-verification-description]').textContent=descriptions[status]||descriptions.unsubmitted;const card=$('.identity-card');if(card)card.hidden=status==='approved';const button=$('[data-open-verification]');button.textContent=actions[status]||actions.unsubmitted;button.disabled=status==='pending';if($('#verificationLevelsDialog')?.open)renderVerificationLevels(verification)} +function renderAccountMetrics(user){const stats=user?.stats;const loggedIn=!!stats;$('#pointsBalance').textContent=loggedIn?stats.pointsBalance.toLocaleString('zh-CN'):'—';$('[data-credit-score]').textContent=loggedIn?stats.creditScore:'—';$('[data-credit-progress]').style.width=loggedIn?`${Math.max(0,Math.min(100,stats.creditScore))}%`:'0';$('[data-breach-rate]').textContent=loggedIn?`${stats.breachRate}%`:'—';$('[data-completed-tasks]').textContent=loggedIn?stats.completedTasks:'—';$('[data-current-streak]').textContent=loggedIn?stats.currentStreak:'—';$('[data-profile-credit]').textContent=loggedIn?stats.creditScore:'—';$('[data-profile-breach]').textContent=loggedIn?`${stats.breachRate}%`:'—';$$('[data-header-credit]').forEach(el=>el.textContent=loggedIn?stats.creditScore:'—');$$('[data-account-action]').forEach(button=>button.disabled=!loggedIn)} +function renderAuth(user){signedInUser=user||null;const loggedIn=!!user;$$('[data-auth-profile]').forEach(el=>el.hidden=!loggedIn);$$('[data-open-login],[data-open-register]').forEach(el=>el.hidden=loggedIn);$('[data-guest-profile]').hidden=loggedIn;$('[data-user-profile]').hidden=!loggedIn;renderAccountMetrics(user);if(loggedIn){const initial=(user.nickname||user.name||'同')[0];$$('[data-user-avatar],[data-profile-avatar]').forEach(el=>el.textContent=initial);$$('[data-user-nickname]').forEach(el=>el.textContent=user.nickname);$('[data-profile-name]').textContent=user.name;$('[data-profile-nickname]').textContent=`@${user.nickname}`;$('[data-profile-school]').textContent=user.school;$('[data-profile-date]').textContent=new Date(user.createdAt).toLocaleDateString('zh-CN',{year:'numeric',month:'2-digit'});$('#welcomeTitle').textContent=`下午好,${user.nickname}`;$('#campusLabel').textContent=`${user.school} · 校园互助广场`;renderVerification(user.verification);loadMyTasks()}else{$('#welcomeTitle').textContent='下午好,同学';$('#campusLabel').textContent='校园互助广场';myTasks=[];renderMyTasks()}loadTasks()} +function saveAuth(result){localStorage.setItem('linkup_session',result.token);localStorage.setItem('linkup_profile',JSON.stringify(result.user));renderAuth(result.user);resumeVerificationLevelsAfterLogin()} +function clearAuth(){localStorage.removeItem('linkup_session');localStorage.removeItem('linkup_profile');renderAuth(null)} +async function hydrateAuth(){const cached=localStorage.getItem('linkup_profile');if(cached){try{renderAuth(JSON.parse(cached))}catch{clearAuth()}}if(!sessionToken()){renderAuth(null);return}try{const result=await apiRequest('/api/auth/me',null,{auth:true});localStorage.setItem('linkup_profile',JSON.stringify(result.user));renderAuth(result.user)}catch{clearAuth()}} +function setRegisterBusy(busy){$('#registerSubmit').disabled=busy;$('#registerSubmit').textContent=busy?'正在验证…':'验证并注册'} +function showRegisterError(message=''){$('#registerError').textContent=message} +async function openRegister(){closeDialogs();showRegisterError();const submit=$('#registerSubmit');if(submit)submit.disabled=true;$('#registerDialog').showModal();setTimeout(()=>$('#realName').focus(),0);try{const policy=await loadPrivacyPolicy();setRegistrationPrivacyVersion(policy)}finally{if(submit)submit.disabled=false}} +function openLogin(){closeDialogs();$('#loginError').textContent='';$('#loginDialog').showModal();setTimeout(()=>$('#loginEmail').focus(),0)} +const countdowns=new Map(); +function startCountdown(button){let seconds=60;clearInterval(countdowns.get(button));button.disabled=true;button.textContent=`${seconds}s 后重试`;const timer=setInterval(()=>{seconds-=1;if(seconds<=0){clearInterval(timer);button.disabled=false;button.textContent='获取验证码'}else button.textContent=`${seconds}s 后重试`},1000);countdowns.set(button,timer)} +async function sendVerificationCode(){ + const email=$('#registerEmail');showRegisterError();if(!email.reportValidity())return; + const button=$('#sendCodeBtn'); + const result=await withButtonFeedback(button,async()=>{ + await apiRequest('/api/auth/send-code',{email:email.value});toast('验证码已发送,请检查邮箱');return true; + },{label:'发送中…',onError:error=>showRegisterError(error.message)}); + if(result&&!result.feedbackError)startCountdown(button); +} +async function sendLoginCode(){const email=$('#loginEmail');$('#loginError').textContent='';if(!email.reportValidity())return;const button=$('#sendLoginCodeBtn');button.disabled=true;button.textContent='发送中…';try{await apiRequest('/api/auth/send-login-code',{email:email.value});toast('登录验证码已发送');startCountdown(button)}catch(error){button.disabled=false;button.textContent='获取验证码';$('#loginError').textContent=error.message}} +async function submitRegistration(event){event.preventDefault();showRegisterError();const form=event.currentTarget;if(!form.reportValidity())return;const values=Object.fromEntries(new FormData(form));setRegisterBusy(true);try{const result=await apiRequest('/api/auth/register',values);saveAuth(result);closeDialogs();form.reset();toast(`注册成功,欢迎你,${result.user.nickname}`)}catch(error){showRegisterError(error.message)}finally{setRegisterBusy(false)}} +async function submitLogin(event){event.preventDefault();const form=event.currentTarget;$('#loginError').textContent='';if(!form.reportValidity())return;const button=$('#loginSubmit');button.disabled=true;button.textContent='正在登录…';try{const result=await apiRequest('/api/auth/login',Object.fromEntries(new FormData(form)));saveAuth(result);closeDialogs();form.reset();toast(`欢迎回来,${result.user.nickname}`)}catch(error){$('#loginError').textContent=error.message}finally{button.disabled=false;button.textContent='登录'}} +function openClaimVerification(verification=signedInUser?.verification){ + const status=verification?.status||'unsubmitted'; + const messages={unsubmitted:'完成学信网认证后即可接单',pending:'认证审核中,通过后即可接单',expired:'认证报告已过期,请重新认证',rejected:'认证审核未通过,请重新提交认证'}; + if(signedInUser&&verification){signedInUser.verification=verification;renderVerification(verification);try{localStorage.setItem('linkup_profile',JSON.stringify(signedInUser))}catch{}} + $('#claimVerificationMessage').textContent=messages[status]||messages.unsubmitted; + const button=$('#claimVerificationGo'); + button.textContent=status==='pending'?'查看认证进度':'去认证'; + button.onclick=()=>{ + closeDialogs();navigate('profile'); + const card=$('.identity-card'); + if(card){card.hidden=false;card.scrollIntoView({block:'center',behavior:'smooth'})} + if(status!=='pending')openVerification(); + }; + closeDialogs();$('#claimVerificationDialog').showModal(); +} +function openVerification(){if(!signedInUser){openLogin();return}$('#verificationError').textContent='';const date=$('#reportExpiresOn');date.min=new Date().toISOString().slice(0,10);$('#verificationDialog').showModal();setTimeout(()=>$('#onlineCode').focus(),0)} +async function submitStudentVerification(event){ + event.preventDefault();const form=event.currentTarget;$('#verificationError').textContent=''; + if(!form.reportValidity())return; + return withButtonFeedback($('#verificationSubmit'),async()=>{ + const values=Object.fromEntries(new FormData(form)); + await apiRequest('/api/student-verification',{onlineCode:values.onlineCode,reportExpiresOn:values.reportExpiresOn},{auth:true}); + const result=await apiRequest('/api/auth/me',null,{auth:true}); + localStorage.setItem('linkup_profile',JSON.stringify(result.user));renderAuth(result.user); + form.reset();closeDialogs();toast('认证申请已提交,等待管理员审核'); + },{label:'正在提交…',onError:error=>{$('#verificationError').textContent=error.message}}); +} +async function openEntries(){if(!signedInUser){openLogin();return}const body=$('#entriesBody');body.innerHTML='

    正在加载明细…

    ';$('#entriesDialog').showModal();try{renderEntries(await apiRequest('/api/points/entries',null,{auth:true}))}catch(error){toast(error.message);body.innerHTML=`

    ${escapeHtml(error.message)}

    `}} +function renderEntries(result){const body=$('#entriesBody');const head=`
    当前余额${Number(result.balance).toLocaleString('zh-CN')}
    可提现${Number(result.withdrawable).toLocaleString('zh-CN')}
    `;const rows=result.entries?.length?`
    ${result.entries.map(e=>`
    ${escapeHtml(e.reason)}${e.delta>0?'+':''}${e.delta}${new Date(e.createdAt).toLocaleString('zh-CN')}
    `).join('')}
    `:'

    暂无积分记录。

    ';body.innerHTML=head+rows} +async function openInvite(){if(!signedInUser){openLogin();return}const body=$('#inviteBody');body.innerHTML='

    正在获取邀请信息…

    ';$('#inviteDialog').showModal();try{renderInvite(await apiRequest('/api/invite-code',null,{auth:true}))}catch(error){toast(error.message);body.innerHTML=`

    ${escapeHtml(error.message)}

    `}} +function renderInvite(info){const body=$('#inviteBody');const warning=`
    慎重邀请

    可提现积分满 80 方可生成邀请码;邀请人注册校验仍要求信用分达到 90。普通受邀用户失约不会自动牵连邀请人,恶意邀请或串通违规经管理员核实后才会调整。

    `;if(info.code){body.innerHTML=`
    ${escapeHtml(info.code.code)}

    邀请码还可被使用 ${info.code.usesLeft}/${info.code.maxUses} 次。

    ${warning}`;body.querySelector('[data-copy-invite]').onclick=async()=>{const text=`【LinkUp 校园互助】邀请邀请码:${info.code.code} +注册时填写此邀请码,你的初始信用分为 90。 +注册地址:${location.origin}`;toast(await copyText(text)?'邀请文案已复制,直接发给同学即可':'复制失败,请长按邀请码手动复制')};async()=>{toast(await copyText(info.code.code)?'邀请码已复制':'复制失败,请长按邀请码手动复制,或检查浏览器剪贴板权限')};return}if(info.eligible){body.innerHTML=`

    当前可提现积分 ${info.withdrawablePoints},符合生成条件。

    ${warning}`;body.querySelector('[data-gen-invite]').onclick=async()=>{try{renderInvite(await apiRequest('/api/invite-code',{}, {auth:true}))}catch(error){toast(error.message)}};return}body.innerHTML=`

    当前可提现积分 ${info.withdrawablePoints},满 80 可生成邀请码。

    ${warning}`} +async function submitReport(event){event.preventDefault();const form=event.currentTarget;if(!form.reportValidity())return;const reason=Object.fromEntries(new FormData(form)).reason;const button=$('#reportSubmit');button.disabled=true;try{await apiRequest('/api/reports',{targetType:'task',targetId:reportTargetId,reason},{auth:true});form.reset();closeDialogs();toast('举报已提交,我们会尽快核实处理')}catch(error){$('#reportError').textContent=error.message}finally{button.disabled=false}} +function openLogoutConfirm(){if(!signedInUser){openLogin();return}$('#logoutDialog').showModal()} +async function logout(){ + return withButtonFeedback($('#confirmLogout'),async()=>{ + let remoteError=null; + try{await apiRequest('/api/auth/logout',{}, {auth:true})}catch(error){remoteError=error} + clearAuth();closeDialogs();navigate('home'); + toast(remoteError?`已清除本机登录状态;${remoteError.message}`:'已退出当前账号'); + },{label:'正在退出…'}); +} +$$('[data-nav]').forEach(b=>b.addEventListener('click',e=>{e.preventDefault();navigate(b.dataset.nav)}));$$('[data-open-publish]').forEach(b=>b.onclick=()=>openPublish(b.dataset.openPublish));$$('[data-open-register]').forEach(b=>b.onclick=openRegister);$$('[data-open-login]').forEach(b=>b.onclick=openLogin);$$('[data-open-verification]').forEach(b=>b.onclick=openVerification);$$('[data-open-entries]').forEach(b=>b.onclick=openEntries);$$('[data-logout]').forEach(b=>b.onclick=logout);$$('[data-close]').forEach(b=>b.onclick=()=>{const dlg=b.closest('dialog');if(dlg&&dlg.open)animateCloseDialog(dlg)});$$('[data-filter]').forEach(b=>b.onclick=()=>{currentFilter=b.dataset.filter;$$('[data-filter]').forEach(x=>x.classList.toggle('active',x===b));render()});$('#searchInput').addEventListener('input',render);$$('[data-publish-cat]').forEach(b=>b.onclick=()=>setPublishType(b.dataset.publishCat));$$('[data-action]').forEach(b=>b.onclick=()=>{if(b.dataset.action==='invite'){openInvite();return}openWallet(b.dataset.action)});$('#sendCodeBtn').onclick=sendVerificationCode;$('#registerForm').onsubmit=submitRegistration;$('#sendLoginCodeBtn').onclick=sendLoginCode;$('#loginForm').onsubmit=submitLogin;$('#verificationForm').onsubmit=submitStudentVerification;$('#reportForm').onsubmit=submitReport;$$('dialog').forEach(d=>d.addEventListener('click',e=>{if(e.target===d)e.preventDefault()}));$$('dialog').forEach(d=>d.addEventListener('cancel',e=>{if(d.open){e.preventDefault();animateCloseDialog(d)}}));$('#loginDialog').addEventListener('close',()=>{if(pendingVerificationLevelsAfterLogin&&!signedInUser&&!$('#registerDialog')?.open)pendingVerificationLevelsAfterLogin=false});$$('[data-mytab]').forEach(b=>b.onclick=()=>{myTab=b.dataset.mytab;$$('[data-mytab]').forEach(x=>x.classList.toggle('active',x===b));renderMyTasks()});const baseRenderForFade=render;render=function(){baseRenderForFade();bump($('#taskList'))}; +$$('[data-open-logout]').forEach(b=>b.onclick=openLogoutConfirm);$('#confirmLogout').onclick=logout; +const verificationLevelTrigger=$('[data-open-verification-levels]'); +if(verificationLevelTrigger){verificationLevelTrigger.onclick=openVerificationLevels;verificationLevelTrigger.onkeydown=event=>{if(event.key==='Enter'||event.key===' '){event.preventDefault();openVerificationLevels()}}} +const baseRenderMyTasksForFade=renderMyTasks;renderMyTasks=function(){baseRenderMyTasksForFade();bump($('#myTasksBody'))}; +render();loadTasks();hydrateAuth(); +async function loadPublicProfile(userId){const body=$('#publicProfileBody');body.innerHTML='
    正在加载主页…
    ';$('#publicProfileDialog').showModal();try{const result=await apiRequest(`/api/users/${encodeURIComponent(userId)}/profile`,null,{auth:true});const user=result.user;const date=user.createdAt?new Date(user.createdAt).toLocaleDateString('zh-CN',{year:'numeric',month:'2-digit',day:'2-digit'}):'—';const level=verificationLevelInfo(user.verification);const verification=level.level>=3?`L${level.level} ${level.name}`:level.level>=2?(user.verification?.label||`L${level.level} ${level.name}`):'邮箱已验证';body.innerHTML=`
    ${escapeHtml((user.nickname||'同')[0])}

    ${escapeHtml(user.nickname||'同学')}

    ${escapeHtml(user.school||'')}

    ${escapeHtml(verification)}
    ${Number(user.creditScore??70)}信用分
    ${Number(user.breachRate??0)}%失信率
    ${Number(user.completedTasks??0)}完成任务
    ${Number(user.currentStreak??0)}连续守约

    注册于 ${escapeHtml(date)}

    `}catch(error){toast(error.message);body.innerHTML=`
    主页加载失败

    ${escapeHtml(error.message)}

    `}} +const originalOpenTaskWithProfiles=openTask;openTask=function(id){originalOpenTaskWithProfiles(id);const t=tasks.find(item=>item.id===id);const publisher=$('#taskDetail .publisher');if(t&&publisher&&t.userId){const name=publisher.querySelector('strong');if(name){name.outerHTML=``}}};document.addEventListener('click',event=>{const trigger=event.target.closest('[data-open-profile]');if(!trigger)return;event.preventDefault();event.stopPropagation();closeDialogs();loadPublicProfile(trigger.dataset.openProfile)});loadTasks(); +// 发布任务的地点统一为学校。已登录用户的学校(通过学信网审核时即为核验学校)始终排在第一项。 +const PUBLISH_SCHOOL_OPTIONS=['山东管理学院','山东大学','中国海洋大学','中国石油大学(华东)','青岛大学','济南大学','山东师范大学','山东财经大学','山东科技大学','青岛科技大学','青岛理工大学','山东建筑大学','齐鲁工业大学','山东农业大学','山东中医药大学','曲阜师范大学','烟台大学','鲁东大学','聊城大学','临沂大学','青岛农业大学','潍坊学院','滨州学院','德州学院','菏泽学院','北京大学','清华大学','中国人民大学','北京师范大学','复旦大学','上海交通大学','浙江大学','南京大学','武汉大学','华中科技大学','中山大学','四川大学','厦门大学']; +function publishSchoolOptions(){const preferred=String(signedInUser?.school||'').trim();const schools=[...new Set([preferred,...PUBLISH_SCHOOL_OPTIONS].filter(Boolean))];return schools.map((school,index)=>'').join('')} +const originalOpenTaskForSchool=openTask; +openTask=function(id){originalOpenTaskForSchool(id);const t=tasks.find(item=>item.id===id);const label=$('#taskDetail .detail-box div span');if(label&&t&&t.type==='partner')label.textContent='活动学校'}; + +document.addEventListener('click',event=>{const option=event.target.closest?.('[data-sort]');if(option){event.preventDefault();currentSort=option.dataset.sort;updateSortMenu();toggleSortMenu(false);render();return}const button=event.target.closest?.('#sortBtn');if(button){event.preventDefault();updateSortMenu();toggleSortMenu();return}if(!event.target.closest?.('.sort-control'))toggleSortMenu(false)},true); +updateSortMenu(); +(function(){const topicButtons=$$('[data-topic]');if(!topicButtons.length)return;const baseRender=render;function renderPartnerTopics(){const partners=sortTasks(tasks.filter(task=>task.type==='partner'&&(currentPartnerTopic==='all'||task.category===currentPartnerTopic)));const grid=$('#partnerGrid');if(!grid)return;grid.innerHTML=partners.length?partners.map(task=>`
    ${task.category}${statusLabel[task.status]||statusLabel.open}

    ${task.title}

    ${task.route}

    发布于 ${fmtPublishedAt(task.createdAt)}

    `).join(''):emptyBoard('还没有该类型的组队活动','换个类型看看,或发起一个搭子。');bindTaskCards()}render=function(){baseRender();renderPartnerTopics()};topicButtons.forEach(button=>button.onclick=()=>{currentPartnerTopic=button.dataset.topic;topicButtons.forEach(item=>{const selected=item===button;item.classList.toggle('active',selected);item.setAttribute('aria-selected',String(selected))});renderPartnerTopics()})})(); +loadTasks(); +let taskDefaults=null; +// 各类目把 task_defaults 的通用字段(phone/pickupPlace/destination)回填到表单字段的映射。 +const DEFAULTS_FIELD_MAP={'快递代取':{phone:'phone',pickupPlace:'pickupPlace',destination:'destination'},'带饭代买':{phone:'phone',pickupPlace:'shop',destination:'destination'},'代排队':{phone:'phone',pickupPlace:'queuePlace'},'代打印/文件取送':{phone:'phone',pickupPlace:'pickupPlace',destination:'destination'}}; +async function loadTaskDefaults(category){if(!signedInUser){taskDefaults=null;return}try{const result=await apiRequest(`/api/task-defaults${category?`?category=${encodeURIComponent(category)}`:''}`,null,{auth:true});taskDefaults=result.defaults||null}catch{taskDefaults=null}} +function applyTaskDefaults(category){const form=$('#publishForm'),defaults=taskDefaults;if(!form||!defaults)return;const map=DEFAULTS_FIELD_MAP[category]||{};Object.entries(map).forEach(([key,name])=>{const field=form.querySelector(`[name="${name}"]`);if(field&&defaults[key])field.value=defaults[key]});const school=form.querySelector('[name="school"]');if(school&&defaults.school&&[...school.options].some(option=>option.value===defaults.school))school.value=defaults.school} +const baseSetPublishTypeWithDefaults=setPublishType; +setPublishType=function(token){baseSetPublishTypeWithDefaults(token);const category=publishCategoryOf(token);if(category){applyTaskDefaults(category);if(signedInUser&&!taskDefaults)loadTaskDefaults(category).then(()=>applyTaskDefaults(category))}}; +const baseOpenPublishWithDefaults=openPublish; +openPublish=async function(type='express'){if(publishCategoryOf(type)&&signedInUser)await loadTaskDefaults(publishCategoryOf(type));baseOpenPublishWithDefaults(type)}; +const baseClearAuthWithDefaults=clearAuth; +clearAuth=function(){taskDefaults=null;baseClearAuthWithDefaults()}; +let notificationItems=[]; +// 消息类型分组:kind → 分组映射;未收录的未知 kind 只在「全部」可见,不报错。 +// notificationFilter 仅存于内存:会话内重开弹窗不重置,刷新页面自然回到「全部」。 +let notificationFilter='all'; +let notificationSummaryUnread=0; +const NOTIFICATION_GROUPS={ + all:{label:'全部',empty:'暂无通知',hint:'任务状态、接单和结算消息会显示在这里。'}, + task:{label:'任务消息',kinds:['task_created','task_claimed','task_proof_uploaded','task_completed','task_cancelled','partner_joined'],empty:'暂无任务消息',hint:'发布、接单、凭证、完成和取消消息会显示在这里。'}, + account:{label:'账户与积分',kinds:['points_adjusted','credit_adjusted','account_sanction'],empty:'暂无账户与积分消息',hint:'积分、信用调整和账号能力处理消息会显示在这里。'}, + system:{label:'系统',kinds:[],empty:'暂无系统消息',hint:'平台公告与系统通知会显示在这里。'} +}; +const NOTIFICATION_KIND_GROUP={};Object.entries(NOTIFICATION_GROUPS).forEach(([key,group])=>(group.kinds||[]).forEach(kind=>{NOTIFICATION_KIND_GROUP[kind]=key})); +function updateNotificationBadge(unread){const badge=$('#notificationBadge');if(!badge)return;const count=Number(unread)||0;badge.hidden=count===0;badge.textContent=count>9?'9+':String(count)} +function notificationTime(timestamp){if(!timestamp)return'';return new Date(Number(timestamp)).toLocaleString('zh-CN',{month:'2-digit',day:'2-digit',hour:'2-digit',minute:'2-digit'})} +async function loadNotificationSummary(){if(!signedInUser){updateNotificationBadge(0);return}try{const result=await apiRequest('/api/notifications',null,{auth:true});updateNotificationBadge(result.unread)}catch{updateNotificationBadge(0)}} +function updateNotificationTabs(){const tabs=$$('[data-notif-filter]');if(!tabs.length)return;tabs.forEach(button=>{const active=button.dataset.notifFilter===notificationFilter;button.classList.toggle('active',active);button.setAttribute('aria-selected',String(active))})} +function setNotificationFilter(filter){if(!NOTIFICATION_GROUPS[filter])return;notificationFilter=filter;updateNotificationTabs();renderNotifications({items:notificationItems,unread:notificationSummaryUnread})} +function renderNotifications(result){notificationItems=result.items||[];notificationSummaryUnread=Number(result.unread)||0;const body=$('#notificationBody'),summary=$('#notificationSummary');if(!body)return;summary.textContent=notificationSummaryUnread?`${notificationSummaryUnread} 条未读通知`:'暂无未读通知';updateNotificationTabs();const group=NOTIFICATION_GROUPS[notificationFilter]||NOTIFICATION_GROUPS.all;const visible=notificationFilter==='all'?notificationItems:notificationItems.filter(item=>NOTIFICATION_KIND_GROUP[item.kind]===notificationFilter);if(!visible.length){body.innerHTML=`
    ${group.empty}

    ${group.hint}

    `;return}body.innerHTML=visible.map(item=>``).join('');body.querySelectorAll('[data-notification-id]').forEach(item=>item.onclick=()=>handleNotificationClick(item))} +async function loadNotifications(){const body=$('#notificationBody');if(body)body.innerHTML='
    正在加载通知…
    ';try{renderNotifications(await apiRequest('/api/notifications',null,{auth:true}))}catch(error){toast(error.message);if(body)body.innerHTML=`
    通知加载失败

    ${escapeHtml(error.message)}

    `}} +async function handleNotificationClick(item){ + const id=item.dataset.notificationId,link=item.dataset.notificationLink; + const result=await withButtonFeedback(item,async()=>{ + await apiRequest(`/api/notifications/${encodeURIComponent(id)}/read`,{}, {auth:true});item.classList.remove('unread'); + const current=notificationItems.find(notification=>notification.id===id);if(current)current.read=true; + updateNotificationBadge(notificationItems.filter(notification=>!notification.read).length);return true; + },{label:'正在打开…'}); + if(!result||result.feedbackError)return result; + if(link?.startsWith('task:')){const taskId=link.slice(5);if(tasks.some(task=>task.id===taskId)){closeDialogs();openTask(taskId)}} + return result; +} +async function markAllNotificationsRead(){ + return withButtonFeedback($('#markAllNotifications'),async()=>{ + await apiRequest('/api/notifications/read-all',{}, {auth:true});notificationItems.forEach(item=>{item.read=true}); + updateNotificationBadge(0);const summary=$('#notificationSummary');if(summary)summary.textContent='暂无未读通知'; + $$('.notification-item').forEach(item=>item.classList.remove('unread'));toast('已将全部通知标记为已读'); + },{label:'标记中…'}); +} +async function openNotifications(){if(!signedInUser){toast('请先登录后查看通知');openLogin();return}$('#notificationDialog').showModal();await loadNotifications()} +const notificationButton=$('#notificationBtn');if(notificationButton)notificationButton.onclick=openNotifications;const markAllButton=$('#markAllNotifications');if(markAllButton)markAllButton.onclick=markAllNotificationsRead;$$('[data-notif-filter]').forEach(button=>button.onclick=()=>setNotificationFilter(button.dataset.notifFilter)); +const baseRenderAuthForNotifications=renderAuth; +renderAuth=function(user){baseRenderAuthForNotifications(user);if(user)loadNotificationSummary();else updateNotificationBadge(0)}; +if(signedInUser)loadNotificationSummary(); + +// 任务配额:每位用户最多保留 10 条未完成任务,已完成记录只展示最近 20 条。 +let myTaskQuota={activeCount:0,activeLimit:10,completedLimit:20}; +const baseRenderMyTasksWithQuota=renderMyTasks; +renderMyTasks=function(){ + if(!signedInUser){myTaskQuota={activeCount:0,activeLimit:10,completedLimit:20};baseRenderMyTasksWithQuota();return} + const body=$('#myTasksBody');if(!body){baseRenderMyTasksWithQuota();return} + const list=myTasks.filter(t=>myTab==='published'?t.role==='published':t.role==='claimed'); + const hint=`
    未完成任务 ${myTaskQuota.activeCount}/${myTaskQuota.activeLimit} 条 · 已完成记录保留最近 ${myTaskQuota.completedLimit} 条
    `; + if(!list.length){body.innerHTML=hint+`
    ${myTab==='published'?'还没有发布过任务':'还没有接受的任务'}

    ${myTab==='published'?'发布的任务可以在这里管理或取消。':'接下的任务会显示在这里。'}

    `;return} + body.innerHTML=hint+list.map(t=>`
    ${escapeHtml(t.title)}${fmtDeadline(t.deadline)}${t.role==='claimed'&&t.phone?` · ${escapeHtml(String(t.phone))}`:''}${t.reward?` · ${t.reward} 积分`:''}发布于 ${fmtPublishedAt(t.createdAt)}
    ${t.status==='done'?'已完成':t.status==='claimed'?'进行中':'待接单'}
    `).join(''); + body.querySelectorAll('[data-my-task]').forEach(el=>{el.onclick=()=>openMyTask(el.dataset.myTask);el.onkeydown=e=>{if(e.key==='Enter')openMyTask(el.dataset.myTask)}}); +}; +const baseLoadMyTasksWithQuota=loadMyTasks; +loadMyTasks=async function(){ + if(!sessionToken()){myTasks=[];myTaskQuota={activeCount:0,activeLimit:10,completedLimit:20};renderMyTasks();return} + try{const result=await apiRequest('/api/my/tasks',null,{auth:true});myTasks=result.items||[];myTaskQuota={activeCount:Number(result.activeCount)||0,activeLimit:Number(result.activeLimit)||10,completedLimit:Number(result.completedLimit)||20}} + catch{myTasks=[];myTaskQuota={activeCount:0,activeLimit:10,completedLimit:20}} + renderMyTasks() +}; +const baseOpenPublishWithQuota=openPublish; +openPublish=async function(type='express'){ + if(signedInUser){await loadMyTasks();if(myTaskQuota.activeCount>=myTaskQuota.activeLimit){toast(`未完成任务已达到 ${myTaskQuota.activeLimit} 条,请先完成任务`);return}} + await baseOpenPublishWithQuota(type) +}; + +const privacyFallback={version:'v1.2',effectiveAt:'2026-09-27',title:'LinkUp 用户隐私政策',sections:[ + {title:'一、我们收集什么信息',content:'注册时收集姓名、昵称、学号、学校和邮箱;使用快递代取时收集手机号、取件码、取件点、送达位置,以及接单人提交的取件照片和送达照片等任务信息;为保障账号安全,记录登录 IP、设备与浏览器信息;举报、认证和客服过程会保留必要的处理记录。'}, + {title:'二、我们如何使用信息',content:'用于邮箱验证、校园分区、任务匹配、积分结算、信用与安全风控、学生身份认证、举报处理和服务通知。快递任务完成时,两张交付凭证会发送至发布者注册邮箱,用于核对单号、包裹外观和送达位置。对外展示以昵称、学校、信用分、失信率等必要信息为主,不公开身份证号、邮箱验证码、取件码和任务凭证照片等敏感信息。信用调整记录将以脱敏形式(变动分值与调整类型,不含详细原因)在公开主页展示。'}, + {title:'三、信息共享',content:'我们不会出售个人信息。完成任务所必需的信息只会在任务双方之间按权限展示;如发生安全事件、违法举报或法律要求,我们可能依法提供必要信息。'}, + {title:'四、保存与删除',content:'账号存续期间保存账号、任务和积分记录;认证、举报及财务相关记录按业务和法律要求保留。你可以通过客服申请更正或删除可删除的信息,法律要求保留的记录除外。'}, + {title:'五、信息安全',content:'我们采取访问控制、验证码保护、密码单向散列和敏感认证信息加密等措施。请妥善保管邮箱、密码和取件信息,发现异常请立即举报。'}, + {title:'六、联系我们',content:'如需查询、更正、删除个人信息或提出隐私问题,请通过 LinkUp 客服联系平台管理员。政策更新后,我们会在页面提示并在必要时重新征得同意。'} +]}; +function renderPrivacyPolicy(policy){const data=policy||privacyFallback;$('#privacyVersion').textContent=`隐私保护 · ${data.version||privacyFallback.version}`;$('#privacyTitle').textContent=data.title||privacyFallback.title;$('#privacyEffective').textContent=`生效日期:${data.effectiveAt||privacyFallback.effectiveAt}`;$('#privacyBody').innerHTML=(data.sections||[]).map(section=>`

    ${escapeHtml(section.title)}

    ${escapeHtml(section.content)}

    `).join('')} +let privacyPolicyLoadPromise=null; +async function loadPrivacyPolicy(){if(!privacyPolicyLoadPromise)privacyPolicyLoadPromise=apiRequest('/api/privacy-policy').catch(()=>privacyFallback).finally(()=>{privacyPolicyLoadPromise=null});return privacyPolicyLoadPromise} +function setRegistrationPrivacyVersion(policy){const field=$('#registerForm [name="privacyPolicyVersion"]');if(field)field.value=String(policy?.version||privacyFallback.version)} +async function openPrivacyPolicy(){const dialog=$('#privacyDialog');if(!dialog)return;dialog.showModal();renderPrivacyPolicy(privacyFallback);const policy=await loadPrivacyPolicy();setRegistrationPrivacyVersion(policy);renderPrivacyPolicy(policy)} +async function submitRegistrationWithPrivacy(event){event.preventDefault();showRegisterError();const form=event.currentTarget;if(!form.reportValidity())return;const values=Object.fromEntries(new FormData(form));if(!values.privacyPolicyVersion||!values.privacyConsent){showRegisterError('请阅读并同意当前版本的隐私政策');return}setRegisterBusy(true);try{const result=await apiRequest('/api/auth/register',values);saveAuth(result);closeDialogs();form.reset();toast(`注册成功,欢迎你,${result.user.nickname}`)}catch(error){showRegisterError(error.message)}finally{setRegisterBusy(false)}} +$('#registerForm').onsubmit=submitRegistrationWithPrivacy; +$$('[data-open-privacy]').forEach(button=>button.onclick=event=>{event.preventDefault();openPrivacyPolicy()}); +function renderCreditDetails(result){const body=$('#creditBody');if(!body)return;const score=Math.max(0,Math.min(100,Number(result.creditScore)||0));const history=result.history?.length?`

    管理员调整记录

    ${result.history.map(item=>`
    ${escapeHtml(item.reason)}${item.delta>0?'+':''}${item.delta}${new Date(item.createdAt).toLocaleString('zh-CN')}
    `).join('')}
    `:'

    暂无管理员调整记录。

    ';body.innerHTML=`
    当前信用分${score}
    ${Number(result.breachRate||0)}%失信率
    ${Number(result.breachCount||0)}失信次数
    ${Number(result.commitments||0)}履约次数
    ${Number(result.completedTasks||0)}完成任务
    ${Number(result.currentStreak||0)}连续守约
    ${result.invitationEligible?'可生成':'未达标'}邀请码资格
    信用分规则

    信用分初始 70 分,正常发布、接单并完成任务会逐步积累;失约、违规或被核实举报会降低信用分。邀请码资格按可提现积分满 80 判断,与信用分无关。

    ${history}`} +async function openCreditDetails(){if(!signedInUser){openLogin();return}const body=$('#creditBody');if(body)body.innerHTML='
    正在加载信用详情…
    ';$('#creditDialog').showModal();try{renderCreditDetails(await apiRequest('/api/credit/summary',null,{auth:true}))}catch(error){toast(error.message);if(body)body.innerHTML=`
    信用详情加载失败

    ${escapeHtml(error.message)}

    `}} +function bindAccountDetailCards(){const wallets=$$('[data-open-points]'),credits=$$('[data-open-credit]');const isInteractive=event=>!!event.target.closest('button,a,input,select,textarea');wallets.forEach(wallet=>{wallet.onclick=event=>{if(!isInteractive(event))openEntries()};wallet.onkeydown=event=>{if((event.key==='Enter'||event.key===' ')&&!isInteractive(event)){event.preventDefault();openEntries()}}});credits.forEach(credit=>{credit.onclick=event=>{if(!isInteractive(event))openCreditDetails()};credit.onkeydown=event=>{if((event.key==='Enter'||event.key===' ')&&!isInteractive(event)){event.preventDefault();openCreditDetails()}}})} +bindAccountDetailCards(); + +// 全屏或移动端浏览器中,底部导航需要跟随可视区域固定,避免主页面与代取页切换后导航消失。 +(function syncFullscreenLayout(){ + const media = window.matchMedia?.('(display-mode: fullscreen)'); + const isBrowserFullscreen = () => { + const screenHeight = Number(window.screen?.height) || 0; + // F11 浏览器全屏不会设置 document.fullscreenElement,用视口高度作为兼容兜底。 + return screenHeight > 0 && window.innerHeight >= screenHeight - 2 && window.outerHeight >= screenHeight - 2; + }; + const sync = () => { + const fullscreen = Boolean(document.fullscreenElement) || Boolean(media?.matches) || isBrowserFullscreen(); + document.body.classList.toggle('is-fullscreen', fullscreen); + }; + document.addEventListener('fullscreenchange', sync); + window.addEventListener('resize', sync, {passive:true}); + window.addEventListener('orientationchange', sync, {passive:true}); + media?.addEventListener?.('change', sync); + sync(); +})(); + +// 将积分余额、信用摘要提升到个人资料区域;原有详细卡片保留在 DOM 中, +// 以兼容既有数据绑定,但默认不重复展示。 +(function moveAccountSummary(){ + const profile=$('[data-user-profile]'),numbers=profile?.querySelector('.profile-numbers'); + if(!profile||!numbers||profile.querySelector('.profile-account-summary'))return; + const summary=document.createElement('div');summary.className='profile-account-summary';summary.innerHTML='
    积分余额—点击查看积分明细
    积分钱包
    '; + // 恢复原有信息层级:认证卡片之后显示积分余额与钱包操作。 + const identity=profile.querySelector('.identity-card'); + if(identity)identity.insertAdjacentElement('afterend',summary);else numbers.insertAdjacentElement('afterend',summary); + const creditStat=numbers.querySelector('[data-profile-credit]')?.parentElement; + if(creditStat){creditStat.dataset.openCredit='';creditStat.setAttribute('role','button');creditStat.setAttribute('tabindex','0');creditStat.setAttribute('aria-label','打开校园信用详情');creditStat.classList.add('profile-credit-action')} + const breachStat=numbers.querySelector('[data-profile-breach]')?.parentElement; + if(breachStat){breachStat.dataset.openCredit='';breachStat.setAttribute('role','button');breachStat.setAttribute('tabindex','0');breachStat.setAttribute('aria-label','打开失信率详情');breachStat.classList.add('profile-credit-action')} + summary.querySelectorAll('[data-summary-wallet]').forEach(button=>button.onclick=()=>openWallet(button.dataset.summaryWallet)); + const originalRenderAccountMetrics=renderAccountMetrics; + renderAccountMetrics=function(user){originalRenderAccountMetrics(user);const stats=user?.stats;$$('[data-profile-points]').forEach(el=>el.textContent=stats?Number(stats.pointsBalance||0).toLocaleString('zh-CN'):'—');$$('[data-profile-summary-credit]').forEach(el=>el.textContent=stats?String(stats.creditScore):'—')}; + renderAccountMetrics(signedInUser);bindAccountDetailCards(); +})(); + +// 密码功能接线:保留 main 分支现有通知、排序、任务及隐私政策 DOM, +// 仅在现有认证表单上补充密码和忘记密码流程。 +(function bindPasswordAuth(){ + const registerForm=$('#registerForm'), loginForm=$('#loginForm'); + if(!registerForm||!loginForm)return; + const makeField=(id,label,name,type,placeholder)=>{const field=document.createElement('div');field.className='field';field.innerHTML=``;return field}; + const registerGrid=registerForm.querySelector('.form-grid'), registerEmailField=$('#registerEmail')?.closest('.field'); + if(registerGrid&®isterEmailField&&!$('#registerPassword')){ + registerGrid.insertBefore(makeField('registerPassword','设置密码','password','password','至少 8 位'),registerEmailField); + registerGrid.insertBefore(makeField('registerPassword2','确认密码','passwordConfirm','password','再次输入密码'),registerEmailField); + } + const loginGrid=loginForm.querySelector('.form-grid'), oldCodeField=$('#loginCode')?.closest('.field'); + if(loginGrid&&oldCodeField&&!$('#loginPassword')){ + const passwordField=makeField('loginPassword','密码','password','password','请输入密码'); + passwordField.classList.add('full'); + passwordField.querySelector('input').autocomplete='current-password'; + loginGrid.insertBefore(passwordField,oldCodeField); + oldCodeField.id='loginCodeField';oldCodeField.hidden=true; + const code=$('#loginCode');code.disabled=true;code.required=false; + const hint=document.createElement('p');hint.className='form-hint';hint.id='loginStepHint';oldCodeField.appendChild(hint); + const forgot=document.createElement('button');forgot.type='button';forgot.className='forgot-pwd';forgot.id='forgotPasswordBtn';forgot.textContent='忘记密码?'; + passwordField.appendChild(forgot); + } + if(!$('#resetPwdDialog')){ + const dialog=document.createElement('dialog');dialog.id='resetPwdDialog';dialog.className='modal register-modal';dialog.innerHTML='
    '; + document.body.appendChild(dialog);dialog.querySelector('[data-close]').onclick=()=>animateCloseDialog(dialog); + } + function resetLoginStep(){const field=$('#loginCodeField'),code=$('#loginCode'),pwd=$('#loginPassword'),hint=$('#loginStepHint');if(field)field.hidden=true;if(code){code.disabled=true;code.required=false;code.value=''}if(pwd){pwd.disabled=false;pwd.required=false}if(hint)hint.textContent=''} + function showLoginCodeStep(message,testCode){const field=$('#loginCodeField'),code=$('#loginCode'),hint=$('#loginStepHint');field.hidden=false;code.disabled=false;code.required=true;hint.textContent=message||'请输入邮箱验证码完成二次验证';if(testCode)code.value=testCode;setTimeout(()=>code.focus(),0)} + function openLoginPassword(){closeDialogs();$('#loginError').textContent='';resetLoginStep();$('#loginDialog').showModal();setTimeout(()=>$('#loginEmail').focus(),0)} + async function sendRiskCode(){ + const email=$('#loginEmail');$('#loginError').textContent='';if(!email.reportValidity())return; + const button=$('#sendLoginCodeBtn'); + const result=await withButtonFeedback(button,async()=>{ + const result=await apiRequest('/api/auth/send-login-code',{email:email.value}); + showLoginCodeStep('验证码已发送,请查收邮箱',result.testCode);toast('登录验证码已发送');return result; + },{label:'发送中…',onError:error=>{$('#loginError').textContent=error.message}}); + if(result&&!result.feedbackError)startCountdown(button); + } + async function submitLoginPassword(event){ + event.preventDefault();const form=event.currentTarget;$('#loginError').textContent='';if(!form.reportValidity())return; + return withButtonFeedback($('#loginSubmit'),async()=>{ + const result=await apiRequest('/api/auth/login',Object.fromEntries(new FormData(form))); + if(result.needCode){showLoginCodeStep(`检测到新设备或网络环境变化,验证码已发送至 ${result.sentTo||'你的邮箱'},10 分钟内有效`,result.testCode);if(!result.testCode)toast('验证码已发送,请查收邮箱');return} + saveAuth(result);closeDialogs();form.reset();resetLoginStep();toast(`欢迎回来,${result.user.nickname}`); + },{label:'正在登录…',onError:error=>{ + $('#loginError').textContent=error.message; + if(String(error.message).includes('尚未设置密码')){$('#loginPassword').disabled=true;showLoginCodeStep('该账号尚未设置密码,请使用邮箱验证码登录')} + }}); + } + function openResetPwd(){closeDialogs();$('#resetPwdError').textContent='';$('#resetEmail').value=$('#loginEmail').value||'';$('#resetPwdDialog').showModal();setTimeout(()=>$('#resetEmail').focus(),0)} + async function sendResetCode(){ + const email=$('#resetEmail');$('#resetPwdError').textContent='';if(!email.reportValidity())return; + const button=$('#sendResetCodeBtn'); + const result=await withButtonFeedback(button,async()=>{ + const result=await apiRequest('/api/auth/send-reset-code',{email:email.value}); + if(result.testCode)$('#resetCode').value=result.testCode;toast('重置验证码已发送,请查收邮箱');return result; + },{label:'发送中…',onError:error=>{$('#resetPwdError').textContent=error.message}}); + if(result&&!result.feedbackError)startCountdown(button); + } + async function submitResetPwd(event){ + event.preventDefault();const form=event.currentTarget;$('#resetPwdError').textContent='';if(!form.reportValidity())return; + const values=Object.fromEntries(new FormData(form)); + if(values.password!==values.passwordConfirm){$('#resetPwdError').textContent='两次输入的密码不一致';return} + return withButtonFeedback($('#resetPwdSubmit'),async()=>{ + await apiRequest('/api/auth/reset-password',values);closeDialogs();form.reset();openLoginPassword(); + $('#loginEmail').value=values.email;$('#loginError').textContent='密码已重置,请使用新密码登录';toast('密码已重置,请使用新密码登录'); + },{label:'正在重置…',onError:error=>{$('#resetPwdError').textContent=error.message}}); + } + async function submitRegistrationPassword(event){ + event.preventDefault();showRegisterError();const form=event.currentTarget;if(!form.reportValidity())return; + const values=Object.fromEntries(new FormData(form)); + if(values.password!==values.passwordConfirm){showRegisterError('两次输入的密码不一致');return} + if(!values.privacyPolicyVersion||!values.privacyConsent){showRegisterError('请阅读并同意当前版本的隐私政策');return} + return withButtonFeedback($('#registerSubmit'),async()=>{ + const result=await apiRequest('/api/auth/register',values);saveAuth(result);closeDialogs();form.reset();toast(`注册成功,欢迎你,${result.user.nickname}`); + },{label:'正在验证…',onError:error=>showRegisterError(error.message)}); + } + loginForm.onsubmit=submitLoginPassword;registerForm.onsubmit=submitRegistrationPassword;const loginCodeButton=$('#sendLoginCodeBtn');if(loginCodeButton)loginCodeButton.onclick=sendRiskCode;const forgotButton=$('#forgotPasswordBtn');if(forgotButton)forgotButton.onclick=openResetPwd;const resetPwdForm=$('#resetPwdForm');if(resetPwdForm)resetPwdForm.onsubmit=submitResetPwd;const resetCodeButton=$('#sendResetCodeBtn');if(resetCodeButton)resetCodeButton.onclick=sendResetCode;$$('[data-back-login]').forEach(item=>item.onclick=openLoginPassword);$$('[data-open-login]').forEach(item=>item.onclick=openLoginPassword);openLogin=openLoginPassword;submitLogin=submitLoginPassword;window.openResetPwd=openResetPwd; +})(); + +// 积分钱包:真实充值/提现 +let walletMode='recharge'; +function openWallet(mode){ + if(!signedInUser){toast('请先登录后操作积分钱包');openLogin();return} + walletMode=mode;const recharge=mode==='recharge'; + $('#walletTitle').textContent=recharge?'充值积分':'提现积分'; + $('#walletDesc').hidden=!recharge; + $('#walletAmountLabel').textContent=recharge?'充值金额(元)':'提现积分数量'; + $('#walletHint').hidden=!recharge; + $('#walletAmount').min=1;$('#walletAmount').step=1; + $('#walletAmount').placeholder=recharge?'最低 1 元':'请输入整数积分'; + $('#walletAmount').value='';$('#walletError').textContent=''; + $('#walletSubmit').textContent=recharge?'确认充值':'确认提现'; + $('#walletDialog').showModal();setTimeout(()=>$('#walletAmount').focus(),0); +} +async function submitWallet(event){ + event.preventDefault();const form=event.currentTarget;$('#walletError').textContent=''; + if(!form.reportValidity())return; + const values=Object.fromEntries(new FormData(form)); + if(walletMode==='withdraw'&&(!Number.isInteger(Number(values.amount))||Number(values.amount)<=0)){$('#walletError').textContent='提现积分需为正整数';return} + return withButtonFeedback($('#walletSubmit'),async()=>{ + const result=await apiRequest(walletMode==='recharge'?'/api/points/recharge':'/api/points/withdraw',values,{auth:true}); + closeDialogs();form.reset(); + if(walletMode==='recharge')toast(`充值成功,${result.points} 积分已到账`); + else toast(`提现成功,到账 ${Number(result.amountYuan).toFixed(2)} 元`); + const me=await apiRequest('/api/auth/me',null,{auth:true}); + localStorage.setItem('linkup_profile',JSON.stringify(me.user));renderAuth(me.user); + },{label:'正在处理…',onError:error=>{$('#walletError').textContent=error.message}}); +} +$('#walletForm').onsubmit=submitWallet; + +// 积分卡片 3D 倾斜 + 流光(弹簧阻尼回正) +(function initWalletTilt(){ + if (matchMedia('(prefers-reduced-motion: reduce)').matches) return; + document.querySelectorAll('.wallet-card,.profile-summary-stat').forEach(card => { + if (card.dataset.tiltBound) return; + card.dataset.tiltBound = '1'; + const glare = document.createElement('span'); + glare.className = 'tilt-glare'; + card.appendChild(glare); + const st = { rx: 0, ry: 0, vrx: 0, vry: 0, tx: 0, ty: 0, raf: 0, active: false, last: 0 }; + const SPRING = 170, DAMP = 22, MAX_TILT = 8; + function step(ts) { + const dt = Math.min(32, (ts - st.last) || 16) / 1000; st.last = ts; + st.vrx += ((st.tx - st.rx) * SPRING - st.vrx * DAMP) * dt; + st.vry += ((st.ty - st.ry) * SPRING - st.vry * DAMP) * dt; + st.rx += st.vrx * dt; st.ry += st.vry * dt; + card.style.setProperty('--rx', st.rx.toFixed(2) + 'deg'); + card.style.setProperty('--ry', st.ry.toFixed(2) + 'deg'); + const settled = !st.active && Math.abs(st.rx) < .05 && Math.abs(st.ry) < .05 && Math.abs(st.vrx) < .05 && Math.abs(st.vry) < .05; + if (settled) { st.raf = 0; card.style.setProperty('--rx', '0deg'); card.style.setProperty('--ry', '0deg'); } + else st.raf = requestAnimationFrame(step); + } + const wake = () => { if (!st.raf) { st.last = performance.now(); st.raf = requestAnimationFrame(step); } }; + const release = () => { st.active = false; st.tx = 0; st.ty = 0; card.classList.remove('tilting'); wake(); }; + function aim(e) { + const r = card.getBoundingClientRect(); + const px = Math.min(1, Math.max(0, (e.clientX - r.left) / r.width)); + const py = Math.min(1, Math.max(0, (e.clientY - r.top) / r.height)); + st.tx = (0.5 - py) * MAX_TILT; + st.ty = (px - 0.5) * MAX_TILT * 1.4; + card.style.setProperty('--gx', (px * 100).toFixed(1) + '%'); + card.style.setProperty('--gy', (py * 100).toFixed(1) + '%'); + } + card.addEventListener('pointerenter', e => { st.active = true; card.classList.add('tilting'); aim(e); wake(); }); + card.addEventListener('pointermove', e => { if (!st.active) return; aim(e); wake(); }); + card.addEventListener('pointerleave', release); + card.addEventListener('pointerdown', e => { st.active = true; card.classList.add('tilting'); aim(e); wake(); }); + card.addEventListener('pointerup', release); + card.addEventListener('pointercancel', release); + }); +})(); + +// 分段 tab 滑动胶囊 +(function initSlidingThumbs(){ + function updateThumb(container,animate=true){ + const thumb=container.querySelector('.sliding-thumb'); + if(!thumb)return; + const active=container.querySelector('button.active'); + if(!active||!active.offsetWidth)return; + if(!animate)thumb.style.transition='none'; + thumb.style.width=`${active.offsetWidth}px`; + thumb.style.transform=`translateX(${active.offsetLeft}px)`; + if(!animate){void thumb.offsetWidth;thumb.style.transition=''} + } + function updateAllThumbs(){document.querySelectorAll('.has-thumb').forEach(c=>updateThumb(c,false))} + document.querySelectorAll('.segment,.mini-tabs,.publish-switch,.topic-pills').forEach(container=>{ + const thumb=document.createElement('span'); + thumb.className='sliding-thumb'; + container.classList.add('has-thumb'); + container.prepend(thumb); + updateThumb(container,false); + container.querySelectorAll('button').forEach(button=>button.addEventListener('click',()=>updateThumb(container))); + }); + window.addEventListener('resize',updateAllThumbs); + if(document.fonts&&document.fonts.ready)document.fonts.ready.then(updateAllThumbs); + const originalNavigateForThumbs=navigate;navigate=function(name){originalNavigateForThumbs(name);requestAnimationFrame(updateAllThumbs)}; + const originalOpenPublishForThumbs=openPublish;openPublish=function(type){originalOpenPublishForThumbs(type);requestAnimationFrame(()=>updateAllThumbs())}; +})(); + +// 官方运营任务只在「我的」页展示,与任务广场的数据和排序链路隔离。 +let officialTaskItems=[]; +const pendingOfficialClaims = new Set(); +function renderOfficialTasks(items){ + officialTaskItems=items||[]; + const entry=$('[data-action="official-tasks"]'); + if(entry)entry.hidden=!signedInUser||officialTaskItems.length===0; + const body=$('#officialTasksBody'); + if(!body)return; + if(!officialTaskItems.length){body.innerHTML='
    暂无官方活动

    有新的官方积分活动时会显示在这里。

    ';return} + body.innerHTML=`
    ${officialTaskItems.map(task=>{ + const remaining=Number(task.remainingClaims||0), quotaRemaining=task.remainingTotal; + const pending=pendingOfficialClaims.has(String(task.id)); + const disabled=pending||remaining<=0||quotaRemaining===0; + const buttonText=pending?'领取中…':quotaRemaining===0?'名额已领完':remaining<=0?'已达领取上限':'领取任务'; + return `

    ${escapeHtml(task.title)}

    +${Number(task.reward)} 积分

    ${escapeHtml(task.detail||'')}

    每账号限领 ${Number(task.perAccountLimit)} 次我已领 ${Number(task.myClaimCount)} 次 · 剩余 ${remaining} 次总名额剩余 ${quotaRemaining===null?'不限':Number(quotaRemaining)}
    `; + }).join('')}
    `; +} +async function refreshOfficialTasksEntry(showError=false){ + const entry=$('[data-action="official-tasks"]'); + if(!signedInUser){if(entry)entry.hidden=true;officialTaskItems=[];return []} + try{const result=await apiRequest('/api/official-tasks',null,{auth:true});renderOfficialTasks(result.items||[]);return officialTaskItems} + catch(error){ + if(showError){toast(error.message);if(officialTaskItems.length)renderOfficialTasks(officialTaskItems);else $('#officialTasksBody').innerHTML=`
    官方活动加载失败

    ${escapeHtml(error.message)}

    `;} + return []; + } +} +async function openOfficialTasks(){ + if(!signedInUser){openLogin();return} + $('#officialTasksDialog').showModal(); + $('#officialTasksBody').innerHTML='
    正在加载官方活动…
    '; + await refreshOfficialTasksEntry(true); +} +async function claimOfficialTask(button){ + if(!signedInUser){openLogin();return} + const taskId=button.dataset.officialTaskId; + if(button.disabled||pendingOfficialClaims.has(taskId))return; + pendingOfficialClaims.add(taskId); + try { return await withButtonFeedback(button,async()=>{ + const result=await apiRequest(`/api/official-tasks/${encodeURIComponent(taskId)}/claim`,{},{auth:true}); + toast(`领取成功,获得 ${Number(result.reward)} 积分`); + await refreshOfficialTasksEntry(true); + },{label:'领取中…',onError:error=>{if(error.status===401)openLogin();}}); + } finally { pendingOfficialClaims.delete(taskId);renderOfficialTasks(officialTaskItems); } +} +const originalOpenWalletForOfficialTasks=openWallet; +openWallet=function(mode){if(mode==='official-tasks'){openOfficialTasks();return}return originalOpenWalletForOfficialTasks(mode)}; +document.addEventListener('click',event=>{ + const claim=event.target.closest?.('[data-official-task-id]'); + if(claim){event.preventDefault();claimOfficialTask(claim);return} + if(event.target.closest?.('[data-nav="profile"]'))setTimeout(refreshOfficialTasksEntry,0); +}); diff --git a/dist/base.html b/dist/base.html new file mode 100644 index 0000000..40f8457 --- /dev/null +++ b/dist/base.html @@ -0,0 +1,78 @@ + + + + + + + + LinkUp · 校园互助 + + + + + + + + + + +
    + + L + LinkUp + + +
    + + + + +
    +
    + +
    + +
    + + + + + + + + + + + + + + diff --git a/dist/components/dialogs/account.html b/dist/components/dialogs/account.html new file mode 100644 index 0000000..aea3492 --- /dev/null +++ b/dist/components/dialogs/account.html @@ -0,0 +1,27 @@ + + + +
    +
    + + + + +
    正在加载信用详情…
    +
    + + + + +
    +
    + + + + +
    +

    充值即时到账,可用于发布跑腿代办任务。

    + + +
    +
    diff --git a/dist/components/dialogs/auth.html b/dist/components/dialogs/auth.html new file mode 100644 index 0000000..d2dc898 --- /dev/null +++ b/dist/components/dialogs/auth.html @@ -0,0 +1,60 @@ + + + +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    验证码 10 分钟内有效,请勿转发给他人。

    +

    填写后可获得邀请信用加成。

    + +
    + + +
    +
    + + + + +
    +
    +
    +
    + +
    + + + +
    +
    + + + + +
    +
    +
    +
    +
    +
    +
    + + + +
    +
    + + + + +
    + + +
    +
    diff --git a/dist/components/dialogs/notifications.html b/dist/components/dialogs/notifications.html new file mode 100644 index 0000000..b83e69b --- /dev/null +++ b/dist/components/dialogs/notifications.html @@ -0,0 +1,15 @@ + + + +
    正在加载通知…
    +
    diff --git a/dist/components/dialogs/official-tasks.html b/dist/components/dialogs/official-tasks.html new file mode 100644 index 0000000..62fa417 --- /dev/null +++ b/dist/components/dialogs/official-tasks.html @@ -0,0 +1,5 @@ + + + +
    正在加载官方活动…
    +
    diff --git a/dist/components/dialogs/privacy.html b/dist/components/dialogs/privacy.html new file mode 100644 index 0000000..a918e63 --- /dev/null +++ b/dist/components/dialogs/privacy.html @@ -0,0 +1,5 @@ + + + +

    正在加载隐私政策…

    +
    diff --git a/dist/components/dialogs/publish.html b/dist/components/dialogs/publish.html new file mode 100644 index 0000000..33f83fb --- /dev/null +++ b/dist/components/dialogs/publish.html @@ -0,0 +1,6 @@ + + + +
    +
    +
    diff --git a/dist/components/dialogs/social.html b/dist/components/dialogs/social.html new file mode 100644 index 0000000..754b4da --- /dev/null +++ b/dist/components/dialogs/social.html @@ -0,0 +1,19 @@ + + +
    +

    校园私聊

    同学

    + +
    +

    +
    +
    + +
    发送一条消息后,等待对方回复。
    +
    +
    + + + + +
    正在加载信用历史…
    +
    diff --git a/dist/components/dialogs/task.html b/dist/components/dialogs/task.html new file mode 100644 index 0000000..4ffd48a --- /dev/null +++ b/dist/components/dialogs/task.html @@ -0,0 +1,20 @@ + + +
    +
    + + + + +
    正在加载主页…
    +
    + + + + +
    +
    + + +
    +
    diff --git a/dist/components/dialogs/verification.html b/dist/components/dialogs/verification.html new file mode 100644 index 0000000..f55a1ac --- /dev/null +++ b/dist/components/dialogs/verification.html @@ -0,0 +1,31 @@ + +
    + + +
    +
    +

    +
    +
    +
    +
    + + + +
    +
    + + + +
    +
    1

    前往学信网申请或延长《教育部学籍在线验证报告》。

    2

    填写报告中的在线验证码和报告有效期。

    3

    平台审核通过后,你的主页将展示“学信网已认证”。

    + 前往学信网查看验证报告 +
    +

    验证码会加密保存,仅认证审核员可在审核时查看。

    +
    + +
    + + +
    +
    diff --git a/dist/components/toast.html b/dist/components/toast.html new file mode 100644 index 0000000..d2dfa20 --- /dev/null +++ b/dist/components/toast.html @@ -0,0 +1,4 @@ +
    + + +
    diff --git a/dist/config.js b/dist/config.js new file mode 100644 index 0000000..6b628a6 --- /dev/null +++ b/dist/config.js @@ -0,0 +1,4 @@ +// Set this to the deployed HTTPS origin of the independent Node.js backend. +// Local development automatically uses same-origin when left empty. +window.LINKUP_API_BASE = ""; + diff --git a/dist/index.html b/dist/index.html new file mode 100644 index 0000000..1d318c0 --- /dev/null +++ b/dist/index.html @@ -0,0 +1,11 @@ + + + + + + LinkUp · 校园互助 + + +

    LinkUp 页面由 base.html 与多文件组件通过后端组合,请使用项目开发服务器访问。

    + + diff --git a/dist/js/toast.js b/dist/js/toast.js new file mode 100644 index 0000000..e7a6099 --- /dev/null +++ b/dist/js/toast.js @@ -0,0 +1,42 @@ +(() => { + let dismissTimer = 0; + let liftFrame = 0; + + function liftAboveDialogs(element) { + if (!element?.showPopover) return; + try { + if (element.matches(':popover-open')) element.hidePopover(); + element.showPopover(); + } catch { + // Older browsers fall back to the fixed-position z-index styling. + } + } + + function show(message) { + const element = document.getElementById('toast'); + if (!element) return; + + const label = element.querySelector('span'); + if (label) label.textContent = String(message ?? ''); + + window.clearTimeout(dismissTimer); + window.cancelAnimationFrame(liftFrame); + liftAboveDialogs(element); + element.classList.add('show'); + + // Some flows open a dialog immediately after calling toast(). Reinsert the + // popover on the next frame so it is the top-most item in the top layer. + liftFrame = window.requestAnimationFrame(() => liftAboveDialogs(element)); + + dismissTimer = window.setTimeout(() => { + element.classList.remove('show'); + window.setTimeout(() => { + try { + if (element.matches(':popover-open')) element.hidePopover(); + } catch {} + }, 180); + }, 2600); + } + + window.LinkUpToast = Object.freeze({ show }); +})(); diff --git a/dist/social.js b/dist/social.js new file mode 100644 index 0000000..f0bbc77 --- /dev/null +++ b/dist/social.js @@ -0,0 +1,329 @@ +let publicProfileUserId = ''; +let activeChatId = ''; +let activeChatPeer = null; +let chatPollTimer = null; +let reportTarget = null; +let publicHistoryFilter = 'all'; + +function closeOtherDialogs(keepId) { + $$('dialog[open]').forEach(dialog => { + if (dialog.id === keepId) return; + dialog.classList.remove('closing'); + dialog.close(); + }); +} + +const previousPublicProfileLoader = loadPublicProfile; +loadPublicProfile = async function (userId) { + publicProfileUserId = String(userId || ''); + await previousPublicProfileLoader(userId); + const body = $('#publicProfileBody'); + const stats = body?.querySelectorAll('.profile-numbers > div'); + if (!stats || stats.length < 2 || !body.querySelector('.public-profile-head h3')) return; + try { + const profile = await apiRequest(`/api/users/${encodeURIComponent(publicProfileUserId)}/profile`, null, {auth:true}); + const breachValue = stats[1].querySelector('strong'); + if (breachValue) breachValue.textContent = profile.user.breachRateLabel || '记录较少'; + } catch (error) { toast(error.message); } + [['score', '查看信用分调整历史'], ['breach', '查看失信记录']].forEach(([kind, label], index) => { + const stat = stats[index]; + stat.dataset.publicCreditHistory = kind; + stat.classList.add('profile-credit-action'); + stat.setAttribute('role', 'button'); + stat.setAttribute('tabindex', '0'); + stat.setAttribute('aria-label', label); + }); + const head = body.querySelector('.public-profile-head'); + if (!head.querySelector('[data-public-chat]')) { + const button = document.createElement('button'); + button.type = 'button'; + button.className = 'public-chat-button'; + button.dataset.publicChat = publicProfileUserId; + button.textContent = '发私信'; + head.append(button); + } +}; + +function showCreditHistory(kind) { + if (!publicProfileUserId) return; + publicHistoryFilter = kind === 'breach' ? 'negative' : 'all'; + const dialog = $('#creditHistoryDialog'); + const body = $('#creditHistoryBody'); + $('#creditHistoryTitle').textContent = kind === 'breach' ? '失信记录' : '信用历史'; + body.innerHTML = '
    正在加载信用历史…
    '; + dialog.showModal(); + const suffix = publicHistoryFilter === 'negative' ? '?negativeOnly=true' : ''; + apiRequest(`/api/users/${encodeURIComponent(publicProfileUserId)}/credit-history${suffix}`, null, {auth:true}) + .then(result => { + const items = result.items || []; + const history = items.length ? `
    ${items.map(item => + `
    ${escapeHtml(item.category)}${Number(item.delta)>0?'+':''}${Number(item.delta)}
    ` + ).join('')}
    ` : '
    暂无可公开的信用记录
    '; + const hidden = Number(result.hiddenCount) > 0 + ? `

    另有 ${Number(result.hiddenCount)} 条更早记录暂不展示,其中未分类历史不会公开。

    ` : ''; + body.innerHTML = history + hidden; + }) + .catch(error => { body.innerHTML = `
    信用历史加载失败

    ${escapeHtml(error.message)}

    `; toast(error.message); }); +} + +async function openChatForUser(userId, button) { + if (!signedInUser) { openLogin(); return; } + return withButtonFeedback(button, async () => { + const result = await apiRequest('/api/chats', {userId:String(userId)}, {auth:true}); + closeOtherDialogs('chatDialog'); + await openChatDialog(result.id, result.peer); + }, {label:'正在打开…', onError:error => { + if (error.status === 401) openLogin(); + }}); +} + +function renderChatMessages(result) { + activeChatPeer = result.peer || activeChatPeer; + const name = activeChatPeer?.nickname || '同学'; + $('#chatPeerName').textContent = name; + const messages = (result.items || []).slice().reverse(); + const list = $('#chatMessages'); + const previousLast = list.lastElementChild?.dataset.messageId || ''; + if (!messages.length) { + list.innerHTML = '
    打个招呼,开始私聊
    '; + } else { + list.innerHTML = messages.map(message => { + const own = String(message.senderId) === String(signedInUser?.id); + const date = message.createdAt ? new Date(Number(message.createdAt)).toLocaleString('zh-CN', {month:'2-digit',day:'2-digit',hour:'2-digit',minute:'2-digit'}) : ''; + return `
    ${escapeHtml(message.content)}
    `; + }).join(''); + } + const last = messages.at(-1); + const waiting = !!last && String(last.senderId) === String(signedInUser?.id); + $('#chatInput').disabled = waiting; + $('#chatSendButton').disabled = waiting || activeButtons.has($('#chatSendButton')); + $('#chatSendRule').textContent = waiting ? '等待对方回复后可继续发送。' : '发送一条消息后,等待对方回复。'; + $('#chatStatus').textContent = ''; + if (last && String(last.id) !== previousLast) list.scrollTop = list.scrollHeight; +} + +async function refreshChatMessages(showError = false) { + if (!activeChatId || !$('#chatDialog').open) return; + try { + const result = await apiRequest(`/api/chats/${encodeURIComponent(activeChatId)}/messages`, null, {auth:true}); + renderChatMessages(result); + } catch (error) { + if (showError) { $('#chatStatus').textContent = error.message; toast(error.message); } + } +} + +async function openChatDialog(conversationId, peer = null) { + activeChatId = String(conversationId); + activeChatPeer = peer; + $('#chatPeerName').textContent = peer?.nickname || '同学'; + $('#chatMessages').innerHTML = '
    正在加载消息…
    '; + $('#chatStatus').textContent = ''; + $('#chatDialog').showModal(); + await refreshChatMessages(true); + clearInterval(chatPollTimer); + chatPollTimer = setInterval(() => refreshChatMessages(), 10000); +} + +async function sendChatMessage(event) { + event.preventDefault(); + const input = $('#chatInput'); + const button = $('#chatSendButton'); + const content = input.value.trim(); + if (!content || !activeChatId || input.disabled || content.length > 200) return; + return withButtonFeedback(button, async () => { + await apiRequest(`/api/chats/${encodeURIComponent(activeChatId)}/messages`, {content}, {auth:true}); + input.value = ''; + input.disabled = true; + $('#chatSendRule').textContent = '等待对方回复后可继续发送。'; + toast('消息已发送'); + await refreshChatMessages(true); + loadNotificationSummary(); + }, {label:'发送中…', disabledAfter:() => input.disabled, onError:error => { + if (error.status === 403) { + input.disabled = true; + $('#chatSendRule').textContent = '等待对方回复后可继续发送。'; + $('#chatStatus').textContent = '等待对方回复后可继续发送。'; + } else { + $('#chatStatus').textContent = error.message; + } + }}); +} + +async function submitSocialReport(event) { + event.preventDefault(); + const form = event.currentTarget; + if (!form.reportValidity()) return; + const reason = Object.fromEntries(new FormData(form)).reason; + const button = $('#reportSubmit'); + const target = reportTarget || {targetType:'task', targetId:reportTargetId}; + return withButtonFeedback(button, async () => { + await apiRequest('/api/reports', { ...target, reason }, {auth:true}); + form.reset(); + closeOtherDialogs(''); + toast('举报已提交,我们会尽快核实处理'); + }, {label:'正在提交…',onError:error => { $('#reportError').textContent = error.message; }}); +} + +const previousOpenTaskForSocial = openTask; +openTask = function (id) { + previousOpenTaskForSocial(id); + const task = tasks.find(item => item.id === id); + const publisher = $('#taskDetail .publisher'); + if (!task?.userId || !publisher) return; + const avatar = publisher.querySelector('.avatar'); + if (avatar && !publisher.querySelector('[data-publisher-actions]')) { + const button = document.createElement('button'); + button.type = 'button'; + button.className = 'publisher-avatar-button'; + button.dataset.publisherActions = task.userId; + button.setAttribute('aria-label', `查看 ${task.user} 主页或发私信`); + button.setAttribute('aria-haspopup', 'menu'); + const face = document.createElement('span'); + face.className = avatar.className; + face.textContent = task.user.slice(0, 1) || '同'; + button.append(face); + avatar.replaceWith(button); + } +}; + +document.addEventListener('click', event => { + const action = event.target.closest('[data-publisher-choice]'); + if (action) { + event.preventDefault(); event.stopPropagation(); + const menu = action.closest('.publisher-action-popover'); + const userId = menu?.dataset.userId; + const choice = action.dataset.publisherChoice; + if (!userId) { menu?.remove(); return; } + if (choice === 'profile') { menu?.remove(); closeOtherDialogs(''); loadPublicProfile(userId); } + else openChatForUser(userId, action).finally(() => menu?.remove()); + return; + } + const avatar = event.target.closest('[data-publisher-actions]'); + if (avatar) { + event.preventDefault(); event.stopPropagation(); + document.querySelectorAll('.publisher-action-popover').forEach(menu => menu.remove()); + const menu = document.createElement('div'); + menu.className = 'publisher-action-popover'; + menu.dataset.userId = avatar.dataset.publisherActions; + menu.setAttribute('role', 'menu'); + menu.innerHTML = ''; + avatar.closest('.publisher').append(menu); + menu.querySelector('button').focus(); + return; + } + if (!event.target.closest('.publisher-action-popover')) document.querySelectorAll('.publisher-action-popover').forEach(menu => menu.remove()); + + const profileChat = event.target.closest('[data-public-chat]'); + if (profileChat) { event.preventDefault(); openChatForUser(profileChat.dataset.publicChat, profileChat); return; } + const history = event.target.closest('[data-public-credit-history]'); + if (history) { event.preventDefault(); showCreditHistory(history.dataset.publicCreditHistory); } +}, true); + +document.addEventListener('keydown', event => { + const history = event.target.closest('[data-public-credit-history]'); + if (history && (event.key === 'Enter' || event.key === ' ')) { + event.preventDefault(); showCreditHistory(history.dataset.publicCreditHistory); + } +}); + +$('#chatForm').addEventListener('submit', sendChatMessage); +$('#chatReportButton').addEventListener('click', () => { + if (!signedInUser) { openLogin(); return; } + reportTarget = {targetType:'chat', targetId:activeChatId, + targetUserId:activeChatPeer?.id, conversationId:activeChatId}; + $('#reportError').textContent = ''; + $('#reportDialog').showModal(); +}); +$('#chatDialog').addEventListener('close', () => { + // A queued close event from the previous opening must not clear a reopened chat. + if ($('#chatDialog').open) return; + clearInterval(chatPollTimer); chatPollTimer = null; + activeChatId = ''; activeChatPeer = null; +}); +$('#reportForm').onsubmit = submitSocialReport; + +NOTIFICATION_GROUPS.chat = {label:'私聊', kinds:['chat_message'], empty:'暂无私聊消息', hint:'同学回复你的私聊后,消息通知会显示在这里。'}; +NOTIFICATION_KIND_GROUP.chat_message = 'chat'; +const notifTabs = document.querySelector('.notif-tabs'); +if (notifTabs && !notifTabs.querySelector('[data-notif-filter="chat"]')) { + const button = document.createElement('button'); + button.type = 'button'; button.className = 'notif-filter'; button.dataset.notifFilter = 'chat'; + button.setAttribute('role','tab'); button.setAttribute('aria-selected','false'); button.textContent = '私聊'; + button.onclick = () => setNotificationFilter('chat'); + notifTabs.append(button); +} +const previousNotificationClick = handleNotificationClick; +handleNotificationClick = async function (item) { + const link = item.dataset.notificationLink || ''; + const opened = await previousNotificationClick(item); + if (!opened || opened.feedbackError) return; + if (link.startsWith('chat:')) { + const chatId = link.slice(5); + closeOtherDialogs('chatDialog'); + await openChatDialog(chatId); + loadNotificationSummary(); + } +}; +setInterval(() => { if (signedInUser) loadNotificationSummary(); }, 30000); + +const previousRenderInviteV1 = renderInvite; +renderInvite = function (info) { + const body = $('#inviteBody'); + const points = Math.max(0, Number(info.withdrawablePoints) || 0); + const progress = Math.min(100, Math.floor(points / 80 * 100)); + const warning = `
    慎重邀请

    可提现积分满 80 可生成邀请码,每个账号限一个,最多使用 2 次。邀请关系会用于平台风控;恶意邀请或串通违规经核实后,管理员可调整邀请人的信用分。注册时邀请人仍须信用分达到 90。

    `; + if (info.code) { + body.innerHTML = `
    ${escapeHtml(info.code.code)}

    邀请码还可被使用 ${Number(info.code.usesLeft)||0}/${Number(info.code.maxUses)||2} 次。

    ${warning}`; + body.querySelector('[data-copy-invite]').onclick = event => withButtonFeedback(event.currentTarget, async () => { + const text = `【LinkUp 校园互助】邀请邀请码:${info.code.code}\n注册时填写此邀请码,你的初始信用分为 90。\n注册地址:${location.origin}`; + if (!await copyText(text)) throw new Error('复制失败,请长按邀请码手动复制'); + toast('邀请文案已复制,直接发给同学即可'); + }, {label:'复制中…'}); + return; + } + const progressHtml = `
    当前可提现积分 ${points} / 80
    `; + if (info.eligible) { + body.innerHTML = `

    当前可提现积分 ${points},已达到生成条件。

    ${progressHtml}${warning}`; + body.querySelector('[data-gen-invite]').onclick = async event => { + return withButtonFeedback(event.currentTarget, async () => { + renderInvite(await apiRequest('/api/invite-code', {}, {auth:true})); toast('邀请码已生成'); + }, {label:'正在生成…'}); + }; + } else { + body.innerHTML = `

    当前可提现积分 ${points},满 80 可生成邀请码。

    ${progressHtml}${warning}`; + } +}; + +const previousRenderCreditDetailsV1 = renderCreditDetails; +renderCreditDetails = function (result) { + const body = $('#creditBody'); + if (!body) return previousRenderCreditDetailsV1(result); + const score = Math.max(0, Math.min(100, Number(result.creditScore) || 0)); + const breach = result.breachRateLabel || '记录较少'; + const pointsProgress = `${result.invitationEligible ? '可生成' : '未达标'} · ${Math.max(0, Number(result.withdrawablePoints) || 0)} / 80`; + const history = result.history?.length + ? `

    信用分变化记录

    ${result.history.map(item => `
    ${escapeHtml(item.reason)}${item.reversedAt ? ' · 已撤销' : ''}${item.delta > 0 ? '+' : ''}${item.delta}${escapeHtml(new Date(Number(item.createdAt)).toLocaleString('zh-CN'))}
    `).join('')}
    ` + : '

    暂无信用分变化记录。

    '; + body.innerHTML = `
    当前信用分(0–100)${score}
    ${escapeHtml(breach)}近 90 天失信率
    ${Number(result.breachCount90d)||0}近 90 天确认失信
    ${Number(result.commitments90d)||0}近 90 天履约承诺
    ${Number(result.completedTasks)||0}完成任务
    ${Number(result.currentStreak)||0}连续守约
    ${escapeHtml(pointsProgress)}可提现积分 / 邀请码门槛
    信用分与积分

    积分用于任务交易与提现;信用分独立记录履约表现,范围为 0–100。普通注册信用分为 70,邀请码注册为 90。正常完成任务分别为发单者 +1、接单者 +2,每 7 天最多获得 +5。邀请码资格按可提现积分满 80 判断,与信用分无关。

    失信率按近 90 天已形成履约承诺的任务数计算;少于 3 条时显示“记录较少”。积分结算不兑换信用分。

    ${history}`; + if (result.pendingCases?.length) { + const notice = document.createElement('div'); + notice.className = 'credit-pending-notice'; + notice.textContent = `有 ${result.pendingCases.length} 条任务信用处理待管理员核实;处理完成前不会计入已确认失信。`; + body.querySelector('.credit-rules')?.after(notice); + } +}; + +const previousRenderAccountMetricsV1 = renderAccountMetrics; +renderAccountMetrics = function (user) { + previousRenderAccountMetricsV1(user); + const stats = user?.stats; + const breach = stats ? (stats.breachRateLabel || '记录较少') : '—'; + $('[data-breach-rate]').textContent = breach; + $('[data-profile-breach]').textContent = breach; +}; + +publisherMeta = function (task) { + const date = task.registeredAt ? new Date(task.registeredAt).toLocaleDateString('zh-CN', {year:'numeric',month:'2-digit',day:'2-digit'}) : '—'; + const rate = typeof task.breachRate === 'number' ? `${task.breachRate}%` : (task.breachRate || '记录较少'); + return `注册于 ${date} · 近 90 天失信率 ${rate}`; +}; diff --git a/dist/styles.css b/dist/styles.css new file mode 100644 index 0000000..9b78048 --- /dev/null +++ b/dist/styles.css @@ -0,0 +1,382 @@ +:root{--text:#10231f;--ink:#10231f;--ink-2:#28443c;--lime:#e8ff5b;--lime-soft:#f5ffbd;--coral:#ff7455;--paper:#f5f7f3;--white:#fff;--line:#dce4df;--muted:#6d7d77;--shadow:0 18px 50px rgba(16,35,31,.09);--radius:22px}*{box-sizing:border-box}html{scroll-behavior:smooth}body{margin:0;background:var(--paper);color:var(--text);font-family:"Noto Sans SC",system-ui,sans-serif;font-size:16px;line-height:1.5}button,input,textarea,select{font:inherit;color:inherit}button{cursor:pointer}.svg-sprite{position:absolute;width:0;height:0;overflow:hidden}svg{width:20px;height:20px;fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round}.topbar{height:76px;background:rgba(255,255,255,.92);backdrop-filter:blur(18px);display:flex;align-items:center;padding:0 max(28px,calc((100vw - 1240px)/2));position:sticky;top:0;z-index:20;border-bottom:1px solid rgba(16,35,31,.08)}.brand{display:flex;align-items:center;gap:10px;color:var(--text);text-decoration:none;font:800 21px/1 Manrope,sans-serif;letter-spacing:-.6px;margin-right:54px}.brand-mark{width:34px;height:34px;border-radius:11px;background:var(--ink);color:var(--lime);display:grid;place-items:center;position:relative;font-size:20px}.brand-mark span{width:7px;height:7px;background:var(--coral);border-radius:50%;position:absolute;right:6px;top:6px}.desktop-nav{align-self:stretch;display:flex;gap:8px}.nav-item{border:0;background:transparent;padding:0 16px;display:flex;align-items:center;gap:8px;font-weight:600;color:#64736e;position:relative}.nav-item:after{content:"";position:absolute;bottom:0;left:16px;right:16px;height:3px;border-radius:3px;background:var(--ink);transform:scaleX(0);transition:.2s}.nav-item.active{color:var(--text)}.nav-item.active:after{transform:scaleX(1)}.top-actions{margin-left:auto;display:flex;align-items:center;gap:16px}.icon-btn{width:42px;height:42px;border:1px solid var(--line);border-radius:50%;background:var(--white);display:grid;place-items:center;position:relative}.icon-btn i{position:absolute;width:7px;height:7px;background:var(--coral);border-radius:50%;right:8px;top:8px;border:2px solid white}.profile-chip{border:0;background:transparent;display:grid;grid-template-columns:36px auto;column-gap:10px;text-align:left;padding:0}.profile-chip .avatar{grid-row:1/3}.profile-chip>span:nth-child(2){font-weight:700;font-size:14px}.profile-chip small{color:var(--muted);font-size:12px}.avatar{background:var(--lime);border-radius:50%;display:grid;place-items:center;width:36px;height:36px;font-weight:800}.avatar.large{width:74px;height:74px;font-size:26px}main{max-width:1240px;margin:0 auto;padding:44px 28px 100px}.view{display:none}.view.active{display:block;animation:fade .35s ease}@keyframes fadeSwap{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:none}} +@keyframes fade{from{opacity:0;transform:translateY(5px)}to{opacity:1;transform:none}}.welcome-row{display:flex;justify-content:space-between;align-items:flex-end;margin-bottom:34px}.eyebrow{font-size:13px;text-transform:uppercase;letter-spacing:.14em;font-weight:800;color:#60716b;margin:0 0 7px}.welcome-row h1,.page-hero h1,.profile-head h1{font:800 clamp(30px,4vw,44px)/1.12 Manrope,"Noto Sans SC",sans-serif;letter-spacing:-1.5px;margin:0}.lead{color:var(--muted);margin:10px 0 0}.lead strong{color:var(--coral)}.quick-actions,.btn{display:flex;align-items:center;gap:10px}.quick-actions{gap:10px}.btn{border:0;border-radius:14px;padding:13px 18px;font-weight:700;justify-content:center}.btn.primary{background:var(--ink);color:white}.btn.primary:hover{background:#203d35}.btn.secondary{background:var(--white);border:1px solid var(--line)}.btn.coral{background:var(--coral);color:white}.dashboard-grid{display:grid;grid-template-columns:minmax(0,1fr) 340px;gap:26px}.main-column,.side-column>*{background:var(--white);border:1px solid rgba(16,35,31,.08);border-radius:var(--radius)}.main-column{padding:24px}.filter-bar,.section-heading{display:flex;align-items:center;justify-content:space-between;gap:16px}.segment,.topic-pills,.mini-tabs{display:flex;align-items:center;gap:4px;background:var(--paper);padding:4px;border-radius:12px}.segment button,.topic-pills button,.mini-tabs button{border:0;background:transparent;border-radius:9px;padding:8px 13px;color:var(--muted);font-weight:600;font-size:14px}.segment button.active,.topic-pills button.active,.mini-tabs button.active{background:var(--white);color:var(--text);box-shadow:0 3px 12px rgba(16,35,31,.08)}.search-box{height:42px;border:1px solid var(--line);border-radius:12px;display:flex;align-items:center;gap:8px;padding:0 12px;width:240px}.search-box svg{color:var(--muted);width:18px}.search-box input{border:0;outline:0;width:100%;background:transparent;font-size:14px}.section-heading{margin:27px 0 12px}.section-heading h2{font:800 19px/1.2 Manrope,"Noto Sans SC",sans-serif;margin:0}.text-btn{border:0;background:transparent;color:var(--muted);font-size:13px}.sort-control .text-btn{display:inline-flex;align-items:center;gap:4px}.sort-control .text-btn svg{width:15px;height:15px;transition:transform .2s}.sort-control .text-btn[aria-expanded="true"] svg{transform:rotate(180deg)}.task-list{display:flex;flex-direction:column}.task-card{display:grid;grid-template-columns:auto 1fr auto;gap:15px;align-items:start;padding:19px 5px;border-top:1px solid #edf0ee;cursor:pointer;transition:.2s}.task-card:hover{background:#f9faf7;margin:0 -10px;padding-left:15px;padding-right:15px;border-radius:14px}.task-icon{width:46px;height:46px;border-radius:14px;display:grid;place-items:center}.task-icon.express{background:var(--lime-soft)}.task-icon.partner{background:#ffe5de}.task-main{min-width:0}.task-topline{display:flex;align-items:center;gap:8px;margin-bottom:5px}.task-topline strong{font-size:16px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.badge{font-size:11px;font-weight:700;padding:3px 7px;border-radius:6px;color:#52605c;background:#eef2ef;white-space:nowrap}.badge.urgent{color:#b84029;background:#fff0ec}.task-route{color:#50605a;font-size:14px;margin:0 0 10px}.task-meta{display:flex;flex-wrap:wrap;gap:12px;color:var(--muted);font-size:12px}.task-meta span{display:flex;gap:4px;align-items:center}.task-meta svg{width:14px;height:14px}.reward{text-align:right;white-space:nowrap}.reward strong{font:800 20px/1 Manrope,sans-serif}.reward strong:before{content:"+";color:var(--coral)} +.reward.plain strong:before{content:none}.reward.plain strong{color:var(--text)}.reward.plain small{margin-top:5px}.reward small{display:block;color:var(--muted);margin-top:7px}.side-column{display:flex;flex-direction:column;gap:16px}.wallet-card{background:var(--ink)!important;color:white!important;padding:22px;border:0!important;overflow:hidden;position:relative;transform:perspective(900px) rotateX(var(--rx,0deg)) rotateY(var(--ry,0deg)) translateZ(0);will-change:transform} +.tilt-glare{position:absolute;inset:0;pointer-events:none;opacity:0;transition:opacity .35s ease;border-radius:inherit;background:radial-gradient(120% 90% at var(--gx,50%) var(--gy,15%),rgba(232,255,91,.16),rgba(232,255,91,.05) 34%,transparent 62%),linear-gradient(115deg,transparent 32%,rgba(255,255,255,.08) 46%,rgba(255,255,255,.02) 52%,transparent 66%)} +.wallet-card.tilting .tilt-glare{opacity:1}.wallet-card:after{content:"";position:absolute;width:190px;height:190px;background:var(--lime);border-radius:50%;right:-112px;bottom:-115px;opacity:.92}.wallet-top{display:flex;justify-content:space-between;font-size:13px;color:#bdcbc6}.wallet-top span{display:flex;gap:7px;align-items:center}.wallet-top svg{width:17px}.wallet-top button{color:white;background:transparent;border:0}.points{margin:18px 0 20px;display:flex;align-items:baseline;gap:7px}.points strong{font:800 38px/1 Manrope,sans-serif;letter-spacing:-1px}.points span{font-size:13px;color:#bdcbc6}.wallet-actions{display:grid;grid-template-columns:1fr 1fr;gap:8px;position:relative;z-index:1}.wallet-actions button{height:39px;border:1px solid rgba(255,255,255,.18);border-radius:10px;background:rgba(255,255,255,.08);color:white;font-weight:700}.wallet-actions button:first-child{background:var(--lime);color:var(--ink);border-color:var(--lime)}.wallet-card>p{color:#93a7a0;font-size:11px;margin:12px 0 0}.trust-card{padding:20px}.trust-score{display:flex;align-items:baseline;justify-content:space-between}.trust-score span{font-weight:700}.trust-score strong{font:800 27px/1 Manrope,sans-serif}.score-track{height:7px;background:#e8eeea;border-radius:10px;margin:13px 0 16px;overflow:hidden}.score-track i{display:block;height:100%;background:var(--coral);border-radius:10px}.trust-meta{display:grid;grid-template-columns:repeat(3,1fr);gap:8px}.trust-meta span{display:flex;flex-direction:column;font-size:11px;color:var(--muted);border-right:1px solid var(--line)}.trust-meta span:last-child{border:0}.trust-meta b{font-size:15px;color:var(--text);margin-bottom:2px}.invite-btn{margin-top:18px;border:0;border-top:1px solid var(--line);padding:16px 0 0;width:100%;background:var(--white);display:flex;align-items:center;gap:10px;text-align:left}.invite-btn>svg:first-child{background:var(--lime-soft);padding:7px;width:34px;height:34px;border-radius:10px}.invite-btn>svg:last-child{margin-left:auto;color:var(--muted)}.invite-btn span{font-weight:700;font-size:14px}.invite-btn small{display:block;color:var(--muted);font-weight:400;margin-top:2px}.safety-note{display:flex;gap:12px;padding:17px 18px;background:#fff9e6!important}.safety-note>svg{color:#8a6b00;flex:0 0 auto}.safety-note strong{font-size:13px}.safety-note p{font-size:11px;color:#776b49;margin:4px 0 0}.page-hero{min-height:230px;border-radius:30px;background:var(--ink);color:white;padding:42px 46px;display:flex;align-items:flex-end;justify-content:space-between;position:relative;overflow:hidden}.page-hero:before{content:"";position:absolute;width:320px;height:320px;border:70px solid var(--lime);border-radius:50%;right:18%;top:-210px;opacity:.94}.page-hero>*{position:relative;z-index:1}.page-hero p:not(.eyebrow){color:#b7c7c2;max-width:520px}.page-hero .eyebrow{color:var(--lime)}.partner-hero{background:#342420}.partner-hero:before{border-color:var(--coral)}.partner-hero .eyebrow{color:#ffc1b2}.stats-strip{display:grid;grid-template-columns:repeat(3,1fr);background:var(--white);margin:-1px 32px 34px;border-radius:0 0 22px 22px;border:1px solid var(--line);border-top:0}.stats-strip div{display:flex;flex-direction:column;padding:18px 28px;border-right:1px solid var(--line)}.stats-strip div:last-child{border:0}.stats-strip b{font:800 19px Manrope,sans-serif}.stats-strip span{font-size:12px;color:var(--muted)}.content-narrow{max-width:850px;margin:0 auto;background:var(--white);border:1px solid var(--line);padding:8px 26px 22px;border-radius:var(--radius)}#view-express .content-narrow{max-width:none;margin:24px 0 0}.muted{color:var(--muted);font-size:13px}.topic-pills{margin:24px 0}.partner-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:18px} +.partner-grid .empty-state{grid-column:1/-1}.partner-card{background:var(--white);border:1px solid var(--line);border-radius:20px;padding:22px;min-height:230px;display:flex;flex-direction:column;cursor:pointer;transition:.2s}.partner-card:hover{transform:translateY(-3px);box-shadow:var(--shadow)}.partner-card .category{font-size:12px;font-weight:800;color:var(--coral);letter-spacing:.08em}.partner-card h3{font-size:18px;margin:12px 0 8px}.partner-card p{color:var(--muted);font-size:14px;margin:0}.partner-card footer{display:flex;align-items:center;justify-content:space-between;margin-top:auto;padding-top:20px}.partner-card footer span{display:flex;align-items:center;gap:7px;font-size:13px}.mini-avatar{width:28px;height:28px;border-radius:50%;background:var(--lime);display:grid!important;place-items:center;font-weight:800}.partner-card footer b{font-size:13px;color:var(--text)}.profile-layout{display:grid;grid-template-columns:1fr 1.2fr;gap:24px}.profile-panel,.activity-panel{background:var(--white);border:1px solid var(--line);border-radius:var(--radius);padding:28px}.profile-head{display:flex;align-items:center;gap:17px}.profile-head h1{font-size:27px}.profile-head p{color:var(--muted);margin:4px 0}.verified{margin-left:auto;background:#eaf7f2;color:#276953;padding:6px 9px;border-radius:8px;font-size:12px;font-weight:700;display:flex;align-items:center;gap:5px}.verified svg{width:15px}.profile-numbers{display:grid;grid-template-columns:repeat(4,1fr);margin-top:28px;border-top:1px solid var(--line);padding-top:22px}.profile-numbers div{display:flex;flex-direction:column}.profile-numbers strong{font:800 18px Manrope,sans-serif}.profile-numbers span{font-size:12px;color:var(--muted)}.activity-panel .section-heading{margin:0 0 10px}.my-task{display:grid;grid-template-columns:auto 1fr auto;align-items:center;gap:12px;border-top:1px solid var(--line);padding:17px 0}.my-task p{font-size:12px;color:var(--muted);margin:3px 0}.my-task>b{font-size:13px}.modal{border:0;border-radius:24px;padding:0;box-shadow:0 32px 90px rgba(9,27,22,.3);max-height:90vh}.modal::backdrop{background:rgba(9,27,22,.6);backdrop-filter:blur(4px)} +@keyframes modalIn{from{opacity:0;transform:translateY(16px) scale(.96)}to{opacity:1;transform:none}} +@keyframes modalOut{to{opacity:0;transform:translateY(12px) scale(.97)}} +@keyframes backdropIn{from{opacity:0}to{opacity:1}} +@keyframes backdropOut{to{opacity:0}} +dialog.modal[open]{animation:modalIn .26s cubic-bezier(.32,.72,.28,1)} +dialog.modal[open]::backdrop{animation:backdropIn .26s ease} +dialog.modal.closing{animation:modalOut .2s ease forwards} +dialog.modal.closing::backdrop{animation:backdropOut .2s ease forwards} +*{scrollbar-width:thin;scrollbar-color:rgba(16,35,31,.28) transparent} +::-webkit-scrollbar{width:7px;height:7px} +::-webkit-scrollbar-track{background:transparent} +::-webkit-scrollbar-thumb{background:rgba(16,35,31,.25);border-radius:99px} +::-webkit-scrollbar-thumb:hover{background:rgba(16,35,31,.42)} +.sliding-thumb{position:absolute;top:4px;bottom:4px;left:0;width:0;background:var(--white);border-radius:9px;box-shadow:0 3px 12px rgba(16,35,31,.08);transition:transform .32s cubic-bezier(.32,.72,.28,1),width .32s cubic-bezier(.32,.72,.28,1);pointer-events:none} +.has-thumb{position:relative} +.has-thumb>button{position:relative;z-index:1} +.has-thumb button.active{background:transparent;box-shadow:none}.modal-close{position:absolute;right:18px;top:18px;border:0;background:var(--paper);width:38px;height:38px;border-radius:50%;display:grid;place-items:center;z-index:2}.task-modal{width:min(580px,calc(100vw - 28px));padding:34px}.detail-type{display:inline-flex;gap:7px;align-items:center;padding:6px 9px;background:var(--lime-soft);border-radius:8px;font-size:12px;font-weight:800}.detail-title{font-size:27px;margin:18px 50px 8px 0}.detail-route{color:var(--muted);margin:0}.detail-box{background:var(--paper);border-radius:16px;padding:16px;margin:22px 0;display:grid;grid-template-columns:1fr 1fr;gap:14px}.detail-box div{display:flex;flex-direction:column}.detail-box span{font-size:12px;color:var(--muted)}.detail-box strong{font-size:14px;margin-top:3px}.publisher{display:flex;align-items:center;gap:11px;border-top:1px solid var(--line);padding-top:17px}.publisher div{display:flex;flex-direction:column}.publisher span{font-size:12px;color:var(--muted)}.publisher em{margin-left:auto;font-style:normal;font-size:12px;color:#287056;background:#eaf7f2;padding:6px 8px;border-radius:8px}.detail-actions{display:grid;grid-template-columns:1fr 2fr;gap:10px;margin-top:24px}.detail-actions button{height:48px;border-radius:13px;font-weight:800}.report-btn{border:1px solid var(--line);background:var(--white)}.accept-btn{border:0;background:var(--ink);color:white}.publish-modal{width:min(650px,calc(100vw - 28px));padding:32px}.modal-title h2{font-size:26px;margin:0}.publish-switch{display:flex;background:var(--paper);padding:4px;border-radius:12px;margin:22px 0}.publish-switch button{flex:1;border:0;background:transparent;padding:10px;border-radius:9px;font-weight:700;color:var(--muted)}.publish-switch button.active{background:var(--white);color:var(--text);box-shadow:0 3px 12px rgba(16,35,31,.08)}.form-grid{display:grid;grid-template-columns:1fr 1fr;gap:14px}.field{display:flex;flex-direction:column;gap:6px}.field.full{grid-column:1/-1}.field label{font-size:13px;font-weight:700}.field input,.field textarea,.field select{border:1px solid var(--line);border-radius:11px;background:var(--white);padding:11px 12px;outline:none}.field input:focus,.field textarea:focus,.field select:focus{border-color:var(--text);box-shadow:0 0 0 3px rgba(16,35,31,.08)}.field textarea{min-height:78px;resize:vertical}.form-hint{font-size:11px;color:var(--muted);margin:3px 0 0}.submit-publish{width:100%;height:49px;border:0;border-radius:13px;background:var(--ink);color:white;font-weight:800;margin-top:20px}.empty-state{text-align:center;padding:55px 10px;color:var(--muted)}.empty-state span{font-weight:800;color:var(--text)}.empty-state p{font-size:13px}.toast{position:fixed;top:auto;right:auto;left:50%;bottom:34px;margin:0;transform:translate(-50%,20px);background:var(--ink);color:white;padding:12px 17px;border-radius:12px;display:flex;gap:9px;align-items:center;z-index:60;opacity:0;pointer-events:none;transition:.25s;box-shadow:var(--shadow)}.toast.show{opacity:1;transform:translate(-50%,0)}.toast svg{color:var(--lime)}.mobile-nav{display:none} +@media(max-width:900px){.desktop-nav{display:none}.topbar{padding:0 20px}.profile-chip>span:nth-child(2),.profile-chip small{display:none}.profile-chip{display:block}.brand{margin-right:0}.dashboard-grid{grid-template-columns:1fr}.side-column{display:grid;grid-template-columns:1fr 1fr}.safety-note{grid-column:1/-1}.partner-grid{grid-template-columns:1fr 1fr}.profile-layout{grid-template-columns:1fr}.page-hero:before{right:-80px}.welcome-row{align-items:flex-start}} +@media(max-width:640px){body{padding-bottom:74px}.toast{bottom:86px}.topbar{height:62px}.top-actions .profile-chip{display:none}.brand{font-size:19px}.brand-mark{width:31px;height:31px}main{padding:27px 14px 55px}.welcome-row{display:block}.welcome-row h1{font-size:30px}.quick-actions{margin-top:22px}.quick-actions .btn{flex:1;padding:12px 10px}.dashboard-grid{display:block}.main-column{padding:15px;border-radius:18px}.side-column{display:flex;margin-top:16px}.filter-bar{display:block}.segment{width:100%;display:grid;grid-template-columns:repeat(3,1fr)}.segment button{padding:8px 4px}.search-box{width:100%;margin-top:10px}.task-card{grid-template-columns:auto 1fr}.task-card .reward{grid-column:2;text-align:left}.reward small{display:inline;margin-left:7px}.task-icon{width:40px;height:40px}.task-topline{align-items:flex-start}.task-meta{gap:7px}.wallet-card{order:-1}.desktop-nav{display:none}.mobile-nav{position:fixed;display:grid;grid-template-columns:repeat(5,1fr);left:0;right:0;bottom:0;height:70px;background:rgba(255,255,255,.96);backdrop-filter:blur(16px);z-index:30;border-top:1px solid var(--line);padding:7px 8px 4px}.mobile-nav button{border:0;background:transparent;color:#77847f;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:2px;font-size:10px}.mobile-nav button.active{color:var(--text)}.mobile-nav svg{width:21px}.mobile-nav .mobile-publish{width:46px;height:46px;background:var(--ink);color:var(--lime);border-radius:14px;justify-self:center;margin-top:2px}.mobile-nav .mobile-publish svg{width:25px;height:25px}.page-hero{padding:30px 24px;min-height:220px;display:block;border-radius:22px}.page-hero .btn{margin-top:22px}.page-hero:before{width:230px;height:230px;border-width:50px;right:-110px;top:-130px}.stats-strip{margin:-1px 12px 22px}.stats-strip div{padding:14px 10px}.stats-strip b{font-size:15px}.content-narrow{padding:6px 15px 15px}.topic-pills{overflow:auto;justify-content:flex-start;padding-bottom:4px;scrollbar-width:none}.topic-pills::-webkit-scrollbar{display:none}.topic-pills button{white-space:nowrap}.partner-grid{grid-template-columns:1fr}.profile-panel,.activity-panel{padding:20px}.profile-head{display:grid;grid-template-columns:auto minmax(0,1fr);align-items:center;column-gap:14px}.profile-head > div{min-width:0}.profile-head .avatar{width:56px;height:56px;font-size:22px}.profile-head .verified{grid-column:1/-1;justify-self:start;margin-top:12px}.profile-numbers{grid-template-columns:1fr 1fr;gap:17px}.profile-numbers div{text-align:center}.modal{border-radius:20px}.task-modal,.publish-modal{padding:25px 20px}.form-grid{grid-template-columns:1fr}.field.full{grid-column:auto}.detail-box{grid-template-columns:1fr}.top-actions{gap:8px}} +@media(prefers-reduced-motion:reduce){*{scroll-behavior:auto!important;animation:none!important;transition:none!important}} +.pickup-codes{display:flex;flex-direction:column;gap:8px}.pickup-code-row{display:grid;grid-template-columns:minmax(0,1fr) 44px;gap:8px}.pickup-code-row input{width:100%;min-width:0}.code-action{border:1px solid var(--ink);border-radius:11px;background:var(--ink);color:var(--lime);font:800 22px/1 Manrope,sans-serif;display:grid;place-items:center;transition:.2s}.code-action:hover{background:var(--ink-2)}.code-action:focus-visible{outline:3px solid rgba(16,35,31,.18);outline-offset:2px}.code-action.remove-code{background:var(--white);color:var(--coral);border-color:var(--line)} +.register-btn{border:1px solid var(--ink);background:var(--ink);color:white;border-radius:11px;padding:9px 14px;font-weight:700;font-size:13px}.register-modal{width:min(650px,calc(100vw - 28px));padding:32px}.register-modal .modal-title>p:last-child{color:var(--muted);font-size:13px;margin:8px 42px 0 0}.verification-row{display:grid;grid-template-columns:minmax(0,1fr) 118px;gap:8px}.verification-row input{min-width:0}.verification-row button{border:1px solid var(--ink);border-radius:11px;background:var(--ink);color:white;font-weight:700;font-size:13px}.verification-row button:disabled{background:#d9dfdc;border-color:#d9dfdc;color:#71807b;cursor:not-allowed}.form-error{min-height:21px;margin:12px 0 -8px;color:#ba3e27;font-size:13px}.submit-publish:disabled{opacity:.55;cursor:not-allowed}@media(max-width:640px){.top-actions .register-btn{display:block;padding:8px 11px}.register-modal{padding:25px 20px}.verification-row{grid-template-columns:minmax(0,1fr) 106px}} +[hidden]{display:none!important} +.fade-swap{animation:fadeSwap .3s ease}.login-btn{border:1px solid var(--line);background:var(--white);border-radius:11px;padding:9px 14px;font-weight:700;font-size:13px}.guest-profile{text-align:center;display:flex;flex-direction:column;align-items:center;padding:18px 0}.guest-profile .avatar{color:var(--text)}.guest-profile h1{font-size:23px;margin:15px 0 5px}.guest-profile p{color:var(--muted);font-size:14px;margin:0 0 20px}.guest-profile .btn{min-width:150px}.logout-btn{margin-top:24px;border:1px solid var(--line);background:var(--white);color:var(--muted);border-radius:10px;padding:10px 14px;font-weight:700;display:inline-flex;align-items:center;justify-content:center;gap:8px;transition:.2s}.logout-btn svg{width:17px;height:17px}.logout-btn:hover{color:#a6422f;border-color:#e8b7ac;background:#fff5f2}.logout-btn:focus-visible{outline:3px solid rgba(255,116,85,.22);outline-offset:2px}.logout-dialog-actions{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-top:24px}.logout-dialog-actions .btn{min-height:48px}.logout-confirm{background:#b94a35;color:white}.logout-confirm:hover{background:#9f3d2b}.logout-confirm:disabled{opacity:.6;cursor:wait}.logout-confirm svg{width:18px;height:18px}.switch-auth{display:block;margin:14px auto 0;border:0;background:transparent;color:var(--ink-2);font-weight:700;font-size:13px} +.forgot-pwd{align-self:flex-end;margin-top:2px;border:0;background:transparent;color:var(--muted);font-weight:500;font-size:12px;line-height:1.2;padding:0;cursor:pointer} +.forgot-pwd:hover{color:var(--text)}.empty-state.compact{padding:55px 10px}.avatar svg{width:23px;height:23px}@media(max-width:640px){.top-actions .login-btn{display:block;padding:8px 11px}.top-actions .register-btn{display:none}} +.identity-card{margin-top:22px;padding:17px;border:1px solid var(--line);background:linear-gradient(135deg,#f7faf6,#f0f7e5);border-radius:16px;display:flex;align-items:center;justify-content:space-between;gap:16px}.identity-copy{display:flex;align-items:center;gap:13px}.identity-copy strong{font-size:15px}.identity-copy p{margin:4px 0 0;color:var(--muted);font-size:13px;line-height:1.5}.identity-icon{width:40px;height:40px;display:grid;place-items:center;border-radius:12px;background:var(--lime);color:var(--ink);flex:none}.identity-icon svg{width:20px;height:20px}.identity-action{white-space:nowrap}.verified.pending{background:#fff5df;color:#976400}.verified.approved{background:#e9f7db;color:#315d14}.verified.rejected,.verified.expired{background:#fff0ec;color:#a6422f}.verification-guide{display:grid;grid-template-columns:28px 1fr;gap:10px 12px;margin:18px 0}.verification-guide span{width:28px;height:28px;border-radius:50%;display:grid;place-items:center;background:var(--ink);color:white;font-size:13px;font-weight:800}.verification-guide p{margin:3px 0;color:var(--muted);font-size:14px;line-height:1.5}.chsi-link{display:inline-flex;align-items:center;color:var(--ink-2);font-size:14px;font-weight:750;text-decoration:underline;text-underline-offset:3px;margin-bottom:18px}.consent-row{grid-column:1/-1;display:flex;gap:9px;align-items:flex-start;color:var(--muted);font-size:13px;line-height:1.5}.consent-row input{width:auto;margin-top:3px}.admin-review-btn{margin:12px 0 0;border:0;background:var(--ink);color:white;border-radius:10px;padding:10px 14px;font-weight:750;display:flex;align-items:center;gap:7px}.admin-review-btn svg{width:16px;height:16px}.admin-modal{width:min(820px,calc(100vw - 28px));padding:32px}.admin-toolbar{display:flex;justify-content:space-between;align-items:center;margin:20px 0 14px}.admin-toolbar .chsi-link{margin:0}.admin-toolbar button{border:1px solid var(--line);background:var(--white);border-radius:9px;padding:8px 12px;font-weight:700}.admin-list{display:flex;flex-direction:column;gap:12px;max-height:58vh;overflow:auto}.review-card{border:1px solid var(--line);border-radius:15px;padding:17px}.review-head{display:flex;justify-content:space-between;gap:16px}.review-head strong{font-size:16px}.review-head span,.review-meta{color:var(--muted);font-size:13px}.review-code{margin:14px 0;padding:12px 14px;border-radius:11px;background:#f3f5f2;display:flex;justify-content:space-between;gap:15px}.review-code code{font-size:15px;font-weight:800;letter-spacing:1px}.review-card textarea{width:100%;min-height:70px;margin-top:10px;border:1px solid var(--line);border-radius:10px;padding:10px}.review-actions{display:flex;justify-content:flex-end;gap:8px;margin-top:10px}.review-actions button{border:1px solid var(--line);border-radius:9px;padding:9px 14px;font-weight:750;background:var(--white)}.review-actions .approve{background:var(--ink);border-color:var(--text);color:white}@media(max-width:640px){.identity-card{align-items:flex-start;flex-direction:column}.identity-action{width:100%}.admin-modal{padding:25px 18px}.review-head,.review-code{flex-direction:column}.review-actions button{flex:1}} +[data-account-action]:disabled{opacity:.48;cursor:not-allowed} + +/* 个人页摘要:积分与信用放到个人资料下方,详细内容通过点击打开。 */ +.account-overview{display:none!important} +.profile-account-summary{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;margin-top:22px;padding-top:22px;border-top:1px solid var(--line)} +.profile-summary-stat{display:flex;flex-direction:column;gap:3px;min-width:0;padding:14px 16px;border:1px solid var(--line);border-radius:14px;background:var(--paper);text-align:left;cursor:pointer;transition:transform .2s,box-shadow .2s,border-color .2s} +.profile-summary-stat:hover{transform:translateY(-2px);box-shadow:var(--shadow);border-color:var(--ink-2)} +.profile-summary-stat:focus-visible{outline:3px solid var(--coral);outline-offset:2px} +.profile-summary-stat span{font-size:12px;color:var(--muted)} +.profile-summary-stat strong{font:800 24px/1.1 Manrope,"Noto Sans SC",sans-serif;color:var(--text)} +.profile-summary-stat small{font-size:11px;color:var(--muted)} +.profile-credit-action{cursor:pointer;padding:8px 10px;margin:-8px -10px}.profile-credit-action:focus-visible{outline:3px solid var(--coral);outline-offset:2px} +.profile-credit-action{width:max-content;max-width:100%;justify-self:center;padding:4px 6px;margin:-4px -6px} +.profile-summary-actions{display:flex;flex-direction:column;justify-content:center;gap:9px;padding:14px 16px;border:1px solid var(--line);border-radius:14px;background:var(--paper)} +.profile-summary-actions>span{font-size:12px;color:var(--muted)} +.profile-summary-actions>div{display:grid;grid-template-columns:1fr 1fr;gap:8px} +.profile-summary-actions button{height:36px;border:1px solid var(--line);border-radius:10px;background:var(--white);font-weight:750;cursor:pointer;transition:transform .2s,background .2s,border-color .2s}.profile-summary-actions button:first-child{background:var(--lime);border-color:var(--lime);color:var(--ink)}.profile-summary-actions button:hover{transform:translateY(-1px);border-color:var(--ink-2)}.profile-summary-actions button:focus-visible{outline:3px solid var(--coral);outline-offset:2px} +.profile-invite-btn{margin-top:22px;padding:16px;border:1px solid var(--line);border-radius:14px;background:var(--paper);color:var(--text);cursor:pointer}.profile-invite-btn:hover{border-color:var(--ink-2)}.profile-invite-btn:focus-visible{outline:3px solid var(--coral);outline-offset:2px}.profile-invite-btn>svg:first-child{flex:none}.profile-invite-btn>span{min-width:0} +@media(max-width:560px){.profile-account-summary{grid-template-columns:1fr 1fr;gap:9px}.profile-summary-stat{padding:12px}.profile-summary-stat strong{font-size:21px}} +@media(max-width:900px){.profile-credit-action{justify-self:center}} + +/* 移动端和 PWA/浏览器全屏时,底部导航始终固定在可视区域上方。 */ +@media(max-width:900px){body{padding-bottom:84px}.mobile-nav{display:grid;position:fixed;inset-inline:0;bottom:0;height:74px;padding:7px 8px 4px;z-index:1000;isolation:isolate}} +@media(display-mode:fullscreen){body{padding-bottom:84px}.mobile-nav{display:grid;position:fixed;inset-inline:0;bottom:0;height:74px;z-index:1000;isolation:isolate}} + +/* 窄屏个人资料头部:认证徽章与姓名保持同一行,避免把统计区向下顶开。 */ +@media(max-width:640px){.profile-head{grid-template-columns:56px minmax(0,1fr) auto;align-items:center;column-gap:10px;row-gap:0}.profile-head .avatar{grid-column:1;grid-row:1}.profile-head>div{grid-column:2;grid-row:1}.profile-head .verified{grid-column:3;grid-row:1;justify-self:end;width:auto;margin:0;white-space:nowrap}} + +.invite-code-box{display:flex;align-items:stretch;gap:10px;margin:16px 0 10px}.invite-code-box code{flex:1;display:flex;align-items:center;justify-content:center;background:var(--ink);color:var(--lime);border-radius:14px;padding:17px 12px;font-size:21px;font-weight:800;letter-spacing:5px;font-family:inherit}.invite-hint{margin:6px 0 0;color:var(--muted);font-size:13px}.invite-rules{margin:16px 0 0;padding:14px 16px;background:var(--paper);border-radius:12px;color:var(--muted);font-size:13px;line-height:1.9}.invite-rules strong{display:block;color:var(--text);margin-bottom:4px}.invite-rules p{margin:0} +.invite-warning{margin:14px 0 0;padding:16px 18px;background:#fdf0ec;border:1px solid #f0cfc5;border-radius:14px;font-size:14px;line-height:1.9}.invite-warning strong{display:flex;align-items:center;gap:8px;margin-bottom:6px;color:#b84432;font-size:15px}.invite-warning strong svg{width:17px;height:17px;fill:none;stroke:#b84432;stroke-width:2;stroke-linecap:round;stroke-linejoin:round}.invite-warning p{margin:0;color:#8a4a3c}.invite-warning b{color:#b84432} +.entries-summary{display:flex;gap:10px;margin:14px 0 10px}.entries-summary div{flex:1;background:var(--paper);border-radius:12px;padding:12px 14px}.entries-summary span{display:block;font-size:12px;color:var(--muted)}.entries-summary strong{font-size:21px;color:var(--text)}.entries-list{display:grid;gap:8px;max-height:320px;overflow:auto}.entry-row{display:flex;align-items:baseline;gap:10px;font-size:13px;padding:11px 13px;background:var(--paper);border-radius:10px}.entry-row span{flex:1;color:var(--text)}.entry-row .pos{color:#356217;font-weight:800}.entry-row .neg{color:#b84432;font-weight:800}.entry-row em{margin-left:auto;color:var(--muted);font-style:normal;font-size:12px} +@media(prefers-color-scheme:dark){*{scrollbar-color:rgba(231,237,233,.26) transparent}::-webkit-scrollbar-thumb{background:rgba(231,237,233,.22)}::-webkit-scrollbar-thumb:hover{background:rgba(231,237,233,.4)}.notification-item.unread{background:#223018;border-color:#31421f}:root{color-scheme:dark;--text:#e7ede9;--paper:#0e1512;--white:#15201b;--line:#243830;--muted:#8ba39a;--lime-soft:#2c3a20;--shadow:0 18px 50px rgba(0,0,0,.5)}.topbar{background:rgba(13,20,17,.88);border-bottom-color:rgba(255,255,255,.06)}.mobile-nav{background:rgba(13,20,17,.96)}.modal{background:#15201b;color:var(--text)}.safety-note{background:#241f0e!important}.task-card:hover{background:#18241f}.review-code{background:#18241f}.badge{background:#1d2b25}.verified{background:#17251a;color:#7fb069}.verified.pending{background:#2b2410;color:#d9b03c}.verified.rejected,.verified.expired{background:#2b1712;color:#e08a72}.badge.urgent{background:#2b1712;color:#e08a72}.task-icon.partner{background:#33221d}.identity-card{background:#131b17}.invite-warning{background:#2b1c16;border-color:#45291f}.invite-warning p{color:#d8a899}.entries-summary div{background:#18241f}.entry-row{background:#18241f}.mobile-publish{background:var(--lime);color:var(--ink)}.field input:focus,.field select:focus,.field textarea:focus{border-color:#3f5a50;box-shadow:0 0 0 3px rgba(255,255,255,.06)}} +.mytask-row{display:flex;align-items:center;justify-content:space-between;gap:10px;background:var(--white);border:1px solid var(--line);border-radius:12px;padding:12px 14px;margin-top:8px} +.mytask-row{cursor:pointer;transition:.2s} +.mytask-row:hover{border-color:var(--ink-2);transform:translateY(-1px)}.mytask-main{min-width:0}.mytask-main strong{display:block;font-size:14px;margin-bottom:2px}.mytask-main small{color:var(--muted);font-size:12px}.mytask-row em{font-style:normal;font-size:12px;font-weight:800;border-radius:999px;padding:5px 10px;flex:none}.mytask-row em.ongoing{background:var(--lime-soft);color:var(--ink)}.mytask-row em.done{background:#17251a;color:#7fb069} +.compact-hero{min-height:150px;padding:30px 40px;border-radius:26px} +.claim-contact{margin:14px 0 0;padding:14px 18px;background:var(--lime-soft);border-radius:12px;display:grid;gap:4px} +.claim-contact strong{font-size:13px;color:var(--ink)} +.claim-contact a{font:800 21px Manrope,"Noto Sans SC",sans-serif;color:var(--ink);text-decoration:none;letter-spacing:1px} +.claim-contact p{margin:0;font-size:13px;color:var(--text)} +.claim-contact .no-phone{margin:2px 0 0;font-size:13px;color:var(--muted)} +/* Public classmate profiles */ +.publisher-link{border:0;background:transparent;color:inherit;padding:0;font:inherit;font-weight:800;text-align:left;text-decoration:underline;text-decoration-color:rgba(25,69,59,.3);text-underline-offset:3px;cursor:pointer} +.publisher-link:hover{color:var(--ink2);text-decoration-color:currentColor} +.profile-modal{width:min(520px,calc(100vw - 32px));padding:28px} +.public-profile-head{display:flex;align-items:center;gap:14px;margin:8px 0 22px} +.public-profile-head h3{margin:0 0 4px;font-size:20px} +.public-profile-head p{margin:0;color:var(--muted)} +.public-profile-head .verified{margin-left:auto;white-space:nowrap} +.public-profile-meta{margin:18px 0 0;color:var(--muted);font-size:13px} +@media(max-width:560px){.public-profile-head{align-items:flex-start;flex-wrap:wrap}.public-profile-head .verified{margin-left:0;width:100%}} +.account-overview{grid-column:1/-1;order:2;display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:24px}.account-overview .wallet-card,.account-overview .trust-card{height:100%} +.account-overview .wallet-card,.account-overview .trust-card{border-radius:var(--radius)}.activity-panel{grid-column:1/-1;order:3}.task-quota-hint{margin:0 0 10px;padding:9px 12px;border-radius:10px;background:var(--paper);color:var(--muted);font-size:12px} +@media(max-width:900px){.account-overview{grid-template-columns:1fr}} +.site-footer{max-width:1240px;margin:-62px auto 92px;padding:0 28px;color:var(--muted);font-size:12px;display:flex;align-items:center;gap:8px}.site-footer button{border:0;background:transparent;color:var(--ink-2);padding:0;text-decoration:underline;text-underline-offset:3px}.privacy-consent{margin-top:2px}.privacy-consent .consent-row{font-size:12px}.inline-policy{border:0;background:transparent;color:var(--ink-2);padding:0;font-weight:750;text-decoration:underline;text-underline-offset:3px}.privacy-modal{width:min(720px,calc(100vw - 28px));padding:32px}.privacy-body{max-height:58vh;overflow:auto;padding-right:4px}.privacy-section{padding:12px 0;border-bottom:1px solid var(--line)}.privacy-section:last-child{border-bottom:0}.privacy-section h3{margin:0 0 5px;font-size:15px}.privacy-section p{margin:0;color:var(--muted);font-size:13px;line-height:1.8}@media(max-width:640px){.site-footer{margin:-24px auto 82px;padding:0 14px;justify-content:center}.privacy-modal{padding:25px 20px}} +.account-detail-card{cursor:pointer;transition:box-shadow .2s}.account-detail-card:hover{box-shadow:var(--shadow)} +.account-overview .trust-card{transition:transform .2s,box-shadow .2s} +.account-overview .trust-card:hover{transform:translateY(-2px)}.account-detail-card:focus-visible{outline:3px solid var(--coral);outline-offset:3px}.credit-detail-score{padding:16px;background:var(--paper);border-radius:14px}.credit-detail-score>div:first-child{display:flex;align-items:baseline;justify-content:space-between}.credit-detail-score span{color:var(--muted);font-size:13px}.credit-detail-score strong{font:800 34px Manrope,sans-serif}.credit-detail-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:1px;margin:14px 0;background:var(--line);border:1px solid var(--line);border-radius:14px;overflow:hidden}.credit-detail-grid div{display:flex;flex-direction:column;gap:2px;padding:14px;background:var(--white)}.credit-detail-grid strong{font:800 18px Manrope,sans-serif}.credit-detail-grid span{color:var(--muted);font-size:12px}.credit-rules{padding:14px 16px;background:var(--lime-soft);border-radius:12px;font-size:13px;line-height:1.7}.credit-rules p{margin:4px 0 0;color:var(--muted)}.credit-history{margin-top:18px}.credit-history h3{font-size:15px;margin:0 0 9px}.credit-history-row{display:flex;align-items:baseline;gap:9px;padding:10px 0;border-bottom:1px solid var(--line);font-size:13px}.credit-history-row span{flex:1}.credit-history-row b.pos{color:#356217}.credit-history-row b.neg{color:#b84432}.credit-history-row em{color:var(--muted);font-size:11px;font-style:normal}@media(max-width:560px){.credit-detail-grid{grid-template-columns:repeat(2,1fr)}.credit-history-row{flex-wrap:wrap}.credit-history-row em{width:100%}} +.sort-control{position:relative}.sort-menu{position:absolute;right:0;top:calc(100% + 8px);z-index:25;min-width:130px;padding:6px;background:var(--white);border:1px solid var(--line);border-radius:12px;box-shadow:0 12px 30px rgba(16,35,31,.14)}.sort-menu[hidden]{display:none}.sort-menu button{display:block;width:100%;border:0;background:transparent;border-radius:8px;padding:9px 12px;text-align:left;color:var(--muted);font-size:13px}.sort-menu button:hover,.sort-menu button.active{background:var(--paper);color:var(--text);font-weight:700} +.icon-btn{overflow:visible}.icon-btn>i[hidden]{display:none}.icon-btn>i{display:block;min-width:16px;height:16px;padding:0 3px;background:var(--coral);border:2px solid var(--white);border-radius:99px;position:absolute;right:-2px;top:-2px;color:var(--white);font-size:9px;font-style:normal;line-height:12px;text-align:center}.notification-toolbar{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-top:8px;color:var(--muted);font-size:12px}.notification-toolbar button{border:0;background:transparent;color:var(--ink-2);font-size:12px;padding:0}.notification-item{display:flex;width:100%;gap:11px;padding:14px 4px;border:0;border-bottom:1px solid var(--line);background:transparent;text-align:left;cursor:pointer}.notification-item:last-child{border-bottom:0}.notification-item:hover{background:var(--paper)}.notification-dot{width:8px;height:8px;margin-top:7px;border-radius:50%;background:transparent;flex:0 0 auto}.notification-item.unread .notification-dot{background:var(--coral)}.notification-copy{display:flex;min-width:0;flex-direction:column;gap:3px}.notification-copy strong{font-size:14px}.notification-copy>span{color:var(--muted);font-size:12px;line-height:1.5}.notification-copy small{color:#94a29d;font-size:11px} + +/* 个人资料头部:认证徽章固定在姓名右上角;信用分仍只保留在统计数字上。 */ +.profile-head{display:grid;grid-template-columns:auto minmax(0,1fr) auto;align-items:start;column-gap:17px;row-gap:0} +.profile-head .avatar{grid-column:1;grid-row:1} +.profile-head>div{grid-column:2;grid-row:1;min-width:0} +.profile-head .verified{grid-column:3;grid-row:1;justify-self:end;margin:0;white-space:nowrap} + +/* 用户端不显示管理审核入口;审核仅从独立管理端进入。 */ +.admin-review-btn{display:none!important} + +/* 全屏壳层:全屏 API、PWA 全屏和 F11 都显示同一套底部导航,并为内容留出安全区。 */ +body.is-fullscreen, +:fullscreen body{padding-bottom:calc(84px + env(safe-area-inset-bottom))} +body.is-fullscreen main, +:fullscreen body main{min-height:100dvh;padding-bottom:calc(110px + env(safe-area-inset-bottom))} +body.is-fullscreen .mobile-nav, +:fullscreen .mobile-nav{ + position:fixed; + display:grid; + grid-template-columns:repeat(5,minmax(0,1fr)); + inset-inline:0; + bottom:0; + height:calc(74px + env(safe-area-inset-bottom)); + padding:7px 8px calc(4px + env(safe-area-inset-bottom)); + z-index:1000; + border-top:1px solid var(--line); + background:rgba(255,255,255,.96); + backdrop-filter:blur(16px); + isolation:isolate; +} +body.is-fullscreen .mobile-nav button, +:fullscreen .mobile-nav button{ + border:0; + background:transparent; + color:#77847f; + display:flex; + flex-direction:column; + align-items:center; + justify-content:center; + gap:2px; + min-width:0; + font-size:10px; +} +body.is-fullscreen .mobile-nav button.active, +:fullscreen .mobile-nav button.active{color:var(--text)} +body.is-fullscreen .mobile-nav svg, +:fullscreen .mobile-nav svg{width:21px} +body.is-fullscreen .mobile-nav .mobile-publish, +:fullscreen .mobile-nav .mobile-publish{ + width:46px; + height:46px; + background:var(--ink); + color:var(--lime); + border-radius:14px; + justify-self:center; + margin-top:2px; +} +body.is-fullscreen .mobile-nav .mobile-publish svg, +:fullscreen .mobile-nav .mobile-publish svg{width:25px;height:25px} +body.is-fullscreen #view-express .content-narrow, +:fullscreen #view-express .content-narrow{margin-bottom:18px} +@media(prefers-color-scheme:dark){ + body.is-fullscreen .mobile-nav, + :fullscreen .mobile-nav{background:rgba(13,20,17,.96)} +} + +/* 宽屏/“全屏页面”同样保留底部主导航,避免仅依赖媒体查询导致入口消失。 */ +@media(min-width:901px){ + body{padding-bottom:84px} + main{padding-bottom:120px} + .mobile-nav{ + position:fixed; + display:grid; + grid-template-columns:repeat(5,minmax(0,1fr)); + inset-inline:0; + bottom:0; + height:74px; + padding:7px 8px 4px; + z-index:1000; + border-top:1px solid var(--line); + background:rgba(255,255,255,.96); + backdrop-filter:blur(16px); + isolation:isolate; + } + .mobile-nav button{ + border:0; + background:transparent; + color:#77847f; + display:flex; + flex-direction:column; + align-items:center; + justify-content:center; + gap:2px; + min-width:0; + font-size:10px; + } + .mobile-nav button.active{color:var(--text)} + .mobile-nav svg{width:21px} + .mobile-nav .mobile-publish{ + width:46px; + height:46px; + background:var(--ink); + color:var(--lime); + border-radius:14px; + justify-self:center; + margin-top:2px; + } + .mobile-nav .mobile-publish svg{width:25px;height:25px} +} +@media(max-width:900px){ + body{padding-bottom:84px} + main{padding-bottom:110px} + .mobile-nav{ + position:fixed; + display:grid; + grid-template-columns:repeat(5,minmax(0,1fr)); + inset-inline:0; + bottom:0; + height:74px; + padding:7px 8px 4px; + z-index:1000; + border-top:1px solid var(--line); + background:rgba(255,255,255,.96); + backdrop-filter:blur(16px); + isolation:isolate; + } + .mobile-nav button{ + border:0; + background:transparent; + color:#77847f; + display:flex; + flex-direction:column; + align-items:center; + justify-content:center; + gap:2px; + min-width:0; + font-size:10px; + } + .mobile-nav button.active{color:var(--text)} + .mobile-nav svg{width:21px} + .mobile-nav .mobile-publish{ + width:46px; + height:46px; + background:var(--ink); + color:var(--lime); + border-radius:14px; + justify-self:center; + margin-top:2px; + } + .mobile-nav .mobile-publish svg{width:25px;height:25px} +} +@media(prefers-color-scheme:dark) and (min-width:901px){ + .mobile-nav{background:rgba(13,20,17,.96)} + .mobile-nav button.active{color:var(--text)} + .mobile-nav .mobile-publish{background:var(--lime);color:var(--ink)} +} +@media(prefers-color-scheme:dark) and (max-width:900px){ + .mobile-nav{background:rgba(13,20,17,.96)} + .mobile-nav button.active{color:var(--text)} + .mobile-nav .mobile-publish{background:var(--lime);color:var(--ink)} +} + +/* 个人页的积分/信用摘要已经并入资料卡,宽屏不再保留隐藏侧栏占位。 */ +.profile-layout{grid-template-columns:minmax(0,1fr)} +.profile-panel,.activity-panel{min-width:0} + +/* 快递页的任务面板填充剩余视口,高屏幕不再留下大片空白。 */ +#view-express .content-narrow{ + min-height:max(338px,calc(100dvh - 382px)); + display:flex; + flex-direction:column; +} +#view-express .content-narrow>.task-list{flex:1;min-height:220px} +#view-express .content-narrow>.task-list>.empty-state{ + min-height:220px; + height:100%; + display:flex; + flex-direction:column; + justify-content:center; +} + +/* 快递代取双照片交付凭证 */ +.proof-panel{margin:22px 0;padding:20px;border:1px solid var(--line);border-radius:18px;background:var(--paper)} +.proof-heading{display:flex;align-items:flex-start;justify-content:space-between;gap:16px} +.proof-heading h2{margin:8px 0 0;font-size:20px} +.proof-count{flex:none;min-width:50px;height:38px;display:grid;place-items:center;border-radius:999px;background:var(--white);color:var(--coral);font:800 15px Manrope,sans-serif} +.proof-count.ready{background:var(--lime);color:var(--ink)} +.proof-intro{margin:12px 0 16px;color:var(--muted);font-size:13px;line-height:1.8} +.proof-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px} +.proof-card{min-width:0;padding:16px;border:1px solid var(--line);border-radius:14px;background:var(--white);display:flex;align-items:center;justify-content:space-between;gap:14px;transition:.2s} +.proof-card.uploaded{border-color:#9dbd70;background:var(--lime-soft)} +.proof-card.uploading{opacity:.62;pointer-events:none} +.proof-card-copy{min-width:0}.proof-card-copy strong{display:block;font-size:14px}.proof-card-copy p{margin:4px 0 0;color:var(--muted);font-size:12px;line-height:1.55}.proof-card-copy small{display:block;margin-top:7px;color:var(--ink-2);font-size:11px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} +.proof-upload-btn{flex:none;display:inline-flex;align-items:center;justify-content:center;min-height:40px;padding:0 13px;border-radius:10px;background:var(--ink);color:white;font-size:12px;font-weight:750;cursor:pointer} +.proof-upload-btn input{position:absolute;width:1px;height:1px;opacity:0;pointer-events:none} + +/* 新个人页将积分卡并入资料面板,沿用原积分钱包的指针跟随 3D 与流光。 */ +.profile-summary-stat{ + position:relative; + overflow:hidden; + transform:perspective(900px) rotateX(var(--rx,0deg)) rotateY(var(--ry,0deg)) translateY(var(--lift,0)) translateZ(0); + transform-style:preserve-3d; + will-change:transform; +} +.profile-summary-stat:hover{--lift:-2px;transform:perspective(900px) rotateX(var(--rx,0deg)) rotateY(var(--ry,0deg)) translateY(var(--lift)) translateZ(0)} +.profile-summary-stat.tilting .tilt-glare{opacity:1} + +/* 极窄屏幕下,积分余额与钱包操作改为上下排列,避免按钮和数字互相挤压。 */ +@media(max-width:460px){ + .profile-account-summary{grid-template-columns:1fr} +} +.proof-status{flex:none;color:var(--muted);font-size:12px;font-weight:700} +.detail-actions:has(>button:only-child){grid-template-columns:1fr} +@media(max-width:700px){.proof-grid{grid-template-columns:1fr}.proof-card{align-items:flex-start;flex-direction:column}.proof-upload-btn{width:100%}} +@media(prefers-color-scheme:dark){.proof-card.uploaded{border-color:#536d36;background:#202c18}.proof-upload-btn{background:var(--lime);color:var(--ink)}} + +.task-published,.partner-card .task-published{display:block;margin:8px 0 0;color:var(--muted);font-size:12px;line-height:1.5;font-weight:400} + +.task-list-heading{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;column-gap:12px;row-gap:8px} +.task-list-heading h2{flex:none;white-space:nowrap} +.task-heading-controls{display:flex;align-items:center;justify-content:flex-end;gap:12px;flex:0 1 auto;min-width:0;max-width:100%;margin-left:auto;white-space:nowrap} +.task-heading-controls .sort-control{flex:none;white-space:nowrap} +.school-control{display:inline-flex;align-items:center;gap:4px;flex:0 1 auto;min-width:0;max-width:179px;color:var(--muted)} +.school-control select{appearance:none;-webkit-appearance:none;flex:0 1 auto;min-width:0;max-width:160px;padding:4px 0;border:0;background:transparent;color:inherit;font:inherit;font-size:13px;line-height:1.2;cursor:pointer;text-overflow:ellipsis;overflow:hidden;white-space:nowrap} +.school-control select:focus-visible{outline:2px solid var(--muted);outline-offset:3px;border-radius:4px} +.school-control option{background:var(--white);color:var(--text)} +.school-control>svg{flex:none;width:15px;height:15px;transition:transform .2s} +@media(max-width:600px){.task-list-heading{column-gap:8px}.task-list-heading h2{font-size:16px}.task-heading-controls{gap:8px}.school-control{min-width:110px}.task-list-heading .text-btn,.school-control select{font-size:12px}.task-list-heading .text-btn{gap:4px;padding-left:0;padding-right:0}} + +/* 任务广场状态:已完成仍可查看,但从视觉上与可接任务区分。 */ +.task-card.is-done,.partner-card.is-done{opacity:.62} +.task-card.is-done:hover,.task-card.is-done:focus-visible,.partner-card.is-done:hover,.partner-card.is-done:focus-visible{opacity:.85} +.task-status{display:inline-flex;align-items:center;white-space:nowrap;margin-right:6px} +.task-status.claimed{background:var(--lime-soft);color:var(--text)} +.task-status.done{background:var(--paper);color:var(--muted)} + +.verification-levels-dialog[open]{display:flex;flex-direction:column;width:min(560px,calc(100vw - 28px));max-height:90vh;max-height:min(90dvh,720px);padding:0;overflow:hidden} +.verification-levels-header{display:flex;align-items:flex-start;justify-content:space-between;gap:16px;flex:none;padding:28px 28px 16px;border-bottom:1px solid var(--line)} +.verification-levels-header .modal-close{position:static;flex:none;margin:0} +.verification-levels-scroll{min-height:0;overflow-y:auto;overscroll-behavior:contain;padding:18px 28px 28px} +.verification-level-status{margin:0 0 16px;padding:12px 14px;border-radius:11px;background:var(--paper);color:var(--text);font-size:13px;line-height:1.6} +.verification-levels-list{display:grid;gap:10px} +.verification-level-card{padding:15px 16px;border:1px solid var(--line);border-radius:14px;background:var(--white)} +.verification-level-card.current{border-color:var(--ink-2);background:var(--lime-soft)} +.verification-level-card-head{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:9px} +.verification-level-card-head h3{margin:0;font-size:16px;line-height:1.3} +.verification-level-card-head>div{display:flex;flex-wrap:wrap;justify-content:flex-end;gap:5px} +.verification-level-current,.verification-level-upcoming{display:inline-block;flex:none;padding:3px 7px;border-radius:6px;font-size:11px;font-weight:800;white-space:nowrap} +.verification-level-current{background:var(--ink);color:var(--lime)} +.verification-level-upcoming{background:var(--paper);color:var(--muted)} +.verification-level-card p{display:flex;gap:8px;margin:5px 0 0;color:var(--muted);font-size:12px;line-height:1.55} +.verification-level-card p strong{flex:none;color:var(--text)} +.verification-level-action{margin-top:18px} +.verification-level-action .btn{width:100%;min-height:46px} +.verification-face-disabled{background:var(--paper);color:var(--muted);border:1px solid var(--line);cursor:not-allowed} +.verification-level-benefit{margin:0;text-align:center;color:var(--muted);font-size:13px} +@media(max-width:640px){.verification-levels-header{padding:20px 18px 13px}.verification-levels-scroll{padding:15px 18px 20px}.verification-level-card{padding:13px}.verification-level-card-head h3{font-size:15px}} +/* 跑腿代办类目:发布类目网格、类目图标底色、垫付提示横幅 */ +.publish-grid{display:flex;flex-wrap:wrap;gap:8px;margin:0 0 18px}.publish-grid button{border:1px solid var(--line);background:var(--white);border-radius:999px;padding:9px 14px;font-weight:700;font-size:13px;color:var(--muted);transition:.2s;cursor:pointer}.publish-grid button:hover{border-color:var(--ink-2);color:var(--text)}.publish-grid button.active{background:var(--ink);border-color:var(--ink);color:var(--lime)} +.task-icon.cat-food{background:#ffeccc} +.task-icon.cat-queue{background:#e1ecff} +.task-icon.cat-print{background:#ece4ff} +.advance-notice{margin:12px 0;padding:12px 16px;background:#fff6e8;border:1px solid #f0d9ad;border-radius:12px;color:#8a6b00;font-size:13px;font-weight:600} +@media(prefers-color-scheme:dark){.task-icon.cat-food{background:#33271a}.task-icon.cat-queue{background:#1d2a3d}.task-icon.cat-print{background:#2a2440}.advance-notice{background:#2b2410;border-color:#453818;color:#d9b03c}.publish-grid button{background:var(--white)}} +/* 消息中心分组筛选 chips:窄屏横向滑动,不与工具栏挤压换行 */ +.notif-tabs{margin:12px 0 0;max-width:100%;display:flex;flex-wrap:nowrap;width:auto;grid-template-columns:none;overflow-x:auto;scrollbar-width:none} +.notif-tabs::-webkit-scrollbar{display:none} +.notif-tabs button{white-space:nowrap;flex:0 0 auto} + +/* 广场筛选条紧凑化:6 类目 chips 收敛宽度;窄屏废弃三列网格改单行横滑。 + 仅作用于 .filter-bar 内的 .segment,不影响通知中心与找搭子 topic-pills。 */ +.filter-bar{flex-wrap:wrap;gap:16px 10px} +.filter-bar .segment{padding:3px;gap:2px} +.filter-bar .segment button{padding:6px 11px;font-size:13px} +@media(min-width:641px){.filter-bar .search-box{flex:1 1 160px;width:auto;min-width:160px;max-width:240px}} +@media(max-width:640px){ + .filter-bar .segment{width:100%;display:flex;flex-wrap:nowrap;grid-template-columns:none;justify-content:flex-start;overflow-x:auto;scrollbar-width:none} + .filter-bar .segment::-webkit-scrollbar{display:none} + .filter-bar .segment button{white-space:nowrap;flex:0 0 auto;padding:8px 11px} +} +/* Publisher actions, public redacted history, and private chat. */ +.publisher{position:relative}.publisher-avatar-button{display:grid;place-items:center;padding:0;border:0;border-radius:50%;background:transparent;cursor:pointer;flex:0 0 auto}.publisher-avatar-button:focus-visible,.publisher-action-popover button:focus-visible,.public-chat-button:focus-visible{outline:3px solid var(--coral);outline-offset:2px}.publisher-action-popover{position:absolute;z-index:5;left:0;top:56px;display:grid;min-width:142px;padding:6px;border:1px solid var(--line);border-radius:13px;background:var(--white);box-shadow:var(--shadow)}.publisher-action-popover button{border:0;background:transparent;padding:10px 12px;border-radius:8px;text-align:left;color:var(--text);cursor:pointer}.publisher-action-popover button:hover{background:var(--paper)}.public-profile-head{position:relative;padding-right:78px}.public-chat-button{position:absolute;right:0;top:50%;transform:translateY(-50%);border:0;border-radius:10px;background:var(--ink);color:#fff;padding:9px 14px;font-weight:700;cursor:pointer}.public-credit-history{display:grid;gap:8px}.public-credit-row{display:grid;grid-template-columns:1fr auto auto;gap:14px;align-items:center;padding:13px 14px;border-radius:12px;background:var(--paper)}.public-credit-row b{font-size:16px}.public-credit-row .neg{color:var(--coral)}.public-credit-row .pos{color:#287056}.public-credit-row time{font-size:12px;color:var(--muted)}.credit-history-hidden{margin:16px 0 0;color:var(--muted);font-size:13px;line-height:1.6}.chat-modal{width:min(560px,calc(100vw - 28px));height:min(720px,calc(100dvh - 28px));max-height:calc(100dvh - 28px);padding:25px;display:flex;flex-direction:column;overflow:hidden}.chat-modal:not([open]){display:none}.chat-header{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:4px 48px 15px 0;border-bottom:1px solid var(--line)}.chat-header h2{margin:0;font-size:23px}.chat-header .eyebrow{margin:0 0 3px}.chat-header .report-btn{padding:9px 14px;border-radius:10px;cursor:pointer}.chat-status{min-height:20px;margin:8px 0 0;color:var(--coral);font-size:13px}.chat-messages{flex:1;min-height:140px;overflow:auto;display:flex;flex-direction:column;gap:12px;padding:12px 2px}.chat-message{max-width:82%;display:flex;flex-direction:column;gap:4px;align-self:flex-start}.chat-message.own{align-self:flex-end;align-items:flex-end}.chat-message>span{white-space:pre-wrap;overflow-wrap:anywhere;padding:10px 13px;border-radius:15px 15px 15px 4px;background:var(--paper);line-height:1.55}.chat-message.own>span{border-radius:15px 15px 4px 15px;background:var(--ink);color:#fff}.chat-message time{font-size:10px;color:var(--muted)}.chat-form{border-top:1px solid var(--line);padding-top:13px}.chat-form textarea{width:100%;resize:none;border:1px solid var(--line);border-radius:12px;background:var(--paper);color:var(--text);padding:11px 12px;font:inherit;outline:none}.chat-form textarea:focus{border-color:var(--ink)}.chat-compose{display:flex;justify-content:space-between;align-items:center;gap:12px;margin-top:8px}.chat-compose span{color:var(--muted);font-size:11px}.chat-compose button{border:0;border-radius:10px;background:var(--ink);color:#fff;font-weight:700;padding:10px 17px;cursor:pointer}.chat-compose button:disabled{opacity:.45;cursor:not-allowed} +@media(max-width:600px){.chat-modal{padding:20px;height:calc(100dvh - 20px);max-height:calc(100dvh - 20px);width:calc(100vw - 20px)}.chat-header{padding-right:42px}.public-credit-row{grid-template-columns:1fr auto;gap:7px}.public-credit-row time{grid-column:1/-1}.public-profile-head{padding-right:72px}} +.invite-progress{margin:12px 0}.invite-progress .score-track{height:7px}.invite-progress small{display:block;margin-top:6px;color:var(--muted);font-size:12px}.credit-rules p+p{margin-top:8px}.public-profile-meta:after{content:' · 失信率统计周期:近90天';display:block;margin-top:5px;color:var(--muted)} +.credit-pending-notice{margin:10px 0;padding:12px 14px;border-radius:12px;background:var(--paper);color:var(--muted);font-size:13px;line-height:1.7} +.official-task-entry{margin-top:10px}.official-tasks-modal{width:min(680px,calc(100vw - 28px));max-height:min(86vh,900px);overflow:auto}.official-task-cards{display:grid;gap:12px}.official-task-card{padding:16px;border:1px solid var(--line);border-radius:16px;background:var(--white)}.official-task-card-head{display:flex;justify-content:space-between;align-items:flex-start;gap:12px}.official-task-card h3{margin:0;font-size:17px;overflow-wrap:anywhere}.official-task-card-head strong{color:#b46915;white-space:nowrap}.official-task-detail{margin:10px 0;color:var(--muted);font-size:13px;line-height:1.65;white-space:pre-wrap;overflow-wrap:anywhere}.official-task-meta{display:flex;flex-wrap:wrap;gap:7px;margin:10px 0 13px}.official-task-meta span{padding:5px 8px;border-radius:99px;background:var(--paper);color:var(--muted);font-size:11px}.official-task-claim{width:100%}.official-task-claim:disabled{opacity:.52;cursor:not-allowed}@media(max-width:600px){.official-tasks-modal{width:calc(100vw - 20px);max-height:calc(100dvh - 20px);padding:20px}.official-task-card{padding:13px}.official-task-card-head{flex-direction:column;gap:6px}} +/* Shared async feedback: retain existing sizes, colors and disabled semantics. */ +button[aria-busy="true"],.proof-upload-btn:has(input[aria-busy="true"]){cursor:wait;opacity:.6;white-space:nowrap} +.proof-card.uploading .proof-upload-btn{pointer-events:none} diff --git a/dist/styles/toast.css b/dist/styles/toast.css new file mode 100644 index 0000000..de27aec --- /dev/null +++ b/dist/styles/toast.css @@ -0,0 +1,12 @@ +.toast { + z-index: 2147483647; + border: 0; +} + +.toast:popover-open { + display: flex; +} + +.toast::backdrop { + display: none; +} diff --git a/dist/views/express.html b/dist/views/express.html new file mode 100644 index 0000000..02d5ca2 --- /dev/null +++ b/dist/views/express.html @@ -0,0 +1,10 @@ +
    +
    +

    顺路一程,送到楼下

    跑腿代办

    快递代取、带饭代买、代排队、代打印,接单实名留痕;任务完成后积分自动到账。

    + +
    +
    +

    可接任务

    按发布时间与紧迫度排序
    +
    +
    +
    diff --git a/dist/views/home.html b/dist/views/home.html new file mode 100644 index 0000000..6e7bd89 --- /dev/null +++ b/dist/views/home.html @@ -0,0 +1,54 @@ +
    +
    +
    +

    校园互助广场

    +

    下午好,同学

    +

    今天附近有 0 个互助需求,顺路帮个忙吧。

    +
    +
    + + +
    +
    + +
    +
    +
    +
    + + + + + + +
    + +
    +
    +

    附近任务

    +
    +
    + + +
    +
    + + +
    +
    +
    +
    + +
    + + +
    +
    diff --git a/dist/views/partner.html b/dist/views/partner.html new file mode 100644 index 0000000..a1f3eae --- /dev/null +++ b/dist/views/partner.html @@ -0,0 +1,14 @@ +
    +
    +

    同频的人,就在附近

    找搭子

    学习、竞赛、运动,把计划变成一起完成的约定。

    + +
    +
    + + + + + +
    +
    +
    diff --git a/dist/views/profile.html b/dist/views/profile.html new file mode 100644 index 0000000..148d0bb --- /dev/null +++ b/dist/views/profile.html @@ -0,0 +1,50 @@ +
    +
    +
    +
    + +

    登录后查看个人信息

    +

    使用注册邮箱和密码登录。

    + +
    + +
    + + + +
    +

    我的任务

    +
    登录后查看你的任务

    发布或接下的任务会集中显示在这里。

    +
    +
    +
    diff --git a/dist/views/task.html b/dist/views/task.html new file mode 100644 index 0000000..c216f13 --- /dev/null +++ b/dist/views/task.html @@ -0,0 +1,3 @@ +
    +
    正在加载任务详情…
    +
    diff --git a/start.sh b/start.sh new file mode 100644 index 0000000..b170f58 --- /dev/null +++ b/start.sh @@ -0,0 +1,81 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")" + +if [ ! -f backend/main.py ]; then + echo "[LinkUp] 未找到 backend/main.py,请确认部署包已完整解压" + exit 1 +fi + +PYTHON_BIN="${PYTHON_BIN:-python3}" +if ! command -v "${PYTHON_BIN}" >/dev/null 2>&1; then + PYTHON_BIN="python" +fi +if ! command -v "${PYTHON_BIN}" >/dev/null 2>&1; then + echo "[LinkUp] 未找到 Python 3.11+,请先安装 Python" + exit 1 +fi +if ! "${PYTHON_BIN}" -c 'import sys; raise SystemExit(0 if sys.version_info >= (3, 11) else 1)'; then + echo "[LinkUp] 需要 Python 3.11+" + exit 1 +fi +if ! "${PYTHON_BIN}" -c 'import fastapi, sqlalchemy, aiosqlite' >/dev/null 2>&1; then + echo "[LinkUp] 缺少 Python 依赖,请执行:${PYTHON_BIN} -m pip install -r backend/requirements.txt" + exit 1 +fi + +RUN_DIR="$(pwd)/.run" +PID_FILE="${RUN_DIR}/linkup.pid" +LOG_FILE="${RUN_DIR}/linkup.log" +PORT="${PORT:-34173}" +WORKERS="${APP_WORKERS:-2}" + +is_running(){ [ -f "${PID_FILE}" ] && kill -0 "$(cat "${PID_FILE}")" 2>/dev/null; } + +start_fg(){ + echo "[LinkUp] FastAPI 前台启动(端口 ${PORT},workers ${WORKERS})" + (cd backend && PORT="${PORT}" APP_WORKERS="${WORKERS}" exec "${PYTHON_BIN}" -m uvicorn main:app --host 0.0.0.0 --port "${PORT}" --workers "${WORKERS}") & + SERVER_PID=$! + cleanup(){ kill "${SERVER_PID}" 2>/dev/null || true; } + trap cleanup EXIT INT TERM + echo "[LinkUp] 就绪:http://<主机IP>:${PORT} · 管理端 /admin.html · Ctrl+C 停止" + wait +} + +start_bg(){ + if is_running; then + echo "[LinkUp] 已在运行(PID $(cat "${PID_FILE}")),如需重启请先执行 bash start.sh stop" + exit 0 + fi + mkdir -p "${RUN_DIR}" + (cd backend && PORT="${PORT}" APP_WORKERS="${WORKERS}" nohup "${PYTHON_BIN}" -m uvicorn main:app --host 0.0.0.0 --port "${PORT}" --workers "${WORKERS}" >> "${LOG_FILE}" 2>&1 & echo $! > "${PID_FILE}") + sleep 1.5 + if is_running && curl -s -m 3 "http://127.0.0.1:${PORT}/api/health" | grep -q '"ok":true'; then + echo "[LinkUp] FastAPI 已就绪:http://<主机IP>:${PORT} · /admin.html" + else + echo "[LinkUp] 启动失败,请查看日志:tail -30 ${LOG_FILE}" + exit 1 + fi +} + +stop_svc(){ + if is_running; then + kill "$(cat "${PID_FILE}")" 2>/dev/null || true + sleep 1 + fi + rm -f "${PID_FILE}" + echo "[LinkUp] 已停止" +} + +status_svc(){ + if is_running; then echo "[LinkUp] 运行中(PID $(cat "${PID_FILE}"),端口 ${PORT})"; else echo "[LinkUp] 未运行"; fi +} + +case "${1:-fg}" in + start) start_bg ;; + stop) stop_svc ;; + restart) stop_svc; start_bg ;; + status) status_svc ;; + log) tail -f "${LOG_FILE}" ;; + *) start_fg ;; +esac diff --git a/start.sh1 b/start.sh1 new file mode 100644 index 0000000..80c5b4f --- /dev/null +++ b/start.sh1 @@ -0,0 +1,100 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")" + +if [ ! -f backend/main.py ]; then + echo "[LinkUp] 未找到 backend/main.py,请确认部署包已完整解压" + exit 1 +fi + +PYTHON_BIN="${PYTHON_BIN:-python3}" +if ! command -v "${PYTHON_BIN}" >/dev/null 2>&1; then + PYTHON_BIN="python" +fi +if ! command -v "${PYTHON_BIN}" >/dev/null 2>&1; then + echo "[LinkUp] 未找到 Python 3.11+,请先安装 Python" + exit 1 +fi +if ! "${PYTHON_BIN}" -c 'import sys; raise SystemExit(0 if sys.version_info >= (3, 11) else 1)'; then + echo "[LinkUp] 需要 Python 3.11+" + exit 1 +fi +if ! "${PYTHON_BIN}" -c 'import fastapi, sqlalchemy, aiosqlite' >/dev/null 2>&1; then + echo "[LinkUp] 缺少 Python 依赖,请执行:${PYTHON_BIN} -m pip install -r backend/requirements.txt" + exit 1 +fi + +RUN_DIR="$(pwd)/.run" +PID_FILE="${RUN_DIR}/linkup.pid" +LOG_FILE="${RUN_DIR}/linkup.log" +PORT="${PORT:-34173}" +WORKERS="${APP_WORKERS:-2}" + +is_running(){ [ -f "${PID_FILE}" ] && kill -0 "$(cat "${PID_FILE}")" 2>/dev/null; } + +start_fg(){ + echo "[LinkUp] FastAPI 前台启动(端口 ${PORT},workers ${WORKERS})" + (cd backend && PORT="${PORT}" APP_WORKERS="${WORKERS}" exec "${PYTHON_BIN}" -m uvicorn main:app --host 0.0.0.0 --port "${PORT}" --workers "${WORKERS}") & + SERVER_PID=$! + cleanup(){ kill "${SERVER_PID}" 2>/dev/null || true; } + trap cleanup EXIT INT TERM + echo "[LinkUp] 就绪:http://<主机IP>:${PORT} · 管理端 /admin.html · Ctrl+C 停止" + wait +} + +start_bg(){ + if is_running; then + echo "[LinkUp] 已在运行(PID $(cat "${PID_FILE}")),如需重启请先执行 bash start.sh stop" + exit 0 + fi + mkdir -p "${RUN_DIR}" + (cd backend && PORT="${PORT}" APP_WORKERS="${WORKERS}" nohup "${PYTHON_BIN}" -m uvicorn main:app --host 0.0.0.0 --port "${PORT}" --workers "${WORKERS}" >> "${LOG_FILE}" 2>&1 & echo $! > "${PID_FILE}") + sleep 1.5 + if is_running && curl -s -m 3 "http://127.0.0.1:${PORT}/api/health" | grep -q '"ok":true'; then + echo "[LinkUp] FastAPI 已就绪:http://<主机IP>:${PORT} · /admin.html" + else + echo "[LinkUp] 启动失败,请查看日志:tail -30 ${LOG_FILE}" + exit 1 + fi +} + +stop_svc(){ + if is_running; then + kill "$(cat "${PID_FILE}")" 2>/dev/null || true + sleep 1 + fi + rm -f "${PID_FILE}" + echo "[LinkUp] 已停止" +} + +status_svc(){ + if is_running; then echo "[LinkUp] 运行中(PID $(cat "${PID_FILE}"),端口 ${PORT})"; else echo "[LinkUp] 未运行"; fi +} + +case "${1:-fg}" in + start) start_bg ;; + stop) stop_svc ;; + restart) stop_svc; start_bg ;; + status) status_svc ;; + log) tail -f "${LOG_FILE}" ;; + *) start_fg ;; +esac +#!/usr/bin/env bash +# 启动脚本:安装依赖(首次)并启动 WorkLog 服务。 +# 用法:bash start.sh +set -euo pipefail + +PROJECT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +cd "$PROJECT_DIR" + +PYTHON="${PYTHON:-python}" + +# 依赖未装时自动安装 +if ! "$PYTHON" -c "import fastapi, uvicorn, sqlalchemy, aiosqlite" >/dev/null 2>&1; then + echo "安装依赖..." + "$PYTHON" -m pip install -r requirements.txt +fi + +mkdir -p data +echo "启动 WorkLog:$PYTHON -m server.main" +exec "$PYTHON" -m server.main