749 lines
28 KiB
Python
749 lines
28 KiB
Python
#!/usr/bin/env python3
|
||
# -*- coding: utf-8 -*-
|
||
"""数据库模块"""
|
||
import sqlite3
|
||
from pathlib import Path
|
||
|
||
import os
|
||
from runtime_mode import PREVIEW_MODE
|
||
DB_PATH = Path(os.environ.get("XBNIU_DB_PATH") or (Path(__file__).parent / ("preview.db" if PREVIEW_MODE else "users.db")))
|
||
if PREVIEW_MODE and DB_PATH.name == "users.db":
|
||
raise RuntimeError("Preview mode must use a separate database")
|
||
DB_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||
|
||
DEFAULT_RENTAL_SETTINGS = {
|
||
"reminder_enabled": True,
|
||
"reminder_minutes": [5, 3, 0],
|
||
"rental_duration_minutes": 19,
|
||
"auto_return_enabled": True,
|
||
# 总轮次包含首轮;默认 1 保持旧行为。
|
||
"rental_rounds": 1,
|
||
"protect_card": True,
|
||
}
|
||
ALLOWED_REMINDER_MINUTES = (10, 5, 3, 2, 1, 0)
|
||
MIN_RENTAL_ROUNDS = 1
|
||
MAX_RENTAL_ROUNDS = 20
|
||
|
||
|
||
def get_db():
|
||
"""获取数据库连接(WAL + 忙等待,避免多线程写入时 database is locked)"""
|
||
conn = sqlite3.connect(str(DB_PATH))
|
||
conn.row_factory = sqlite3.Row
|
||
conn.execute("PRAGMA journal_mode=WAL")
|
||
conn.execute("PRAGMA busy_timeout=5000")
|
||
return conn
|
||
|
||
|
||
def init_db():
|
||
"""初始化数据库"""
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
|
||
cursor.execute("""
|
||
CREATE TABLE IF NOT EXISTS users (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
email TEXT UNIQUE NOT NULL,
|
||
password_hash TEXT NOT NULL,
|
||
access_token TEXT,
|
||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||
reminder_enabled INTEGER NOT NULL DEFAULT 1,
|
||
reminder_minutes TEXT NOT NULL DEFAULT '5,3,0',
|
||
rental_duration_minutes INTEGER NOT NULL DEFAULT 19,
|
||
auto_return_enabled INTEGER NOT NULL DEFAULT 1,
|
||
rental_rounds INTEGER NOT NULL DEFAULT 1,
|
||
protect_card INTEGER NOT NULL DEFAULT 1
|
||
)
|
||
""")
|
||
|
||
# 迁移:老库的 wx_signature 列重命名为 access_token(语义变更:存 accessToken 而非一次性签名)
|
||
try:
|
||
cursor.execute("ALTER TABLE users RENAME COLUMN wx_signature TO access_token")
|
||
except sqlite3.OperationalError:
|
||
pass # 已重命名过或新库
|
||
for col in ["token_id", "access_token"]:
|
||
try:
|
||
cursor.execute(f"ALTER TABLE users ADD COLUMN {col} TEXT")
|
||
except sqlite3.OperationalError:
|
||
pass
|
||
for col_def in [
|
||
("reminder_enabled", "INTEGER NOT NULL DEFAULT 1"),
|
||
("reminder_minutes", "TEXT NOT NULL DEFAULT '5,3,0'"),
|
||
("rental_duration_minutes", "INTEGER NOT NULL DEFAULT 19"),
|
||
("auto_return_enabled", "INTEGER NOT NULL DEFAULT 1"),
|
||
("rental_rounds", "INTEGER NOT NULL DEFAULT 1"),
|
||
("protect_card", "INTEGER NOT NULL DEFAULT 1"),
|
||
]:
|
||
try:
|
||
cursor.execute(f"ALTER TABLE users ADD COLUMN {col_def[0]} {col_def[1]}")
|
||
except sqlite3.OperationalError:
|
||
pass
|
||
# 老数据清洗:40 位 hex 是抓包的一次性 hsf-x-signature,不是 accessToken(JWT 以 eyJ 开头),置空
|
||
try:
|
||
cursor.execute("""
|
||
UPDATE users SET access_token = NULL
|
||
WHERE access_token IS NOT NULL
|
||
AND length(access_token) = 40
|
||
AND access_token NOT LIKE 'eyJ%'
|
||
""")
|
||
except sqlite3.OperationalError:
|
||
pass
|
||
|
||
cursor.execute("""
|
||
CREATE TABLE IF NOT EXISTS sessions (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
user_id INTEGER NOT NULL,
|
||
token TEXT UNIQUE NOT NULL,
|
||
expires_at TIMESTAMP NOT NULL,
|
||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||
FOREIGN KEY (user_id) REFERENCES users(id)
|
||
)
|
||
""")
|
||
|
||
# 多设备登录:为每台设备记录标识信息(用于“我的 → 登录设备管理”展示与下线)
|
||
for col_def in [("device_name", "TEXT"), ("device_id", "TEXT"),
|
||
("user_agent", "TEXT"), ("last_active", "TIMESTAMP")]:
|
||
try:
|
||
cursor.execute(f"ALTER TABLE sessions ADD COLUMN {col_def[0]} {col_def[1]}")
|
||
except sqlite3.OperationalError:
|
||
pass
|
||
|
||
cursor.execute("""
|
||
CREATE TABLE IF NOT EXISTS reminders (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
user_id INTEGER NOT NULL,
|
||
bike_code TEXT NOT NULL,
|
||
email TEXT NOT NULL,
|
||
duration INTEGER NOT NULL,
|
||
start_time TIMESTAMP,
|
||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||
FOREIGN KEY (user_id) REFERENCES users(id)
|
||
)
|
||
""")
|
||
|
||
cursor.execute("""
|
||
CREATE TABLE IF NOT EXISTS rentals (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
order_id TEXT,
|
||
bike_code TEXT NOT NULL,
|
||
email TEXT NOT NULL,
|
||
user_id INTEGER,
|
||
start_time TIMESTAMP NOT NULL,
|
||
end_time TIMESTAMP NOT NULL,
|
||
expired INTEGER DEFAULT 0,
|
||
source TEXT DEFAULT 'reminder',
|
||
notified_10 INTEGER DEFAULT 0,
|
||
notified_5 INTEGER DEFAULT 0,
|
||
notified_3 INTEGER DEFAULT 0,
|
||
notified_2 INTEGER DEFAULT 0,
|
||
notified_1 INTEGER DEFAULT 0,
|
||
notified_0 INTEGER DEFAULT 0,
|
||
renewal_round INTEGER NOT NULL DEFAULT 1,
|
||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||
)
|
||
""")
|
||
|
||
# 邮件一键还车的能力令牌。数据库只保存 SHA-256 摘要,
|
||
# 邮件中的原始 token 泄漏数据库时不可被反推。
|
||
cursor.execute("""
|
||
CREATE TABLE IF NOT EXISTS rental_return_tokens (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
rental_id INTEGER NOT NULL,
|
||
token_hash TEXT UNIQUE NOT NULL,
|
||
expires_at TIMESTAMP NOT NULL,
|
||
used_at TIMESTAMP,
|
||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||
FOREIGN KEY (rental_id) REFERENCES rentals(id)
|
||
)
|
||
""")
|
||
cursor.execute("""
|
||
CREATE INDEX IF NOT EXISTS idx_return_tokens_rental
|
||
ON rental_return_tokens(rental_id)
|
||
""")
|
||
|
||
for col in ["duration", "notified_10", "notified_5", "notified_3",
|
||
"notified_2", "notified_1", "notified_0", "user_id",
|
||
"renewal_round"]:
|
||
try:
|
||
if col == "user_id":
|
||
cursor.execute(f"ALTER TABLE rentals ADD COLUMN {col} INTEGER")
|
||
elif col == "renewal_round":
|
||
cursor.execute(f"ALTER TABLE rentals ADD COLUMN {col} INTEGER NOT NULL DEFAULT 1")
|
||
else:
|
||
cursor.execute(f"ALTER TABLE rentals ADD COLUMN {col} INTEGER DEFAULT 0")
|
||
except sqlite3.OperationalError:
|
||
pass
|
||
|
||
cursor.execute("""
|
||
CREATE TABLE IF NOT EXISTS bike_history (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
bike_code TEXT NOT NULL,
|
||
latitude REAL,
|
||
longitude REAL,
|
||
status INTEGER DEFAULT 1,
|
||
state INTEGER DEFAULT 1,
|
||
electric REAL DEFAULT 100,
|
||
recorded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||
)
|
||
""")
|
||
|
||
for col_def in [("state", "INTEGER DEFAULT 1"), ("electric", "REAL DEFAULT 100")]:
|
||
try:
|
||
cursor.execute(f"ALTER TABLE bike_history ADD COLUMN {col_def[0]} {col_def[1]}")
|
||
except sqlite3.OperationalError:
|
||
pass
|
||
|
||
# 分析查询均按 bike_code / recorded_at 过滤,无索引会全表扫描
|
||
cursor.execute("""
|
||
CREATE INDEX IF NOT EXISTS idx_history_code_time
|
||
ON bike_history(bike_code, recorded_at)
|
||
""")
|
||
cursor.execute("CREATE INDEX IF NOT EXISTS idx_history_time ON bike_history(recorded_at)")
|
||
|
||
cursor.execute("""
|
||
CREATE TABLE IF NOT EXISTS snapshots (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
snapshot_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||
total_bikes INTEGER DEFAULT 0,
|
||
available_count INTEGER DEFAULT 0,
|
||
inuse_count INTEGER DEFAULT 0,
|
||
locked_count INTEGER DEFAULT 0,
|
||
reserved_count INTEGER DEFAULT 0,
|
||
low_count INTEGER DEFAULT 0,
|
||
data_json TEXT,
|
||
source TEXT DEFAULT 'web',
|
||
recorded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||
)
|
||
""")
|
||
|
||
try:
|
||
cursor.execute("ALTER TABLE rentals ADD COLUMN source TEXT DEFAULT 'reminder'")
|
||
except sqlite3.OperationalError:
|
||
pass
|
||
try:
|
||
cursor.execute("ALTER TABLE rentals ADD COLUMN order_id TEXT")
|
||
except sqlite3.OperationalError:
|
||
pass
|
||
try:
|
||
cursor.execute("ALTER TABLE rentals ADD COLUMN rider_user_id INTEGER")
|
||
except sqlite3.OperationalError:
|
||
pass
|
||
|
||
# 兼容修复:历史遗留的共享订单若 source 未被正确标记,按 rider_user_id 回填
|
||
try:
|
||
cursor.execute("""
|
||
UPDATE rentals SET source = 'shared'
|
||
WHERE rider_user_id IS NOT NULL AND rider_user_id != user_id
|
||
AND (source IS NULL OR source != 'shared')
|
||
""")
|
||
except sqlite3.OperationalError:
|
||
pass
|
||
|
||
# ===== 共享电动车 =====
|
||
cursor.execute("""
|
||
CREATE TABLE IF NOT EXISTS share_requests (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
from_user_id INTEGER NOT NULL,
|
||
to_user_id INTEGER NOT NULL,
|
||
status TEXT NOT NULL DEFAULT 'pending',
|
||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||
)
|
||
""")
|
||
|
||
cursor.execute("""
|
||
CREATE TABLE IF NOT EXISTS shares (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
owner_user_id INTEGER NOT NULL,
|
||
rider_user_id INTEGER NOT NULL,
|
||
daily_limit INTEGER NOT NULL DEFAULT 3,
|
||
require_card INTEGER NOT NULL DEFAULT 0,
|
||
card_min_times INTEGER NOT NULL DEFAULT 0,
|
||
status TEXT NOT NULL DEFAULT 'active',
|
||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||
unbound_by INTEGER
|
||
)
|
||
""")
|
||
try:
|
||
cursor.execute("CREATE UNIQUE INDEX IF NOT EXISTS idx_shares_pair ON shares(owner_user_id, rider_user_id)")
|
||
except sqlite3.OperationalError:
|
||
pass
|
||
|
||
# 共享电动车:双方给对方起的私密昵称备注(微信式给备注)
|
||
# owner_remark = 共享方(owner) 给 用车方(rider) 起的备注(owner 侧显示)
|
||
# rider_remark = 用车方(rider) 给 共享方(owner) 起的备注(rider 侧显示)
|
||
for _col in ["owner_remark", "rider_remark"]:
|
||
try:
|
||
cursor.execute(f"ALTER TABLE shares ADD COLUMN {_col} TEXT")
|
||
except sqlite3.OperationalError:
|
||
pass
|
||
|
||
cursor.execute("""
|
||
CREATE TABLE IF NOT EXISTS share_usage (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
owner_user_id INTEGER NOT NULL,
|
||
rider_user_id INTEGER NOT NULL,
|
||
use_date TEXT NOT NULL,
|
||
used_count INTEGER NOT NULL DEFAULT 0,
|
||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||
)
|
||
""")
|
||
try:
|
||
cursor.execute("CREATE UNIQUE INDEX IF NOT EXISTS idx_share_usage_day ON share_usage(owner_user_id, rider_user_id, use_date)")
|
||
except sqlite3.OperationalError:
|
||
pass
|
||
|
||
# ===== 注册邀请码(管理员签发,注册时必填并核销) =====
|
||
cursor.execute("""
|
||
CREATE TABLE IF NOT EXISTS invite_codes (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
code TEXT UNIQUE NOT NULL,
|
||
max_uses INTEGER NOT NULL DEFAULT 1,
|
||
used_count INTEGER NOT NULL DEFAULT 0,
|
||
used_by TEXT NOT NULL DEFAULT '',
|
||
note TEXT NOT NULL DEFAULT '',
|
||
disabled INTEGER NOT NULL DEFAULT 0,
|
||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||
)
|
||
""")
|
||
|
||
# ===== 校园地点(教学楼/兴趣点 POI + 停车区) =====
|
||
# 坐标统一存 GCJ02(与上游车辆接口同一坐标系);前端点选得到的是百度 BD09,
|
||
# 入库前先经 coordtransform.bd09togcj02 转换。polygon 为 JSON 数组 [[lat,lng],...]。
|
||
cursor.execute("""
|
||
CREATE TABLE IF NOT EXISTS campus_locations (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
name TEXT NOT NULL,
|
||
kind TEXT NOT NULL DEFAULT 'poi',
|
||
latitude REAL,
|
||
longitude REAL,
|
||
radius INTEGER,
|
||
polygon TEXT,
|
||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||
)
|
||
""")
|
||
try:
|
||
cursor.execute("ALTER TABLE campus_locations ADD COLUMN radius INTEGER")
|
||
except sqlite3.OperationalError:
|
||
pass
|
||
|
||
# ===== 订单起终点(从哪里骑到哪里)+ 实际还车时间 + 轮次覆盖 =====
|
||
for col_def in [
|
||
("start_latitude", "REAL"), ("start_longitude", "REAL"),
|
||
("end_latitude", "REAL"), ("end_longitude", "REAL"),
|
||
("start_label", "TEXT"), ("end_label", "TEXT"),
|
||
("returned_at", "TIMESTAMP"),
|
||
("rounds_override", "INTEGER"),
|
||
]:
|
||
try:
|
||
cursor.execute(f"ALTER TABLE rentals ADD COLUMN {col_def[0]} {col_def[1]}")
|
||
except sqlite3.OperationalError:
|
||
pass
|
||
|
||
# ===== 用车订阅规则(定时查看某停车点附近车辆,可选自动开锁) =====
|
||
cursor.execute("""
|
||
CREATE TABLE IF NOT EXISTS subscribe_rules (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
user_id INTEGER NOT NULL,
|
||
location_id INTEGER,
|
||
weekday INTEGER NOT NULL DEFAULT 0,
|
||
minute_of_day INTEGER NOT NULL DEFAULT 720,
|
||
notify_enabled INTEGER NOT NULL DEFAULT 1,
|
||
auto_unlock INTEGER NOT NULL DEFAULT 0,
|
||
enabled INTEGER NOT NULL DEFAULT 1,
|
||
last_fired_on TEXT NOT NULL DEFAULT '',
|
||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||
)
|
||
""")
|
||
# 自动开锁的筛选 / 排序 / 重试配置
|
||
for col_def in [
|
||
("kinds", "TEXT NOT NULL DEFAULT 'small,big,red'"), # 允许车型:small/big/red
|
||
("min_electric", "INTEGER NOT NULL DEFAULT 0"), # 电量下限
|
||
("max_electric", "INTEGER NOT NULL DEFAULT 100"), # 电量上限
|
||
("sort_by", "TEXT NOT NULL DEFAULT 'electric_desc'"), # 排序:electric_desc/electric_asc/distance_asc
|
||
("retry_times", "INTEGER NOT NULL DEFAULT 3"), # 被他人抢先时的候选重试次数
|
||
]:
|
||
try:
|
||
cursor.execute(f"ALTER TABLE subscribe_rules ADD COLUMN {col_def[0]} {col_def[1]}")
|
||
except sqlite3.OperationalError:
|
||
pass
|
||
|
||
for column in ("last_run_at TEXT", "last_run_status TEXT", "last_run_message TEXT"):
|
||
try:
|
||
cursor.execute("ALTER TABLE subscribe_rules ADD COLUMN " + column)
|
||
except sqlite3.OperationalError:
|
||
pass
|
||
|
||
# ===== 凭据告警去重(同一凭据同一级别只发一次) =====
|
||
cursor.execute("""
|
||
CREATE TABLE IF NOT EXISTS credential_alerts (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
target TEXT NOT NULL,
|
||
level TEXT NOT NULL,
|
||
sent_on TEXT NOT NULL,
|
||
sent_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||
UNIQUE(target, level)
|
||
)
|
||
""")
|
||
|
||
# ===== 数据导出直链令牌(1 小时有效,免登录下载) =====
|
||
cursor.execute("""
|
||
CREATE TABLE IF NOT EXISTS export_tokens (
|
||
token TEXT PRIMARY KEY,
|
||
scope TEXT NOT NULL DEFAULT 'history_csv',
|
||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||
expires_at TIMESTAMP NOT NULL
|
||
)
|
||
""")
|
||
|
||
# 用户告警接收邮箱(凭据失效提醒;空则回退账号邮箱)
|
||
try:
|
||
cursor.execute("ALTER TABLE users ADD COLUMN alert_email TEXT")
|
||
except sqlite3.OperationalError:
|
||
pass
|
||
|
||
conn.commit()
|
||
conn.close()
|
||
|
||
|
||
|
||
|
||
def get_user_auth(user_id: int):
|
||
"""获取用户凭据,返回 (token_id, access_token)。
|
||
token_id 必填(上游唯一强校验项);access_token 选填(用于实时计算签名)。"""
|
||
if not user_id:
|
||
return None, None
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
cursor.execute("SELECT token_id, access_token FROM users WHERE id = ?", (user_id,))
|
||
row = cursor.fetchone()
|
||
conn.close()
|
||
if row and row["token_id"]:
|
||
return row["token_id"], row["access_token"]
|
||
return None, None
|
||
|
||
|
||
def parse_reminder_minutes(value):
|
||
"""解析提醒时间,只保留 UI 支持的节点,去重后降序。"""
|
||
if value is None:
|
||
return list(DEFAULT_RENTAL_SETTINGS["reminder_minutes"])
|
||
if isinstance(value, str):
|
||
raw = [part.strip() for part in value.split(",") if part.strip()]
|
||
elif isinstance(value, (list, tuple, set)):
|
||
raw = list(value)
|
||
else:
|
||
raw = []
|
||
selected = set()
|
||
for item in raw:
|
||
try:
|
||
minute = int(item)
|
||
except (TypeError, ValueError):
|
||
continue
|
||
if minute in ALLOWED_REMINDER_MINUTES:
|
||
selected.add(minute)
|
||
return [minute for minute in ALLOWED_REMINDER_MINUTES if minute in selected]
|
||
|
||
|
||
def normalize_rental_settings(data: dict):
|
||
"""校验并标准化来自用户端或管理端的用车设置。"""
|
||
if not isinstance(data, dict):
|
||
raise ValueError("设置格式不正确")
|
||
|
||
def parse_bool(name, default):
|
||
value = data.get(name, default)
|
||
if isinstance(value, bool):
|
||
return value
|
||
if value in (0, 1, "0", "1"):
|
||
return str(value) == "1"
|
||
if isinstance(value, str) and value.lower() in ("true", "false"):
|
||
return value.lower() == "true"
|
||
raise ValueError(f"{name} 必须是布尔值")
|
||
|
||
raw_minutes = data.get("reminder_minutes", DEFAULT_RENTAL_SETTINGS["reminder_minutes"])
|
||
if not isinstance(raw_minutes, (list, tuple, set)):
|
||
raise ValueError("提醒时间必须为数组")
|
||
try:
|
||
numeric_minutes = [int(value) for value in raw_minutes]
|
||
except (TypeError, ValueError):
|
||
raise ValueError("提醒时间包含无效值")
|
||
invalid = [value for value in numeric_minutes if value not in ALLOWED_REMINDER_MINUTES]
|
||
if invalid:
|
||
raise ValueError("提醒时间仅支持 10、5、3、2、1、0 分钟")
|
||
|
||
try:
|
||
duration = int(data.get("rental_duration_minutes", 19))
|
||
except (TypeError, ValueError):
|
||
raise ValueError("用车到期时间必须是整数")
|
||
if duration < 1 or duration > 180:
|
||
raise ValueError("用车到期时间须在 1 到 180 分钟之间")
|
||
|
||
try:
|
||
rounds = int(data.get("rental_rounds", MIN_RENTAL_ROUNDS))
|
||
except (TypeError, ValueError):
|
||
raise ValueError("自动续租轮次必须是整数")
|
||
if rounds < MIN_RENTAL_ROUNDS or rounds > MAX_RENTAL_ROUNDS:
|
||
raise ValueError(f"自动续租轮次须在 {MIN_RENTAL_ROUNDS} 到 {MAX_RENTAL_ROUNDS} 轮之间")
|
||
|
||
return {
|
||
"reminder_enabled": parse_bool("reminder_enabled", True),
|
||
"reminder_minutes": parse_reminder_minutes(numeric_minutes),
|
||
"rental_duration_minutes": duration,
|
||
"auto_return_enabled": parse_bool("auto_return_enabled", True),
|
||
"rental_rounds": rounds,
|
||
"protect_card": parse_bool("protect_card", True),
|
||
}
|
||
|
||
|
||
def get_user_rental_settings(user_id: int):
|
||
"""获取用户用车策略;无用户或老数据均返回安全默认值。"""
|
||
defaults = dict(DEFAULT_RENTAL_SETTINGS)
|
||
defaults["reminder_minutes"] = list(DEFAULT_RENTAL_SETTINGS["reminder_minutes"])
|
||
if not user_id:
|
||
return defaults
|
||
conn = get_db()
|
||
try:
|
||
row = conn.execute("""
|
||
SELECT reminder_enabled, reminder_minutes, rental_duration_minutes,
|
||
auto_return_enabled, rental_rounds, protect_card
|
||
FROM users WHERE id = ?
|
||
""", (user_id,)).fetchone()
|
||
except sqlite3.OperationalError:
|
||
# 兼容尚未执行 init_db 迁移的测试库/启动早期连接。
|
||
conn.close()
|
||
return defaults
|
||
conn.close()
|
||
if not row:
|
||
return defaults
|
||
try:
|
||
duration = int(row["rental_duration_minutes"])
|
||
except (TypeError, ValueError):
|
||
duration = defaults["rental_duration_minutes"]
|
||
try:
|
||
rounds = int(row["rental_rounds"])
|
||
except (KeyError, TypeError, ValueError):
|
||
rounds = defaults["rental_rounds"]
|
||
rounds = max(MIN_RENTAL_ROUNDS, min(MAX_RENTAL_ROUNDS, rounds))
|
||
return {
|
||
"reminder_enabled": bool(row["reminder_enabled"]),
|
||
"reminder_minutes": parse_reminder_minutes(row["reminder_minutes"]),
|
||
"rental_duration_minutes": max(1, min(180, duration)),
|
||
"auto_return_enabled": bool(row["auto_return_enabled"]),
|
||
"rental_rounds": rounds,
|
||
"protect_card": bool(row["protect_card"]),
|
||
}
|
||
|
||
|
||
def save_user_rental_settings(user_id: int, settings: dict):
|
||
"""保存已通过路由层校验的用车策略。"""
|
||
reminder_minutes = parse_reminder_minutes(settings.get("reminder_minutes"))
|
||
duration = int(settings.get("rental_duration_minutes", 19))
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
cursor.execute("""
|
||
UPDATE users SET reminder_enabled = ?, reminder_minutes = ?,
|
||
rental_duration_minutes = ?, auto_return_enabled = ?,
|
||
rental_rounds = ?, protect_card = ?
|
||
WHERE id = ?
|
||
""", (
|
||
1 if settings.get("reminder_enabled") else 0,
|
||
",".join(str(v) for v in reminder_minutes),
|
||
duration,
|
||
1 if settings.get("auto_return_enabled") else 0,
|
||
int(settings.get("rental_rounds", MIN_RENTAL_ROUNDS)),
|
||
1 if settings.get("protect_card", True) else 0,
|
||
user_id,
|
||
))
|
||
changed = cursor.rowcount
|
||
conn.commit()
|
||
conn.close()
|
||
return bool(changed)
|
||
|
||
|
||
# ===== 注册邀请码 =====
|
||
|
||
def create_invite_codes(count: int, max_uses: int, note: str = ""):
|
||
"""批量签发邀请码,返回生成的明文码列表(仅签发时可见完整列表)。"""
|
||
import secrets
|
||
codes = []
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789" # 去掉易混淆的 I/O/0/1
|
||
while len(codes) < count:
|
||
code = "XB-" + "".join(secrets.choice(alphabet) for _ in range(6))
|
||
try:
|
||
cursor.execute(
|
||
"INSERT INTO invite_codes (code, max_uses, note) VALUES (?, ?, ?)",
|
||
(code, max(1, min(999, max_uses)), (note or "")[:100]))
|
||
codes.append(code)
|
||
except sqlite3.IntegrityError:
|
||
continue # 撞码重生成
|
||
conn.commit()
|
||
conn.close()
|
||
return codes
|
||
|
||
|
||
def list_invite_codes():
|
||
"""列出所有邀请码(含使用进度与使用人)。"""
|
||
conn = get_db()
|
||
rows = [dict(r) for r in conn.execute(
|
||
"SELECT * FROM invite_codes ORDER BY id DESC")]
|
||
conn.close()
|
||
return rows
|
||
|
||
|
||
def set_invite_code_disabled(code_id: int, disabled: bool):
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
cursor.execute("UPDATE invite_codes SET disabled = ? WHERE id = ?",
|
||
(1 if disabled else 0, code_id))
|
||
changed = cursor.rowcount
|
||
conn.commit()
|
||
conn.close()
|
||
return bool(changed)
|
||
|
||
|
||
def delete_invite_code(code_id: int):
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
cursor.execute("DELETE FROM invite_codes WHERE id = ?", (code_id,))
|
||
changed = cursor.rowcount
|
||
conn.commit()
|
||
conn.close()
|
||
return bool(changed)
|
||
|
||
|
||
def consume_invite_code(code: str, email: str):
|
||
"""核销邀请码(原子操作:仅未停用且未用满时通过)。返回 (ok, message)。"""
|
||
code = (code or "").strip().upper()
|
||
if not code:
|
||
return False, "请输入邀请码"
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
cursor.execute("""
|
||
UPDATE invite_codes
|
||
SET used_count = used_count + 1,
|
||
used_by = CASE WHEN used_by = '' THEN ? ELSE used_by || ',' || ? END
|
||
WHERE code = ? AND disabled = 0 AND used_count < max_uses
|
||
""", (email, email, code))
|
||
ok = cursor.rowcount == 1
|
||
conn.commit()
|
||
conn.close()
|
||
if ok:
|
||
return True, ""
|
||
# 未通过时给出具体原因
|
||
conn = get_db()
|
||
row = conn.execute("SELECT disabled, used_count, max_uses FROM invite_codes WHERE code = ?",
|
||
(code,)).fetchone()
|
||
conn.close()
|
||
if not row:
|
||
return False, "邀请码无效"
|
||
if row["disabled"]:
|
||
return False, "邀请码已被停用"
|
||
return False, "邀请码已被用完"
|
||
|
||
|
||
def get_user_display_name(user_id: int) -> str:
|
||
"""获取用户显示名称"""
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
cursor.execute("SELECT email, access_token, token_id FROM users WHERE id = ?", (user_id,))
|
||
row = cursor.fetchone()
|
||
conn.close()
|
||
if not row:
|
||
return "未知用户"
|
||
email = row["email"]
|
||
if row["token_id"]:
|
||
name = email.split("@")[0]
|
||
return f"{name}"
|
||
return email
|
||
|
||
|
||
def get_all_users():
|
||
"""获取所有用户列表"""
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
cursor.execute("""
|
||
SELECT id, email, access_token, token_id,
|
||
reminder_enabled, reminder_minutes, rental_duration_minutes, auto_return_enabled,
|
||
rental_rounds, protect_card,
|
||
CASE WHEN token_id IS NOT NULL AND token_id != '' THEN 1 ELSE 0 END as has_auth,
|
||
CASE WHEN access_token IS NOT NULL AND access_token != '' THEN 1 ELSE 0 END as has_access_token
|
||
FROM users ORDER BY id
|
||
""")
|
||
users = [dict(r) for r in cursor.fetchall()]
|
||
conn.close()
|
||
for user in users:
|
||
user["reminder_enabled"] = bool(user.get("reminder_enabled"))
|
||
user["auto_return_enabled"] = bool(user.get("auto_return_enabled"))
|
||
user["rental_rounds"] = max(
|
||
MIN_RENTAL_ROUNDS,
|
||
min(MAX_RENTAL_ROUNDS, int(user.get("rental_rounds") or MIN_RENTAL_ROUNDS)),
|
||
)
|
||
user["protect_card"] = bool(user.get("protect_card"))
|
||
user["reminder_minutes"] = parse_reminder_minutes(user.get("reminder_minutes"))
|
||
return users
|
||
|
||
|
||
def get_all_rentals(limit=200):
|
||
"""获取所有租车记录(共享订单附带骑行者邮箱)"""
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
cursor.execute("""
|
||
SELECT r.*, u.email as user_email, ru.email as rider_email
|
||
FROM rentals r
|
||
LEFT JOIN users u ON r.user_id = u.id
|
||
LEFT JOIN users ru ON r.rider_user_id = ru.id
|
||
ORDER BY r.id DESC LIMIT ?
|
||
""", (limit,))
|
||
rentals = [dict(r) for r in cursor.fetchall()]
|
||
conn.close()
|
||
return rentals
|
||
|
||
|
||
def get_rental_status_label(expired: int, end_time: str) -> str:
|
||
"""返回租车状态标签"""
|
||
if expired:
|
||
return "已完成"
|
||
import datetime as dt
|
||
tz = dt.timezone(dt.timedelta(hours=8))
|
||
now = dt.datetime.now(tz)
|
||
try:
|
||
end = dt.datetime.strptime(end_time, "%Y-%m-%d %H:%M:%S").replace(tzinfo=tz)
|
||
if now > end:
|
||
return "已超时"
|
||
return "进行中"
|
||
except:
|
||
return "未知"
|
||
|
||
|
||
def get_user_alert_email(user_id: int) -> str:
|
||
"""获取用户告警接收邮箱;未设置时回退账号邮箱。"""
|
||
if not user_id:
|
||
return ""
|
||
conn = get_db()
|
||
try:
|
||
row = conn.execute("SELECT email, alert_email FROM users WHERE id = ?", (user_id,)).fetchone()
|
||
except sqlite3.OperationalError:
|
||
# 旧库/极简 schema 缺 alert_email 列:回退账号邮箱
|
||
row = None
|
||
try:
|
||
row = conn.execute("SELECT email, NULL AS alert_email FROM users WHERE id = ?",
|
||
(user_id,)).fetchone()
|
||
except sqlite3.OperationalError:
|
||
row = None
|
||
conn.close()
|
||
if not row:
|
||
return ""
|
||
return (row["alert_email"] or "").strip() or (row["email"] or "").strip()
|
||
|
||
|
||
def set_user_alert_email(user_id: int, email: str) -> bool:
|
||
email = (email or "").strip()
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
cursor.execute("UPDATE users SET alert_email = ? WHERE id = ?", (email or None, user_id))
|
||
changed = cursor.rowcount
|
||
conn.commit()
|
||
conn.close()
|
||
return bool(changed)
|