LinkUp initial import

This commit is contained in:
2026-10-29 16:27:16 +08:00
commit 155058f0f3
50 changed files with 10624 additions and 0 deletions
+4
View File
@@ -0,0 +1,4 @@
.env
data/
__pycache__/
*.pyc
+23
View File
@@ -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"]
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 MiB

+18
View File
@@ -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
+104
View File
@@ -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 数据库文件。切换数据库前请先备份并用迁移脚本验证行数。
+37
View File
@@ -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 = ""
+393
View File
@@ -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,
]
+3851
View File
File diff suppressed because it is too large Load Diff
+24
View File
@@ -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"
}
}
}
}
+13
View File
@@ -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"
}
}
+11
View File
@@ -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
+1085
View File
File diff suppressed because it is too large Load Diff
+2
View File
@@ -0,0 +1,2 @@
-r ../requirements.txt
httpx>=0.27,<1
+217
View File
@@ -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"], [])
+222
View File
@@ -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="<img onerror=alert(1)>", 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"], "<img onerror=alert(1)>")
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, "官方任务 · <img onerror=alert(1)>") 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()
+662
View File
@@ -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()
+716
View File
@@ -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":"<img onerror=alert(1)>"}, 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("<img onerror=alert(1)>", [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()
+65
View File
@@ -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())
+229
View File
@@ -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)
+12
View File
@@ -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`。
+278
View File
@@ -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 `<span class="status-pill account-status ${escapeHtml(status)} ${style}">${labels[status] || '正常'}${date ? ` · 至 ${date}` : ''}</span>`;
}
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 = '<div class="loading">正在加载登录日志…</div>';
}
try {
const params = loginFilters();
params.set('offset', String(loginLogOffset));
const result = await api(`/api/admin/login-logs?${params}`);
const rows = result.items.map(item => `<div class="security-log-row">
<span class="${item.success ? 'success' : 'failure'}">${item.success ? '成功' : '失败'}</span>
<span>${escapeHtml(item.emailAttempted || '未知账号')}</span>
<span>${escapeHtml(item.method === 'password' ? '密码' : '验证码')}</span>
<span>${escapeHtml(item.ip || '—')}</span>
<span title="${escapeHtml(item.userAgent || '')}">${escapeHtml(summarizeAdminUa(item.userAgent))}</span>
<time>${adminDate(item.createdAt)}</time></div>`).join('');
if (!more) list.innerHTML = rows || '<div class="empty">暂无登录日志</div>';
else list.insertAdjacentHTML('beforeend', rows);
loginLogOffset = result.nextOffset ?? loginLogOffset;
$('#loginLogsMore').hidden = result.nextOffset === null;
} catch (error) {
if (!more) list.innerHTML = `<div class="empty">${escapeHtml(error.message)}</div>`;
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 = '<div class="loading">正在加载操作日志…</div>';
}
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 => `<div class="security-log-row audit">
<span>${escapeHtml(item.action)}</span><span>${escapeHtml(item.adminId)}</span>
<span>${escapeHtml(item.targetUserId || '—')}</span><span>${escapeHtml(item.detail || '')}</span>
<span>${escapeHtml(item.ip || '—')}</span><time>${adminDate(item.createdAt)}</time></div>`).join('');
if (!more) list.innerHTML = rows || '<div class="empty">暂无操作日志</div>';
else list.insertAdjacentHTML('beforeend', rows);
auditLogOffset = result.nextOffset ?? auditLogOffset;
$('#auditLogsMore').hidden = result.nextOffset === null;
} catch (error) {
if (!more) list.innerHTML = `<div class="empty">${escapeHtml(error.message)}</div>`;
else if (!activeButtons.has($('#auditLogsMore'))) toast(error.message);
return {refreshError:error};
}
}
async function loadAdminUsers() {
const list = $('#userList');
const query = $('#userSearch').value.trim();
list.innerHTML = '<div class="loading">正在加载用户…</div>';
try {
const result = await api(`/api/admin/users?q=${encodeURIComponent(query)}`);
if (!result.items.length) {
list.innerHTML = '<div class="empty">没有匹配的用户</div>';
updateBulkSelection();
return;
}
list.innerHTML = result.items.map(item => `<article class="user-row" data-uid="${escapeHtml(item.id)}">
<label class="user-select-wrap"><input class="user-select" type="checkbox" data-user-id="${escapeHtml(item.id)}" ${selectedUserIds.has(item.id) ? 'checked' : ''} aria-label="选择 ${escapeHtml(item.nickname)}"></label>
<div class="user-info"><strong>${escapeHtml(item.name)} · @${escapeHtml(item.nickname)}</strong>
<div class="review-meta">学号 ${escapeHtml(item.studentId)} · ${escapeHtml(item.school)} · ${escapeHtml(item.email)}</div>
<div class="user-admin-actions"><button type="button" data-security-user="${escapeHtml(item.id)}">安全信息 / 处理历史</button>
<button type="button" data-sanction-user="ban" data-uid="${escapeHtml(item.id)}">封禁</button>
<button type="button" data-sanction-user="restrict" data-uid="${escapeHtml(item.id)}">限制</button>
<button type="button" data-sanction-user="lift" data-uid="${escapeHtml(item.id)}" ${(item.status || 'active') === 'active' ? 'disabled title="该账号当前没有生效中的处理"' : ''}>解除</button></div>
</div>
<div class="credit-now"><span class="credit-score">信用分 <b>${item.creditScore}</b></span><small>积分余额 ${item.pointsBalance}</small>${statusBadge(item)}</div>
<div class="adjust-actions">
<form class="credit-form adjustment-form" data-kind="credit"><span class="adjust-label">信用</span><input class="delta-input" type="number" step="1" min="-100" max="100" required placeholder="±1—100"><div class="adjust-reason-fields"><input class="reason-input" type="text" maxlength="200" required placeholder="信用调整原因"></div><button class="primary" type="submit">调整</button></form>
<form class="credit-form points-form adjustment-form" data-kind="points"><span class="adjust-label">积分</span><input class="delta-input" type="number" step="1" min="-1000000" max="1000000" required placeholder="±积分"><div class="adjust-reason-fields"><input class="reason-input" type="text" maxlength="200" required placeholder="积分调整原因"></div><button class="refresh" type="submit">调整</button></form>
</div></article>`).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 = `<div class="empty">${escapeHtml(error.message)}</div>`;
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 = '<div class="loading">正在读取安全信息与处理历史…</div>';
$('#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 => `<tr><td>${escapeHtml(item.ip)}</td><td>${adminDate(item.firstSeen)}</td><td>${adminDate(item.lastSeen)}</td></tr>`).join('') : '<tr><td colspan="3">暂无已知 IP</td></tr>';
const activeSessions = security.sessions.length ? security.sessions.map(item => `<tr><td>${escapeHtml(summarizeAdminUa(item.userAgent))}</td><td>${escapeHtml(item.ip || '—')}</td><td title="${escapeHtml(item.userAgent || '')}">${escapeHtml(item.userAgent || '未知设备')}</td><td>${adminDate(item.createdAt)}</td></tr>`).join('') : '<tr><td colspan="4">暂无活跃会话</td></tr>';
const logins = security.loginLogs.length ? security.loginLogs.map(item => `<tr><td>${item.success ? '成功' : '失败'}</td><td>${escapeHtml(item.emailAttempted || '—')}</td><td>${escapeHtml(item.method)}</td><td>${escapeHtml(item.ip || '—')}</td><td title="${escapeHtml(item.userAgent || '')}">${escapeHtml(summarizeAdminUa(item.userAgent))}</td><td>${adminDate(item.createdAt)}</td></tr>`).join('') : '<tr><td colspan="6">暂无登录记录</td></tr>';
const history = sanctions.items.length ? sanctions.items.map(item => `<tr><td>${escapeHtml(({ ban: '封禁', restrict: '限制', lift: '解除' })[item.action] || item.action)} · ${escapeHtml(scopeLabel(item.scope))}${item.active ? ' · 生效中' : ''}${item.liftedAt ? ' · 已解除' : ''}</td><td>${escapeHtml(item.category || '—')}</td><td>${escapeHtml(item.reason)}</td><td>${escapeHtml(item.adminName)} · ${adminDate(item.createdAt)}</td><td>${item.expiresAt ? adminDate(item.expiresAt) : item.action === 'lift' ? '—' : '永久'}${item.liftedAt ? `<br>解除:${escapeHtml(item.liftedByName || '管理员')} · ${adminDate(item.liftedAt)}` : ''}</td></tr>`).join('') : '<tr><td colspan="5">暂无制裁处理记录</td></tr>';
body.innerHTML = `<h2>用户安全信息</h2>
<section><h3>已知登录 IP</h3><div class="security-table-wrap"><table><thead><tr><th>IP</th><th>首次出现</th><th>最近出现</th></tr></thead><tbody>${ips}</tbody></table></div></section>
<section><h3>活跃会话</h3><div class="security-table-wrap"><table><thead><tr><th>设备摘要</th><th>IP</th><th>浏览器信息</th><th>创建时间</th></tr></thead><tbody>${activeSessions}</tbody></table></div></section>
<section><h3>近期登录记录(最多 20 条)</h3><div class="security-table-wrap"><table><thead><tr><th>结果</th><th>邮箱</th><th>方式</th><th>IP</th><th>设备</th><th>时间</th></tr></thead><tbody>${logins}</tbody></table></div></section>
<section><h3>账号处理历史</h3><div class="security-table-wrap"><table><thead><tr><th>动作</th><th>用户可见分类</th><th>内部理由</th><th>操作人 / 时间</th><th>期限与解除</th></tr></thead><tbody>${history}</tbody></table></div></section>`;
} catch (error) { body.innerHTML = `<div class="empty">${escapeHtml(error.message)}</div>`; 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; },
};
+154
View File
@@ -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 '<option value="">选择调整原因(必填)</option>' + adjustmentReasons.map(item => {
const delta = item.defaultDelta === null ? '按原处罚' : (item.defaultDelta > 0 ? '+' : '') + item.defaultDelta;
return '<option value="' + escapeHtml(item.value) + '">' + escapeHtml(item.label + '(默认 ' + delta + ')') + '</option>';
}).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 = '<option value="">先选原处罚记录</option>'; 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 = '<option value="">正在加载可撤销处罚…</option>';
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 = '<option value="">选择原处罚记录(必填)</option>' + eligible.map(item =>
'<option value="' + escapeHtml(item.id) + '">' + escapeHtml(new Date(Number(item.createdAt)).toLocaleDateString('zh-CN') + ' · ' + item.reason + ' · ' + item.delta + ' 分 · ID ' + item.id) + '</option>'
).join('');
if (!eligible.length) reversal.innerHTML = '<option value="">没有可撤销的处罚记录</option>';
} catch (error) {
reversal.innerHTML = '<option value="">加载失败:' + escapeHtml(error.message) + '</option>';
toast(error.message);
}
}
updatePreview();
};
selector.addEventListener('change', updateReason);
delta.addEventListener('input', updatePreview);
});
const bulkReason = $('#bulkCreditReasonType');
if (bulkReason) bulkReason.innerHTML = '<option value="">选择原因</option>' + adjustmentReasons.map(item =>
'<option value="' + escapeHtml(item.value) + '" ' + (item.value === 'other' ? '' : 'disabled') + '>' +
escapeHtml(item.label + (item.value === 'other' ? '(批量调整仅适用于其他)' : '(逐人处理)')) + '</option>'
).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 = '<div class="loading">正在加载记录…</div>';
try {
const result = await api('/api/admin/credit-adjustments');
if (!result.items.length) { log.innerHTML = '<div class="empty">暂无调整记录</div>'; return; }
log.innerHTML = result.items.map(item => '<div class="log-row"><strong>' + escapeHtml(item.userName) + ' · @' + escapeHtml(item.userNickname) + '</strong><span class="' + (item.delta < 0 ? 'neg' : 'pos') + '">' + (item.delta > 0 ? '+' : '') + item.delta + '</span><span class="log-category">' + escapeHtml(item.category || '未分类') + '</span><span>' + escapeHtml(item.reason) + '</span><em>' + escapeHtml(item.adminName || '系统') + ' · ' + escapeHtml(new Date(Number(item.createdAt)).toLocaleString('zh-CN')) + (item.reversedAt ? ' · 已撤销' : '') + '</em></div>').join('');
} catch (error) { log.innerHTML = '<div class="empty">' + escapeHtml(error.message) + '</div>'; 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 = '<div class="loading">正在加载举报记录…</div>';
const statusText = {open:'待处理', reviewed:'已核实', dismissed:'已驳回'};
try {
const result = await api(`/api/admin/reports?status=${status}`);
if (!result.items.length) { list.innerHTML = `<div class="empty">暂无${statusText[status]||''}的举报</div>`; 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 ? `<div class="review-data"><div class="data-box"><span>被举报任务</span><code>${escapeHtml(item.task.title)}</code></div><div class="data-box"><span>发布者</span><strong>${escapeHtml(item.task.owner.name)} · ${escapeHtml(item.task.owner.studentId)}</strong></div><div class="data-box"><span>任务状态</span><strong>${escapeHtml(item.task.status)}</strong></div><div class="data-box"><span>任务积分</span><strong>${item.task.reward}</strong></div></div>` : '';
const snapshot = (item.messageSnapshot||[]).length ? `<section class="message-snapshot"><strong>举报会话 · 最近 ${(item.messageSnapshot||[]).length} 条消息</strong>${item.messageSnapshot.map(message => `<div class="snapshot-message"><b>${escapeHtml(message.senderId===item.reporter.id?item.reporter.nickname:(item.targetUser?.nickname||'对方'))}</b><span>${escapeHtml(message.content)}</span><time>${new Date(Number(message.createdAt)).toLocaleString('zh-CN')}</time></div>`).join('')}</section>` : '';
const actions = item.status === 'open' ? '<textarea maxlength="200" placeholder="处理备注(可选)"></textarea><div class="review-actions"><button type="button" data-rhandle="dismissed">驳回举报</button><button type="button" class="approve" data-rhandle="reviewed">核实处理</button></div>' : '';
return `<article class="review-card report-card" data-rid="${escapeHtml(item.id)}"><div class="review-top"><div><h3>${escapeHtml(item.reporter.name)} · @${escapeHtml(item.reporter.nickname)} ${escapeHtml(title)}</h3><div class="review-meta">举报人邮箱 ${escapeHtml(item.reporter.email)} · ${new Date(item.createdAt).toLocaleString('zh-CN')}</div></div><span class="status-pill ${escapeHtml(item.status)}">${statusText[item.status]||escapeHtml(item.status)}</span></div><div class="report-reason"><span>举报理由</span><p>${escapeHtml(item.reason)}</p></div>${taskInfo}${snapshot}${!item.task&&!isChat?'<div class="review-meta">任务已被删除</div>':''}${item.handlingNote?`<p class="review-note">处理备注:${escapeHtml(item.handlingNote)}</p>`:''}${actions}</article>`;
}).join('');
list.querySelectorAll('[data-rhandle]').forEach(button => button.onclick = () => handleReport(button));
} catch (error) { list.innerHTML = `<div class="empty">${escapeHtml(error.message)}</div>`; return {refreshError:error}; }
};
+135
View File
File diff suppressed because one or more lines are too long
+160
View File
@@ -0,0 +1,160 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="description" content="LinkUp 校园互助管理端">
<title>LinkUp 管理端</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Manrope:wght@500;600;700;800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="admin.css?v=v1-button-feedback-groups-1">
</head>
<body>
<div class="admin-shell">
<aside class="sidebar">
<a class="brand" href="index.html" aria-label="返回 LinkUp"><span>L</span><strong>LinkUp</strong></a>
<p class="side-label">管理中心</p>
<button class="side-item active" data-view="review-center"><span>✓</span>审核中心</button>
<button class="side-item" data-view="credit"><span>◎</span>用户信用管理</button>
<button class="side-item" data-view="official-tasks"><span>★</span>官方任务</button>
<button class="side-item" data-view="analytics"><span>▥</span>运营分析</button>
<button class="side-item" data-view="log-center"><span>≡</span>日志审计</button>
<div class="side-bottom"><small>当前管理员</small><strong id="adminName">未登录</strong><span id="adminEmail">—</span><button id="logoutBtn" hidden>退出管理端</button></div>
</aside>
<main>
<section class="login-view" id="loginView">
<div class="login-card">
<span class="login-mark">L</span>
<p class="eyebrow">LINKUP ADMIN</p>
<h1>管理员登录</h1>
<p>仅配置在管理员名单中的账号可以进入审核后台。</p>
<form id="adminLoginForm">
<label>管理员邮箱<input id="adminLoginEmail" name="email" type="email" required autocomplete="email" placeholder="请输入管理员邮箱"></label>
<label>邮箱验证码<div class="code-row"><input name="code" inputmode="numeric" pattern="\d{6}" maxlength="6" required autocomplete="one-time-code" placeholder="6 位验证码"><button type="button" id="sendAdminCode">获取验证码</button></div></label>
<p class="form-error" id="loginError" role="alert"></p>
<button class="primary full" id="adminLoginSubmit">登录管理端</button>
</form>
</div>
</section>
<section class="dashboard" id="dashboard" hidden>
<section class="admin-group" id="reviewCenter">
<div class="panel-head group-heading"><strong>审核中心</strong><div class="tabs" role="tablist" aria-label="审核类型"><button type="button" class="active" role="tab" aria-selected="true" data-admin-tab="reviews" aria-controls="reviewPanel">学生认证审核</button><button type="button" role="tab" aria-selected="false" data-admin-tab="reports" aria-controls="reportsPanel">举报处理</button></div></div>
<header id="reviewHeader"><div><p class="eyebrow">学生身份管理</p><h1>认证审核</h1><p>核对学籍状态、姓名、学校及报告有效期。</p></div><div class="refresh-actions"><time data-updated="refreshBtn" aria-live="polite"></time><button class="refresh" id="refreshBtn">刷新数据</button></div></header>
<div class="stats-grid" id="reviewStats">
<article><span>待审核</span><strong id="pendingCount">0</strong><small>需要处理</small></article>
<article><span>已认证</span><strong id="approvedCount">0</strong><small>当前累计</small></article>
<article><span>已驳回</span><strong id="rejectedCount">0</strong><small>当前累计</small></article>
<article><span>注册用户</span><strong id="userCount">0</strong><small>平台账号</small></article>
</div>
<section class="review-panel" id="reviewPanel">
<div class="panel-head"><div class="tabs" role="tablist"><button class="active" data-status="pending">待审核</button><button data-status="approved">已通过</button><button data-status="rejected">已驳回</button></div><div class="refresh-actions"><time data-updated="refreshBtn" aria-live="polite"></time><a href="https://www.chsi.com.cn/xlcx/bgcx.jsp" target="_blank" rel="noopener noreferrer">打开学信网核验页 ↗</a></div></div>
<div class="review-list" id="reviewList"><div class="loading">正在加载认证申请…</div></div>
</section>
<section class="review-panel" id="reportsPanel" hidden>
<div class="panel-head"><div class="tabs" role="tablist"><button class="active" data-rstatus="open">待处理</button><button data-rstatus="reviewed">已核实</button><button data-rstatus="dismissed">已驳回</button></div><div class="refresh-actions"><time data-updated="reportsRefresh" aria-live="polite"></time><button type="button" class="refresh" id="reportsRefresh">刷新</button></div></div>
<div class="review-list" id="reportsList"><div class="loading">正在加载举报记录…</div></div>
</section>
</section>
<section class="review-panel" id="creditPanel" hidden>
<div class="panel-head credit-panel-heading"><div><strong>用户信用管理</strong><p class="panel-note">搜索用户、查看账号状态,统一管理信用与积分。</p></div><label class="user-search"><span>搜索用户</span><input id="userSearch" type="search" placeholder="姓名 / 昵称 / 学号 / 学校 / 邮箱"></label></div>
<div class="bulk-toolbar credit-bulk-toolbar">
<div class="bulk-selection"><strong>批量信用调整</strong><label class="select-all"><input id="selectAllUsers" type="checkbox">全选当前结果</label><span id="selectedUserCount">已选 0 人</span></div>
<div class="bulk-fields"><label><span>调整分值</span><input id="bulkCreditDelta" type="number" step="1" min="-100" max="100" placeholder="信用 ±1—100"></label><label><span>调整原因</span><select id="bulkCreditReasonType" required aria-label="批量调整原因"><option value="">选择原因</option><option value="other">其他(仅适用于无任务关联的说明)</option></select></label><label class="bulk-note"><span>核实依据 / 备注</span><input id="bulkCreditReason" type="text" maxlength="200" placeholder="补充说明/调整备注(必填)"></label><button class="primary" type="button" id="bulkCreditBtn">批量调整信用</button></div>
<p class="panel-note">信用与积分调整都会记录,并向用户发送通知。</p>
</div>
<div class="user-list" id="userList"><div class="loading">正在加载用户…</div></div>
<div class="panel-head"><strong class="log-title">最近调整记录</strong><div class="refresh-actions"><time data-updated="adjustRefresh" aria-live="polite"></time><button type="button" class="refresh" id="adjustRefresh">刷新记录</button></div></div>
<div class="adjust-log" id="adjustLog"><div class="loading">暂无调整记录</div></div>
</section>
<section class="admin-group" id="logCenter" hidden>
<div class="panel-head group-heading"><strong>日志审计</strong><div class="tabs" role="tablist" aria-label="日志类型"><button type="button" class="active" role="tab" aria-selected="true" data-admin-tab="login-logs" aria-controls="loginLogsPanel">登录日志</button><button type="button" role="tab" aria-selected="false" data-admin-tab="audit-logs" aria-controls="auditLogsPanel">管理操作日志</button></div></div>
<section class="review-panel" id="loginLogsPanel" hidden>
<div class="panel-head"><div><strong>登录日志</strong><time data-updated="loginLogsRefresh" aria-live="polite"></time></div><div class="log-filters"><input id="loginFilterUser" placeholder="用户 ID"><input id="loginFilterIp" placeholder="IP"><select id="loginFilterSuccess"><option value="">全部结果</option><option value="true">成功</option><option value="false">失败</option></select><select id="loginFilterMethod"><option value="">全部方式</option><option value="password">密码</option><option value="code">验证码</option></select><button type="button" class="refresh" id="loginLogsRefresh">筛选 / 刷新</button></div></div>
<div class="security-log-table" id="loginLogsList"><div class="loading">暂无登录记录</div></div><button type="button" class="refresh load-more" id="loginLogsMore" hidden>加载更多</button>
</section>
<section class="review-panel" id="auditLogsPanel" hidden>
<div class="panel-head"><div><strong>管理操作日志</strong><time data-updated="auditLogsRefresh" aria-live="polite"></time></div><div class="log-filters"><input id="auditFilterAdmin" placeholder="管理员 ID"><input id="auditFilterAction" placeholder="操作类型"><button type="button" class="refresh" id="auditLogsRefresh">筛选 / 刷新</button></div></div>
<div class="security-log-table" id="auditLogsList"><div class="loading">暂无操作记录</div></div><button type="button" class="refresh load-more" id="auditLogsMore" hidden>加载更多</button>
</section>
</section>
<section class="review-panel official-admin-panel" id="officialTasksPanel" hidden>
<div class="panel-head"><div><strong>官方任务</strong><p class="analytics-note">平台运营活动不进入任务广场;领取奖励计入用户普通积分,不可提现。</p></div><div class="refresh-actions"><time data-updated="officialTasksRefresh" aria-live="polite"></time><button type="button" class="refresh" id="officialTasksRefresh">刷新列表</button></div></div>
<form id="officialTaskForm" class="official-task-form">
<section class="official-form-group">
<h2>基础信息</h2>
<div class="official-field-grid official-basic-grid">
<label><span>任务标题</span><input name="title" type="text" minlength="1" maxlength="60" required placeholder="例如:体验新功能并反馈"></label>
<label class="full"><span>任务详情</span><textarea name="detail" maxlength="500" rows="3" placeholder="说明参与方式与完成要求(最多 500 字)"></textarea></label>
</div>
</section>
<section class="official-form-group">
<h2>奖励与限额</h2>
<div class="official-field-grid official-reward-grid">
<label><span>单次奖励</span><span class="official-input-unit"><input name="reward" type="number" min="1" max="5000" step="1" value="10" required><span>积分</span></span></label>
<label><span>每账号最多领取</span><span class="official-input-unit"><input name="perAccountLimit" type="number" min="1" max="99" step="1" value="1" required><span>次</span></span></label>
<label><span>总名额上限</span><span class="official-input-unit"><input name="totalQuota" type="number" min="0" step="1" value="0" required><span>人</span></span><small>填 0 表示不限总人数/次数</small></label>
</div>
</section>
<section class="official-form-group">
<h2>上架设置</h2>
<div class="official-field-grid official-listing-grid">
<label class="full"><span>下架时间(可选)</span><input name="deadline" type="datetime-local"><small>到期后自动从用户列表隐藏</small></label>
</div>
</section>
<div class="official-form-actions"><button class="primary" type="submit">创建并立即上线</button></div>
</form>
<div class="official-list-heading"><strong>已发布任务</strong></div>
<div class="official-task-list" id="officialTaskList"><div class="loading">正在加载官方任务…</div></div>
</section>
<section class="review-panel analytics-panel" id="analyticsPanel" hidden>
<div class="panel-head analytics-toolbar">
<div class="analytics-title-group"><p class="analytics-eyebrow">LINKUP · INSIGHTS</p><strong>运营分析</strong><time data-updated="analyticsRefresh" aria-live="polite"></time><p class="analytics-note">掌握平台增长、任务流转与用户发布情况。统计按服务器本地时区自然日计算,发布量包含已取消任务。</p></div>
<div class="analytics-controls"><label><span>统计周期</span><select id="analyticsDays" aria-label="运营分析统计天数"><option value="7" selected>近 7 天</option><option value="14">近 14 天</option><option value="30">近 30 天</option></select></label><button type="button" class="refresh" id="analyticsRefresh"><span aria-hidden="true">↻</span> 刷新数据</button></div>
</div>
<div class="stats-grid analytics-kpis">
<article class="analytics-kpi kpi-registration"><div class="analytics-kpi-heading"><span>今日注册</span><i aria-hidden="true"><svg viewBox="0 0 24 24"><path d="M16 20v-1.5a4 4 0 0 0-4-4H7a4 4 0 0 0-4 4V20M9.5 10.5a3.5 3.5 0 1 0 0-7 3.5 3.5 0 0 0 0 7ZM17 11a3 3 0 1 0-1-5.8M17 14.5a4 4 0 0 1 4 4V20"/></svg></i></div><strong id="analyticsTodayRegistrations">0</strong><small id="analyticsInviteRatio">累计邀请注册 0,邀请占比 0%</small></article>
<article class="analytics-kpi kpi-publish"><div class="analytics-kpi-heading"><span>今日发布</span><i aria-hidden="true"><svg viewBox="0 0 24 24"><path d="M4 19V5M4 19h17M8 15l3-4 3 2 5-7"/><path d="M16 6h3v3"/></svg></i></div><strong id="analyticsTodayTasks">0</strong><small id="analyticsTodayTaskTypes">代取 0 · 组队 0</small></article>
<article class="analytics-kpi kpi-invite"><div class="analytics-kpi-heading"><span>今日邀请注册</span><i aria-hidden="true"><svg viewBox="0 0 24 24"><path d="M15 19v-1.2a3.8 3.8 0 0 0-3.8-3.8H7.8A3.8 3.8 0 0 0 4 17.8V19M9.5 10.5a3.2 3.2 0 1 0 0-6.4 3.2 3.2 0 0 0 0 6.4ZM18 8v6M15 11h6"/></svg></i></div><strong id="analyticsTodayInvites">0</strong><small>按邀请关系创建日期统计</small></article>
<article class="analytics-kpi kpi-claim"><div class="analytics-kpi-heading"><span>平均接单时长</span><i aria-hidden="true"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5"/><path d="M12 7v5l3 2"/></svg></i></div><strong id="analyticsAvgClaim">0 分钟</strong><small id="analyticsMedianClaim">中位数 0 分钟</small></article>
</div>
<section class="analytics-section analytics-trend-section">
<div class="analytics-section-heading"><div><h2>注册与发布趋势</h2><p>每日注册量和任务发布量</p></div><div class="analytics-legend"><span><i class="registration-key"></i>注册</span><span><i class="task-key"></i>发布</span></div></div>
<div class="analytics-chart-scroll"><div class="analytics-chart" id="analyticsTrend"><div class="loading">正在加载趋势…</div></div></div>
</section>
<section class="analytics-section analytics-price-section">
<div class="analytics-section-heading"><div><h2>悬赏区间分析</h2><p>最易被接取按平均接单时长最短判定,接单率作为辅助指标;样本为发布任务数。</p></div></div>
<div class="analytics-table-wrap"><table><thead><tr><th>悬赏区间</th><th>发布</th><th>被接</th><th>接单率</th><th>平均接单时长</th></tr></thead><tbody id="analyticsPriceBuckets"><tr><td colspan="5" class="table-empty">正在加载…</td></tr></tbody></table></div>
<p class="analytics-best" id="analyticsBestBucket"></p>
</section>
<section class="analytics-section analytics-user-section">
<div class="analytics-section-heading"><div><h2>用户发布行为</h2><p>统计全部任务状态,发过任务的用户作为平均值分母;10 个单独计数,超过 10 个归入 10+。</p></div></div>
<div class="analytics-columns">
<div><h3>发布数量分布</h3><div class="analytics-table-wrap"><table><thead><tr><th>发布任务数</th><th>用户数</th></tr></thead><tbody id="analyticsDistribution"><tr><td colspan="2" class="table-empty">正在加载…</td></tr></tbody></table></div><p class="analytics-average" id="analyticsAvgPublished"></p></div>
<div><h3>发布量 Top 10</h3><ol class="analytics-top" id="analyticsTopPublishers"><li class="table-empty">正在加载…</li></ol></div>
</div>
</section>
</section>
</section>
</main>
</div>
<div class="toast" id="adminToast" role="status"></div>
<dialog class="admin-modal" id="sanctionDialog">
<button class="modal-close" type="button" data-sanction-close aria-label="关闭">×</button>
<form id="sanctionForm"><h2 id="sanctionTitle">账号处理</h2><input type="hidden" name="userId"><input type="hidden" name="action">
<div class="field" data-sanction-category><label for="sanctionCategory">面向用户的原因分类</label><select id="sanctionCategory" name="category" required><option value="">请选择</option><option>多次失约</option><option>涉嫌欺诈</option><option>骚扰他人</option><option>其他违规</option></select></div>
<fieldset class="sanction-scopes" data-sanction-scopes><legend>限制功能(可多选)</legend><label><input type="checkbox" name="scope" value="publish">发单</label><label><input type="checkbox" name="scope" value="claim">接单</label><label><input type="checkbox" name="scope" value="withdraw">提现</label></fieldset>
<div class="field" data-sanction-duration><label for="sanctionDuration">处理时长</label><select id="sanctionDuration" name="duration"><option value="permanent">永久</option><option value="7">7 天</option><option value="30">30 天</option><option value="custom">自定义天数</option></select><input id="sanctionCustomDays" type="number" min="1" max="3650" placeholder="1—3650 天" hidden></div>
<div class="field"><label for="sanctionReason">内部处理理由(仅管理员可见)</label><textarea id="sanctionReason" name="reason" required maxlength="400" rows="4"></textarea></div>
<p class="review-meta">面向用户只展示原因分类;内部理由不会出现在被处理账号可见的通知或登录响应中。</p><button class="primary full" id="sanctionSubmit">提交处理</button>
</form>
</dialog>
<dialog class="admin-modal user-detail-modal" id="userDetailDialog"><button class="modal-close" type="button" data-detail-close aria-label="关闭">×</button><div id="userDetailBody"></div></dialog>
<script src="config.js"></script>
<script src="admin.js?v=v1-button-feedback-groups-1"></script>
<script src="admin-security.js?v=v1-button-feedback-groups-1"></script>
<script src="admin-social.js?v=v1-button-feedback-groups-1"></script>
</body>
</html>
+138
View File
@@ -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=>({'&':'&amp;','<':'&lt;','>':'&gt;',"'":'&#39;','"':'&quot;'}[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 `<div class="analytics-day"><div class="analytics-bars"><span class="analytics-bar registration-bar" style="height:${regHeight}%" title="${escapeHtml(item.date)} 注册 ${item.registrations}" aria-label="${escapeHtml(item.date)} 注册 ${item.registrations}"></span><span class="analytics-bar task-bar" style="height:${taskHeight}%" title="${escapeHtml(item.date)} 发布 ${item.tasks}" aria-label="${escapeHtml(item.date)} 发布 ${item.tasks}"></span></div><time>${escapeHtml(item.date.slice(5))}</time></div>`}).join('');
$('#analyticsPriceBuckets').innerHTML=tasks.priceBuckets.map(bucket=>`<tr class="${bucket.insufficient?'insufficient':''} ${tasks.bestBucket?.label===bucket.label?'best-bucket':''}"><td>${escapeHtml(bucket.label)} ${bucket.insufficient?'<small>样本不足</small>':''} ${tasks.bestBucket?.label===bucket.label?'<strong class="best-tag">最易被接取</strong>':''}</td><td>${analyticsNumber(bucket.published)}</td><td>${analyticsNumber(bucket.claimed)}</td><td>${(bucket.claimRate*100).toFixed(1)}%</td><td>${analyticsNumber(bucket.avgClaimMinutes)} 分钟</td></tr>`).join('')||'<tr><td colspan="5" class="table-empty">暂无悬赏任务</td></tr>';
$('#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=>`<tr><td>${item.label==='10+'?'10+(超过 10 个)':`${escapeHtml(item.label)} 个`}</td><td>${analyticsNumber(item.userCount)}</td></tr>`).join('')||'<tr><td colspan="2" class="table-empty">暂无发布记录</td></tr>';
$('#analyticsAvgPublished').textContent=`平均每位发布者 ${analyticsNumber(result.perUser.avgPublished)} 个任务(${analyticsNumber(result.perUser.publisherCount)} 位发布者)`;
$('#analyticsTopPublishers').innerHTML=result.perUser.topPublishers.length?result.perUser.topPublishers.map(item=>`<li><span>${escapeHtml(item.nickname)}</span><strong>${analyticsNumber(item.count)} 个</strong></li>`).join(''):'<li class="table-empty">暂无发布记录</li>';
}catch(error){$('#analyticsTrend').innerHTML=`<div class="empty">${escapeHtml(error.message)}</div>`;$('#analyticsPriceBuckets').innerHTML=`<tr><td colspan="5" class="table-empty">${escapeHtml(error.message)}</td></tr>`;$('#analyticsDistribution').innerHTML=`<tr><td colspan="2" class="table-empty">${escapeHtml(error.message)}</td></tr>`;$('#analyticsTopPublishers').innerHTML=`<li class="table-empty">${escapeHtml(error.message)}</li>`;$('#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='<div class="loading">正在加载认证申请…</div>';try{const result=await api(`/api/admin/student-verifications?status=${currentStatus}`);if(!result.items.length){list.innerHTML=`<div class="empty">暂无${statusText(currentStatus)}申请</div>`;return}list.innerHTML=result.items.map(item=>`<article class="review-card" data-id="${escapeHtml(item.id)}"><div class="review-top"><div><h3>${escapeHtml(item.name)} · ${escapeHtml(item.school)}</h3><div class="review-meta">学号 ${escapeHtml(item.studentId)} · ${escapeHtml(item.email)}</div></div><div><span class="status-pill ${escapeHtml(item.status)}">${statusText(item.status)}</span><div class="review-time">${new Date(item.submittedAt).toLocaleString('zh-CN')}</div></div></div><div class="review-data"><div class="data-box"><span>学信网在线验证码</span><code>${escapeHtml(item.onlineCode)}</code></div><div class="data-box"><span>报告有效期</span><strong>${escapeHtml(item.reportExpiresOn)}</strong></div></div>${item.status==='pending'?'<textarea maxlength="200" placeholder="驳回时请填写原因"></textarea><div class="review-actions"><button type="button" data-decision="rejected">驳回</button><button type="button" class="approve" data-decision="approved">通过认证</button></div>':`<p class="review-note">审核备注:${escapeHtml(item.reviewNote||'无')}</p>`}</article>`).join('');$$('[data-decision]').forEach(button=>button.onclick=()=>review(button))}catch(error){list.innerHTML=`<div class="empty">${escapeHtml(error.message)}</div>`;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='<div class="loading">正在加载举报记录…</div>';try{const result=await api(`/api/admin/reports?status=${status}`);if(!result.items.length){list.innerHTML=`<div class="empty">暂无${{open:'待处理',reviewed:'已核实',dismissed:'已驳回'}[status]||''}的举报</div>`;return}list.innerHTML=result.items.map(item=>`<article class="review-card report-card" data-rid="${escapeHtml(item.id)}"><div class="review-top"><div><h3>${escapeHtml(item.reporter.name)} · @${escapeHtml(item.reporter.nickname)} 举报了任务</h3><div class="review-meta">举报人邮箱 ${escapeHtml(item.reporter.email)} · ${new Date(item.createdAt).toLocaleString('zh-CN')}</div></div><span class="status-pill ${escapeHtml(item.status)}">${{open:'待处理',reviewed:'已核实',dismissed:'已驳回'}[item.status]||item.status}</span></div><div class="report-reason"><span>举报理由</span><p>${escapeHtml(item.reason)}</p></div>${item.task?`<div class="review-data"><div class="data-box"><span>被举报任务</span><code>${escapeHtml(item.task.title)}</code></div><div class="data-box"><span>发布者</span><strong>${escapeHtml(item.task.owner.name)} · ${escapeHtml(item.task.owner.studentId)}</strong></div><div class="data-box"><span>任务状态</span><strong>${escapeHtml(item.task.status)}</strong></div><div class="data-box"><span>任务积分</span><strong>${item.task.reward}</strong></div></div>`:'<div class="review-meta">任务已被删除</div>'}${item.handlingNote?`<p class="review-note">处理备注:${escapeHtml(item.handlingNote)}</p>`:''}${item.status==='open'&&item.task?`<textarea maxlength="200" placeholder="处理备注(可选)"></textarea><div class="review-actions"><button type="button" data-rhandle="dismissed">驳回举报</button><button type="button" class="approve" data-rhandle="reviewed">核实违规</button></div>`:item.status==='open'?'<div class="review-actions"><button type="button" class="approve" data-rhandle="reviewed">标记已处理</button></div>':''}</article>`).join('');list.querySelectorAll('[data-rhandle]').forEach(button=>button.onclick=()=>handleReport(button))}catch(error){list.innerHTML=`<div class="empty">${escapeHtml(error.message)}</div>`;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='<div class="loading">正在加载记录…</div>';try{const result=await api('/api/admin/credit-adjustments');if(!result.items.length){log.innerHTML='<div class="empty">暂无调整记录</div>';return}log.innerHTML=result.items.map(item=>`<div class="log-row"><strong>${escapeHtml(item.userName)} · @${escapeHtml(item.userNickname)}</strong><span class="${item.delta<0?'neg':'pos'}">${item.delta>0?'+':''}${item.delta}</span><span>${escapeHtml(item.reason)}</span><em>${escapeHtml(item.adminName)} · ${new Date(item.createdAt).toLocaleString('zh-CN')}</em></div>`).join('')}catch(error){log.innerHTML=`<div class="empty">${escapeHtml(error.message)}</div>`;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='<div class="loading">正在加载用户…</div>';try{const result=await api(`/api/admin/users?q=${encodeURIComponent(q)}`);if(!result.items.length){list.innerHTML='<div class="empty">没有匹配的用户</div>';updateBulkSelection();return}list.innerHTML=result.items.map(item=>`<article class="user-row" data-uid="${escapeHtml(item.id)}"><label class="user-select-wrap"><input class="user-select" type="checkbox" data-user-id="${escapeHtml(item.id)}" ${selectedUserIds.has(item.id)?'checked':''} aria-label="选择 ${escapeHtml(item.nickname)}"></label><div class="user-info"><strong>${escapeHtml(item.name)} · @${escapeHtml(item.nickname)}</strong><div class="review-meta">学号 ${escapeHtml(item.studentId)} · ${escapeHtml(item.school)} · ${escapeHtml(item.email)}</div></div><div class="credit-now">信用 <b>${item.creditScore}</b><small>积分 ${item.pointsBalance}</small></div><form class="credit-form"><input class="delta-input" type="number" step="1" min="-100" max="100" required placeholder="±1—100"><input class="reason-input" type="text" maxlength="200" required placeholder="调整原因(必填)"><button type="submit">调整</button></form></article>`).join('');list.querySelectorAll('.credit-form').forEach(form=>form.onsubmit=event=>submitCreditAdjust(event,form));bindBulkUserSelection()}catch(error){list.innerHTML=`<div class="empty">${escapeHtml(error.message)}</div>`;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='<div class="loading">正在加载用户…</div>';try{const result=await api(`/api/admin/users?q=${encodeURIComponent(q)}`);if(!result.items.length){list.innerHTML='<div class="empty">没有匹配的用户</div>';updateBulkSelection();return}list.innerHTML=result.items.map(item=>`<article class="user-row" data-uid="${escapeHtml(item.id)}"><label class="user-select-wrap"><input class="user-select" type="checkbox" data-user-id="${escapeHtml(item.id)}" ${selectedUserIds.has(item.id)?'checked':''} aria-label="选择 ${escapeHtml(item.nickname)}"></label><div class="user-info"><strong>${escapeHtml(item.name)} · @${escapeHtml(item.nickname)}</strong><div class="review-meta">学号 ${escapeHtml(item.studentId)} · ${escapeHtml(item.school)} · ${escapeHtml(item.email)}</div></div><div class="credit-now"><span>信用 <b>${item.creditScore}</b></span><small>积分余额 ${item.pointsBalance}</small></div><div class="adjust-actions"><form class="credit-form adjustment-form" data-kind="credit"><span class="adjust-label">信用</span><input class="delta-input" type="number" step="1" min="-100" max="100" required placeholder="±1—100"><input class="reason-input" type="text" maxlength="200" required placeholder="信用调整原因"><button type="submit">调整</button></form><form class="credit-form points-form adjustment-form" data-kind="points"><span class="adjust-label">积分</span><input class="delta-input" type="number" step="1" min="-1000000" max="1000000" required placeholder="±积分"><input class="reason-input" type="text" maxlength="200" required placeholder="积分调整原因"><button type="submit">调整</button></form></div></article>`).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=`<div class="empty">${escapeHtml(error.message)}</div>`;updateBulkSelection()}}
async function loadOfficialTasks(){const list=$('#officialTaskList');list.innerHTML='<div class="loading">正在加载官方任务…</div>';try{const result=await api('/api/admin/official-tasks');if(!result.items.length){list.innerHTML='<div class="empty">暂无官方任务</div>';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'&&quota>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?`<div class="official-quota"><div class="official-quota-copy"><span>已领 ${claimCount} / 总量 ${quota}</span><strong>${progress}%</strong></div><div class="official-quota-track" role="progressbar" aria-label="名额使用进度" aria-valuemin="0" aria-valuemax="${quota}" aria-valuenow="${Math.min(claimCount,quota)}"><span style="width:${progress}%"></span></div></div>`:'';return `<article class="official-admin-card" data-official-admin-id="${escapeHtml(item.id)}"><h3><span class="official-admin-title">${escapeHtml(item.title)}</span><span class="status-pill ${statusClass}">${status}</span></h3><p>${escapeHtml(item.detail||'无详情')}</p><div class="official-admin-meta"><span>单次奖励 ${Number(item.reward)} 积分</span><span>每账号限领 ${Number(item.perAccountLimit)} 次</span><span>已领取 ${claimCount} 次</span><span>领取人数 ${Number(item.claimedUsers)} 人</span><span>剩余总名额 ${remaining}</span><span>下架时间 ${item.deadline?adminDate(item.deadline):'不限'}</span></div>${quotaProgress}${item.status==='active'?'<button type="button" class="refresh" data-close-official-task>下线任务</button>':''}</article>`}).join('');list.querySelectorAll('[data-close-official-task]').forEach(button=>button.onclick=()=>closeOfficialTask(button))}catch(error){list.innerHTML=`<div class="empty">${escapeHtml(error.message)}</div>`;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;
Vendored
+709
View File
@@ -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='<option value="all">全部学校</option>'+schools.map(school=>`<option value="${escapeHtml(school)}">${escapeHtml(school)}</option>`).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='<option value="">学校加载失败</option>'}
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} <svg aria-hidden="true"><use href="#i-chevron-down"/></svg>`;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=>`<svg><use href="#${id}"/></svg>`;
function taskCard(t){const meta=isErrandTask(t)?errandMeta(t):null;const cat=isErrandTask(t)?errandCategory(t):'';return `<article class="task-card${t.status==="done"?" is-done":""}" data-task="${t.id}" tabindex="0" role="button" aria-label="查看${t.title}"><span class="task-icon ${t.type}${meta?` ${meta.cls}`:''}">${icon(t.type==='partner'?'i-people':meta.icon)}</span><div class="task-main"><div class="task-topline"><strong>${t.title}</strong><span class="badge task-status ${t.status||"open"}">${statusLabel[t.status]||statusLabel.open}</span><span class="badge ${t.urgent?'urgent':''}">${t.type==='partner'?(t.category||'找搭子'):(cat==='快递代取'?(t.urgent?'较紧急':'普通件'):cat)}</span></div><p class="task-route">${t.route}</p><div class="task-meta"><span>${icon('i-pin')}${t.place}</span><span>${icon('i-clock')}${t.time}</span><span>${icon('i-shield')}信用 ${t.credit}</span></div><p class="task-published">发布于 ${fmtPublishedAt(t.createdAt)}</p></div><div class="reward${t.reward?'':' plain'}"><strong>${t.reward||t.joined||'组队'}</strong><small>${t.reward?'积分':'组队中'}</small></div></article>`}
const emptyBoard=(title,hint)=>`<div class="empty-state compact"><span>${title}</span><p>${hint}</p></div>`;
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=>`<article class="partner-card${t.status==="done"?" is-done":""}" data-task="${t.id}" tabindex="0"><span class="category">${t.category}</span><span class="badge task-status ${t.status||"open"}">${statusLabel[t.status]||statusLabel.open}</span><h3>${t.title}</h3><p>${t.route}</p><p class="task-published">发布于 ${fmtPublishedAt(t.createdAt)}</p><footer><span><i class="mini-avatar">${t.user[0]}</i>${t.user}</span><b>${t.joined?`${t.joined} 人`:'招组队中'}</b></footer></article>`).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?`<div class="claim-contact"><strong>已接单 · 联系发布者</strong>${t.phone?`<a href="tel:${t.phone}">${t.phone}</a>`:`<p class="no-phone">该任务发布于旧版本,未留存手机号,请按任务信息交接或联系平台协助</p>`}${cat==='快递代取'?(t.pickupCodes&&t.pickupCodes.length?`<p>取件码:${t.pickupCodes.join(' / ')}</p>`:'<p>取件码见备注或与发布者确认'):''}</div>`:'';let actions;if(t.status==='done')actions='<span class="badge task-status done">已完成</span>';else if(t.status==='claimed')actions=(errand&&(t.claimedByMe||t.mine))?'<button class="accept-btn" data-manage-task>上传凭证并完成任务</button>':'<span class="badge task-status claimed">进行中</span>';else if(errand){if(t.mine)actions='<button class="report-btn" data-cancel-task>取消发布</button><button class="accept-btn" disabled>我发布的任务</button>';else actions=`<button class="report-btn" data-report>举报</button><button class="accept-btn" data-accept>确认接单${t.reward?` · ${t.reward} 积分`:''}</button>`}else if(t.joinedByMe)actions='<button class="accept-btn" disabled>已申请 · 等待发起人确认</button>';else actions='<button class="report-btn" data-report>举报</button><button class="accept-btn" data-accept>申请加入</button>';$('#taskDetail').innerHTML=`<span class="detail-type">${icon(t.type==='partner'?'i-people':meta.icon)}${t.type==='partner'?(t.category||'找搭子'):cat}</span><span class="badge task-status ${t.status||"open"}">${statusLabel[t.status]||statusLabel.open}</span><h2 class="detail-title">${t.title}</h2><p class="detail-route">${t.route}</p><p class="task-published">发布于 ${fmtPublishedAt(t.createdAt)}</p><div class="detail-box"><div><span>${t.type==='partner'?'活动地点':'所在学校'}</span><strong>${t.place}</strong></div><div><span>${t.type==='partner'?'时间':(cat==='快递代取'?'最晚送达':'最晚完成')}</span><strong>${t.time}</strong></div><div><span>任务积分</span><strong>${t.reward?`${t.reward} 积分`:'组队互助'}</strong></div><div><span>${t.type==='partner'?'当前人数':(meta.fourth||'任务说明')}</span><strong>${t.type==='partner'?(t.joined||'—'):'详见下方备注'}</strong></div></div>${claimBox}${errand&&meta.notice?`<p class="advance-notice">${meta.notice}</p>`:''}<p>${t.note||''}</p><div class="publisher"><span class="avatar">${t.user[0]}</span><div><strong>${t.user}</strong><span>${publisherMeta(t)}</span></div><em>信用 ${t.credit}</em></div><div class="detail-actions">${actions}</div>`;$('#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=>`<div class="field"><label>${label}</label><input required name="deadline" type="datetime-local"></div>`;
const rewardField='<div class="field"><label>任务积分</label><input required name="reward" type="number" min="200" max="1500" value="300"><p class="form-hint">单次任务 200—1500 积分</p></div>';
const noteField=placeholder=>`<div class="field full"><label>备注</label><textarea name="note" placeholder="${placeholder}"></textarea></div>`;
const advanceNotice=category=>{const notice=ERRAND_META[category]?.notice;return notice?`<p class="advance-notice">${notice}</p>`:''};
function schoolSelectField(hint){return '<div class="field full"><label>所在学校</label><select required name="school"><option value="">请选择学校</option>'+publishSchoolOptions()+'</select><p class="form-hint">'+hint+'</p></div>'}
function errandFields(category){
if(category==='带饭代买')return `<div class="field"><label>购买店铺</label><input required name="shop" placeholder="例:二食堂麻辣烫"></div><div class="field"><label>送达位置</label><input required name="destination" placeholder="例:C12-518 门口"></div><div class="field full"><label>物品描述</label><input name="items" placeholder="例:微辣,不要香菜,两双筷子"></div>`;
if(category==='代排队')return `<div class="field"><label>排队地点</label><input required name="queuePlace" placeholder="例:校医院门诊大厅"></div><div class="field"><label>时段说明</label><input name="timeSlot" placeholder="例:明早 8 点开始放号"></div><div class="field full"><label>事项描述</label><textarea required name="matter" placeholder="说明要排什么队、办什么事、需要带回什么凭证"></textarea></div>`;
if(category==='代打印/文件取送')return `<div class="field"><label>取件地点</label><input required name="pickupPlace" placeholder="例:校内打印店"></div><div class="field"><label>交付位置</label><input required name="destination" placeholder="例:C12-518 门口"></div><div class="field full"><label>打印要求</label><textarea name="requirement" placeholder="例:双面 A4 共 3 份,黑色装订"></textarea></div>`;
return `<div class="field"><label>手机号</label><input required name="phone" type="tel" placeholder="用于接单后联系"></div><div class="field pickup-code-field"><label>取件码</label><div class="pickup-codes" data-pickup-codes><div class="pickup-code-row"><input required name="pickupCode[]" placeholder="例:5-12-3041" aria-label="取件码 1"><button type="button" class="code-action add-code" data-add-code aria-label="添加取件码">+</button></div></div></div><div class="field full"><label>快递单号(选填)</label><input name="trackingNo" placeholder="多个单号用逗号分隔"></div><div class="field"><label>校内取件点</label><input required name="pickupPlace" placeholder="例:大学城菜鸟驿站"></div><div class="field"><label>校内送达位置</label><input required name="destination" placeholder="例:C12-518 门口"></div>${deadlineField('最晚送达时间')}${rewardField}<div class="field full"><label>快递描述</label><select name="sizeDesc"><option>小件</option><option>大件</option><option>多个包裹</option></select></div>${noteField('重量、易碎提醒或交接说明')}`;
}
function formTemplate(token){const normalized=normalizePublishToken(token);if(normalized==='partner')return `<div class="form-grid">${schoolSelectField('组队范围限校内,优先显示你的已认证学校。')}<div class="field"><label>任务类型</label><select name="category"><option>考研自习</option><option>竞赛组队</option><option>运动健身</option><option>兴趣社交</option></select></div>${deadlineField('最晚组队时间')}<div class="field full"><label>标题</label><input required name="title" placeholder="一句话说清想找什么搭子"></div><div class="field"><label>联系方式</label><input required name="contact" placeholder="手机号或微信号"></div><div class="field"><label>所需人数</label><input required name="slots" type="number" min="1" max="20" value="2"></div><div class="field full"><label>个人经历与组队要求</label><textarea required name="experience" placeholder="介绍当前进度、计划和希望队友具备的条件"></textarea></div><div class="field full"><label>比赛官网链接(选填)</label><input type="url" name="link" placeholder="https://"><p class="form-hint">外部链接将在人工审核后展示</p></div></div><button class="submit-publish">发布组队</button>`;const category=publishCategoryOf(normalized),phoneField='<div class="field"><label>手机号</label><input required name="phone" type="tel" placeholder="用于接单后联系"></div>';if(category==='快递代取')return `<div class="form-grid">${schoolSelectField('互助范围限校内,优先显示你的已认证学校。')}${errandFields(category)}</div><button class="submit-publish">确认发布</button>`;if(category==='代排队')return `<div class="form-grid">${schoolSelectField('互助范围限校内,优先显示你的已认证学校。')}${phoneField}${errandFields(category)}${deadlineField('最晚完成时间')}${rewardField}${noteField('补充说明或交接要求')}</div>${advanceNotice(category)}<button class="submit-publish">确认发布</button>`;return `<div class="form-grid">${schoolSelectField('互助范围限校内,优先显示你的已认证学校。')}${phoneField}${errandFields(category)}${deadlineField(category==='带饭代买'?'最晚送达时间':'最晚完成时间')}${rewardField}${noteField('补充说明或交接要求')}</div>${advanceNotice(category)}<button class="submit-publish">确认发布</button>`}
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=`<input required name="pickupCode[]" placeholder="例:5-12-3041" aria-label="取件码 ${index}"><button type="button" class="code-action remove-code" data-remove-code aria-label="删除取件码 ${index}">−</button>`;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='<div class="empty-state compact"><span>登录后查看你的任务</span><p>发布或接下的任务会集中显示在这里。</p></div>';return}const list=myTasks.filter(t=>myTab==='published'?t.role==='published':t.role==='claimed');if(!list.length){body.innerHTML=`<div class="empty-state compact"><span>${myTab==='published'?'还没有发布过任务':'还没有接受的任务'}</span><p>${myTab==='published'?'发布的任务可以在这里管理或取消。':'接下的任务会显示在这里。'}</p></div>`;return}body.innerHTML=list.map(t=>`<article class="mytask-row" data-my-task="${t.id}" tabindex="0" role="button"><div class="mytask-main"><strong>${escapeHtml(t.title)}</strong><small>${fmtDeadline(t.deadline)}${t.role==='claimed'&&t.phone?` · ${escapeHtml(String(t.phone))}`:''}${t.reward?` · ${t.reward} 积分`:''}</small><small class="task-published">发布于 ${fmtPublishedAt(t.createdAt)}</small></div><em class="${t.status==='done'?'done':'ongoing'}">${t.status==='done'?'已完成':t.status==='claimed'?'进行中':'待接单'}</em></article>`).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='<div class="loading">正在加载任务详情…</div>';navigate('task');
try{const result=await apiRequest(`/api/my/tasks/${id}`,null,{auth:true});renderTaskManage(result.task)}
catch(error){toast(error.message);body.innerHTML=`<div class="empty-state compact"><span>加载失败</span><p>${escapeHtml(error.message)}</p></div>`}}
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 `<div class="proof-card ${uploaded?'uploaded':''}" data-proof-card="${kind}"><div class="proof-card-copy"><strong>${uploaded?'✓ ':''}${label}</strong><p>${help}</p>${uploaded?`<small>${filename}</small>`:''}</div>${canUpload?`<label class="proof-upload-btn"><input type="file" accept="image/jpeg,image/png,image/webp" capture="environment" data-proof-upload="${kind}"><span>${uploaded?'重新拍摄并上传':'拍照或选择照片'}</span></label>`:`<span class="proof-status">${uploaded?'已上传':'等待接单人上传'}</span>`}</div>`
}
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='<button class="report-btn" data-manage-cancel>取消发布</button>';
if(errand&&t.status==='claimed'){
const label=owner?'确认完成 · 积分转给接单同学':'确认送达 · 完成任务';
actions=`<button class="accept-btn" data-manage-complete ${proofReady?'':'disabled'}>${proofReady?label:'上传两张照片后可完成'}</button>${owner&&!publisherCannotCancel?`<button class="report-btn" data-manage-owner-cancel>取消任务${publisherCancelBand==='grace'?'(全额退款)':`(补偿骑手 ${publisherCompensation} 积分)`}</button>`:''}`;
}
const codes=t.pickupCodes&&t.pickupCodes.length?`<div class="claim-contact"><strong>取件码</strong><p>${t.pickupCodes.map(escapeHtml).join(' / ')}</p></div>`:'';
const proofBlock=errand&&['claimed','done'].includes(t.status)?`<section class="proof-panel"><div class="proof-heading"><div><span class="detail-type">交付凭证</span><h2>两张照片缺一不可</h2></div><strong class="proof-count ${proofReady?'ready':''}">${Number(Boolean(proofItems.pickup?.uploaded))+Number(Boolean(proofItems.delivery?.uploaded))}/2</strong></div><p class="proof-intro">${meta.proofIntro}</p><div class="proof-grid">${proofCard('pickup',meta.pickupLabel,meta.pickupHelp,proofItems.pickup,canUpload)}${proofCard('delivery',meta.deliveryLabel,meta.deliveryHelp,proofItems.delivery,canUpload)}</div></section>`:'';
const partnerBlock=t.type==='partner'&&owner?`<div class="section-heading"><h2>申请加入的同学(${(t.participants||[]).length})</h2></div>${t.participants&&t.participants.length?`<div class="notif-list">${t.participants.map(p=>`<div class="notification-item"><span class="notification-copy"><strong>${escapeHtml(p.nickname)}</strong><span>${escapeHtml(p.school||'')} · 信用 ${p.credit} · ${new Date(p.joinedAt).toLocaleString('zh-CN')}</span></span></div>`).join('')}</div>`:'<p class="muted">还没有同学申请,等待中。</p>'}`:'';
body.innerHTML=`<div class="section-heading" style="margin-top:0"><button class="text-btn" data-manage-back>← 返回我的任务</button><span class="badge">${statusLabel[t.status]||t.status}</span></div><span class="detail-type">${icon(errand?(meta.icon):'i-people')}${errand?errandCategory(t):(t.category||'找搭子')}</span><h1 class="detail-title">${escapeHtml(t.title)}</h1><p class="detail-route">${t.deadline?fmtDeadline(t.deadline):'时间待定'} · 发布于 ${fmtPublishedAt(t.createdAt)}</p><div class="detail-box"><div><span>${errand?'所在学校':'活动学校'}</span><strong>${escapeHtml(t.place)}</strong></div><div><span>任务积分</span><strong>${t.reward?`${t.reward} 积分`:'组队互助'}</strong></div>${errand?`<div><span>联系方式</span><strong>${escapeHtml(t.contact||'—')}</strong></div>`:`<div><span>当前名额</span><strong>${t.slots?`${(t.participants||[]).length}/${t.slots} 人`:'不限'}</strong></div>`}</div>${codes}<p>${t.note?escapeHtml(t.note):escapeHtml(t.detail||'')}</p>${owner&&errand&&t.status!=='done'?'<p class="muted">接单人上传两张凭证后才能完成任务并结算积分。</p>':''}${publisherCannotCancel?'<p class="muted">已上传送达照,任务不可撤销;请通过完成确认或举报处理。</p>':''}${proofBlock}${partnerBlock}${actions?`<div class="detail-actions">${actions}</div>`:''}<button class="logout-btn" data-manage-back2>返回我的任务</button>`;
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=>({'&':'&amp;','<':'&lt;','>':'&gt;',"'":'&#39;','"':'&quot;'}[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 `<section class="verification-level-card${active?' current':''}"${active?' aria-current="true"':''}><div class="verification-level-card-head"><h3>L${item.level} ${escapeHtml(item.name)}</h3><div>${item.upcoming?'<span class="verification-level-upcoming">即将上线</span>':''}${active?'<span class="verification-level-current">当前等级</span>':''}</div></div><p><strong>解锁条件</strong>${escapeHtml(item.condition)}</p><p><strong>对应权限</strong>${escapeHtml(item.permission)}</p>${item.benefit?`<p><strong>更多权益</strong>${escapeHtml(item.benefit)}</p>`:''}</section>`;
}).join('');
const action=$('#verificationLevelAction');
if(current.level===1){action.innerHTML='<button type="button" class="btn primary" data-level-upgrade>去认证升级</button>';action.querySelector('button').onclick=()=>{const dialog=$('#verificationLevelsDialog');dialog.close();if(status==='pending')openClaimVerification(verification);else openVerification()}};
if(current.level===2)action.innerHTML='<button type="button" class="btn verification-face-disabled" disabled aria-disabled="true">人脸识别 即将上线</button>';
if(current.level===3)action.innerHTML='<p class="verification-level-benefit">'+escapeHtml(current.benefit)+'</p>';
}
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='<p class="invite-hint">正在加载明细…</p>';$('#entriesDialog').showModal();try{renderEntries(await apiRequest('/api/points/entries',null,{auth:true}))}catch(error){toast(error.message);body.innerHTML=`<p class="form-error">${escapeHtml(error.message)}</p>`}}
function renderEntries(result){const body=$('#entriesBody');const head=`<div class="entries-summary"><div><span>当前余额</span><strong>${Number(result.balance).toLocaleString('zh-CN')}</strong></div><div><span>可提现</span><strong>${Number(result.withdrawable).toLocaleString('zh-CN')}</strong></div></div>`;const rows=result.entries?.length?`<div class="entries-list">${result.entries.map(e=>`<div class="entry-row"><span>${escapeHtml(e.reason)}</span><b class="${e.delta<0?'neg':'pos'}">${e.delta>0?'+':''}${e.delta}</b><em>${new Date(e.createdAt).toLocaleString('zh-CN')}</em></div>`).join('')}</div>`:'<p class="invite-hint">暂无积分记录。</p>';body.innerHTML=head+rows}
async function openInvite(){if(!signedInUser){openLogin();return}const body=$('#inviteBody');body.innerHTML='<p class="invite-hint">正在获取邀请信息…</p>';$('#inviteDialog').showModal();try{renderInvite(await apiRequest('/api/invite-code',null,{auth:true}))}catch(error){toast(error.message);body.innerHTML=`<p class="form-error">${escapeHtml(error.message)}</p>`}}
function renderInvite(info){const body=$('#inviteBody');const warning=`<div class="invite-warning"><strong><svg><use href="#i-shield"/></svg>慎重邀请</strong><p>可提现积分满 80 方可生成邀请码;邀请人注册校验仍要求信用分达到 90。普通受邀用户失约不会自动牵连邀请人,恶意邀请或串通违规经管理员核实后才会调整。</p></div>`;if(info.code){body.innerHTML=`<div class="invite-code-box"><code>${escapeHtml(info.code.code)}</code><button type="button" class="btn primary" data-copy-invite>复制</button></div><p class="invite-hint">邀请码还可被使用 ${info.code.usesLeft}/${info.code.maxUses} 次。</p>${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=`<p class="invite-hint">当前可提现积分 ${info.withdrawablePoints},符合生成条件。</p><button type="button" class="submit-publish" data-gen-invite>生成邀请码</button>${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=`<p class="invite-hint">当前可提现积分 ${info.withdrawablePoints},满 80 可生成邀请码。</p>${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='<div class="loading">正在加载主页…</div>';$('#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=`<div class="public-profile-head"><span class="avatar large">${escapeHtml((user.nickname||'同')[0])}</span><div><h3>${escapeHtml(user.nickname||'同学')}</h3><p>${escapeHtml(user.school||'')}</p></div><span class="verified">${escapeHtml(verification)}</span></div><div class="profile-numbers"><div><strong>${Number(user.creditScore??70)}</strong><span>信用分</span></div><div><strong>${Number(user.breachRate??0)}%</strong><span>失信率</span></div><div><strong>${Number(user.completedTasks??0)}</strong><span>完成任务</span></div><div><strong>${Number(user.currentStreak??0)}</strong><span>连续守约</span></div></div><p class="public-profile-meta">注册于 ${escapeHtml(date)}</p>`}catch(error){toast(error.message);body.innerHTML=`<div class="empty-state compact"><span>主页加载失败</span><p>${escapeHtml(error.message)}</p></div>`}}
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=`<button type="button" class="publisher-link" data-open-profile="${escapeHtml(t.userId)}">${name.textContent}</button>`}}};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)=>'<option value="'+escapeHtml(school)+'">'+(index===0&&preferred===school?'我的学校 · ':'')+escapeHtml(school)+'</option>').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=>`<article class="partner-card${task.status==="done"?" is-done":""}" data-task="${task.id}" tabindex="0"><span class="category">${task.category}</span><span class="badge task-status ${task.status||"open"}">${statusLabel[task.status]||statusLabel.open}</span><h3>${task.title}</h3><p>${task.route}</p><p class="task-published">发布于 ${fmtPublishedAt(task.createdAt)}</p><footer><span><i class="mini-avatar">${task.user[0]}</i>${task.user}</span><b>${task.joined?`${task.joined} 人`:'招组队中'}</b></footer></article>`).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=`<div class="empty-state compact"><span>${group.empty}</span><p>${group.hint}</p></div>`;return}body.innerHTML=visible.map(item=>`<button type="button" class="notification-item ${item.read?'':'unread'}" data-notification-id="${escapeHtml(item.id)}" data-notification-link="${escapeHtml(item.link||'')}"><span class="notification-dot"></span><span class="notification-copy"><strong>${escapeHtml(item.title)}</strong><span>${escapeHtml(item.content)}</span><small>${notificationTime(item.createdAt)}</small></span></button>`).join('');body.querySelectorAll('[data-notification-id]').forEach(item=>item.onclick=()=>handleNotificationClick(item))}
async function loadNotifications(){const body=$('#notificationBody');if(body)body.innerHTML='<div class="empty-state compact"><span>正在加载通知…</span></div>';try{renderNotifications(await apiRequest('/api/notifications',null,{auth:true}))}catch(error){toast(error.message);if(body)body.innerHTML=`<div class="empty-state compact"><span>通知加载失败</span><p>${escapeHtml(error.message)}</p></div>`}}
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=`<div class="task-quota-hint">未完成任务 ${myTaskQuota.activeCount}/${myTaskQuota.activeLimit} 条 · 已完成记录保留最近 ${myTaskQuota.completedLimit} 条</div>`;
if(!list.length){body.innerHTML=hint+`<div class="empty-state compact"><span>${myTab==='published'?'还没有发布过任务':'还没有接受的任务'}</span><p>${myTab==='published'?'发布的任务可以在这里管理或取消。':'接下的任务会显示在这里。'}</p></div>`;return}
body.innerHTML=hint+list.map(t=>`<article class="mytask-row" data-my-task="${t.id}" tabindex="0" role="button"><div class="mytask-main"><strong>${escapeHtml(t.title)}</strong><small>${fmtDeadline(t.deadline)}${t.role==='claimed'&&t.phone?` · ${escapeHtml(String(t.phone))}`:''}${t.reward?` · ${t.reward} 积分`:''}</small><small class="task-published">发布于 ${fmtPublishedAt(t.createdAt)}</small></div><em class="${t.status==='done'?'done':'ongoing'}">${t.status==='done'?'已完成':t.status==='claimed'?'进行中':'待接单'}</em></article>`).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=>`<section class="privacy-section"><h3>${escapeHtml(section.title)}</h3><p>${escapeHtml(section.content)}</p></section>`).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?`<div class="credit-history"><h3>管理员调整记录</h3>${result.history.map(item=>`<div class="credit-history-row"><span>${escapeHtml(item.reason)}</span><b class="${item.delta<0?'neg':'pos'}">${item.delta>0?'+':''}${item.delta}</b><em>${new Date(item.createdAt).toLocaleString('zh-CN')}</em></div>`).join('')}</div>`:'<p class="invite-hint">暂无管理员调整记录。</p>';body.innerHTML=`<div class="credit-detail-score"><div><span>当前信用分</span><strong>${score}</strong></div><div class="score-track"><i style="width:${score}%"></i></div></div><div class="credit-detail-grid"><div><strong>${Number(result.breachRate||0)}%</strong><span>失信率</span></div><div><strong>${Number(result.breachCount||0)}</strong><span>失信次数</span></div><div><strong>${Number(result.commitments||0)}</strong><span>履约次数</span></div><div><strong>${Number(result.completedTasks||0)}</strong><span>完成任务</span></div><div><strong>${Number(result.currentStreak||0)}</strong><span>连续守约</span></div><div><strong>${result.invitationEligible?'可生成':'未达标'}</strong><span>邀请码资格</span></div></div><div class="credit-rules"><strong>信用分规则</strong><p>信用分初始 70 分,正常发布、接单并完成任务会逐步积累;失约、违规或被核实举报会降低信用分。邀请码资格按可提现积分满 80 判断,与信用分无关。</p></div>${history}`}
async function openCreditDetails(){if(!signedInUser){openLogin();return}const body=$('#creditBody');if(body)body.innerHTML='<div class="empty-state compact"><span>正在加载信用详情…</span></div>';$('#creditDialog').showModal();try{renderCreditDetails(await apiRequest('/api/credit/summary',null,{auth:true}))}catch(error){toast(error.message);if(body)body.innerHTML=`<div class="empty-state compact"><span>信用详情加载失败</span><p>${escapeHtml(error.message)}</p></div>`}}
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='<div class="profile-summary-stat" data-open-points role="button" tabindex="0" aria-label="打开积分中心"><span>积分余额</span><strong data-profile-points>—</strong><small>点击查看积分明细</small></div><div class="profile-summary-actions"><span>积分钱包</span><div><button type="button" data-summary-wallet="recharge">充值</button><button type="button" data-summary-wallet="withdraw">提现</button></div></div>';
// 恢复原有信息层级:认证卡片之后显示积分余额与钱包操作。
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=`<label for="${id}">${label}</label><input id="${id}" name="${name}" type="${type}" minlength="8" autocomplete="new-password" placeholder="${placeholder}">`;return field};
const registerGrid=registerForm.querySelector('.form-grid'), registerEmailField=$('#registerEmail')?.closest('.field');
if(registerGrid&&registerEmailField&&!$('#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='<button class="modal-close" data-close aria-label="关闭">×</button><div class="modal-title"><p class="eyebrow">账号安全</p><h2>重置密码</h2><p>使用注册邮箱验证码设置新密码。</p></div><form id="resetPwdForm"><div class="form-grid"><div class="field full"><label for="resetEmail">注册邮箱</label><input id="resetEmail" name="email" type="email" required autocomplete="email" placeholder="请输入注册邮箱"></div><div class="field full"><label for="resetCode">邮箱验证码</label><div class="verification-row"><input id="resetCode" name="code" required inputmode="numeric" pattern="\\d{6}" maxlength="6" placeholder="6 位验证码"><button type="button" id="sendResetCodeBtn">获取验证码</button></div></div><div class="field"><label for="resetPassword">新密码</label><input id="resetPassword" name="password" type="password" required minlength="8" autocomplete="new-password" placeholder="至少 8 位"></div><div class="field"><label for="resetPassword2">确认新密码</label><input id="resetPassword2" name="passwordConfirm" type="password" required minlength="8" autocomplete="new-password" placeholder="再次输入密码"></div></div><p class="form-error" id="resetPwdError" role="alert"></p><button class="submit-publish" id="resetPwdSubmit">重置密码</button><button type="button" class="switch-auth" data-back-login>返回登录</button></form>';
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='<div class="empty-state compact"><span>暂无官方活动</span><p>有新的官方积分活动时会显示在这里。</p></div>';return}
body.innerHTML=`<div class="official-task-cards">${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 `<article class="official-task-card" data-official-task="${escapeHtml(task.id)}"><div class="official-task-card-head"><h3>${escapeHtml(task.title)}</h3><strong>+${Number(task.reward)} 积分</strong></div><p class="official-task-detail">${escapeHtml(task.detail||'')}</p><div class="official-task-meta"><span>每账号限领 ${Number(task.perAccountLimit)} 次</span><span>我已领 ${Number(task.myClaimCount)} 次 · 剩余 ${remaining} 次</span><span>总名额剩余 ${quotaRemaining===null?'不限':Number(quotaRemaining)}</span></div><button type="button" class="submit-publish official-task-claim" data-official-task-id="${escapeHtml(task.id)}" ${disabled?'disabled':''}>${buttonText}</button></article>`;
}).join('')}</div>`;
}
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=`<div class="empty-state compact"><span>官方活动加载失败</span><p>${escapeHtml(error.message)}</p></div>`;}
return [];
}
}
async function openOfficialTasks(){
if(!signedInUser){openLogin();return}
$('#officialTasksDialog').showModal();
$('#officialTasksBody').innerHTML='<div class="loading">正在加载官方活动…</div>';
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);
});
+78
View File
@@ -0,0 +1,78 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="theme-color" content="#10231f">
<meta name="description" content="LinkUp 校园互助平台,连接可信同学,解决跑腿代办与组队找搭子。">
<title>LinkUp · 校园互助</title>
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Crect width='64' height='64' rx='16' fill='%2310231f'/%3E%3Cpath d='M18 18v28h22' fill='none' stroke='%23e8ff5b' stroke-width='8' stroke-linecap='round' stroke-linejoin='round'/%3E%3Ccircle cx='43' cy='21' r='7' fill='%23ff7a59'/%3E%3C/svg%3E">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Manrope:wght@500;600;700;800&family=Noto+Sans+SC:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="styles.css?v=v1-button-feedback-groups-1">
<link rel="stylesheet" href="styles/toast.css?v=multipage-split">
</head>
<body>
<svg class="svg-sprite" aria-hidden="true">
<symbol id="i-home" viewBox="0 0 24 24"><path d="m3 11 9-8 9 8v9a1 1 0 0 1-1 1h-5v-7H9v7H4a1 1 0 0 1-1-1z"/></symbol>
<symbol id="i-box" viewBox="0 0 24 24"><path d="m4 7 8-4 8 4-8 4zM4 7v10l8 4 8-4V7M12 11v10"/></symbol>
<symbol id="i-people" viewBox="0 0 24 24"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8M22 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75"/></symbol>
<symbol id="i-user" viewBox="0 0 24 24"><circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0 1 16 0"/></symbol>
<symbol id="i-plus" viewBox="0 0 24 24"><path d="M12 5v14M5 12h14"/></symbol>
<symbol id="i-pin" viewBox="0 0 24 24"><path d="M20 10c0 5-8 11-8 11S4 15 4 10a8 8 0 1 1 16 0Z"/><circle cx="12" cy="10" r="2.5"/></symbol>
<symbol id="i-clock" viewBox="0 0 24 24"><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></symbol>
<symbol id="i-meal" viewBox="0 0 24 24"><path d="M4 11h16a8 8 0 0 1-16 0Z"/><path d="M8 11V7m4 4V7m4 4V7"/><path d="M5 20h14"/></symbol>
<symbol id="i-print" viewBox="0 0 24 24"><path d="M7 8V3h10v5"/><path d="M5 8h14a2 2 0 0 1 2 2v6h-4M3 10a2 2 0 0 1 2-2"/><path d="M3 10v6h4"/><rect x="7" y="14" width="10" height="7"/></symbol>
<symbol id="i-wallet" viewBox="0 0 24 24"><path d="M3 6a2 2 0 0 1 2-2h14v16H5a2 2 0 0 1-2-2z"/><path d="M3 8h16M15 13h6v4h-6a2 2 0 0 1 0-4Z"/></symbol>
<symbol id="i-shield" viewBox="0 0 24 24"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"/><path d="m9 12 2 2 4-5"/></symbol>
<symbol id="i-arrow" viewBox="0 0 24 24"><path d="m9 18 6-6-6-6"/></symbol>
<symbol id="i-chevron-down" viewBox="0 0 24 24"><path d="m6 9 6 6 6-6"/></symbol>
<symbol id="i-search" viewBox="0 0 24 24"><circle cx="11" cy="11" r="7"/><path d="m20 20-4-4"/></symbol>
<symbol id="i-close" viewBox="0 0 24 24"><path d="m6 6 12 12M18 6 6 18"/></symbol>
<symbol id="i-bell" viewBox="0 0 24 24"><path d="M18 8a6 6 0 0 0-12 0c0 7-3 7-3 7h18s-3 0-3-7M10 20h4"/></symbol>
<symbol id="i-check" viewBox="0 0 24 24"><path d="m5 12 4 4L19 6"/></symbol>
<symbol id="i-logout" viewBox="0 0 24 24"><path d="M10 5V3H4v18h6v-2M14 8l4 4-4 4M8 12h10"/></symbol>
</svg>
<header class="topbar">
<a class="brand" href="#" data-nav="home" aria-label="LinkUp 首页">
<span class="brand-mark">L<span></span></span>
<span>LinkUp</span>
</a>
<nav class="desktop-nav" aria-label="主导航">
<button class="nav-item active" data-nav="home"><svg><use href="#i-home"/></svg>广场</button>
<button class="nav-item" data-nav="express"><svg><use href="#i-box"/></svg>跑腿代办</button>
<button class="nav-item" data-nav="partner"><svg><use href="#i-people"/></svg>找搭子</button>
</nav>
<div class="top-actions">
<button class="icon-btn" id="notificationBtn" data-open-notifications aria-label="通知"><svg><use href="#i-bell"/></svg><i id="notificationBadge" hidden></i></button>
<button class="register-btn" data-open-register>邮箱注册</button>
<button class="login-btn" data-open-login>用户登录</button>
<button class="profile-chip" data-nav="profile" data-auth-profile hidden><span class="avatar" data-user-avatar></span><span data-user-nickname></span><small>信用 <span data-header-credit>—</span></small></button>
</div>
</header>
<main>
<!-- LINKUP_VIEWS -->
</main>
<footer class="site-footer"><button type="button" data-open-privacy>隐私政策</button><span>·</span><span>LinkUp 校园互助</span></footer>
<nav class="mobile-nav" aria-label="移动端导航">
<button class="active" data-nav="home"><svg><use href="#i-home"/></svg><span>广场</span></button>
<button data-nav="express"><svg><use href="#i-box"/></svg><span>跑腿</span></button>
<button class="mobile-publish" data-open-publish="errand:快递代取"><svg><use href="#i-plus"/></svg></button>
<button data-nav="partner"><svg><use href="#i-people"/></svg><span>搭子</span></button>
<button data-nav="profile"><svg><use href="#i-user"/></svg><span>我的</span></button>
</nav>
<!-- LINKUP_DIALOGS -->
<!-- LINKUP_TOAST -->
<script src="config.js"></script>
<script src="js/toast.js?v=multipage-split"></script>
<script src="app.js?v=v1-button-feedback-groups-1"></script>
<script src="social.js?v=v1-button-feedback-groups-1"></script>
</body>
</html>
+27
View File
@@ -0,0 +1,27 @@
<dialog id="entriesDialog" class="modal register-modal">
<button class="modal-close" data-close aria-label="关闭"><svg><use href="#i-close"/></svg></button>
<div class="modal-title"><p class="eyebrow">积分钱包</p><h2>积分中心</h2><p>查看余额、可提现积分和每笔积分变动。</p></div>
<div id="entriesBody"></div>
</dialog>
<dialog id="creditDialog" class="modal register-modal">
<button class="modal-close" data-close aria-label="关闭"><svg><use href="#i-close"/></svg></button>
<div class="modal-title"><p class="eyebrow">校园信用</p><h2>信用详情</h2><p>信用表现会影响任务排序、邀请资格和校园互助体验。</p></div>
<div id="creditBody"><div class="empty-state compact"><span>正在加载信用详情…</span></div></div>
</dialog>
<dialog id="inviteDialog" class="modal register-modal">
<button class="modal-close" data-close aria-label="关闭"><svg><use href="#i-close"/></svg></button>
<div class="modal-title"><p class="eyebrow">邀请奖励</p><h2>邀请同学加入</h2><p>可提现积分满 80 即可生成专属邀请码;注册时邀请人信用分仍须达到 90。</p></div>
<div id="inviteBody"></div>
</dialog>
<dialog id="walletDialog" class="modal register-modal">
<button class="modal-close" data-close aria-label="关闭"><svg><use href="#i-close"/></svg></button>
<div class="modal-title"><p class="eyebrow">积分钱包</p><h2 id="walletTitle">充值积分</h2><p id="walletDesc">按 1 元 = 100 积分比例到账。</p></div>
<form id="walletForm">
<div class="form-grid"><div class="field full"><label for="walletAmount" id="walletAmountLabel">充值金额(元)</label><input id="walletAmount" name="amount" type="number" min="1" step="1" required placeholder="最低 1 元"><p class="form-hint" id="walletHint">充值即时到账,可用于发布跑腿代办任务。</p></div></div>
<p class="form-error" id="walletError" role="alert"></p>
<button class="submit-publish" id="walletSubmit">确认充值</button>
</form>
</dialog>
+60
View File
@@ -0,0 +1,60 @@
<dialog id="registerDialog" class="modal register-modal">
<button class="modal-close" data-close aria-label="关闭"><svg><use href="#i-close"/></svg></button>
<div class="modal-title"><p class="eyebrow">校园身份认证</p><h2>创建 LinkUp 账号</h2><p>一个学号只能注册一个账号,邮箱验证后完成注册。</p></div>
<form id="registerForm">
<div class="form-grid">
<div class="field"><label for="realName">姓名</label><input id="realName" name="name" required maxlength="40" autocomplete="name" placeholder="请输入真实姓名"></div>
<div class="field"><label for="nickname">昵称</label><input id="nickname" name="nickname" required maxlength="30" placeholder="对外展示的名字"></div>
<div class="field"><label for="studentId">学号</label><input id="studentId" name="studentId" required minlength="4" maxlength="32" pattern="[A-Za-z0-9_-]+" autocomplete="off" placeholder="每个学号仅限一个账号"></div>
<div class="field"><label for="school">学校</label><input id="school" name="school" required maxlength="80" autocomplete="organization" placeholder="请输入学校全称"></div>
<div class="field"><label for="registerPassword">设置密码</label><input id="registerPassword" name="password" type="password" required minlength="8" autocomplete="new-password" placeholder="至少 8 位"></div>
<div class="field"><label for="registerPassword2">确认密码</label><input id="registerPassword2" name="passwordConfirm" type="password" required minlength="8" autocomplete="new-password" placeholder="再次输入密码"></div>
<div class="field full"><label for="registerEmail">邮箱</label><input id="registerEmail" name="email" required type="email" autocomplete="email" placeholder="用于接收验证码"></div>
<div class="field full"><label for="emailCode">邮箱验证码</label><div class="verification-row"><input id="emailCode" name="code" required inputmode="numeric" pattern="\d{6}" maxlength="6" autocomplete="one-time-code" placeholder="6 位验证码"><button type="button" id="sendCodeBtn">获取验证码</button></div><p class="form-hint">验证码 10 分钟内有效,请勿转发给他人。</p></div>
<div class="field full"><label for="inviteCodeField">邀请码(选填)</label><input id="inviteCodeField" name="inviteCode" maxlength="16" autocomplete="off" placeholder="填写同学的邀请码"><p class="form-hint">填写后可获得邀请信用加成。</p></div>
<div class="field full privacy-consent"><label class="consent-row"><input id="privacyConsent" name="privacyConsent" value="1" type="checkbox" required><span>我已阅读并同意 <button type="button" class="inline-policy" data-open-privacy>《LinkUp 用户隐私政策》</button></span></label><input type="hidden" name="privacyPolicyVersion" value=""></div>
</div>
<p class="form-error" id="registerError" role="alert"></p>
<button class="submit-publish" id="registerSubmit">验证并注册</button>
</form>
</dialog>
<dialog id="loginDialog" class="modal register-modal">
<button class="modal-close" data-close aria-label="关闭"><svg><use href="#i-close"/></svg></button>
<div class="modal-title"><p class="eyebrow">欢迎回来</p><h2>用户登录</h2><p>使用注册邮箱和密码登录;异常环境需邮箱二次验证。</p></div>
<form id="loginForm">
<div class="form-grid">
<div class="field full"><label for="loginEmail">注册邮箱</label><input id="loginEmail" name="email" required type="email" autocomplete="email" placeholder="请输入注册邮箱"></div>
<div class="field full"><label for="loginPassword">密码</label><input id="loginPassword" name="password" type="password" required minlength="8" autocomplete="current-password" placeholder="请输入密码"><button type="button" class="forgot-pwd" id="forgotPasswordBtn">忘记密码?</button></div>
<div class="field full" id="loginCodeField" hidden><label for="loginCode">邮箱验证码</label><div class="verification-row"><input id="loginCode" name="code" disabled required inputmode="numeric" pattern="\d{6}" maxlength="6" autocomplete="one-time-code" placeholder="6 位验证码"><button type="button" id="sendLoginCodeBtn">重新获取</button></div><p class="form-hint" id="loginStepHint"></p></div>
</div>
<p class="form-error" id="loginError" role="alert"></p>
<button class="submit-publish" id="loginSubmit">登录</button>
<button type="button" class="switch-auth" data-open-register>还没有账号?立即注册</button>
</form>
</dialog>
<dialog id="resetPwdDialog" class="modal register-modal">
<button class="modal-close" data-close aria-label="关闭"><svg><use href="#i-close"/></svg></button>
<div class="modal-title"><p class="eyebrow">账号安全</p><h2>重置密码</h2><p>使用注册邮箱验证码设置新密码。</p></div>
<form id="resetPwdForm">
<div class="form-grid">
<div class="field full"><label for="resetEmail">注册邮箱</label><input id="resetEmail" name="email" type="email" required autocomplete="email" placeholder="请输入注册邮箱"></div>
<div class="field full"><label for="resetCode">邮箱验证码</label><div class="verification-row"><input id="resetCode" name="code" required inputmode="numeric" pattern="\d{6}" maxlength="6" placeholder="6 位验证码"><button type="button" id="sendResetCodeBtn">获取验证码</button></div></div>
<div class="field"><label for="resetPassword">新密码</label><input id="resetPassword" name="password" type="password" required minlength="8" autocomplete="new-password" placeholder="至少 8 位"></div>
<div class="field"><label for="resetPassword2">确认新密码</label><input id="resetPassword2" name="passwordConfirm" type="password" required minlength="8" autocomplete="new-password" placeholder="再次输入密码"></div>
</div>
<p class="form-error" id="resetPwdError" role="alert"></p>
<button class="submit-publish" id="resetPwdSubmit">重置密码</button>
<button type="button" class="switch-auth" data-back-login>返回登录</button>
</form>
</dialog>
<dialog id="logoutDialog" class="modal register-modal logout-modal">
<button class="modal-close" data-close aria-label="关闭"><svg><use href="#i-close"/></svg></button>
<div class="modal-title"><p class="eyebrow">账号安全</p><h2>确认退出当前账号?</h2><p>退出后会清除本设备的登录状态,再次使用时需要重新登录。</p></div>
<div class="logout-dialog-actions">
<button type="button" class="btn secondary" data-close>取消</button>
<button type="button" class="btn logout-confirm" id="confirmLogout"><svg><use href="#i-logout"/></svg><span>确认退出</span></button>
</div>
</dialog>
+15
View File
@@ -0,0 +1,15 @@
<dialog id="notificationDialog" class="modal register-modal">
<button class="modal-close" data-close aria-label="关闭"><svg><use href="#i-close"/></svg></button>
<div class="modal-title">
<p class="eyebrow">消息中心</p>
<h2>通知</h2>
<div class="notification-toolbar"><span id="notificationSummary">—</span><button type="button" id="markAllNotifications">全部标为已读</button></div>
<div class="notif-tabs segment" role="tablist" aria-label="消息类型">
<button type="button" class="active" data-notif-filter="all" role="tab" aria-selected="true">全部</button>
<button type="button" data-notif-filter="task" role="tab" aria-selected="false">任务消息</button>
<button type="button" data-notif-filter="account" role="tab" aria-selected="false">账户与积分</button>
<button type="button" data-notif-filter="system" role="tab" aria-selected="false">系统</button>
</div>
</div>
<div id="notificationBody"><div class="empty-state compact"><span>正在加载通知…</span></div></div>
</dialog>
+5
View File
@@ -0,0 +1,5 @@
<dialog id="officialTasksDialog" class="modal register-modal official-tasks-modal">
<button class="modal-close" data-close aria-label="关闭"><svg><use href="#i-close"/></svg></button>
<div class="modal-title"><p class="eyebrow">平台活动</p><h2>官方任务</h2><p>领取活动任务即可获得积分;奖励计入普通积分余额,不可提现。</p></div>
<div id="officialTasksBody"><div class="loading">正在加载官方活动…</div></div>
</dialog>
+5
View File
@@ -0,0 +1,5 @@
<dialog id="privacyDialog" class="modal register-modal privacy-modal">
<button class="modal-close" data-close aria-label="关闭"><svg><use href="#i-close"/></svg></button>
<div class="modal-title"><p class="eyebrow" id="privacyVersion">隐私保护</p><h2 id="privacyTitle">LinkUp 用户隐私政策</h2><p id="privacyEffective">请在注册前阅读本政策。</p></div>
<div id="privacyBody" class="privacy-body"><p>正在加载隐私政策…</p></div>
</dialog>
+6
View File
@@ -0,0 +1,6 @@
<dialog id="publishDialog" class="modal publish-modal">
<button class="modal-close" data-close aria-label="关闭"><svg><use href="#i-close"/></svg></button>
<div class="modal-title"><p class="eyebrow">发布互助</p><h2 id="publishTitle">发布快递代取</h2></div>
<div class="publish-grid" role="tablist" aria-label="任务类目"><button class="active" data-publish-cat="errand:快递代取">快递代取</button><button data-publish-cat="errand:带饭代买">带饭代买</button><button data-publish-cat="errand:代排队">代排队</button><button data-publish-cat="errand:代打印/文件取送">代打印</button><button data-publish-cat="partner">找搭子</button></div>
<form id="publishForm"></form>
</dialog>
+19
View File
@@ -0,0 +1,19 @@
<dialog id="chatDialog" class="modal chat-modal">
<button class="modal-close" data-close aria-label="关闭"><svg><use href="#i-close"/></svg></button>
<div class="chat-header">
<div><p class="eyebrow">校园私聊</p><h2 id="chatPeerName">同学</h2></div>
<button type="button" class="report-btn" id="chatReportButton">举报</button>
</div>
<p id="chatStatus" class="chat-status" role="status"></p>
<div id="chatMessages" class="chat-messages" aria-live="polite"></div>
<form id="chatForm" class="chat-form">
<textarea id="chatInput" maxlength="200" rows="2" placeholder="发送文字消息(最多 200 字)" aria-label="私聊消息"></textarea>
<div class="chat-compose"><span id="chatSendRule">发送一条消息后,等待对方回复。</span><button type="submit" id="chatSendButton">发送</button></div>
</form>
</dialog>
<dialog id="creditHistoryDialog" class="modal register-modal credit-history-modal">
<button class="modal-close" data-close aria-label="关闭"><svg><use href="#i-close"/></svg></button>
<div class="modal-title"><p class="eyebrow">公开主页</p><h2 id="creditHistoryTitle">信用历史</h2><p>只展示变动分值、调整类型和日期,不包含详细原因。</p></div>
<div id="creditHistoryBody"><div class="loading">正在加载信用历史…</div></div>
</dialog>
+20
View File
@@ -0,0 +1,20 @@
<dialog id="taskDialog" class="modal task-modal">
<button class="modal-close" data-close aria-label="关闭"><svg><use href="#i-close"/></svg></button>
<div id="taskDetail"></div>
</dialog>
<dialog id="publicProfileDialog" class="modal profile-modal">
<button class="modal-close" data-close aria-label="关闭"><svg><use href="#i-close"/></svg></button>
<div class="modal-title"><p class="eyebrow">校园公开主页</p><h2>同学主页</h2></div>
<div id="publicProfileBody"><div class="loading">正在加载主页…</div></div>
</dialog>
<dialog id="reportDialog" class="modal register-modal">
<button class="modal-close" data-close aria-label="关闭"><svg><use href="#i-close"/></svg></button>
<div class="modal-title"><p class="eyebrow">安全互助</p><h2>举报内容</h2><p>举报信息会单独存档供平台审核,你的身份对对方保密。</p></div>
<form id="reportForm">
<div class="field full"><label>举报理由</label><textarea name="reason" required minlength="5" maxlength="200" placeholder="说明违规情况,例如虚假任务、骚扰、诈骗等(5—200 字)"></textarea></div>
<p class="form-error" id="reportError" role="alert"></p>
<button class="submit-publish" id="reportSubmit">提交举报</button>
</form>
</dialog>
+31
View File
@@ -0,0 +1,31 @@
<dialog id="verificationLevelsDialog" class="modal register-modal verification-levels-dialog" aria-labelledby="verificationLevelsTitle">
<div class="verification-levels-header">
<div class="modal-title"><p class="eyebrow">校园身份</p><h2 id="verificationLevelsTitle">认证等级说明</h2></div>
<button class="modal-close" data-close aria-label="关闭认证等级说明"><svg><use href="#i-close"/></svg></button>
</div>
<div class="verification-levels-scroll">
<p id="verificationLevelStatus" class="verification-level-status" role="status"></p>
<div id="verificationLevelsList" class="verification-levels-list"></div>
<div id="verificationLevelAction" class="verification-level-action"></div>
</div>
</dialog>
<dialog id="claimVerificationDialog" class="modal register-modal" aria-labelledby="claimVerificationTitle" aria-describedby="claimVerificationMessage">
<button class="modal-close" data-close aria-label="关闭"><svg><use href="#i-close"/></svg></button>
<div class="modal-title"><p class="eyebrow">接单需要认证</p><h2 id="claimVerificationTitle">学信网在校生认证</h2><p id="claimVerificationMessage"></p></div>
<div class="detail-actions"><button type="button" class="report-btn" data-close>暂不接单</button><button type="button" class="accept-btn" id="claimVerificationGo">去认证</button></div>
</dialog>
<dialog id="verificationDialog" class="modal register-modal">
<button class="modal-close" data-close aria-label="关闭"><svg><use href="#i-close"/></svg></button>
<div class="modal-title"><p class="eyebrow">认证等级 L2</p><h2>学信网在校生认证</h2><p>提交《教育部学籍在线验证报告》的在线验证码,由平台人工核验。</p></div>
<form id="verificationForm">
<div class="verification-guide"><span>1</span><p>前往学信网申请或延长《教育部学籍在线验证报告》。</p><span>2</span><p>填写报告中的在线验证码和报告有效期。</p><span>3</span><p>平台审核通过后,你的主页将展示“学信网已认证”。</p></div>
<a class="chsi-link" href="https://www.chsi.com.cn/xlcx/bgys.jsp" target="_blank" rel="noopener noreferrer">前往学信网查看验证报告</a>
<div class="form-grid">
<div class="field full"><label for="onlineCode">在线验证码</label><input id="onlineCode" name="onlineCode" required minlength="8" maxlength="32" pattern="[A-Za-z0-9-]+" autocomplete="off" placeholder="请输入报告中的在线验证码"><p class="form-hint">验证码会加密保存,仅认证审核员可在审核时查看。</p></div>
<div class="field full"><label for="reportExpiresOn">报告有效期至</label><input id="reportExpiresOn" name="reportExpiresOn" required type="date"></div>
<label class="consent-row"><input name="consent" type="checkbox" required><span>我同意平台仅为核验在校生身份使用以上信息。</span></label>
</div>
<p class="form-error" id="verificationError" role="alert"></p>
<button class="submit-publish" id="verificationSubmit">提交审核</button>
</form>
</dialog>
+4
View File
@@ -0,0 +1,4 @@
<div class="toast" id="toast" role="status" aria-live="polite" aria-atomic="true" popover="manual">
<svg aria-hidden="true"><use href="#i-check"/></svg>
<span></span>
</div>
+4
View File
@@ -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 = "";
+11
View File
@@ -0,0 +1,11 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LinkUp · 校园互助</title>
</head>
<body>
<p>LinkUp 页面由 <code>base.html</code> 与多文件组件通过后端组合,请使用项目开发服务器访问。</p>
</body>
</html>
+42
View File
@@ -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 });
})();
+329
View File
@@ -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 = '<div class="loading">正在加载信用历史…</div>';
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 ? `<div class="public-credit-history">${items.map(item =>
`<article class="public-credit-row"><span>${escapeHtml(item.category)}</span><b class="${Number(item.delta)<0?'neg':'pos'}">${Number(item.delta)>0?'+':''}${Number(item.delta)}</b><time>${escapeHtml(item.date)}</time></article>`
).join('')}</div>` : '<div class="empty-state compact"><span>暂无可公开的信用记录</span></div>';
const hidden = Number(result.hiddenCount) > 0
? `<p class="credit-history-hidden">另有 ${Number(result.hiddenCount)} 条更早记录暂不展示,其中未分类历史不会公开。</p>` : '';
body.innerHTML = history + hidden;
})
.catch(error => { body.innerHTML = `<div class="empty-state compact"><span>信用历史加载失败</span><p>${escapeHtml(error.message)}</p></div>`; 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 = '<div class="empty-state compact"><span>打个招呼,开始私聊</span></div>';
} 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 `<div class="chat-message ${own?'own':'peer'}" data-message-id="${escapeHtml(message.id)}"><span>${escapeHtml(message.content)}</span><time>${escapeHtml(date)}</time></div>`;
}).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 = '<div class="loading">正在加载消息…</div>';
$('#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 = '<button type="button" role="menuitem" data-publisher-choice="profile">查看主页</button><button type="button" role="menuitem" data-publisher-choice="chat">发私信</button>';
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 = `<div class="invite-warning"><strong><svg><use href="#i-shield"/></svg>慎重邀请</strong><p>可提现积分满 <b>80</b> 可生成邀请码,每个账号限一个,最多使用 2 次。邀请关系会用于平台风控;恶意邀请或串通违规经核实后,管理员可调整邀请人的信用分。注册时邀请人仍须信用分达到 90。</p></div>`;
if (info.code) {
body.innerHTML = `<div class="invite-code-box"><code>${escapeHtml(info.code.code)}</code><button type="button" class="btn primary" data-copy-invite>复制</button></div><p class="invite-hint">邀请码还可被使用 ${Number(info.code.usesLeft)||0}/${Number(info.code.maxUses)||2} 次。</p>${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 = `<div class="invite-progress"><div class="score-track"><i style="width:${progress}%"></i></div><small>当前可提现积分 ${points} / 80</small></div>`;
if (info.eligible) {
body.innerHTML = `<p class="invite-hint">当前可提现积分 ${points},已达到生成条件。</p>${progressHtml}<button type="button" class="submit-publish" data-gen-invite>生成邀请码</button>${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 = `<p class="invite-hint">当前可提现积分 ${points},满 80 可生成邀请码。</p>${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
? `<div class="credit-history"><h3>信用分变化记录</h3>${result.history.map(item => `<div class="credit-history-row"><span>${escapeHtml(item.reason)}${item.reversedAt ? ' · 已撤销' : ''}</span><b class="${item.delta < 0 ? 'neg' : 'pos'}">${item.delta > 0 ? '+' : ''}${item.delta}</b><em>${escapeHtml(new Date(Number(item.createdAt)).toLocaleString('zh-CN'))}</em></div>`).join('')}</div>`
: '<p class="invite-hint">暂无信用分变化记录。</p>';
body.innerHTML = `<div class="credit-detail-score"><div><span>当前信用分(0–100)</span><strong>${score}</strong></div><div class="score-track"><i style="width:${score}%"></i></div></div><div class="credit-detail-grid"><div><strong>${escapeHtml(breach)}</strong><span>近 90 天失信率</span></div><div><strong>${Number(result.breachCount90d)||0}</strong><span>近 90 天确认失信</span></div><div><strong>${Number(result.commitments90d)||0}</strong><span>近 90 天履约承诺</span></div><div><strong>${Number(result.completedTasks)||0}</strong><span>完成任务</span></div><div><strong>${Number(result.currentStreak)||0}</strong><span>连续守约</span></div><div><strong>${escapeHtml(pointsProgress)}</strong><span>可提现积分 / 邀请码门槛</span></div></div><div class="credit-rules"><strong>信用分与积分</strong><p>积分用于任务交易与提现;信用分独立记录履约表现,范围为 0–100。普通注册信用分为 70,邀请码注册为 90。正常完成任务分别为发单者 +1、接单者 +2,每 7 天最多获得 +5。邀请码资格按可提现积分满 80 判断,与信用分无关。</p><p>失信率按近 90 天已形成履约承诺的任务数计算;少于 3 条时显示“记录较少”。积分结算不兑换信用分。</p></div>${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}`;
};
+382
View File
@@ -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}
+12
View File
@@ -0,0 +1,12 @@
.toast {
z-index: 2147483647;
border: 0;
}
.toast:popover-open {
display: flex;
}
.toast::backdrop {
display: none;
}
+10
View File
@@ -0,0 +1,10 @@
<section class="view" id="view-express">
<div class="page-hero compact-hero">
<div><p class="eyebrow">顺路一程,送到楼下</p><h1>跑腿代办</h1><p>快递代取、带饭代买、代排队、代打印,接单实名留痕;任务完成后积分自动到账。</p></div>
<button class="btn primary" data-open-publish="errand:快递代取"><svg><use href="#i-plus"/></svg>发布跑腿任务</button>
</div>
<div class="content-narrow">
<div class="section-heading"><h2>可接任务</h2><span class="muted">按发布时间与紧迫度排序</span></div>
<div class="task-list" id="expressList"></div>
</div>
</section>
+54
View File
@@ -0,0 +1,54 @@
<section class="view active" id="view-home">
<div class="welcome-row">
<div>
<p class="eyebrow" id="campusLabel">校园互助广场</p>
<h1 id="welcomeTitle">下午好,同学</h1>
<p class="lead">今天附近有 <strong id="nearbyCount">0</strong> 个互助需求,顺路帮个忙吧。</p>
</div>
<div class="quick-actions">
<button class="btn secondary" data-open-publish="partner"><svg><use href="#i-people"/></svg>找搭子</button>
<button class="btn primary" data-open-publish="errand:快递代取"><svg><use href="#i-plus"/></svg>发布跑腿</button>
</div>
</div>
<div class="dashboard-grid">
<section class="main-column">
<div class="filter-bar">
<div class="segment" role="tablist" aria-label="任务类型">
<button class="active" data-filter="all">全部</button>
<button data-filter="errand:快递代取">快递代取</button>
<button data-filter="errand:带饭代买">带饭代买</button>
<button data-filter="errand:代排队">代排队</button>
<button data-filter="errand:代打印/文件取送">代打印</button>
<button data-filter="partner">找搭子</button>
</div>
<label class="search-box"><svg><use href="#i-search"/></svg><input id="searchInput" type="search" placeholder="搜地点、活动或关键词" aria-label="搜索任务"></label>
</div>
<div class="section-heading task-list-heading">
<h2>附近任务</h2>
<div class="task-heading-controls">
<div class="school-control">
<select id="schoolFilter" aria-label="浏览学校" disabled><option value="">加载学校…</option></select>
<svg aria-hidden="true"><use href="#i-chevron-down"/></svg>
</div>
<div class="sort-control">
<button id="sortBtn" class="text-btn" type="button" aria-haspopup="listbox" aria-expanded="false">综合排序 <svg aria-hidden="true"><use href="#i-chevron-down"/></svg></button>
<div id="sortMenu" class="sort-menu" role="listbox" hidden>
<button type="button" role="option" data-sort="combined" aria-selected="true">综合排序</button>
<button type="button" role="option" data-sort="latest" aria-selected="false">最新发布</button>
<button type="button" role="option" data-sort="urgent" aria-selected="false">最紧急</button>
<button type="button" role="option" data-sort="reward" aria-selected="false">积分最高</button>
<button type="button" role="option" data-sort="open-first" aria-selected="false">未接取优先</button>
</div>
</div>
</div>
</div>
<div class="task-list" id="taskList"></div>
<div class="empty-state" id="emptyState" hidden><span>没有匹配的任务</span><p>换个关键词,或成为第一个发布需求的人。</p></div>
</section>
<aside class="side-column">
<section class="safety-note"><svg><use href="#i-shield"/></svg><div><strong>安全互助提示</strong><p>代取必须使用接单者本人身份码。发现异常可在任务详情内举报。</p></div></section>
</aside>
</div>
</section>
+14
View File
@@ -0,0 +1,14 @@
<section class="view" id="view-partner">
<div class="page-hero partner-hero">
<div><p class="eyebrow">同频的人,就在附近</p><h1>找搭子</h1><p>学习、竞赛、运动,把计划变成一起完成的约定。</p></div>
<button class="btn coral" data-open-publish="partner"><svg><use href="#i-plus"/></svg>发布组队</button>
</div>
<div class="topic-pills" role="tablist" aria-label="找搭子类型">
<button class="active" type="button" data-topic="all" role="tab" aria-selected="true">全部</button>
<button type="button" data-topic="考研自习" role="tab" aria-selected="false">考研自习</button>
<button type="button" data-topic="竞赛组队" role="tab" aria-selected="false">竞赛组队</button>
<button type="button" data-topic="运动健身" role="tab" aria-selected="false">运动健身</button>
<button type="button" data-topic="兴趣社交" role="tab" aria-selected="false">兴趣社交</button>
</div>
<div class="partner-grid" id="partnerGrid"></div>
</section>
+50
View File
@@ -0,0 +1,50 @@
<section class="view" id="view-profile">
<div class="profile-layout">
<section class="profile-panel">
<div class="guest-profile" data-guest-profile>
<span class="avatar large"><svg><use href="#i-user"/></svg></span>
<h1>登录后查看个人信息</h1>
<p>使用注册邮箱和密码登录。</p>
<button class="btn primary" data-open-login>用户登录</button>
</div>
<div data-user-profile hidden>
<div class="profile-head">
<span class="avatar large" data-profile-avatar></span>
<div><h1 data-profile-name></h1><p><span data-profile-nickname></span> · <span data-profile-school></span></p></div>
<span class="verified" data-verification-badge><svg><use href="#i-shield"/></svg><span data-verification-label>邮箱已验证</span></span>
</div>
<div class="profile-numbers">
<div><strong data-profile-credit>—</strong><span>信用分(0–100)</span></div>
<div><strong data-profile-breach>—</strong><span>近 90 天失信率</span></div>
<div class="profile-credit-action" data-open-verification-levels role="button" tabindex="0" aria-label="查看认证等级说明"><strong data-verification-level>L1</strong><span>认证等级</span></div>
<div><strong data-profile-date>—</strong><span>注册时间</span></div>
</div>
<div class="identity-card">
<div class="identity-copy"><span class="identity-icon"><svg><use href="#i-shield"/></svg></span><div><strong>在校生认证</strong><p data-verification-description>正在加载认证状态…</p></div></div>
<button class="btn primary identity-action" data-open-verification>开始认证</button>
</div>
<button type="button" class="invite-btn profile-invite-btn" data-action="invite" data-account-action><svg><use href="#i-people"/></svg><span>邀请好友 · 邀请码<small>可提现积分满 80 可生成 · 邀请得 300 积分</small></span><svg><use href="#i-arrow"/></svg></button>
<button type="button" class="invite-btn profile-invite-btn official-task-entry" data-action="official-tasks" data-account-action hidden><svg><use href="#i-wallet"/></svg><span>官方任务<small>领取活动任务 · 完成后获得积分</small></span><svg><use href="#i-arrow"/></svg></button>
<button type="button" class="logout-btn" data-open-logout><svg><use href="#i-logout"/></svg><span>退出当前账号</span></button>
</div>
</section>
<section class="account-overview">
<section class="wallet-card account-detail-card" data-open-points role="button" tabindex="0" aria-label="打开积分中心">
<div class="wallet-top"><span><svg><use href="#i-wallet"/></svg>交易积分余额</span><button type="button" data-open-entries>明细</button></div>
<div class="points"><strong id="pointsBalance">—</strong><span>积分</span></div>
<div class="wallet-actions"><button data-action="recharge" data-account-action>充值</button><button data-action="withdraw" data-account-action>提现</button></div>
</section>
<section class="trust-card account-detail-card" data-open-credit role="button" tabindex="0" aria-label="打开校园信用详情">
<div class="trust-score"><span>信用分(履约记录)</span><strong data-credit-score>—</strong></div>
<div class="score-track"><i data-credit-progress style="width:0"></i></div>
<div class="trust-meta"><span><b data-breach-rate>—</b>近 90 天失信率</span><span><b data-completed-tasks>—</b>完成任务</span><span><b data-current-streak>—</b>连续守约</span></div>
</section>
</section>
<section class="activity-panel">
<div class="section-heading"><h2>我的任务</h2><div class="mini-tabs"><button type="button" class="active" data-mytab="published">我发布的</button><button type="button" data-mytab="accepted">我接受的</button></div></div>
<div id="myTasksBody"><div class="empty-state compact"><span data-activity-empty>登录后查看你的任务</span><p>发布或接下的任务会集中显示在这里。</p></div></div>
</section>
</div>
</section>
+3
View File
@@ -0,0 +1,3 @@
<section class="view" id="view-task">
<div class="content-narrow" id="taskManageBody"><div class="loading">正在加载任务详情…</div></div>
</section>
+81
View File
@@ -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
+100
View File
@@ -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