WorkLog initial import
This commit is contained in:
@@ -0,0 +1,17 @@
|
|||||||
|
# 复制为 .env 后按需修改(.env 不入库)
|
||||||
|
WORKLOG_HOST=127.0.0.1
|
||||||
|
WORKLOG_PORT=37777
|
||||||
|
WORKLOG_DB=./data/worklog.db
|
||||||
|
WORKLOG_SESSION_DAYS=30
|
||||||
|
WORKLOG_DEV_MODE=false
|
||||||
|
# 外网部署必填:邮件链接只使用此配置,不读取客户端 Host/代理头
|
||||||
|
# WORKLOG_BASE_URL=https://worklog.example.com
|
||||||
|
|
||||||
|
# 邮箱验证码 SMTP(缺少配置时拒绝发码;本机调试需显式启用 DEV_MODE 并绑定 127.0.0.1)
|
||||||
|
# WORKLOG_SMTP_HOST=smtp.qq.com
|
||||||
|
# WORKLOG_SMTP_PORT=465
|
||||||
|
# WORKLOG_SMTP_USER=notify@example.com
|
||||||
|
# WORKLOG_SMTP_PASSWORD=授权码
|
||||||
|
# WORKLOG_SMTP_FROM=WorkLog <notify@example.com>
|
||||||
|
# WORKLOG_SMTP_TLS=ssl
|
||||||
|
# WORKLOG_EMAIL_CODE_TTL_MIN=10
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
.env
|
||||||
|
data/
|
||||||
|
__pycache__/
|
||||||
|
*.pyc
|
||||||
+23
@@ -0,0 +1,23 @@
|
|||||||
|
FROM python:3.11-slim
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY requirements.txt /app/requirements.txt
|
||||||
|
RUN pip install --no-cache-dir -r /app/requirements.txt
|
||||||
|
|
||||||
|
COPY server /app/server
|
||||||
|
COPY dist /app/dist
|
||||||
|
COPY config.toml /app/config.toml
|
||||||
|
|
||||||
|
RUN mkdir -p /app/data
|
||||||
|
|
||||||
|
ENV WORKLOG_HOST=0.0.0.0 \
|
||||||
|
WORKLOG_PORT=37777 \
|
||||||
|
WORKLOG_DB=/app/data/worklog.db \
|
||||||
|
WORKLOG_FRONTEND=/app/dist
|
||||||
|
|
||||||
|
EXPOSE 37777
|
||||||
|
|
||||||
|
VOLUME /app/data
|
||||||
|
|
||||||
|
CMD ["python", "-m", "server.main"]
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
# WorkLog · 活动记录网站
|
||||||
|
|
||||||
|
以**账号**为单位记录每人参加的活动:注册账号 → 发布/报名活动 → 每条参加记录带状态与备注 → 在「成员」里点开任何人,查看 TA 公开的活动记录与统计。
|
||||||
|
|
||||||
|
后端 FastAPI + SQLAlchemy(异步)+ SQLite,前端原生 HTML/CSS/JS(无构建步骤),后端同端口托管前端。
|
||||||
|
|
||||||
|
## 功能
|
||||||
|
|
||||||
|
- **账号体系**:邮箱 + 六位数字验证码注册/登录(注册需填写姓名、所属部门、邮箱、手机号),Bearer 会话默认 30 天有效,可改姓名、部门、签名和手机号
|
||||||
|
- **活动记录**:标题 / 分类(8 类)/ 时间 / 地点 / 描述 / 名额 / 公开或私密;发起人自动写入一条参加记录
|
||||||
|
- **参加方式**:在活动墙自行报名公开活动;或由**发起人按账号名代登记**(适合"帮大家统一记录"的场景)
|
||||||
|
- **状态与备注**:报名中 / 已参加 / 缺席,本人或发起人可改;每人可写自己的备注
|
||||||
|
- **我的记录**:按状态筛选、搜索、出席率与分类统计
|
||||||
|
- **看到别人**:成员列表带每人统计;他人主页只展示公开活动的记录(私密活动仅发起人与参加者可见)
|
||||||
|
|
||||||
|
## 快速开始
|
||||||
|
|
||||||
|
依赖已在系统 Python(3.13)中可用。若在干净环境:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python -m pip install -r requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
启动(在 WorkLog 目录下):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python -m server.main
|
||||||
|
```
|
||||||
|
|
||||||
|
打开 http://127.0.0.1:37777 ,注册账号即可使用。
|
||||||
|
|
||||||
|
配置见 `config.toml`,可用环境变量覆盖:`WORKLOG_HOST` / `WORKLOG_PORT` / `WORKLOG_DB` / `WORKLOG_SESSION_DAYS`(复制 `.env.example` 为 `.env` 也可以)。数据落在 `data/worklog.db`,`.gitignore` 已排除。
|
||||||
|
|
||||||
|
注册表单与后端统一校验五项必填内容:姓名不超过 32 字符、所属部门从固定列表选择、有效邮箱、不重复的 11 位大陆手机号、6 位数字邮箱验证码。用户名和旧版兼容字段由后端生成,用户无需填写;历史账号缺少部门或手机号仍可登录。升级已有服务器请看 `UPGRADE.md`。
|
||||||
|
|
||||||
|
## 安全与部署
|
||||||
|
|
||||||
|
活动发布和「我也参加过」直接生效,现版本没有管理员审核流程。
|
||||||
|
|
||||||
|
- **验证码**:数据库保存带盐的 PBKDF2 摘要;每条最多尝试 5 次,一次使用后失效,同用途重新发码会废止旧码。每邮箱 10 分钟最多发码 5 次,每 IP 最多发码 30 次、提交注册/登录校验 60 次;限流计数保存在 SQLite,服务重启后仍有效。
|
||||||
|
- **开发模式**:默认关闭。缺少 SMTP 配置时返回 503,不回显验证码;仅本机调试可设置 `WORKLOG_DEV_MODE=true`,同时将 `WORKLOG_HOST=127.0.0.1`。发码接口还会检查连接来源为回环地址。
|
||||||
|
- **会话和邮件链接**:数据库只保存随机令牌的 SHA-256 摘要。邮件链接 GET 只展示确认页,POST 确认后才登记,令牌只能消费一次;活动改成私密后旧邀请被拒绝。默认关闭 Uvicorn 访问日志,避免邮件 URL 凭据入日志。
|
||||||
|
- **隐私与页面防护**:邮箱和手机号只在本人资料中返回,成员列表、他人主页及概览不包含私密活动统计;页面输出转义用户内容,启用 CSP、防嵌入、禁止 MIME 嗅探和无 Referer 策略,API/邮件确认页禁止缓存。浏览器修改请求仅接受同源提交。
|
||||||
|
- **数据库升级**:启动自动补充尝试次数和限流表,将旧会话/邮件令牌转成摘要;旧明文验证码会作废,需重新获取。计数更新不依赖 SQLite 3.35 才加入的 `RETURNING` 语法,兼容较旧的服务器 SQLite。邮箱(忽略大小写)和非空手机号有唯一索引;若历史数据重复,需先处理冲突再启动。升级前保留数据库备份。
|
||||||
|
|
||||||
|
将 SMTP 主机、端口、账号及授权码写入本机 `.env`(参考 `.env.example`)。共享的 `config.toml` 不保存凭据,打包脚本排除 `.env`、数据库文件及 WAL/SHM 文件。已经分发过的明文授权码需要在邮箱服务端更换,历史压缩包和数据库备份应妥善保管。
|
||||||
|
|
||||||
|
外网部署时设置 `WORKLOG_BASE_URL=https://你的域名`,并通过 HTTPS 访问。邮件链接只使用此配置,留空时回退到本机地址,不信任请求 Host 或转发头。默认不信任代理 IP 头;部署在反向代理后时,应用会按代理连接 IP 汇总限流,可在代理层另外设置客户端限流,同时避免记录 `/join/` 令牌 URL。前端仍将 Bearer 令牌保存在浏览器 localStorage,使用完应退出登录。
|
||||||
|
|
||||||
|
## 目录结构
|
||||||
|
|
||||||
|
```
|
||||||
|
WorkLog/
|
||||||
|
├── server/
|
||||||
|
│ ├── main.py # FastAPI 应用:账号、活动、参加记录、统计 API + 前端托管
|
||||||
|
│ ├── models.py # 用户、会话、验证码、活动、参加记录、邮件链接、限流计数
|
||||||
|
│ └── security.py # PBKDF2 口令散列、会话令牌
|
||||||
|
├── dist/
|
||||||
|
│ ├── index.html
|
||||||
|
│ ├── assets/styles.css
|
||||||
|
│ └── js/app.js # 前端 SPA 逻辑
|
||||||
|
├── tests/ # API、邮件通知及安全回归测试(unittest + httpx ASGI)
|
||||||
|
├── config.toml # 端口 / 数据库路径 / 会话天数
|
||||||
|
└── requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
## API 一览
|
||||||
|
|
||||||
|
| 方法 | 路径 | 说明 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| POST | `/api/auth/register` / `login` / `logout` | 注册 / 登录 / 退出 |
|
||||||
|
| GET/PATCH | `/api/auth/me` | 我的资料与统计 / 改资料、密码 |
|
||||||
|
| GET | `/api/activities` | `scope=all/mine/joined/upcoming`,支持 `q`、`category`、`user_id`、`date_from/to` |
|
||||||
|
| POST | `/api/activities` | 创建(可代登记 participants) |
|
||||||
|
| GET/PATCH/DELETE | `/api/activities/{id}` | 详情 / 编辑(仅发起人)/ 删除(仅发起人) |
|
||||||
|
| POST | `/api/activities/{id}/join` · `leave` | 报名 / 退出 |
|
||||||
|
| POST | `/api/activities/{id}/participants` | 发起人按账号名添加成员 |
|
||||||
|
| PATCH/DELETE | `/api/activities/{id}/participants/{user_id}` | 改状态备注 / 移出 |
|
||||||
|
| GET | `/api/users` · `/api/users/{id}` | 成员列表 / 他人主页(公开记录+统计) |
|
||||||
|
| GET | `/api/stats/overview` | 全站概览 |
|
||||||
|
| GET | `/api/health` · `/api/meta` | 健康检查 / 分类字典 |
|
||||||
|
|
||||||
|
运行测试:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python -m unittest discover -s tests -v
|
||||||
|
```
|
||||||
+22
@@ -0,0 +1,22 @@
|
|||||||
|
# 本次更新与服务器升级
|
||||||
|
|
||||||
|
## 注册表单
|
||||||
|
|
||||||
|
姓名、所属部门、邮箱、手机号和邮箱验证码全部必填,前后端规则保持一致。邮箱用于登录及接收验证码;手机号为 11 位大陆手机号,邮箱和手机号不能重复。验证码限定 6 位数字,支持系统自动填充。校验失败显示具体中文原因,避免出现 `[object Object]`。姓名和部门对成员展示,邮箱和手机号只在本人资料返回。
|
||||||
|
|
||||||
|
现有数据库的 `users` 表已经包含全部注册字段,不需要手动加字段。旧版 `username`、`password_hash`、`role` 非空列继续由后端写入,兼容服务器当前表结构。新注册必须选择部门,旧账号中的空部门或空手机号不影响登录。
|
||||||
|
|
||||||
|
## 数据库核对结果(2026-10-14)
|
||||||
|
|
||||||
|
按用户提供的 `worklog.db`、`worklog.db-wal`、`worklog.db-shm` 的配套副本检查,当前数据库完整性正常:7 个账号、5 场活动、17 条参加记录;无重复邮箱/手机号,无外键引用错误。
|
||||||
|
|
||||||
|
另附的 `worklog.db.bak-20261014-105608` 是更早的快照,有 19 条外键引用异常,且参加记录比当前库少。本次更新以当前数据库及配套 WAL 为准,不需要恢复该旧备份。此次核对不改动提供的四个原始文件。
|
||||||
|
|
||||||
|
## 更新已有服务器
|
||||||
|
|
||||||
|
1. 停止 WorkLog 服务,并备份服务器当前数据库。若有 WAL,保留主库和配套 WAL/SHM,或使用 SQLite backup 接口生成完整备份,不要只在运行时单独复制主库。
|
||||||
|
2. 将 ZIP 解压到新目录,再覆盖服务器项目中的 `server/`、`dist/`、`tests/`、`requirements.txt`、`start.sh` 及文档。保留服务器原有的 `data/`、`.env`、`config.toml`,避免覆盖数据库、端口及 SMTP 配置。
|
||||||
|
3. 在项目目录执行 `python -m pip install -r requirements.txt`,然后按原方式重启(例如 `python -m server.main` 或 `bash start.sh`)。要求 Python 3.11 或以上。
|
||||||
|
4. 启动会自动完成兼容升级:补充验证码尝试次数和限流表、创建邮箱/手机号唯一索引,并将旧会话和邮件令牌转为摘要;旧明文验证码会失效,需要重新获取。既有账号、活动及参加记录保留。
|
||||||
|
|
||||||
|
生产环境关闭 `WORKLOG_DEV_MODE` 并保留有效的 SMTP 配置;邮件链接的公网地址通过 `WORKLOG_BASE_URL` 设置。包内仅提供 `.env.example` 配置示例,不包含本机凭据和数据库。
|
||||||
+181
@@ -0,0 +1,181 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""WorkLog 数据库清除脚本(Windows / Linux 通用)。
|
||||||
|
|
||||||
|
用法:
|
||||||
|
python clear_db.py 交互式选择清除范围
|
||||||
|
python clear_db.py --junk -y 只清过期会话、已用/过期验证码(安全,不动业务数据)
|
||||||
|
python clear_db.py --activities -y 清空活动和参加记录(保留用户)
|
||||||
|
python clear_db.py --all -y 清空全部业务数据(恢复初始状态)
|
||||||
|
|
||||||
|
可选参数:
|
||||||
|
--db PATH 指定数据库文件(默认按 WORKLOG_DB / config.toml 的 database.path 解析)
|
||||||
|
--no-backup 清除前不做备份(默认备份为 <库名>.bak-时间戳,放在同目录)
|
||||||
|
-y, --yes 跳过确认
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import os
|
||||||
|
import sqlite3
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
PROJECT_DIR = Path(__file__).resolve().parent
|
||||||
|
|
||||||
|
TABLES = ("users", "sessions", "email_verifications", "activities", "participations")
|
||||||
|
|
||||||
|
SCOPE_NAMES = {
|
||||||
|
"junk": "只清理过期数据(过期会话、已用/过期验证码)",
|
||||||
|
"activities": "清空活动数据(活动 + 参加记录,用户保留)",
|
||||||
|
"all": "清空全部业务数据(用户、活动、会话、验证码,恢复初始状态)",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_db_path(explicit: str | None) -> Path:
|
||||||
|
"""与 server/main.py 相同的解析顺序:--db > WORKLOG_DB > config.toml > ./data/worklog.db"""
|
||||||
|
raw = explicit or os.getenv("WORKLOG_DB")
|
||||||
|
if not raw:
|
||||||
|
raw = "./data/worklog.db"
|
||||||
|
config_path = Path(os.getenv("WORKLOG_CONFIG", str(PROJECT_DIR / "config.toml")))
|
||||||
|
try:
|
||||||
|
import tomllib
|
||||||
|
|
||||||
|
with open(config_path, "rb") as fh:
|
||||||
|
cfg = tomllib.load(fh)
|
||||||
|
raw = cfg.get("database", {}).get("path", raw)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
path = Path(raw)
|
||||||
|
return path if path.is_absolute() else PROJECT_DIR / path
|
||||||
|
|
||||||
|
|
||||||
|
def table_counts(conn: sqlite3.Connection) -> dict[str, int | None]:
|
||||||
|
counts: dict[str, int | None] = {}
|
||||||
|
for table in TABLES:
|
||||||
|
try:
|
||||||
|
counts[table] = conn.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0]
|
||||||
|
except sqlite3.OperationalError:
|
||||||
|
counts[table] = None
|
||||||
|
return counts
|
||||||
|
|
||||||
|
|
||||||
|
def build_plan(scope: str, now_ms: int):
|
||||||
|
"""返回 [(说明, DELETE 语句, 参数)]。all 必须先删子表再删父表,避免外键阻塞。"""
|
||||||
|
if scope == "junk":
|
||||||
|
return [
|
||||||
|
("过期登录会话", "DELETE FROM sessions WHERE expires_at < ?", (now_ms,)),
|
||||||
|
(
|
||||||
|
"已用/过期邮箱验证码",
|
||||||
|
"DELETE FROM email_verifications WHERE used = 1 OR expires_at < ?",
|
||||||
|
(now_ms,),
|
||||||
|
),
|
||||||
|
]
|
||||||
|
if scope == "activities":
|
||||||
|
return [
|
||||||
|
("参加记录", "DELETE FROM participations", ()),
|
||||||
|
("活动", "DELETE FROM activities", ()),
|
||||||
|
]
|
||||||
|
return [
|
||||||
|
("参加记录", "DELETE FROM participations", ()),
|
||||||
|
("活动", "DELETE FROM activities", ()),
|
||||||
|
("登录会话", "DELETE FROM sessions", ()),
|
||||||
|
("邮箱验证码", "DELETE FROM email_verifications", ()),
|
||||||
|
("用户", "DELETE FROM users", ()),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
parser = argparse.ArgumentParser(description="WorkLog 数据库清除脚本")
|
||||||
|
group = parser.add_mutually_exclusive_group()
|
||||||
|
group.add_argument("--junk", action="store_true", help="只清过期会话和已用/过期验证码")
|
||||||
|
group.add_argument("--activities", action="store_true", help="清空活动与参加记录,保留用户")
|
||||||
|
group.add_argument("--all", action="store_true", help="清空全部业务数据")
|
||||||
|
parser.add_argument("--db", help="数据库文件路径(默认 WORKLOG_DB / config.toml)")
|
||||||
|
parser.add_argument("--no-backup", action="store_true", help="清除前不备份")
|
||||||
|
parser.add_argument("-y", "--yes", action="store_true", help="跳过确认")
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
scope = (
|
||||||
|
"junk"
|
||||||
|
if args.junk
|
||||||
|
else "activities"
|
||||||
|
if args.activities
|
||||||
|
else "all"
|
||||||
|
if args.all
|
||||||
|
else None
|
||||||
|
)
|
||||||
|
|
||||||
|
db_path = resolve_db_path(args.db)
|
||||||
|
if not db_path.exists():
|
||||||
|
print(f"[!] 数据库不存在:{db_path}")
|
||||||
|
return 1
|
||||||
|
|
||||||
|
conn = sqlite3.connect(str(db_path))
|
||||||
|
counts = table_counts(conn)
|
||||||
|
print(f"数据库:{db_path} ({db_path.stat().st_size / 1024:.0f} KB)")
|
||||||
|
print("当前数据:")
|
||||||
|
for table in TABLES:
|
||||||
|
value = counts[table]
|
||||||
|
print(f" {table:<20}{value if value is not None else '(表不存在)'}")
|
||||||
|
|
||||||
|
if scope is None:
|
||||||
|
print("\n请选择清除范围:")
|
||||||
|
print(" 1) 只清理过期数据(过期会话、已用/过期验证码)—— 安全")
|
||||||
|
print(" 2) 清空活动数据(活动 + 参加记录,保留用户)")
|
||||||
|
print(" 3) 清空全部数据(用户、活动、会话、验证码,恢复初始状态)")
|
||||||
|
print(" 0) 取消")
|
||||||
|
choice = input("请输入编号: ").strip()
|
||||||
|
scope = {"1": "junk", "2": "activities", "3": "all"}.get(choice)
|
||||||
|
if scope is None:
|
||||||
|
print("已取消。")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
plan = build_plan(scope, int(time.time() * 1000))
|
||||||
|
print(f"\n即将执行:{SCOPE_NAMES[scope]}")
|
||||||
|
for name, _, _ in plan:
|
||||||
|
print(f" - 删除{name}")
|
||||||
|
if scope != "junk":
|
||||||
|
print("注意:清除后已登录用户会被强制下线,该操作不可撤销(有备份可恢复)。")
|
||||||
|
if not args.yes:
|
||||||
|
if input("输入 yes 继续: ").strip().lower() != "yes":
|
||||||
|
print("已取消。")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
if not args.no_backup:
|
||||||
|
stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
|
||||||
|
backup_path = db_path.with_name(f"{db_path.name}.bak-{stamp}")
|
||||||
|
dest = sqlite3.connect(str(backup_path))
|
||||||
|
with dest:
|
||||||
|
conn.backup(dest)
|
||||||
|
dest.close()
|
||||||
|
print(f"已备份到:{backup_path}")
|
||||||
|
|
||||||
|
total = 0
|
||||||
|
try:
|
||||||
|
with conn:
|
||||||
|
for name, sql, params in plan:
|
||||||
|
cursor = conn.execute(sql, params)
|
||||||
|
print(f" 已删除{name}: {cursor.rowcount} 条")
|
||||||
|
total += cursor.rowcount
|
||||||
|
except sqlite3.OperationalError as exc:
|
||||||
|
print(f"[!] 清除失败:{exc}")
|
||||||
|
print(" 若提示表不存在,请先启动一次服务(python -m server.main)完成建表后再试。")
|
||||||
|
conn.close()
|
||||||
|
return 1
|
||||||
|
print(f"共删除 {total} 条记录。")
|
||||||
|
|
||||||
|
try:
|
||||||
|
conn.execute("PRAGMA wal_checkpoint(TRUNCATE)")
|
||||||
|
conn.execute("VACUUM")
|
||||||
|
print(f"完成(VACUUM 后 {db_path.stat().st_size / 1024:.0f} KB)。")
|
||||||
|
except sqlite3.Error as exc:
|
||||||
|
print(f"VACUUM 已跳过({exc}),不影响清除结果。")
|
||||||
|
conn.close()
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
+35
@@ -0,0 +1,35 @@
|
|||||||
|
# WorkLog 配置。环境变量优先级更高:WORKLOG_HOST / WORKLOG_PORT / WORKLOG_DB / WORKLOG_SESSION_DAYS
|
||||||
|
# SMTP 凭据放在本机 .env;未配置邮件服务时拒绝发送验证码。
|
||||||
|
|
||||||
|
[server]
|
||||||
|
host = "0.0.0.0"
|
||||||
|
port = 37777
|
||||||
|
frontend_dir = "./dist"
|
||||||
|
# 对外访问地址(用于邮件里的链接)。留空时使用本机地址;
|
||||||
|
# 通过固定域名/IP 访问时建议写全,如 "http://你的服务器IP:37777"
|
||||||
|
base_url = ""
|
||||||
|
|
||||||
|
[notify]
|
||||||
|
# 有人发起活动(参与不算)时,给其他所有已注册用户发邮件通知,邮件里带"一键我也参加过"按钮
|
||||||
|
enabled = true
|
||||||
|
|
||||||
|
[database]
|
||||||
|
path = "./data/worklog.db"
|
||||||
|
|
||||||
|
[auth]
|
||||||
|
# 登录有效期(天)
|
||||||
|
session_days = 30
|
||||||
|
# 仅限绑定 127.0.0.1 的本机开发;生产必须关闭
|
||||||
|
dev_mode = false
|
||||||
|
|
||||||
|
[smtp]
|
||||||
|
host = "smtp.qq.com"
|
||||||
|
port = 465
|
||||||
|
user = ""
|
||||||
|
password = ""
|
||||||
|
# 发件人,留空则用 user
|
||||||
|
from = ""
|
||||||
|
# ssl / starttls / none
|
||||||
|
tls = "ssl"
|
||||||
|
# 验证码有效期(分钟)
|
||||||
|
code_ttl_min = 10
|
||||||
Vendored
+410
@@ -0,0 +1,410 @@
|
|||||||
|
/* WorkLog 活动记录 — 样式 */
|
||||||
|
|
||||||
|
:root {
|
||||||
|
--bg: #f4f6fa;
|
||||||
|
--card: #ffffff;
|
||||||
|
--ink: #1f2430;
|
||||||
|
--muted: #6b7280;
|
||||||
|
--line: #e5e8ef;
|
||||||
|
--primary: #4361ee;
|
||||||
|
--primary-ink: #ffffff;
|
||||||
|
--primary-soft: #eef1fd;
|
||||||
|
--ok: #12805c;
|
||||||
|
--ok-soft: #e2f5ec;
|
||||||
|
--warn: #b45309;
|
||||||
|
--warn-soft: #fdf1e0;
|
||||||
|
--bad: #b42323;
|
||||||
|
--bad-soft: #fdeaea;
|
||||||
|
--radius: 14px;
|
||||||
|
--shadow: 0 1px 2px rgba(17, 24, 39, .05), 0 8px 24px -12px rgba(17, 24, 39, .12);
|
||||||
|
}
|
||||||
|
|
||||||
|
* { box-sizing: border-box; }
|
||||||
|
|
||||||
|
html, body {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
background: var(--bg);
|
||||||
|
color: var(--ink);
|
||||||
|
font-family: "PingFang SC", "Microsoft YaHei", "Segoe UI", system-ui, sans-serif;
|
||||||
|
font-size: 15px;
|
||||||
|
line-height: 1.55;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hidden { display: none !important; }
|
||||||
|
.muted { color: var(--muted); font-size: 13px; }
|
||||||
|
|
||||||
|
button { font: inherit; cursor: pointer; }
|
||||||
|
input, select, textarea {
|
||||||
|
font: inherit;
|
||||||
|
color: var(--ink);
|
||||||
|
background: #fff;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: 10px;
|
||||||
|
padding: 9px 12px;
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
input:focus, select:focus, textarea:focus { border-color: var(--primary); box-shadow: 0 0 0 3px rgba(67, 97, 238, .15); }
|
||||||
|
textarea { width: 100%; resize: vertical; }
|
||||||
|
|
||||||
|
.btn {
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
background: #fff;
|
||||||
|
color: var(--ink);
|
||||||
|
border-radius: 10px;
|
||||||
|
padding: 9px 16px;
|
||||||
|
font-weight: 500;
|
||||||
|
transition: .15s;
|
||||||
|
}
|
||||||
|
.btn:hover { border-color: var(--primary); color: var(--primary); }
|
||||||
|
.btn.primary { background: var(--primary); border-color: var(--primary); color: var(--primary-ink); }
|
||||||
|
.btn.primary:hover { filter: brightness(1.08); color: #fff; }
|
||||||
|
.btn.danger { color: var(--bad); border-color: #f2c4c4; }
|
||||||
|
.btn.danger:hover { background: var(--bad-soft); }
|
||||||
|
.btn.ghost { border-color: transparent; background: transparent; }
|
||||||
|
.btn.ghost:hover { background: var(--primary-soft); }
|
||||||
|
.btn.sm { padding: 5px 10px; font-size: 13px; border-radius: 8px; }
|
||||||
|
.btn.block { width: 100%; }
|
||||||
|
.btn:disabled { opacity: .55; cursor: not-allowed; }
|
||||||
|
|
||||||
|
/* ---------- 顶栏 ---------- */
|
||||||
|
#topbar {
|
||||||
|
position: sticky;
|
||||||
|
top: 0;
|
||||||
|
z-index: 50;
|
||||||
|
background: rgba(255, 255, 255, .92);
|
||||||
|
backdrop-filter: blur(8px);
|
||||||
|
border-bottom: 1px solid var(--line);
|
||||||
|
}
|
||||||
|
.topbar-inner {
|
||||||
|
max-width: 1080px;
|
||||||
|
margin: 0 auto;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 18px;
|
||||||
|
padding: 10px 20px;
|
||||||
|
}
|
||||||
|
.brand { font-weight: 700; font-size: 17px; white-space: nowrap; }
|
||||||
|
#nav { display: flex; gap: 4px; flex: 1; }
|
||||||
|
#nav a {
|
||||||
|
color: var(--muted);
|
||||||
|
text-decoration: none;
|
||||||
|
padding: 7px 12px;
|
||||||
|
border-radius: 9px;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
#nav a:hover { color: var(--ink); background: var(--primary-soft); }
|
||||||
|
#nav a.active { color: var(--primary); background: var(--primary-soft); }
|
||||||
|
.topbar-user { display: flex; align-items: center; gap: 10px; white-space: nowrap; }
|
||||||
|
#topbar-name { font-weight: 600; font-size: 14px; }
|
||||||
|
.menu-toggle { display: none; background: none; border: none; font-size: 20px; }
|
||||||
|
|
||||||
|
/* ---------- 布局 ---------- */
|
||||||
|
.container { max-width: 1080px; margin: 0 auto; padding: 24px 20px 60px; }
|
||||||
|
.container.narrow { max-width: 640px; }
|
||||||
|
.page-head {
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-end;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 16px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
.page-head h2 { margin: 0 0 2px; font-size: 22px; }
|
||||||
|
.page-head p { margin: 0; }
|
||||||
|
.filters { display: flex; gap: 8px; flex-wrap: wrap; }
|
||||||
|
.filters input, .filters select { min-width: 130px; }
|
||||||
|
|
||||||
|
.stats-row { display: flex; gap: 10px; flex-wrap: wrap; margin-bottom: 18px; }
|
||||||
|
.stat {
|
||||||
|
background: var(--card);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
padding: 10px 16px;
|
||||||
|
min-width: 96px;
|
||||||
|
box-shadow: var(--shadow);
|
||||||
|
}
|
||||||
|
.stat b { display: block; font-size: 20px; }
|
||||||
|
.stat span { color: var(--muted); font-size: 12px; }
|
||||||
|
|
||||||
|
.chips { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 14px; }
|
||||||
|
.chip {
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
background: #fff;
|
||||||
|
border-radius: 999px;
|
||||||
|
padding: 4px 12px;
|
||||||
|
font-size: 13px;
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
.chip.active { background: var(--primary); border-color: var(--primary); color: #fff; }
|
||||||
|
.chip:hover { border-color: var(--primary); color: var(--primary); }
|
||||||
|
.chip.active:hover { color: #fff; }
|
||||||
|
|
||||||
|
/* ---------- 卡片列表 ---------- */
|
||||||
|
.card-list { display: flex; flex-direction: column; gap: 12px; }
|
||||||
|
.acard {
|
||||||
|
background: var(--card);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
padding: 16px 18px;
|
||||||
|
box-shadow: var(--shadow);
|
||||||
|
transition: .15s;
|
||||||
|
}
|
||||||
|
.acard:hover { border-color: #c9d4f5; }
|
||||||
|
.acard-top { display: flex; justify-content: space-between; align-items: flex-start; gap: 12px; }
|
||||||
|
.acard h3 { margin: 0; font-size: 17px; cursor: pointer; }
|
||||||
|
.acard h3:hover { color: var(--primary); }
|
||||||
|
.acard-meta { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 8px; align-items: center; }
|
||||||
|
.meta-item { color: var(--muted); font-size: 13px; display: inline-flex; align-items: center; gap: 4px; }
|
||||||
|
.acard-desc { margin: 10px 0 0; color: #3d4351; font-size: 14px; white-space: pre-wrap; }
|
||||||
|
.acard-foot {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
margin-top: 12px;
|
||||||
|
padding-top: 12px;
|
||||||
|
border-top: 1px dashed var(--line);
|
||||||
|
}
|
||||||
|
.faces { display: flex; align-items: center; }
|
||||||
|
.face {
|
||||||
|
width: 28px;
|
||||||
|
height: 28px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: var(--primary);
|
||||||
|
color: #fff;
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 600;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
border: 2px solid #fff;
|
||||||
|
margin-left: -8px;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.face:first-child { margin-left: 0; }
|
||||||
|
.face.more { background: #e7eaf3; color: var(--muted); }
|
||||||
|
.face:hover { transform: translateY(-2px); }
|
||||||
|
.faces-label { margin-left: 8px; font-size: 13px; color: var(--muted); }
|
||||||
|
.acard-actions { display: flex; gap: 8px; flex-wrap: wrap; }
|
||||||
|
|
||||||
|
.tag {
|
||||||
|
display: inline-block;
|
||||||
|
padding: 2px 10px;
|
||||||
|
border-radius: 999px;
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
.tag.cat { background: var(--primary-soft); color: var(--primary); }
|
||||||
|
.tag.pub { background: #e9f0fb; color: #275bd6; }
|
||||||
|
.tag.pri { background: #f0e9fb; color: #6d3fc0; }
|
||||||
|
.tag.joined { background: #e8f1fd; color: #1d5bbf; }
|
||||||
|
.tag.attended { background: var(--ok-soft); color: var(--ok); }
|
||||||
|
.tag.absent { background: var(--bad-soft); color: var(--bad); }
|
||||||
|
.tag.full { background: #f1f2f6; color: var(--muted); }
|
||||||
|
|
||||||
|
/* ---------- 成员 ---------- */
|
||||||
|
.member-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fill, minmax(230px, 1fr));
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
.mcard {
|
||||||
|
background: var(--card);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
padding: 16px;
|
||||||
|
box-shadow: var(--shadow);
|
||||||
|
cursor: pointer;
|
||||||
|
transition: .15s;
|
||||||
|
}
|
||||||
|
.mcard:hover { border-color: #c9d4f5; transform: translateY(-2px); }
|
||||||
|
.mcard-top { display: flex; align-items: center; gap: 12px; }
|
||||||
|
.avatar {
|
||||||
|
width: 44px;
|
||||||
|
height: 44px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: linear-gradient(135deg, #4361ee, #7c3aed);
|
||||||
|
color: #fff;
|
||||||
|
font-weight: 600;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
font-size: 17px;
|
||||||
|
flex: none;
|
||||||
|
}
|
||||||
|
.mcard b { display: block; }
|
||||||
|
.mcard .muted { margin-top: 2px; }
|
||||||
|
.mcard-stats { display: flex; gap: 14px; margin-top: 12px; }
|
||||||
|
.mcard-stats div b { font-size: 16px; }
|
||||||
|
.mcard-stats div span { display: block; font-size: 12px; color: var(--muted); }
|
||||||
|
.mcard-bio { margin-top: 10px; font-size: 13px; color: #3d4351; }
|
||||||
|
|
||||||
|
/* ---------- 个人主页 ---------- */
|
||||||
|
.profile-header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 16px;
|
||||||
|
background: var(--card);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
padding: 20px;
|
||||||
|
box-shadow: var(--shadow);
|
||||||
|
margin-bottom: 14px;
|
||||||
|
}
|
||||||
|
.profile-header .avatar { width: 60px; height: 60px; font-size: 24px; }
|
||||||
|
.profile-header h2 { margin: 0; font-size: 20px; }
|
||||||
|
.profile-header p { margin: 3px 0 0; }
|
||||||
|
|
||||||
|
/* ---------- 认证页 ---------- */
|
||||||
|
.auth-wrap { min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 24px; }
|
||||||
|
.auth-card {
|
||||||
|
width: 100%;
|
||||||
|
max-width: 400px;
|
||||||
|
background: var(--card);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: 18px;
|
||||||
|
padding: 32px 28px;
|
||||||
|
box-shadow: var(--shadow);
|
||||||
|
}
|
||||||
|
.auth-title { margin: 0; font-size: 24px; text-align: center; }
|
||||||
|
.auth-sub { text-align: center; color: var(--muted); margin: 6px 0 18px; font-size: 13px; }
|
||||||
|
.tabs { display: flex; background: var(--bg); border-radius: 10px; padding: 4px; margin-bottom: 18px; }
|
||||||
|
.tab { flex: 1; border: none; background: transparent; padding: 8px; border-radius: 8px; font-weight: 500; color: var(--muted); }
|
||||||
|
.tab.active { background: #fff; color: var(--ink); box-shadow: var(--shadow); }
|
||||||
|
|
||||||
|
/* ---------- 表单 ---------- */
|
||||||
|
form label, .form-card label { display: block; margin-top: 14px; font-size: 13px; color: #3d4351; font-weight: 500; }
|
||||||
|
form input, form select, form textarea, .form-card input, .form-card select { width: 100%; margin-top: 5px; }
|
||||||
|
.hint-inline { color: var(--muted); font-weight: 400; }
|
||||||
|
.form-error { color: var(--bad); font-size: 13px; min-height: 18px; margin-top: 8px; }
|
||||||
|
.form-hint { font-size: 12px; margin-top: -6px; }
|
||||||
|
.code-row { display: flex; gap: 8px; margin-top: 5px; }
|
||||||
|
.code-row input { flex: 1; margin-top: 0; }
|
||||||
|
.code-row button { flex: none; white-space: nowrap; }
|
||||||
|
.code-row button:disabled { opacity: .55; cursor: not-allowed; }
|
||||||
|
.form-card { margin-bottom: 14px; }
|
||||||
|
.form-card h3 { margin: 0 0 4px; font-size: 16px; }
|
||||||
|
.form-row { display: flex; gap: 10px; }
|
||||||
|
.form-row > * { flex: 1; }
|
||||||
|
.form-actions { display: flex; gap: 10px; justify-content: flex-end; margin-top: 18px; }
|
||||||
|
.checkline { display: flex; align-items: center; gap: 8px; margin-top: 14px; font-size: 14px; }
|
||||||
|
.checkline input { width: auto; margin: 0; }
|
||||||
|
|
||||||
|
/* ---------- 弹层 ---------- */
|
||||||
|
.modal-mask {
|
||||||
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
|
background: rgba(15, 23, 42, .45);
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
justify-content: center;
|
||||||
|
padding: 40px 16px;
|
||||||
|
z-index: 100;
|
||||||
|
overflow-y: auto;
|
||||||
|
}
|
||||||
|
.modal {
|
||||||
|
background: var(--card);
|
||||||
|
border-radius: 18px;
|
||||||
|
width: 100%;
|
||||||
|
max-width: 560px;
|
||||||
|
padding: 24px;
|
||||||
|
box-shadow: 0 24px 60px -12px rgba(15, 23, 42, .35);
|
||||||
|
animation: pop .18s ease-out;
|
||||||
|
}
|
||||||
|
@keyframes pop { from { transform: translateY(10px); opacity: 0; } to { transform: none; opacity: 1; } }
|
||||||
|
.modal h3 { margin: 0 0 4px; font-size: 18px; }
|
||||||
|
.modal .modal-sub { margin: 0 0 10px; }
|
||||||
|
|
||||||
|
/* 详情 */
|
||||||
|
.detail-head { display: flex; justify-content: space-between; gap: 12px; align-items: flex-start; }
|
||||||
|
.detail-meta { display: grid; grid-template-columns: 1fr 1fr; gap: 8px 16px; margin: 14px 0; font-size: 14px; }
|
||||||
|
.detail-meta span.lbl { color: var(--muted); font-size: 12px; display: block; }
|
||||||
|
.detail-desc {
|
||||||
|
background: var(--bg);
|
||||||
|
border-radius: 10px;
|
||||||
|
padding: 12px 14px;
|
||||||
|
font-size: 14px;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
margin: 12px 0;
|
||||||
|
}
|
||||||
|
.p-list { margin: 8px 0 0; padding: 0; list-style: none; }
|
||||||
|
.p-list li {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 8px 0;
|
||||||
|
border-top: 1px dashed var(--line);
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
.p-list li:first-child { border-top: none; }
|
||||||
|
.p-list .grow { flex: 1; }
|
||||||
|
.p-list .who { cursor: pointer; }
|
||||||
|
.p-list .who:hover { color: var(--primary); }
|
||||||
|
.p-list select { padding: 4px 8px; font-size: 13px; width: auto; }
|
||||||
|
.p-list .note { color: var(--muted); font-size: 12px; }
|
||||||
|
.add-member-row { display: flex; gap: 8px; margin-top: 12px; }
|
||||||
|
.add-member-row input { flex: 1; }
|
||||||
|
|
||||||
|
/* ---------- 空态 / 加载 ---------- */
|
||||||
|
.empty {
|
||||||
|
text-align: center;
|
||||||
|
color: var(--muted);
|
||||||
|
padding: 60px 20px;
|
||||||
|
border: 1px dashed var(--line);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
background: rgba(255, 255, 255, .6);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- Toast ---------- */
|
||||||
|
.toast {
|
||||||
|
position: fixed;
|
||||||
|
left: 50%;
|
||||||
|
bottom: 36px;
|
||||||
|
transform: translateX(-50%);
|
||||||
|
background: #1f2430;
|
||||||
|
color: #fff;
|
||||||
|
padding: 10px 18px;
|
||||||
|
border-radius: 999px;
|
||||||
|
font-size: 14px;
|
||||||
|
z-index: 200;
|
||||||
|
box-shadow: 0 10px 30px -8px rgba(0, 0, 0, .4);
|
||||||
|
}
|
||||||
|
.toast.err { background: var(--bad); }
|
||||||
|
|
||||||
|
/* ---------- 响应式 ---------- */
|
||||||
|
@media (max-width: 760px) {
|
||||||
|
#nav {
|
||||||
|
display: none;
|
||||||
|
position: absolute;
|
||||||
|
top: 100%;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
background: #fff;
|
||||||
|
border-bottom: 1px solid var(--line);
|
||||||
|
flex-direction: column;
|
||||||
|
padding: 8px;
|
||||||
|
}
|
||||||
|
#nav.open { display: flex; }
|
||||||
|
.menu-toggle { display: block; margin-left: auto; }
|
||||||
|
.topbar-user { display: none; }
|
||||||
|
#new-activity-btn { display: none; }
|
||||||
|
.detail-meta { grid-template-columns: 1fr; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 成员简表 */
|
||||||
|
#members-table { width: 100%; border-collapse: collapse; background: #fff; border: 1px solid var(--border, #e5e7eb); border-radius: 10px; overflow: hidden; }
|
||||||
|
#members-table th, #members-table td { padding: 10px 14px; text-align: left; border-bottom: 1px solid var(--border, #e5e7eb); font-size: 14px; }
|
||||||
|
#members-table th { background: #f9fafb; color: #6b7280; font-weight: 600; font-size: 13px; }
|
||||||
|
#members-table tbody tr:last-child td { border-bottom: none; }
|
||||||
|
#members-table tbody tr:hover { background: #f9fafb; }
|
||||||
|
|
||||||
|
/* 审核 */
|
||||||
|
.badge { display: inline-block; min-width: 16px; padding: 0 5px; margin-left: 4px; border-radius: 8px; background: #ef4444; color: #fff; font-size: 11px; line-height: 16px; text-align: center; }
|
||||||
|
.review-row { display: flex; align-items: center; gap: 10px; padding: 10px 0; border-bottom: 1px solid #f0f0f0; }
|
||||||
|
.review-row:last-child { border-bottom: none; }
|
||||||
|
.review-row .grow { flex: 1; }
|
||||||
|
.tag.pending { background: #fef3c7; color: #92400e; }
|
||||||
|
.review-add { display: flex; align-items: center; gap: 8px; margin: 12px 0; }
|
||||||
|
.review-add input { flex: 1; margin-top: 0; }
|
||||||
Vendored
+181
@@ -0,0 +1,181 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>WorkLog · 活动记录</title>
|
||||||
|
<link rel="stylesheet" href="/assets/styles.css?v=5" />
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="app">
|
||||||
|
<!-- 顶栏 -->
|
||||||
|
<header id="topbar" class="hidden">
|
||||||
|
<div class="topbar-inner">
|
||||||
|
<div class="brand" id="brand">📘 WorkLog</div>
|
||||||
|
<nav id="nav">
|
||||||
|
<a href="#" data-view="feed">活动墙</a>
|
||||||
|
<a href="#" data-view="mine">我的记录</a>
|
||||||
|
<a href="#" data-view="members">成员</a>
|
||||||
|
<a href="#" data-view="profile">设置</a>
|
||||||
|
</nav>
|
||||||
|
<div class="topbar-user">
|
||||||
|
<span id="topbar-name"></span>
|
||||||
|
<button class="btn ghost sm" id="logout-btn">退出</button>
|
||||||
|
</div>
|
||||||
|
<button class="btn primary" id="new-activity-btn">+ 记录活动</button>
|
||||||
|
<button class="menu-toggle" id="menu-toggle">☰</button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<!-- 登录 / 注册 -->
|
||||||
|
<section id="auth-view" class="view hidden">
|
||||||
|
<div class="auth-wrap">
|
||||||
|
<div class="auth-card">
|
||||||
|
<h1 class="auth-title">📘 WorkLog</h1>
|
||||||
|
<p class="auth-sub">用一条条活动记录,攒下一起做过的事</p>
|
||||||
|
<div class="tabs">
|
||||||
|
<button class="tab active" data-auth="login">登录</button>
|
||||||
|
<button class="tab" data-auth="register">注册新账号</button>
|
||||||
|
</div>
|
||||||
|
<form id="login-form">
|
||||||
|
<label>邮箱 *<input name="email" type="email" required autocomplete="email" placeholder="注册时使用的邮箱" /></label>
|
||||||
|
<label>邮箱验证码 *
|
||||||
|
<div class="code-row">
|
||||||
|
<input name="email_code" type="text" required minlength="6" maxlength="6" pattern="[0-9]{6}" inputmode="numeric" autocomplete="one-time-code" title="请输入 6 位数字验证码" placeholder="6 位验证码" />
|
||||||
|
<button type="button" class="btn" id="login-code-btn">获取验证码</button>
|
||||||
|
</div>
|
||||||
|
</label>
|
||||||
|
<div class="form-error" id="login-error"></div>
|
||||||
|
<div class="form-hint muted" id="login-hint"></div>
|
||||||
|
<button class="btn primary block" type="submit" id="login-submit">登录</button>
|
||||||
|
</form>
|
||||||
|
<form id="register-form" class="hidden">
|
||||||
|
<label>姓名 *<input name="display_name" required maxlength="32" autocomplete="name" placeholder="真实姓名,展示用" /></label>
|
||||||
|
<label>所属部门 *<select name="department" required><option value="" disabled selected>请选择部门</option></select></label>
|
||||||
|
<label>邮箱 *<input name="email" type="email" required maxlength="255" autocomplete="email" placeholder="用于登录和接收验证码" /></label>
|
||||||
|
<label>手机号 *<input name="phone" type="tel" required minlength="11" maxlength="11" pattern="1[3-9][0-9]{9}" inputmode="numeric" autocomplete="tel-national" title="请填写正确的 11 位手机号" placeholder="11 位手机号" /></label>
|
||||||
|
<p class="form-hint muted">姓名和部门向成员展示;邮箱、手机号仅自己可见。</p>
|
||||||
|
<label>邮箱验证码 *
|
||||||
|
<div class="code-row">
|
||||||
|
<input name="email_code" type="text" required minlength="6" maxlength="6" pattern="[0-9]{6}" inputmode="numeric" autocomplete="one-time-code" title="请输入 6 位数字验证码" placeholder="6 位验证码" />
|
||||||
|
<button type="button" class="btn" id="send-code-btn">获取验证码</button>
|
||||||
|
</div>
|
||||||
|
</label>
|
||||||
|
<div class="form-error" id="register-error" role="alert"></div>
|
||||||
|
<div class="form-hint muted" id="register-hint" role="status"></div>
|
||||||
|
<button class="btn primary block" type="submit" id="register-submit">创建账号</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- 活动墙 -->
|
||||||
|
<main id="feed-view" class="view hidden">
|
||||||
|
<div class="container">
|
||||||
|
<div class="page-head">
|
||||||
|
<div>
|
||||||
|
<h2>活动墙</h2>
|
||||||
|
<p class="muted" id="feed-sub">看看大家都在参加什么</p>
|
||||||
|
</div>
|
||||||
|
<div class="filters">
|
||||||
|
<input id="feed-q" placeholder="搜索活动 / 地点" />
|
||||||
|
<select id="feed-dept"><option value="">全部部门</option></select>
|
||||||
|
<select id="feed-scope">
|
||||||
|
<option value="all">全部可见</option>
|
||||||
|
<option value="mine">我发起的</option>
|
||||||
|
<option value="joined">我参加的</option>
|
||||||
|
<option value="upcoming">未开始的</option>
|
||||||
|
</select>
|
||||||
|
<button class="btn" id="feed-refresh">刷新</button>
|
||||||
|
<button class="btn primary" id="feed-new">+ 记录活动</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div id="feed-stats" class="stats-row"></div>
|
||||||
|
<div id="feed-list" class="card-list"></div>
|
||||||
|
<div id="feed-empty" class="empty hidden">还没有活动记录,点右上角「+ 记录活动」创建第一条吧。</div>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<!-- 我的记录 -->
|
||||||
|
<main id="mine-view" class="view hidden">
|
||||||
|
<div class="container">
|
||||||
|
<div class="page-head">
|
||||||
|
<div>
|
||||||
|
<h2>我的记录</h2>
|
||||||
|
<p class="muted">按账号记录你参加过的每一场活动</p>
|
||||||
|
</div>
|
||||||
|
<div class="filters">
|
||||||
|
<input id="mine-q" placeholder="搜索标题 / 地点" />
|
||||||
|
<select id="mine-status">
|
||||||
|
<option value="">全部状态</option>
|
||||||
|
<option value="joined">报名中</option>
|
||||||
|
<option value="attended">已参加</option>
|
||||||
|
<option value="absent">缺席</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div id="mine-stats" class="stats-row"></div>
|
||||||
|
<div id="mine-list" class="card-list"></div>
|
||||||
|
<div id="mine-empty" class="empty hidden">还没有记录。去活动墙报名,或点「+ 记录活动」自己发起一条。</div>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<!-- 成员 -->
|
||||||
|
<main id="members-view" class="view hidden">
|
||||||
|
<div class="container">
|
||||||
|
<div class="page-head">
|
||||||
|
<div><h2>成员</h2><p class="muted">点开任意成员,查看 TA 的活动记录</p></div>
|
||||||
|
<div class="filters">
|
||||||
|
<select id="members-dept"></select>
|
||||||
|
<input id="members-q" placeholder="搜索账号 / 昵称" />
|
||||||
|
<button id="members-compact" class="btn btn-ghost" type="button">简表</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div id="members-list" class="member-grid"></div>
|
||||||
|
<table id="members-table" class="hidden">
|
||||||
|
<thead><tr><th>姓名</th><th>部门</th><th>参加数</th></tr></thead>
|
||||||
|
<tbody></tbody>
|
||||||
|
</table>
|
||||||
|
<div id="members-empty" class="empty hidden">没有找到成员。</div>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<!-- 他人主页 -->
|
||||||
|
<main id="user-view" class="view hidden">
|
||||||
|
<div class="container">
|
||||||
|
<button class="btn ghost" id="user-back">← 返回</button>
|
||||||
|
<div id="user-header" class="profile-header"></div>
|
||||||
|
<div id="user-stats" class="stats-row"></div>
|
||||||
|
<div id="user-list" class="card-list"></div>
|
||||||
|
<div id="user-empty" class="empty hidden">TA 的公开记录还很少。</div>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<!-- 设置 -->
|
||||||
|
<main id="profile-view" class="view hidden">
|
||||||
|
<div class="container narrow">
|
||||||
|
<div class="page-head"><div><h2>账号设置</h2></div></div>
|
||||||
|
<div class="card form-card">
|
||||||
|
<h3>个人资料</h3>
|
||||||
|
<label>姓名<input id="pf-name" maxlength="32" /></label>
|
||||||
|
<label>所属部门<select id="pf-dept"><option value="">未选择</option></select></label>
|
||||||
|
<label>手机号<input id="pf-phone" maxlength="11" inputmode="numeric" /></label>
|
||||||
|
<label>绑定邮箱<div class="muted" id="pf-email" style="margin-top:4px"></div></label>
|
||||||
|
<button class="btn primary" id="pf-save">保存资料</button>
|
||||||
|
</div>
|
||||||
|
<div class="card form-card">
|
||||||
|
<h3>登录方式</h3>
|
||||||
|
<p class="muted">使用注册邮箱 + 邮箱验证码登录,无需密码。登录状态保持 30 天。</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<!-- 活动详情 / 新建弹层 -->
|
||||||
|
<div id="modal-root"></div>
|
||||||
|
|
||||||
|
<div id="toast" class="toast hidden"></div>
|
||||||
|
|
||||||
|
<script src="/js/app.js?v=10"></script>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Vendored
+738
@@ -0,0 +1,738 @@
|
|||||||
|
/* WorkLog 活动记录 — 前端逻辑(原生 JS,无构建步骤) */
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
(() => {
|
||||||
|
const API = "/api";
|
||||||
|
const TOKEN_KEY = "worklog_token";
|
||||||
|
|
||||||
|
// ------------------------------------------------------------- 工具
|
||||||
|
const $ = (sel) => document.querySelector(sel);
|
||||||
|
const $$ = (sel) => Array.from(document.querySelectorAll(sel));
|
||||||
|
|
||||||
|
const esc = (s) =>
|
||||||
|
String(s ?? "").replace(/[&<>"']/g, (c) =>
|
||||||
|
({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]));
|
||||||
|
|
||||||
|
let departments = [];
|
||||||
|
|
||||||
|
const fmtDate = (ms) =>
|
||||||
|
new Date(ms).toLocaleString("zh-CN", {
|
||||||
|
year: "numeric", month: "2-digit", day: "2-digit",
|
||||||
|
hour: "2-digit", minute: "2-digit", hour12: false,
|
||||||
|
});
|
||||||
|
const fmtDay = (ms) =>
|
||||||
|
new Date(ms).toLocaleDateString("zh-CN", { year: "numeric", month: "2-digit", day: "2-digit" });
|
||||||
|
|
||||||
|
const STATUS_LABEL = { joined: "已确认", attended: "已参加", absent: "缺席" };
|
||||||
|
const toLocalInput = (ms) => {
|
||||||
|
const d = new Date(ms - new Date().getTimezoneOffset() * 60000);
|
||||||
|
return d.toISOString().slice(0, 16);
|
||||||
|
};
|
||||||
|
|
||||||
|
let toastTimer = null;
|
||||||
|
const toast = (msg, isErr = false) => {
|
||||||
|
const el = $("#toast");
|
||||||
|
el.textContent = msg;
|
||||||
|
el.classList.toggle("err", isErr);
|
||||||
|
el.classList.remove("hidden");
|
||||||
|
clearTimeout(toastTimer);
|
||||||
|
toastTimer = setTimeout(() => el.classList.add("hidden"), 2600);
|
||||||
|
};
|
||||||
|
|
||||||
|
// ------------------------------------------------------------- API
|
||||||
|
const getToken = () => localStorage.getItem(TOKEN_KEY) || "";
|
||||||
|
const setToken = (t) => (t ? localStorage.setItem(TOKEN_KEY, t) : localStorage.removeItem(TOKEN_KEY));
|
||||||
|
|
||||||
|
function apiErrorMessage(detail, status) {
|
||||||
|
if (typeof detail === "string") return detail;
|
||||||
|
if (Array.isArray(detail)) {
|
||||||
|
const labels = { display_name: "姓名", department: "所属部门", email: "邮箱", phone: "手机号", email_code: "邮箱验证码" };
|
||||||
|
return detail.map((error) => {
|
||||||
|
const field = labels[error.loc?.at(-1)] || "填写内容";
|
||||||
|
if (error.type === "missing") return `请填写${field}`;
|
||||||
|
if (error.type === "string_too_long") return `${field}最多填写 ${error.ctx?.max_length} 个字符`;
|
||||||
|
if (error.type === "string_too_short") return `${field}至少填写 ${error.ctx?.min_length} 个字符`;
|
||||||
|
const message = String(error.msg || "格式不正确").replace(/^Value error,\s*/, "");
|
||||||
|
return /[\u4e00-\u9fff]/.test(message) ? message : `${field}格式不正确`;
|
||||||
|
}).join(";");
|
||||||
|
}
|
||||||
|
return `请求失败(${status})`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function api(path, { method = "GET", body } = {}) {
|
||||||
|
const headers = { "Content-Type": "application/json" };
|
||||||
|
const token = getToken();
|
||||||
|
if (token) headers.Authorization = `Bearer ${token}`;
|
||||||
|
let res;
|
||||||
|
try {
|
||||||
|
res = await fetch(API + path, {
|
||||||
|
method, headers,
|
||||||
|
body: body === undefined ? undefined : JSON.stringify(body),
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
throw new Error("网络异常,请稍后重试");
|
||||||
|
}
|
||||||
|
const data = await res.json().catch(() => ({}));
|
||||||
|
if (!res.ok) {
|
||||||
|
if (res.status === 401 && getToken()) {
|
||||||
|
setToken("");
|
||||||
|
showAuth();
|
||||||
|
throw new Error("登录已过期,请重新登录");
|
||||||
|
}
|
||||||
|
throw new Error(apiErrorMessage(data.detail, res.status));
|
||||||
|
}
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------- 状态
|
||||||
|
const state = {
|
||||||
|
me: null,
|
||||||
|
view: "feed",
|
||||||
|
feed: { q: "", department: "", scope: "all", items: [] },
|
||||||
|
mine: { q: "", status: "", items: [], stats: null },
|
||||||
|
members: { q: "", items: [] },
|
||||||
|
user: { id: "", data: null },
|
||||||
|
};
|
||||||
|
|
||||||
|
// ------------------------------------------------------------- 视图切换
|
||||||
|
const VIEWS = ["auth", "feed", "mine", "members", "user", "profile"];
|
||||||
|
function show(view) {
|
||||||
|
state.view = view;
|
||||||
|
VIEWS.forEach((v) => $(`#${v}-view`).classList.toggle("hidden", v !== view));
|
||||||
|
const logged = !!state.me;
|
||||||
|
$("#topbar").classList.toggle("hidden", view === "auth" || !logged);
|
||||||
|
$$("#nav a").forEach((a) => a.classList.toggle("active", a.dataset.view === view));
|
||||||
|
$("#nav").classList.remove("open");
|
||||||
|
if (view === "feed") loadFeed();
|
||||||
|
if (view === "mine") loadMine();
|
||||||
|
if (view === "members") loadMembers();
|
||||||
|
if (view === "profile") fillProfile();
|
||||||
|
}
|
||||||
|
const showAuth = () => show("auth");
|
||||||
|
|
||||||
|
function enterApp(me) {
|
||||||
|
state.me = me;
|
||||||
|
$("#topbar-name").textContent = me.display_name;
|
||||||
|
show("feed");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------- 验证码(注册/登录共用)
|
||||||
|
function bindSendCode(btnId, emailSel, hintSel, errSel, purpose) {
|
||||||
|
let cooldownUntil = 0; // 发出成功后的冷却截止时间戳,期间按钮保持禁用
|
||||||
|
$(btnId).addEventListener("click", async () => {
|
||||||
|
const btn = $(btnId);
|
||||||
|
const emailInput = $(emailSel);
|
||||||
|
const email = emailInput.value.trim();
|
||||||
|
if (!emailInput.checkValidity() || !email) {
|
||||||
|
$(errSel).textContent = "请先填写正确的邮箱地址";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (Date.now() < cooldownUntil) return; // 冷却期内忽略连点
|
||||||
|
$(errSel).textContent = "";
|
||||||
|
btn.disabled = true;
|
||||||
|
btn.textContent = "发送中…";
|
||||||
|
try {
|
||||||
|
const data = await api("/auth/send-code", { method: "POST", body: { email, purpose } });
|
||||||
|
if (data.dev_code) {
|
||||||
|
$(hintSel).textContent = `【本机开发模式】验证码:${data.dev_code}`;
|
||||||
|
} else {
|
||||||
|
$(hintSel).textContent = "验证码已发送到你的邮箱,请注意查收";
|
||||||
|
}
|
||||||
|
cooldownUntil = Date.now() + 60_000;
|
||||||
|
let left = 60;
|
||||||
|
const tick = () => {
|
||||||
|
if (Date.now() >= cooldownUntil && left <= 0) { btn.disabled = false; btn.textContent = "获取验证码"; return; }
|
||||||
|
btn.textContent = `${left}s 后重发`;
|
||||||
|
left -= 1;
|
||||||
|
setTimeout(tick, 1000);
|
||||||
|
};
|
||||||
|
tick();
|
||||||
|
} catch (err) {
|
||||||
|
btn.disabled = false;
|
||||||
|
btn.textContent = "获取验证码";
|
||||||
|
$(errSel).textContent = err.message;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------- 认证
|
||||||
|
$("#login-form").addEventListener("submit", async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const f = e.target;
|
||||||
|
const btn = $("#login-submit");
|
||||||
|
$("#login-error").textContent = "";
|
||||||
|
btn.disabled = true;
|
||||||
|
try {
|
||||||
|
const data = await api("/auth/login", {
|
||||||
|
method: "POST",
|
||||||
|
body: { email: f.email.value.trim(), email_code: f.email_code.value.trim() },
|
||||||
|
});
|
||||||
|
setToken(data.token);
|
||||||
|
enterApp(data.user);
|
||||||
|
} catch (err) { $("#login-error").textContent = err.message; }
|
||||||
|
finally { btn.disabled = false; }
|
||||||
|
});
|
||||||
|
bindSendCode("#login-code-btn", "#login-form [name=email]", "#login-hint", "#login-error", "login");
|
||||||
|
|
||||||
|
$("#register-form").addEventListener("submit", async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const f = e.target;
|
||||||
|
const btn = $("#register-submit");
|
||||||
|
$("#register-error").textContent = "";
|
||||||
|
if (!f.display_name.value.trim()) {
|
||||||
|
$("#register-error").textContent = "请填写姓名";
|
||||||
|
f.display_name.focus();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!f.department.value) {
|
||||||
|
$("#register-error").textContent = "请选择所属部门";
|
||||||
|
f.department.focus();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!/^1[3-9]\d{9}$/.test(f.phone.value.trim())) {
|
||||||
|
$("#register-error").textContent = "请填写正确的 11 位手机号";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
btn.disabled = true;
|
||||||
|
try {
|
||||||
|
const data = await api("/auth/register", {
|
||||||
|
method: "POST",
|
||||||
|
body: {
|
||||||
|
display_name: f.display_name.value.trim(),
|
||||||
|
department: f.department.value,
|
||||||
|
email: f.email.value.trim(),
|
||||||
|
phone: f.phone.value.trim(),
|
||||||
|
email_code: f.email_code.value.trim(),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
setToken(data.token);
|
||||||
|
enterApp(data.user);
|
||||||
|
toast("欢迎加入 WorkLog 🎉");
|
||||||
|
} catch (err) { $("#register-error").textContent = err.message; }
|
||||||
|
finally { btn.disabled = false; }
|
||||||
|
});
|
||||||
|
bindSendCode("#send-code-btn", "#register-form [name=email]", "#register-hint", "#register-error", "register");
|
||||||
|
|
||||||
|
$$(".tab").forEach((t) =>
|
||||||
|
t.addEventListener("click", () => {
|
||||||
|
$$(".tab").forEach((x) => x.classList.toggle("active", x === t));
|
||||||
|
$("#login-form").classList.toggle("hidden", t.dataset.auth !== "login");
|
||||||
|
$("#register-form").classList.toggle("hidden", t.dataset.auth !== "register");
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
$("#logout-btn").addEventListener("click", async () => {
|
||||||
|
try { await api("/auth/logout", { method: "POST" }); } catch { /* ignore */ }
|
||||||
|
setToken("");
|
||||||
|
state.me = null;
|
||||||
|
showAuth();
|
||||||
|
});
|
||||||
|
|
||||||
|
// ------------------------------------------------------------- 顶栏
|
||||||
|
$("#brand").addEventListener("click", () => show("feed"));
|
||||||
|
$("#new-activity-btn").addEventListener("click", () => openActivityForm());
|
||||||
|
$("#feed-new").addEventListener("click", () => openActivityForm());
|
||||||
|
$("#menu-toggle").addEventListener("click", () => $("#nav").classList.toggle("open"));
|
||||||
|
$$("#nav a").forEach((a) =>
|
||||||
|
a.addEventListener("click", (e) => { e.preventDefault(); show(a.dataset.view); })
|
||||||
|
);
|
||||||
|
|
||||||
|
// ------------------------------------------------------------- 活动卡片
|
||||||
|
const initials = (name) => {
|
||||||
|
const s = String(name || "?").trim();
|
||||||
|
// 中文取第一个字,避免溢出小圆头像
|
||||||
|
return esc(/[\u4e00-\u9fff]/.test(s) ? s.slice(0, 1) : s.slice(0, 2).toUpperCase());
|
||||||
|
};
|
||||||
|
|
||||||
|
function activityCard(a, opts = {}) {
|
||||||
|
const mine = a.my_participation;
|
||||||
|
const isOrganizer = a.organizer_id === state.me.id;
|
||||||
|
const full = a.capacity && a.participant_count >= a.capacity;
|
||||||
|
const statusTag = mine
|
||||||
|
? `<span class="tag ${mine.status}">${STATUS_LABEL[mine.status] || mine.status}</span>`
|
||||||
|
: "";
|
||||||
|
const visTag = a.visibility === "private"
|
||||||
|
? `<span class="tag pri">私密</span>`
|
||||||
|
: `<span class="tag pub">公开</span>`;
|
||||||
|
|
||||||
|
const faces = a.participants.slice(0, 6).map((p) =>
|
||||||
|
`<span class="face" data-user="${p.user_id}" title="${esc(p.display_name)}">${initials(p.display_name)}</span>`
|
||||||
|
).join("");
|
||||||
|
const more = a.participant_count > 6
|
||||||
|
? `<span class="face more">+${a.participant_count - 6}</span>` : "";
|
||||||
|
|
||||||
|
const actions = [];
|
||||||
|
// "我也参加过":点击直接加入
|
||||||
|
if (!mine && a.visibility === "public" && !full) {
|
||||||
|
actions.push(`<button class="btn primary sm" data-act="claim">我也参加过</button>`);
|
||||||
|
}
|
||||||
|
if (mine && !isOrganizer) {
|
||||||
|
actions.push(`<button class="btn sm" data-act="leave">退出</button>`);
|
||||||
|
}
|
||||||
|
if (isOrganizer) {
|
||||||
|
actions.push(`<button class="btn sm" data-act="edit">编辑</button>`);
|
||||||
|
actions.push(`<button class="btn danger sm" data-act="delete">删除</button>`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return `
|
||||||
|
<div class="acard" data-id="${a.id}">
|
||||||
|
<div class="acard-top">
|
||||||
|
<div>
|
||||||
|
<h3 data-act="open">${esc(a.title)}</h3>
|
||||||
|
<div class="acard-meta">
|
||||||
|
${visTag}${statusTag}
|
||||||
|
${full ? `<span class="tag full">已满 ${a.capacity} 人</span>` : ""}
|
||||||
|
<span class="meta-item">📅 ${fmtDate(a.start_at)}</span>
|
||||||
|
${a.location ? `<span class="meta-item">📍 ${esc(a.location)}</span>` : ""}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
${a.description ? `<p class="acard-desc">${esc(a.description).slice(0, 160)}${a.description.length > 160 ? "…" : ""}</p>` : ""}
|
||||||
|
<div class="acard-foot">
|
||||||
|
<div class="faces">
|
||||||
|
${faces}${more}
|
||||||
|
<span class="faces-label">${a.participant_count} 人${opts.showOrganizer && a.organizer ? ` · ${esc(a.organizer.display_name)} 记录` : ""}</span>
|
||||||
|
</div>
|
||||||
|
<div class="acard-actions">${actions.join("")}</div>
|
||||||
|
</div>
|
||||||
|
</div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function bindCardEvents(container) {
|
||||||
|
container.querySelectorAll(".acard").forEach((card) => {
|
||||||
|
const id = card.dataset.id;
|
||||||
|
const activity = findActivity(id);
|
||||||
|
card.querySelectorAll("[data-act]").forEach((btn) => {
|
||||||
|
btn.addEventListener("click", async (e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
const act = btn.dataset.act;
|
||||||
|
if (act === "open") return openDetail(id);
|
||||||
|
if (act === "claim") {
|
||||||
|
try { await api(`/activities/${id}/claim`, { method: "POST" }); toast("已加入这条记录"); refreshCurrent(); }
|
||||||
|
catch (err) { toast(err.message, true); }
|
||||||
|
}
|
||||||
|
if (act === "leave") {
|
||||||
|
if (!confirm("确定退出这条活动吗?")) return;
|
||||||
|
try { await api(`/activities/${id}/leave`, { method: "POST" }); toast("已退出"); refreshCurrent(); }
|
||||||
|
catch (err) { toast(err.message, true); }
|
||||||
|
}
|
||||||
|
if (act === "edit") return openActivityForm(activity);
|
||||||
|
if (act === "delete") {
|
||||||
|
if (!confirm("删除后该活动及所有人的参加记录都会消失,确定?")) return;
|
||||||
|
try { await api(`/activities/${id}`, { method: "DELETE" }); toast("已删除"); refreshCurrent(); }
|
||||||
|
catch (err) { toast(err.message, true); }
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
card.querySelectorAll("[data-user]").forEach((f) =>
|
||||||
|
f.addEventListener("click", (e) => { e.stopPropagation(); openUser(f.dataset.user); })
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function findActivity(id) {
|
||||||
|
return (
|
||||||
|
state.feed.items.find((x) => x.id === id) ||
|
||||||
|
state.mine.items.find((x) => x.id === id) ||
|
||||||
|
(state.user.data && state.user.data.items.find((x) => x.id === id)) ||
|
||||||
|
null
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function refreshCurrent() {
|
||||||
|
if (state.view === "feed") loadFeed();
|
||||||
|
else if (state.view === "mine") loadMine();
|
||||||
|
else if (state.view === "user" && state.user.id) loadUser(state.user.id);
|
||||||
|
else if (state.view === "members") loadMembers();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------- 活动墙
|
||||||
|
async function loadFeed() {
|
||||||
|
const p = new URLSearchParams();
|
||||||
|
if (state.feed.q) p.set("q", state.feed.q);
|
||||||
|
if (state.feed.department) p.set("department", state.feed.department);
|
||||||
|
if (state.feed.scope && state.feed.scope !== "all") p.set("scope", state.feed.scope);
|
||||||
|
const data = await api(`/activities?${p}`);
|
||||||
|
state.feed.items = data.items;
|
||||||
|
$("#feed-list").innerHTML = data.items.map((a) => activityCard(a, { showOrganizer: true })).join("");
|
||||||
|
$("#feed-list").classList.toggle("hidden", !data.items.length);
|
||||||
|
$("#feed-empty").classList.toggle("hidden", !!data.items.length);
|
||||||
|
bindCardEvents($("#feed-list"));
|
||||||
|
try {
|
||||||
|
const ov = await api("/stats/overview");
|
||||||
|
$("#feed-stats").innerHTML = `
|
||||||
|
<div class="stat"><b>${ov.members}</b><span>成员</span></div>
|
||||||
|
<div class="stat"><b>${ov.activities}</b><span>公开活动</span></div>
|
||||||
|
<div class="stat"><b>${ov.records}</b><span>参加记录</span></div>
|
||||||
|
<div class="stat"><b>${ov.upcoming}</b><span>未开始</span></div>`;
|
||||||
|
} catch { $("#feed-stats").innerHTML = ""; }
|
||||||
|
}
|
||||||
|
|
||||||
|
$("#feed-q").addEventListener("input", debounce(() => { state.feed.q = $("#feed-q").value.trim(); loadFeed(); }, 350));
|
||||||
|
$("#feed-dept").addEventListener("change", () => { state.feed.department = $("#feed-dept").value; loadFeed(); });
|
||||||
|
$("#feed-scope").addEventListener("change", () => { state.feed.scope = $("#feed-scope").value; loadFeed(); });
|
||||||
|
$("#feed-refresh").addEventListener("click", loadFeed);
|
||||||
|
|
||||||
|
// ------------------------------------------------------------- 我的记录
|
||||||
|
async function loadMine() {
|
||||||
|
const data = await api("/auth/me");
|
||||||
|
state.mine.stats = data.stats;
|
||||||
|
const all = await api(`/activities?scope=joined&limit=200`);
|
||||||
|
state.mine.items = all.items;
|
||||||
|
renderMine();
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderMine() {
|
||||||
|
const { q, status } = { q: $("#mine-q").value.trim(), status: $("#mine-status").value };
|
||||||
|
let items = state.mine.items;
|
||||||
|
if (q) items = items.filter((a) => (a.title + a.location).toLowerCase().includes(q.toLowerCase()));
|
||||||
|
if (status) items = items.filter((a) => a.my_participation && a.my_participation.status === status);
|
||||||
|
|
||||||
|
const s = state.mine.stats || {};
|
||||||
|
$("#mine-stats").innerHTML = `
|
||||||
|
<div class="stat"><b>${s.total ?? 0}</b><span>全部记录</span></div>
|
||||||
|
<div class="stat"><b>${s.attended ?? 0}</b><span>已参加</span></div>
|
||||||
|
<div class="stat"><b>${s.joined ?? 0}</b><span>报名中</span></div>
|
||||||
|
<div class="stat"><b>${s.absent ?? 0}</b><span>缺席</span></div>
|
||||||
|
<div class="stat"><b>${Math.round((s.attendance_rate || 0) * 100)}%</b><span>出席率</span></div>`;
|
||||||
|
|
||||||
|
$("#mine-list").innerHTML = items.map((a) => activityCard(a)).join("");
|
||||||
|
$("#mine-list").classList.toggle("hidden", !items.length);
|
||||||
|
$("#mine-empty").classList.toggle("hidden", !!items.length);
|
||||||
|
bindCardEvents($("#mine-list"));
|
||||||
|
}
|
||||||
|
|
||||||
|
$("#mine-q").addEventListener("input", debounce(renderMine, 200));
|
||||||
|
$("#mine-status").addEventListener("change", renderMine);
|
||||||
|
|
||||||
|
// ------------------------------------------------------------- 成员
|
||||||
|
async function loadMembers() {
|
||||||
|
const q = $("#members-q").value.trim();
|
||||||
|
const dept = $("#members-dept").value;
|
||||||
|
const p = new URLSearchParams();
|
||||||
|
if (q) p.set("q", q);
|
||||||
|
if (dept) p.set("department", dept);
|
||||||
|
const data = await api(`/users?${p}`);
|
||||||
|
state.members.items = data.items;
|
||||||
|
const compact = !$("#members-table").classList.contains("hidden");
|
||||||
|
$("#members-list").innerHTML = data.items.map((u) => `
|
||||||
|
<div class="mcard" data-user="${u.id}">
|
||||||
|
<div class="mcard-top">
|
||||||
|
<div class="avatar">${initials(u.display_name)}</div>
|
||||||
|
<div>
|
||||||
|
<b>${esc(u.display_name)}</b>
|
||||||
|
<div class="muted">${u.department ? esc(u.department) : ""}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="mcard-stats">
|
||||||
|
<div><b>${u.total}</b><span>参加</span></div>
|
||||||
|
<div><b>${u.attended}</b><span>已参加</span></div>
|
||||||
|
<div><b>${u.organized}</b><span>发起</span></div>
|
||||||
|
</div>
|
||||||
|
</div>`).join("");
|
||||||
|
$("#members-table tbody").innerHTML = data.items.map((u) => `
|
||||||
|
<tr data-user="${u.id}">
|
||||||
|
<td><b>${esc(u.display_name)}</b></td>
|
||||||
|
<td>${esc(u.department || "—")}</td>
|
||||||
|
<td>${u.total}</td>
|
||||||
|
</tr>`).join("");
|
||||||
|
$("#members-list").classList.toggle("hidden", !data.items.length || compact);
|
||||||
|
$("#members-table").classList.toggle("hidden", !data.items.length || !compact);
|
||||||
|
$("#members-empty").classList.toggle("hidden", !!data.items.length);
|
||||||
|
$$("#members-list .mcard").forEach((c) =>
|
||||||
|
c.addEventListener("click", () => openUser(c.dataset.user))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
$("#members-compact").addEventListener("click", () => {
|
||||||
|
const table = $("#members-table");
|
||||||
|
const toCompact = table.classList.contains("hidden");
|
||||||
|
table.classList.toggle("hidden", !toCompact);
|
||||||
|
$("#members-list").classList.toggle("hidden", toCompact || !$("#members-list").innerHTML);
|
||||||
|
$("#members-compact").textContent = toCompact ? "卡片" : "简表";
|
||||||
|
});
|
||||||
|
|
||||||
|
$("#members-q").addEventListener("input", debounce(loadMembers, 300));
|
||||||
|
$("#members-dept").addEventListener("change", loadMembers);
|
||||||
|
|
||||||
|
function fillMembersDept() {
|
||||||
|
$("#members-dept").innerHTML = `<option value="">全部部门</option>` +
|
||||||
|
(departments || []).map((d) => `<option>${esc(d)}</option>`).join("");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------- 他人主页
|
||||||
|
async function openUser(userId) {
|
||||||
|
$("#user-view").classList.add("hidden");
|
||||||
|
state.user.id = userId;
|
||||||
|
await loadUser(userId);
|
||||||
|
show("user");
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadUser(userId) {
|
||||||
|
const data = await api(`/users/${userId}`);
|
||||||
|
state.user.data = data;
|
||||||
|
const u = data.user;
|
||||||
|
$("#user-header").innerHTML = `
|
||||||
|
<div class="avatar">${initials(u.display_name)}</div>
|
||||||
|
<div>
|
||||||
|
<h2>${esc(u.display_name)} ${data.is_self ? '<span class="tag pub">我</span>' : ""}</h2>
|
||||||
|
<p class="muted">${u.department ? `${esc(u.department)} · ` : ""}加入于 ${fmtDay(u.created_at)}</p>
|
||||||
|
</div>`;
|
||||||
|
const s = data.stats;
|
||||||
|
$("#user-stats").innerHTML = `
|
||||||
|
<div class="stat"><b>${s.total}</b><span>可见记录</span></div>
|
||||||
|
<div class="stat"><b>${s.attended}</b><span>已参加</span></div>
|
||||||
|
<div class="stat"><b>${s.organized}</b><span>发起</span></div>
|
||||||
|
<div class="stat"><b>${Math.round((s.attendance_rate || 0) * 100)}%</b><span>出席率</span></div>`;
|
||||||
|
$("#user-list").innerHTML = data.items.map((a) => activityCard(a)).join("");
|
||||||
|
$("#user-list").classList.toggle("hidden", !data.items.length);
|
||||||
|
$("#user-empty").classList.toggle("hidden", !!data.items.length);
|
||||||
|
bindCardEvents($("#user-list"));
|
||||||
|
}
|
||||||
|
|
||||||
|
$("#user-back").addEventListener("click", () => show("members"));
|
||||||
|
|
||||||
|
// ------------------------------------------------------------- 弹层
|
||||||
|
function modal(html) {
|
||||||
|
$("#modal-root").innerHTML = `<div class="modal-mask"><div class="modal">${html}</div></div>`;
|
||||||
|
const mask = $("#modal-root .modal-mask");
|
||||||
|
mask.addEventListener("click", (e) => { if (e.target === mask) closeModal(); });
|
||||||
|
document.addEventListener("keydown", escListener);
|
||||||
|
return mask;
|
||||||
|
}
|
||||||
|
const escListener = (e) => { if (e.key === "Escape") closeModal(); };
|
||||||
|
const closeModal = () => { $("#modal-root").innerHTML = ""; document.removeEventListener("keydown", escListener); };
|
||||||
|
|
||||||
|
// ---- 新建 / 编辑活动
|
||||||
|
function openActivityForm(existing = null) {
|
||||||
|
const isEdit = !!existing;
|
||||||
|
modal(`
|
||||||
|
<h3>${isEdit ? "编辑活动" : "记录一场活动"}</h3>
|
||||||
|
<p class="modal-sub muted">提交后立即生效,所有人可见。</p>
|
||||||
|
<form id="act-form">
|
||||||
|
<label>活动名称 *<input name="title" required maxlength="120" value="${esc(existing?.title || "")}" placeholder="例如:周三晚例会" /></label>
|
||||||
|
<div class="form-row">
|
||||||
|
<label>开始时间 *<input name="start_at" type="datetime-local" required value="${existing ? toLocalInput(existing.start_at) : ""}" /></label>
|
||||||
|
<label>地点<input name="location" maxlength="120" value="${esc(existing?.location || "")}" placeholder="如:3 号会议室" /></label>
|
||||||
|
</div>
|
||||||
|
<label>备注 <span class="hint-inline">(选填)</span><textarea name="description" rows="3" maxlength="2000" placeholder="做什么、带什么、注意事项…">${esc(existing?.description || "")}</textarea></label>
|
||||||
|
<label class="checkline"><input type="checkbox" name="visibility" ${!existing || existing.visibility === "public" ? "checked" : ""} /> 公开活动(所有人可见;不勾选则仅参加者可见)</label>
|
||||||
|
<div class="form-error" id="act-error"></div>
|
||||||
|
<div class="form-actions">
|
||||||
|
<button type="button" class="btn" id="act-cancel">取消</button>
|
||||||
|
<button class="btn primary" type="submit" id="act-submit">${isEdit ? "保存修改" : "提交记录"}</button>
|
||||||
|
</div>
|
||||||
|
</form>`);
|
||||||
|
|
||||||
|
$("#act-cancel").addEventListener("click", closeModal);
|
||||||
|
$("#act-form").addEventListener("submit", async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const f = e.target;
|
||||||
|
const btn = $("#act-submit");
|
||||||
|
const startMs = f.start_at.value ? new Date(f.start_at.value).getTime() : 0;
|
||||||
|
if (!startMs) { $("#act-error").textContent = "请选择开始时间"; return; }
|
||||||
|
const body = {
|
||||||
|
title: f.title.value.trim(),
|
||||||
|
start_at: startMs,
|
||||||
|
location: f.location.value.trim(),
|
||||||
|
description: f.description.value.trim(),
|
||||||
|
visibility: f.visibility.checked ? "public" : "private",
|
||||||
|
};
|
||||||
|
btn.disabled = true;
|
||||||
|
try {
|
||||||
|
if (isEdit) {
|
||||||
|
await api(`/activities/${existing.id}`, { method: "PATCH", body });
|
||||||
|
toast("已保存");
|
||||||
|
} else {
|
||||||
|
const data = await api("/activities", { method: "POST", body });
|
||||||
|
toast(data.duplicate ? "这条记录刚刚已提交过" : "已记录 ✓");
|
||||||
|
}
|
||||||
|
closeModal();
|
||||||
|
refreshCurrent();
|
||||||
|
} catch (err) {
|
||||||
|
$("#act-error").textContent = err.message;
|
||||||
|
btn.disabled = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 活动详情
|
||||||
|
async function openDetail(id) {
|
||||||
|
let data;
|
||||||
|
try { data = await api(`/activities/${id}`); } catch (err) { toast(err.message, true); return; }
|
||||||
|
const a = data.activity;
|
||||||
|
const canEdit = data.can_edit;
|
||||||
|
const mine = a.my_participation;
|
||||||
|
const full = a.capacity && a.participant_count >= a.capacity;
|
||||||
|
|
||||||
|
const rows = a.participants.map((p) => {
|
||||||
|
const isSelfRow = p.user_id === state.me.id;
|
||||||
|
const canManage = canEdit || isSelfRow;
|
||||||
|
const statusSel = canManage
|
||||||
|
? `<select data-role="status" data-uid="${p.user_id}">
|
||||||
|
${["joined", "attended", "absent"].map((s) => `<option value="${s}" ${p.status === s ? "selected" : ""}>${STATUS_LABEL[s]}</option>`).join("")}
|
||||||
|
</select>`
|
||||||
|
: `<span class="tag ${p.status}">${STATUS_LABEL[p.status] || p.status}</span>`;
|
||||||
|
const removeBtn = (canEdit && p.role !== "organizer") || (isSelfRow && p.role !== "organizer")
|
||||||
|
? `<button class="btn ghost sm" data-role="remove" data-uid="${p.user_id}" title="移出">✕</button>`
|
||||||
|
: "";
|
||||||
|
return `<li>
|
||||||
|
<span class="face" data-user="${p.user_id}">${initials(p.display_name)}</span>
|
||||||
|
<span class="grow"><span class="who" data-user="${p.user_id}">${esc(p.display_name)}</span>
|
||||||
|
${p.role === "organizer" ? '<span class="muted">· 记录人</span>' : ""}
|
||||||
|
${p.note ? `<div class="note">${esc(p.note)}</div>` : ""}
|
||||||
|
</span>
|
||||||
|
${statusSel}${removeBtn}
|
||||||
|
</li>`;
|
||||||
|
}).join("");
|
||||||
|
|
||||||
|
const claimBtn = !mine && a.visibility === "public" && !full
|
||||||
|
? `<button class="btn primary" id="d-claim">我也参加过</button>` : "";
|
||||||
|
const leaveBtn = mine && !canEdit
|
||||||
|
? `<button class="btn" id="d-leave">退出</button>` : "";
|
||||||
|
const editBtn = canEdit ? `<button class="btn" id="d-edit">编辑</button>` : "";
|
||||||
|
const delBtn = canEdit ? `<button class="btn danger" id="d-del">删除</button>` : "";
|
||||||
|
const noteRow = mine
|
||||||
|
? `<label>我的备注
|
||||||
|
<input id="d-note" maxlength="500" value="${esc(mine.note || "")}" placeholder="如:带了水和球拍" /></label>`
|
||||||
|
: "";
|
||||||
|
|
||||||
|
modal(`
|
||||||
|
<div class="detail-head">
|
||||||
|
<div>
|
||||||
|
<h3>${esc(a.title)}</h3>
|
||||||
|
<div class="acard-meta">
|
||||||
|
${a.visibility === "private" ? `<span class="tag pri">私密</span>` : `<span class="tag pub">公开</span>`}
|
||||||
|
${mine ? `<span class="tag ${mine.status}">${STATUS_LABEL[mine.status] || mine.status}</span>` : ""}
|
||||||
|
${full ? `<span class="tag full">名额已满</span>` : ""}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<button class="btn ghost sm" id="d-close">✕</button>
|
||||||
|
</div>
|
||||||
|
<div class="detail-meta">
|
||||||
|
<div><span class="lbl">时间</span>📅 ${fmtDate(a.start_at)}${a.start_at >= Date.now() ? "(未开始)" : ""}</div>
|
||||||
|
<div><span class="lbl">地点</span>📍 ${a.location ? esc(a.location) : "未填写"}</div>
|
||||||
|
<div><span class="lbl">记录人</span>${esc(a.organizer?.display_name || "未知")}</div>
|
||||||
|
<div><span class="lbl">人数</span>${a.participant_count}${a.capacity ? ` / ${a.capacity}` : ""} · 已参加 ${a.attended_count}</div>
|
||||||
|
</div>
|
||||||
|
${a.description ? `<div class="detail-desc">${esc(a.description)}</div>` : ""}
|
||||||
|
${noteRow}
|
||||||
|
<h4 style="margin:14px 0 2px">一起参加过(${a.participant_count})</h4>
|
||||||
|
<ul class="p-list">${rows || '<li class="muted">还没有其他人的参加记录</li>'}</ul>
|
||||||
|
<div class="form-actions">
|
||||||
|
${claimBtn}${leaveBtn}${editBtn}${delBtn}
|
||||||
|
</div>`);
|
||||||
|
|
||||||
|
$("#d-close").addEventListener("click", closeModal);
|
||||||
|
|
||||||
|
const reload = async () => {
|
||||||
|
closeModal();
|
||||||
|
await openDetail(id);
|
||||||
|
refreshCurrent();
|
||||||
|
};
|
||||||
|
|
||||||
|
const on = (sel, fn) => { const el = $(sel); if (el) el.addEventListener("click", fn); };
|
||||||
|
on("#d-claim", async () => { try { await api(`/activities/${id}/claim`, { method: "POST" }); toast("已加入这条记录"); reload(); } catch (err) { toast(err.message, true); } });
|
||||||
|
on("#d-leave", async () => {
|
||||||
|
if (!confirm("确定退出这条活动吗?")) return;
|
||||||
|
try { await api(`/activities/${id}/leave`, { method: "POST" }); toast("已退出"); reload(); } catch (err) { toast(err.message, true); }
|
||||||
|
});
|
||||||
|
on("#d-edit", () => openActivityForm(a));
|
||||||
|
on("#d-del", async () => {
|
||||||
|
if (!confirm("删除后该活动及所有人的参加记录都会消失,确定?")) return;
|
||||||
|
try { await api(`/activities/${id}`, { method: "DELETE" }); toast("已删除"); closeModal(); refreshCurrent(); } catch (err) { toast(err.message, true); }
|
||||||
|
});
|
||||||
|
|
||||||
|
const noteInput = $("#d-note");
|
||||||
|
if (noteInput) {
|
||||||
|
let timer = null;
|
||||||
|
noteInput.addEventListener("input", () => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
timer = setTimeout(async () => {
|
||||||
|
try {
|
||||||
|
await api(`/activities/${id}/participants/${state.me.id}`, { method: "PATCH", body: { note: noteInput.value } });
|
||||||
|
} catch (err) { toast(err.message, true); }
|
||||||
|
}, 600);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
$$("#modal-root [data-role=status]").forEach((sel) =>
|
||||||
|
sel.addEventListener("change", async () => {
|
||||||
|
try {
|
||||||
|
await api(`/activities/${id}/participants/${sel.dataset.uid}`, { method: "PATCH", body: { status: sel.value } });
|
||||||
|
toast("状态已更新");
|
||||||
|
reload();
|
||||||
|
} catch (err) { toast(err.message, true); }
|
||||||
|
})
|
||||||
|
);
|
||||||
|
$$("#modal-root [data-role=remove]").forEach((btn) =>
|
||||||
|
btn.addEventListener("click", async () => {
|
||||||
|
if (!confirm("将该成员移出这条活动?")) return;
|
||||||
|
try { await api(`/activities/${id}/participants/${btn.dataset.uid}`, { method: "DELETE" }); toast("已移出"); reload(); }
|
||||||
|
catch (err) { toast(err.message, true); }
|
||||||
|
})
|
||||||
|
);
|
||||||
|
$$("#modal-root [data-user]").forEach((f) =>
|
||||||
|
f.addEventListener("click", () => { closeModal(); openUser(f.dataset.user); })
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------- 设置
|
||||||
|
function fillProfile() {
|
||||||
|
$("#pf-name").value = state.me.display_name;
|
||||||
|
$("#pf-dept").value = state.me.department || "";
|
||||||
|
$("#pf-phone").value = state.me.phone || "";
|
||||||
|
$("#pf-email").textContent = state.me.email || "(未绑定)";
|
||||||
|
}
|
||||||
|
$("#pf-save").addEventListener("click", async () => {
|
||||||
|
const phone = $("#pf-phone").value.trim();
|
||||||
|
if (phone && !/^1[3-9]\d{9}$/.test(phone)) { toast("请填写正确的 11 位手机号", true); return; }
|
||||||
|
try {
|
||||||
|
const data = await api("/auth/me", { method: "PATCH", body: { display_name: $("#pf-name").value.trim(), department: $("#pf-dept").value, phone } });
|
||||||
|
state.me = data.user;
|
||||||
|
$("#topbar-name").textContent = state.me.display_name;
|
||||||
|
toast("资料已保存");
|
||||||
|
} catch (err) { toast(err.message, true); }
|
||||||
|
});
|
||||||
|
|
||||||
|
// ------------------------------------------------------------- 启动
|
||||||
|
function debounce(fn, wait) {
|
||||||
|
let t = null;
|
||||||
|
return (...args) => { clearTimeout(t); t = setTimeout(() => fn(...args), wait); };
|
||||||
|
}
|
||||||
|
|
||||||
|
function fillFeedDept() {
|
||||||
|
$("#feed-dept").innerHTML = `<option value="">全部部门</option>` +
|
||||||
|
(departments || []).map((d) => `<option>${esc(d)}</option>`).join("");
|
||||||
|
}
|
||||||
|
|
||||||
|
async function boot() {
|
||||||
|
try {
|
||||||
|
const m = await api("/meta");
|
||||||
|
departments = m.departments || [];
|
||||||
|
// 注册页部门下拉:固定五个部门
|
||||||
|
const deptOptions =
|
||||||
|
`<option value="" disabled selected>请选择部门</option>` +
|
||||||
|
departments.map((d) => `<option>${esc(d)}</option>`).join("");
|
||||||
|
$("#register-form [name=department]").innerHTML = deptOptions;
|
||||||
|
// 设置页部门下拉(可留空表示未选择)
|
||||||
|
$("#pf-dept").innerHTML =
|
||||||
|
`<option value="">未选择</option>` +
|
||||||
|
departments.map((d) => `<option>${esc(d)}</option>`).join("");
|
||||||
|
// 活动墙部门筛选:固定五个部门,未登录即可用
|
||||||
|
fillFeedDept();
|
||||||
|
// 成员页部门筛选
|
||||||
|
fillMembersDept();
|
||||||
|
} catch {
|
||||||
|
$("#register-error").textContent = "部门信息加载失败,请刷新页面重试";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!getToken()) return showAuth();
|
||||||
|
try {
|
||||||
|
const data = await api("/auth/me");
|
||||||
|
enterApp(data.user);
|
||||||
|
} catch { showAuth(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
boot();
|
||||||
|
})();
|
||||||
+66
@@ -0,0 +1,66 @@
|
|||||||
|
@echo off
|
||||||
|
setlocal enabledelayedexpansion
|
||||||
|
|
||||||
|
rem ============================================================
|
||||||
|
rem Package script: stop the local WorkLog service, then zip the
|
||||||
|
rem project. The database (data/), logs and caches are excluded.
|
||||||
|
rem Usage: package.bat (output: worklog-<timestamp>.zip in this folder)
|
||||||
|
rem ============================================================
|
||||||
|
|
||||||
|
set "PROJECT_DIR=%~dp0"
|
||||||
|
if "%PROJECT_DIR:~-1%"=="\" set "PROJECT_DIR=%PROJECT_DIR:~0,-1%"
|
||||||
|
|
||||||
|
if not defined WORKLOG_PORT set "WORKLOG_PORT=37777"
|
||||||
|
|
||||||
|
rem ---------- 1. stop the service listening on the port ----------
|
||||||
|
echo [1/2] Checking port %WORKLOG_PORT% ...
|
||||||
|
set "STOPPED="
|
||||||
|
for /f "tokens=5" %%P in ('netstat -ano ^| findstr /r /c:":%WORKLOG_PORT% .*LISTENING"') do (
|
||||||
|
if not "%%P"=="0" (
|
||||||
|
echo Stopping PID=%%P
|
||||||
|
taskkill /F /PID %%P >nul 2>&1
|
||||||
|
set "STOPPED=1"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
if defined STOPPED (
|
||||||
|
echo Local service stopped.
|
||||||
|
timeout /t 1 /nobreak >nul
|
||||||
|
) else (
|
||||||
|
echo Nothing listening on port %WORKLOG_PORT%.
|
||||||
|
)
|
||||||
|
|
||||||
|
rem ---------- 2. package ----------
|
||||||
|
for /f %%I in ('powershell -NoProfile -Command "Get-Date -Format yyyyMMdd-HHmmss"') do set "STAMP=%%I"
|
||||||
|
set "ZIP_NAME=worklog-%STAMP%.zip"
|
||||||
|
set "ZIP_PATH=%PROJECT_DIR%\%ZIP_NAME%"
|
||||||
|
set "STAGE=%TEMP%\worklog-pkg-%STAMP%"
|
||||||
|
|
||||||
|
echo [2/2] Packing ...
|
||||||
|
if exist "%STAGE%" rmdir /s /q "%STAGE%"
|
||||||
|
mkdir "%STAGE%" >nul 2>&1
|
||||||
|
|
||||||
|
rem Exclude dirs: __pycache__ / .venv / .git / data (data holds the database)
|
||||||
|
robocopy "%PROJECT_DIR%" "%STAGE%" /E /XD __pycache__ .venv .git data /XF .env .env.* .run-dev.log *.log *.pyc *.zip *.db *.db-* *.sqlite *.sqlite-* *.sqlite3 *.sqlite3-* *.bak* /NFL /NDL /NJH /NJS /NP >nul
|
||||||
|
if errorlevel 8 (
|
||||||
|
echo Copy failed, aborted.
|
||||||
|
rmdir /s /q "%STAGE%" >nul 2>&1
|
||||||
|
exit /b 1
|
||||||
|
)
|
||||||
|
copy /y "%PROJECT_DIR%\.env.example" "%STAGE%\.env.example" >nul
|
||||||
|
|
||||||
|
if exist "%ZIP_PATH%" del /f /q "%ZIP_PATH%"
|
||||||
|
rem Python zipfile keeps forward slashes in entry names (Compress-Archive writes backslashes)
|
||||||
|
python -c "import os,zipfile;S=r'%STAGE%';O=r'%ZIP_PATH%';z=zipfile.ZipFile(O,'w',zipfile.ZIP_DEFLATED);[z.write(os.path.join(R,f),os.path.relpath(os.path.join(R,f),S).replace(chr(92),'/')) for R,D,F in os.walk(S) for f in F];z.close()"
|
||||||
|
if errorlevel 1 (
|
||||||
|
echo Compression failed, aborted.
|
||||||
|
rmdir /s /q "%STAGE%" >nul 2>&1
|
||||||
|
exit /b 1
|
||||||
|
)
|
||||||
|
|
||||||
|
rmdir /s /q "%STAGE%" >nul 2>&1
|
||||||
|
|
||||||
|
for %%I in ("%ZIP_PATH%") do set "ZIP_SIZE=%%~zI"
|
||||||
|
echo.
|
||||||
|
echo Done: %ZIP_PATH%
|
||||||
|
echo Size: %ZIP_SIZE% bytes (database data/ excluded)
|
||||||
|
endlocal
|
||||||
+68
@@ -0,0 +1,68 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# 打包脚本:停掉本地正在运行的 WorkLog 服务,然后打成 zip(不含数据库/日志/运行产物)。
|
||||||
|
# 用法:bash package.sh (产物:worklog-<日期>.zip,放在项目同级目录)
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
PROJECT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
APP_NAME="WorkLog"
|
||||||
|
PORT="${WORKLOG_PORT:-37777}"
|
||||||
|
PYTHON="${PYTHON:-python}"
|
||||||
|
|
||||||
|
# ---------- 1. 关闭本地服务 ----------
|
||||||
|
# 优先按端口找进程(Windows 用 netstat,Linux/mac 用 lsof/ss)
|
||||||
|
stopped=0
|
||||||
|
if command -v netstat.exe >/dev/null 2>&1 && command -v taskkill.exe >/dev/null 2>&1; then
|
||||||
|
pids=$(netstat.exe -ano | grep -E "TCP.*:${PORT}\s.*LISTENING" | awk '{print $5}' | sort -u || true)
|
||||||
|
for pid in $pids; do
|
||||||
|
if [ -n "$pid" ] && [ "$pid" != "0" ]; then
|
||||||
|
echo "停止进程 PID=$pid (端口 $PORT)"
|
||||||
|
taskkill.exe //F //PID "$pid" || true
|
||||||
|
stopped=1
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
else
|
||||||
|
if command -v lsof >/dev/null 2>&1; then
|
||||||
|
pids=$(lsof -ti tcp:"$PORT" 2>/dev/null || true)
|
||||||
|
elif command -v ss >/dev/null 2>&1; then
|
||||||
|
pids=$(ss -lptn "sport = :$PORT" 2>/dev/null | grep -oP 'pid=\K[0-9]+' | sort -u)
|
||||||
|
else
|
||||||
|
pids=""
|
||||||
|
fi
|
||||||
|
for pid in $pids; do
|
||||||
|
echo "停止进程 PID=$pid (端口 $PORT)"
|
||||||
|
kill -9 "$pid" 2>/dev/null || true
|
||||||
|
stopped=1
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
[ "$stopped" = "1" ] && echo "本地服务已停止" || echo "端口 $PORT 上没有运行中的服务"
|
||||||
|
sleep 1
|
||||||
|
|
||||||
|
# ---------- 2. 打包 ----------
|
||||||
|
STAMP="$(date +%Y%m%d-%H%M%S)"
|
||||||
|
ZIP_NAME="worklog-${STAMP}.zip"
|
||||||
|
|
||||||
|
# 用 Python zipfile 打包(Windows Git Bash 无 zip 命令),排除数据库/日志/缓存
|
||||||
|
"$PYTHON" - "$PROJECT_DIR" "$ZIP_NAME" << 'PYEOF'
|
||||||
|
import fnmatch, os, sys, zipfile
|
||||||
|
|
||||||
|
project, zip_name = os.path.abspath(sys.argv[1]), sys.argv[2]
|
||||||
|
out_path = os.path.join(os.path.dirname(project), zip_name)
|
||||||
|
skip_dirs = {"__pycache__", ".venv", ".git", "data"}
|
||||||
|
skip_files = {".env", ".run-dev.log"}
|
||||||
|
skip_ext = (".pyc", ".zip", ".log")
|
||||||
|
|
||||||
|
with zipfile.ZipFile(out_path, "w", zipfile.ZIP_DEFLATED) as zf:
|
||||||
|
for root, dirs, files in os.walk(project):
|
||||||
|
dirs[:] = [d for d in dirs if d not in skip_dirs]
|
||||||
|
for f in files:
|
||||||
|
if (f in skip_files or f.endswith(skip_ext)
|
||||||
|
or (f.startswith('.env.') and f != '.env.example')
|
||||||
|
or any(fnmatch.fnmatch(f, pattern) for pattern in ('*.db', '*.db-*', '*.sqlite', '*.sqlite-*', '*.sqlite3', '*.sqlite3-*', '*.bak*'))):
|
||||||
|
continue
|
||||||
|
full = os.path.join(root, f)
|
||||||
|
arc = os.path.relpath(full, project).replace(os.sep, "/")
|
||||||
|
zf.write(full, arc)
|
||||||
|
print("packed ->", out_path)
|
||||||
|
PYEOF
|
||||||
|
|
||||||
|
echo "打包完成:$(dirname "$PROJECT_DIR")/$ZIP_NAME"
|
||||||
+248
@@ -0,0 +1,248 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""WorkLog 数据库损坏检测与修复脚本(Windows / Linux 通用,只用标准库)。
|
||||||
|
|
||||||
|
用法:
|
||||||
|
python repair_db.py --check 只做完整性检测
|
||||||
|
python repair_db.py 检测,损坏则恢复到 <库名>.recovered
|
||||||
|
python repair_db.py --replace -y 恢复后用修复库替换原库(坏库存为 .corrupt-时间戳)
|
||||||
|
|
||||||
|
说明:
|
||||||
|
"database disk image is malformed" 表示数据库文件损坏,常见诱因:
|
||||||
|
服务运行中直接拷贝/上传覆盖了 db 文件、文件传输被截断、磁盘写满、
|
||||||
|
残留的 -wal/-shm 文件与主库不匹配。
|
||||||
|
修复优先用 sqlite3 命令行的 .recover(最完整);没有 sqlite3 命令时
|
||||||
|
退化为逐表读取复制(损坏页所在表的数据可能缺失,脚本会逐表报告)。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import sqlite3
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
PROJECT_DIR = Path(__file__).resolve().parent
|
||||||
|
TABLES = ("users", "sessions", "email_verifications", "activities", "participations")
|
||||||
|
SIDE_SUFFIXES = ("-wal", "-shm", "-journal")
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_db_path(explicit: str | None) -> Path:
|
||||||
|
"""与 server/main.py / clear_db.py 一致:--db > WORKLOG_DB > config.toml > ./data/worklog.db"""
|
||||||
|
raw = explicit or os.getenv("WORKLOG_DB")
|
||||||
|
if not raw:
|
||||||
|
raw = "./data/worklog.db"
|
||||||
|
config_path = Path(os.getenv("WORKLOG_CONFIG", str(PROJECT_DIR / "config.toml")))
|
||||||
|
try:
|
||||||
|
import tomllib
|
||||||
|
|
||||||
|
with open(config_path, "rb") as fh:
|
||||||
|
cfg = tomllib.load(fh)
|
||||||
|
raw = cfg.get("database", {}).get("path", raw)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
path = Path(raw)
|
||||||
|
return path if path.is_absolute() else PROJECT_DIR / path
|
||||||
|
|
||||||
|
|
||||||
|
def integrity_report(path: Path) -> tuple[bool, str]:
|
||||||
|
"""返回 (是否完好, 详情)。只读打开,不改动文件。"""
|
||||||
|
try:
|
||||||
|
conn = sqlite3.connect(f"file:{path}?mode=ro", uri=True)
|
||||||
|
except sqlite3.DatabaseError as exc:
|
||||||
|
return False, f"无法打开数据库:{exc}"
|
||||||
|
try:
|
||||||
|
rows = conn.execute("PRAGMA integrity_check").fetchall()
|
||||||
|
except sqlite3.DatabaseError as exc:
|
||||||
|
return False, str(exc)
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
bad = [r[0] for r in rows if r[0] != "ok"]
|
||||||
|
return (not bad), ("ok" if not bad else ";".join(bad[:5]))
|
||||||
|
|
||||||
|
|
||||||
|
def table_counts(path: Path) -> dict[str, int | None]:
|
||||||
|
counts: dict[str, int | None] = {}
|
||||||
|
try:
|
||||||
|
conn = sqlite3.connect(f"file:{path}?mode=ro", uri=True)
|
||||||
|
except sqlite3.DatabaseError:
|
||||||
|
return {t: None for t in TABLES}
|
||||||
|
for table in TABLES:
|
||||||
|
try:
|
||||||
|
counts[table] = conn.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0]
|
||||||
|
except sqlite3.DatabaseError:
|
||||||
|
counts[table] = None
|
||||||
|
conn.close()
|
||||||
|
return counts
|
||||||
|
|
||||||
|
|
||||||
|
def recover_with_cli(src: Path, dst: Path) -> bool:
|
||||||
|
"""sqlite3 命令行可用时用 .recover,最完整。"""
|
||||||
|
cli = shutil.which("sqlite3")
|
||||||
|
if not cli:
|
||||||
|
return False
|
||||||
|
proc = subprocess.run([cli, str(src), ".recover"], capture_output=True, text=True)
|
||||||
|
if proc.returncode != 0 or not proc.stdout.strip():
|
||||||
|
return False
|
||||||
|
dst.unlink(missing_ok=True)
|
||||||
|
out = sqlite3.connect(str(dst))
|
||||||
|
try:
|
||||||
|
out.executescript(proc.stdout)
|
||||||
|
out.commit()
|
||||||
|
except sqlite3.DatabaseError:
|
||||||
|
out.close()
|
||||||
|
return False
|
||||||
|
out.close()
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def recover_with_python(src: Path, dst: Path) -> tuple[bool, list[str]]:
|
||||||
|
"""兜底方案:只读打开坏库,逐表复制到新库。返回 (是否成功, 说明)。"""
|
||||||
|
notes: list[str] = []
|
||||||
|
try:
|
||||||
|
ro = sqlite3.connect(f"file:{src}?mode=ro&immutable=1", uri=True)
|
||||||
|
except sqlite3.DatabaseError as exc:
|
||||||
|
return False, [f"坏库打不开:{exc}"]
|
||||||
|
try:
|
||||||
|
master = ro.execute(
|
||||||
|
"SELECT type, name, sql FROM sqlite_master WHERE sql IS NOT NULL"
|
||||||
|
).fetchall()
|
||||||
|
except sqlite3.DatabaseError as exc:
|
||||||
|
ro.close()
|
||||||
|
return False, [f"连表结构都读不出来,无法恢复({exc}),只能删库重建。"]
|
||||||
|
|
||||||
|
dst.unlink(missing_ok=True)
|
||||||
|
out = sqlite3.connect(str(dst))
|
||||||
|
tables: list[str] = []
|
||||||
|
for typ, name, sql in master:
|
||||||
|
if name.startswith("sqlite_"):
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
out.execute(sql)
|
||||||
|
if typ == "table":
|
||||||
|
tables.append(name)
|
||||||
|
except sqlite3.DatabaseError as exc:
|
||||||
|
notes.append(f"跳过 {typ} {name}:{exc}")
|
||||||
|
out.commit()
|
||||||
|
|
||||||
|
for table in tables:
|
||||||
|
recovered = 0
|
||||||
|
truncated = False
|
||||||
|
try:
|
||||||
|
cur = ro.execute(f'SELECT * FROM "{table}"')
|
||||||
|
except sqlite3.DatabaseError as exc:
|
||||||
|
notes.append(f"表 {table} 无法读取:{exc}")
|
||||||
|
continue
|
||||||
|
cols = [d[0] for d in cur.description]
|
||||||
|
col_list = ",".join(f'"{c}"' for c in cols)
|
||||||
|
marks = ",".join("?" * len(cols))
|
||||||
|
insert = f'INSERT OR IGNORE INTO "{table}" ({col_list}) VALUES ({marks})'
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
batch = cur.fetchmany(200)
|
||||||
|
except sqlite3.DatabaseError as exc:
|
||||||
|
notes.append(f"表 {table} 读取中断于第 {recovered} 行之后:{exc}")
|
||||||
|
truncated = True
|
||||||
|
break
|
||||||
|
if not batch:
|
||||||
|
break
|
||||||
|
try:
|
||||||
|
out.executemany(insert, batch)
|
||||||
|
out.commit()
|
||||||
|
recovered += len(batch)
|
||||||
|
except sqlite3.DatabaseError:
|
||||||
|
# 这一批里混着坏行,逐行抢救能救多少是多少
|
||||||
|
for row in batch:
|
||||||
|
try:
|
||||||
|
out.execute(insert, row)
|
||||||
|
recovered += 1
|
||||||
|
except sqlite3.DatabaseError:
|
||||||
|
pass
|
||||||
|
out.commit()
|
||||||
|
print(f" 表 {table}: 恢复 {recovered} 行" + ("(有缺失)" if truncated else ""))
|
||||||
|
|
||||||
|
out.commit()
|
||||||
|
out.close()
|
||||||
|
ro.close()
|
||||||
|
return True, notes
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
parser = argparse.ArgumentParser(description="WorkLog 数据库损坏检测与修复")
|
||||||
|
parser.add_argument("--db", help="数据库文件路径(默认 WORKLOG_DB / config.toml)")
|
||||||
|
parser.add_argument("--check", action="store_true", help="只检测,不修复")
|
||||||
|
parser.add_argument("--replace", action="store_true", help="修复成功后替换原库(坏库自动备份)")
|
||||||
|
parser.add_argument("-y", "--yes", action="store_true", help="跳过确认")
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
db_path = resolve_db_path(args.db)
|
||||||
|
if not db_path.exists():
|
||||||
|
print(f"[!] 数据库不存在:{db_path}")
|
||||||
|
return 1
|
||||||
|
|
||||||
|
print(f"数据库:{db_path} ({db_path.stat().st_size / 1024:.0f} KB)")
|
||||||
|
for suffix in SIDE_SUFFIXES:
|
||||||
|
side = db_path.with_name(db_path.name + suffix)
|
||||||
|
if side.exists():
|
||||||
|
print(f" 注意:存在伴随文件 {side.name} ({side.stat().st_size / 1024:.0f} KB)")
|
||||||
|
|
||||||
|
healthy, report = integrity_report(db_path)
|
||||||
|
if healthy:
|
||||||
|
print("完整性检查:通过,数据库没有损坏。")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
print(f"完整性检查:损坏({report})")
|
||||||
|
if args.check:
|
||||||
|
return 1
|
||||||
|
|
||||||
|
if not args.yes:
|
||||||
|
print("修复前请确认服务已停止(运行中的服务继续写坏库会越写越糟)。")
|
||||||
|
if input("输入 yes 继续: ").strip().lower() != "yes":
|
||||||
|
print("已取消。")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
recovered_path = db_path.with_suffix(db_path.suffix + ".recovered")
|
||||||
|
notes: list[str] = []
|
||||||
|
if recover_with_cli(db_path, recovered_path):
|
||||||
|
print("已用 sqlite3 .recover 完成恢复。")
|
||||||
|
else:
|
||||||
|
print("sqlite3 命令行不可用,用逐表复制方式恢复……")
|
||||||
|
ok, notes = recover_with_python(db_path, recovered_path)
|
||||||
|
if not ok:
|
||||||
|
for line in notes:
|
||||||
|
print(f" {line}")
|
||||||
|
print("[!] 恢复失败。若数据不重要,删除该库重启服务即可重建空库。")
|
||||||
|
return 1
|
||||||
|
|
||||||
|
ok2, report2 = integrity_report(recovered_path)
|
||||||
|
print(f"修复库完整性:{'通过' if ok2 else '仍有问题(' + report2 + ')'}")
|
||||||
|
print("修复后各表行数:")
|
||||||
|
for table, count in table_counts(recovered_path).items():
|
||||||
|
print(f" {table:<20}{count if count is not None else '(表不存在)'}")
|
||||||
|
for line in notes:
|
||||||
|
print(f" 备注:{line}")
|
||||||
|
|
||||||
|
if args.replace:
|
||||||
|
stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
|
||||||
|
corrupt_backup = db_path.with_name(f"{db_path.name}.corrupt-{stamp}")
|
||||||
|
db_path.rename(corrupt_backup)
|
||||||
|
for suffix in SIDE_SUFFIXES:
|
||||||
|
side = db_path.with_name(db_path.name + suffix)
|
||||||
|
if side.exists():
|
||||||
|
# 旧库的 wal/shm 绝不能留给新库用,一并挪走
|
||||||
|
side.rename(db_path.with_name(f"{db_path.name}{suffix}.corrupt-{stamp}"))
|
||||||
|
recovered_path.replace(db_path)
|
||||||
|
print(f"已替换。坏库保留在:{corrupt_backup}")
|
||||||
|
print("现在可以启动服务了(python -m server.main 或 bash start.sh)。")
|
||||||
|
else:
|
||||||
|
print(f"修复库在:{recovered_path}")
|
||||||
|
print("确认无误后手动替换:")
|
||||||
|
print(f" mv {db_path} {db_path}.corrupt && mv {recovered_path} {db_path}")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
fastapi>=0.115,<1
|
||||||
|
uvicorn[standard]>=0.30,<1
|
||||||
|
SQLAlchemy>=2.0.36,<3
|
||||||
|
aiosqlite>=0.20,<1
|
||||||
|
aiosmtplib>=3,<6
|
||||||
|
pydantic>=2.7,<3
|
||||||
|
# 仅测试时需要
|
||||||
|
httpx>=0.27,<1
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""WorkLog 活动记录网站后端包。"""
|
||||||
+1495
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,131 @@
|
|||||||
|
"""数据库表结构(SQLAlchemy Core)。
|
||||||
|
|
||||||
|
四张表:users(账号)、sessions(登录会话)、activities(活动)、
|
||||||
|
participations(参加记录,也就是"某人参加过某活动"这一事实)。
|
||||||
|
时间统一存毫秒时间戳整数,前端用 new Date(ms) 渲染。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from sqlalchemy import (
|
||||||
|
Column,
|
||||||
|
ForeignKey,
|
||||||
|
Index,
|
||||||
|
Integer,
|
||||||
|
MetaData,
|
||||||
|
String,
|
||||||
|
Table,
|
||||||
|
Text,
|
||||||
|
UniqueConstraint,
|
||||||
|
func,
|
||||||
|
)
|
||||||
|
|
||||||
|
metadata = MetaData()
|
||||||
|
|
||||||
|
auth_limits = Table(
|
||||||
|
"auth_limits", metadata,
|
||||||
|
Column("key", String(64), primary_key=True),
|
||||||
|
Column("window_start", Integer, nullable=False),
|
||||||
|
Column("count", Integer, nullable=False),
|
||||||
|
)
|
||||||
|
|
||||||
|
users = Table(
|
||||||
|
"users",
|
||||||
|
metadata,
|
||||||
|
Column("id", String(36), primary_key=True),
|
||||||
|
Column("username", String(64), nullable=False, unique=True),
|
||||||
|
Column("display_name", String(64), nullable=False),
|
||||||
|
Column("department", String(64), nullable=False, default=""),
|
||||||
|
Column("email", String(255), nullable=False, default=""),
|
||||||
|
# 登录改为邮箱+验证码后不再用密码,但列保留(老数据兼容)
|
||||||
|
Column("password_hash", String(255), nullable=False, default=""),
|
||||||
|
# 邮箱用于验证码登录;新用户注册必填手机号,一人一号(历史空值保留兼容)
|
||||||
|
Column("phone", String(11), nullable=False, default=""),
|
||||||
|
# 遗留列:管理员体系已移除,但老库的 role 列带 NOT NULL 约束,插入必须带上
|
||||||
|
Column("role", String(16), nullable=False, default="member"),
|
||||||
|
Column("bio", String(200), nullable=False, default=""),
|
||||||
|
Column("created_at", Integer, nullable=False),
|
||||||
|
Column("last_login_at", Integer, nullable=False, default=0),
|
||||||
|
)
|
||||||
|
Index("ix_users_email", users.c.email)
|
||||||
|
Index("uq_users_email", func.lower(users.c.email), unique=True, sqlite_where=users.c.email != "")
|
||||||
|
Index("uq_users_phone", users.c.phone, unique=True, sqlite_where=users.c.phone != "")
|
||||||
|
|
||||||
|
email_verifications = Table(
|
||||||
|
"email_verifications",
|
||||||
|
metadata,
|
||||||
|
Column("id", String(36), primary_key=True),
|
||||||
|
Column("email", String(255), nullable=False),
|
||||||
|
Column("code", String(255), nullable=False),
|
||||||
|
Column("attempts", Integer, nullable=False, default=0),
|
||||||
|
# 预留:register / reset 等用途
|
||||||
|
Column("purpose", String(32), nullable=False, default="register"),
|
||||||
|
Column("expires_at", Integer, nullable=False),
|
||||||
|
Column("used", Integer, nullable=False, default=0),
|
||||||
|
Column("created_at", Integer, nullable=False),
|
||||||
|
)
|
||||||
|
Index("ix_email_verifications_email", email_verifications.c.email)
|
||||||
|
|
||||||
|
sessions = Table(
|
||||||
|
"sessions",
|
||||||
|
metadata,
|
||||||
|
Column("token", String(64), primary_key=True),
|
||||||
|
Column("user_id", String(36), ForeignKey("users.id", ondelete="CASCADE"), nullable=False),
|
||||||
|
Column("created_at", Integer, nullable=False),
|
||||||
|
Column("expires_at", Integer, nullable=False),
|
||||||
|
)
|
||||||
|
Index("ix_sessions_user", sessions.c.user_id)
|
||||||
|
|
||||||
|
activities = Table(
|
||||||
|
"activities",
|
||||||
|
metadata,
|
||||||
|
Column("id", String(36), primary_key=True),
|
||||||
|
Column("title", String(120), nullable=False),
|
||||||
|
Column("start_at", Integer, nullable=False),
|
||||||
|
Column("location", String(120), nullable=False, default=""),
|
||||||
|
Column("description", Text, nullable=False, default=""),
|
||||||
|
Column("visibility", String(16), nullable=False, default="public"),
|
||||||
|
# 名额上限;NULL 表示不限
|
||||||
|
Column("capacity", Integer, nullable=True),
|
||||||
|
# 兼容老库保留该列;无审核流后恒为 approved
|
||||||
|
Column("status", String(16), nullable=False, default="approved"),
|
||||||
|
Column("organizer_id", String(36), ForeignKey("users.id"), nullable=False),
|
||||||
|
Column("created_at", Integer, nullable=False),
|
||||||
|
Column("updated_at", Integer, nullable=False),
|
||||||
|
)
|
||||||
|
Index("ix_activities_start", activities.c.start_at)
|
||||||
|
Index("ix_activities_organizer", activities.c.organizer_id)
|
||||||
|
|
||||||
|
participations = Table(
|
||||||
|
"participations",
|
||||||
|
metadata,
|
||||||
|
Column("id", String(36), primary_key=True),
|
||||||
|
Column("activity_id", String(36), ForeignKey("activities.id", ondelete="CASCADE"), nullable=False),
|
||||||
|
Column("user_id", String(36), ForeignKey("users.id", ondelete="CASCADE"), nullable=False),
|
||||||
|
# organizer 为发起人,member 为共同参加人("我也参加过")
|
||||||
|
Column("role", String(16), nullable=False, default="member"),
|
||||||
|
# 参加状态:joined 已确认 / attended 已参加 / absent 缺席
|
||||||
|
Column("status", String(16), nullable=False, default="joined"),
|
||||||
|
Column("note", String(500), nullable=False, default=""),
|
||||||
|
Column("joined_at", Integer, nullable=False),
|
||||||
|
Column("updated_at", Integer, nullable=False),
|
||||||
|
UniqueConstraint("activity_id", "user_id", name="uq_participation_activity_user"),
|
||||||
|
)
|
||||||
|
Index("ix_participations_user", participations.c.user_id)
|
||||||
|
|
||||||
|
join_links = Table(
|
||||||
|
"join_links",
|
||||||
|
metadata,
|
||||||
|
# 邮件"一键我也参加过"的令牌:点一次即消费,转正为一条参加记录
|
||||||
|
Column("id", String(36), primary_key=True),
|
||||||
|
Column("token", String(64), nullable=False, unique=True),
|
||||||
|
Column("activity_id", String(36), ForeignKey("activities.id", ondelete="CASCADE"), nullable=False),
|
||||||
|
Column("user_id", String(36), ForeignKey("users.id", ondelete="CASCADE"), nullable=False),
|
||||||
|
Column("expires_at", Integer, nullable=False),
|
||||||
|
# 0=可用 1=已点击 2=已失效(活动删除等)
|
||||||
|
Column("used", Integer, nullable=False, default=0),
|
||||||
|
Column("created_at", Integer, nullable=False),
|
||||||
|
)
|
||||||
|
Index("ix_join_links_activity", join_links.c.activity_id)
|
||||||
|
|
||||||
|
TABLES = (users, sessions, email_verifications, activities, participations, join_links)
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
"""口令散列与登录令牌。只依赖标准库,避免额外依赖。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
|
import secrets
|
||||||
|
|
||||||
|
ALGORITHM = "pbkdf2_sha256"
|
||||||
|
ITERATIONS = 240_000
|
||||||
|
|
||||||
|
|
||||||
|
def hash_password(password: str) -> str:
|
||||||
|
"""返回 pbkdf2_sha256$<迭代次数>$<盐hex>$<摘要hex>。"""
|
||||||
|
salt = secrets.token_bytes(16)
|
||||||
|
digest = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, ITERATIONS)
|
||||||
|
return f"{ALGORITHM}${ITERATIONS}${salt.hex()}${digest.hex()}"
|
||||||
|
|
||||||
|
|
||||||
|
def verify_password(password: str, stored: str) -> bool:
|
||||||
|
try:
|
||||||
|
algorithm, iterations, salt_hex, digest_hex = stored.split("$")
|
||||||
|
if algorithm != ALGORITHM:
|
||||||
|
return False
|
||||||
|
digest = hashlib.pbkdf2_hmac(
|
||||||
|
"sha256", password.encode("utf-8"), bytes.fromhex(salt_hex), int(iterations)
|
||||||
|
)
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
return False
|
||||||
|
return hmac.compare_digest(digest.hex(), digest_hex)
|
||||||
|
|
||||||
|
|
||||||
|
def new_token() -> str:
|
||||||
|
"""会话令牌,43 个字符的 URL 安全随机串。"""
|
||||||
|
return secrets.token_urlsafe(32)
|
||||||
|
|
||||||
|
|
||||||
|
def token_digest(token: str) -> str:
|
||||||
|
"""数据库只保存高熵令牌的摘要,数据库副本不能直接充当登录凭据。"""
|
||||||
|
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
#!/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, aiosmtplib, tomllib; from pydantic import field_validator" >/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
|
||||||
Reference in New Issue
Block a user