167 lines
7.4 KiB
Python
167 lines
7.4 KiB
Python
#!/usr/bin/env python3
|
||
# -*- coding: utf-8 -*-
|
||
"""订阅提醒路由:规则的增删改查(每用户最多 5 条)。
|
||
|
||
规则除「停车点 + 星期 + 时间」外,还带自动开锁配置:
|
||
- kinds:允许车型 small/big/red(小车/大车/红车)
|
||
- min_electric / max_electric:电量区间
|
||
- sort_by:electric_desc(默认) / electric_asc / distance_asc
|
||
- retry_times:被他人抢先时的候选重试次数(1-10,默认 3)
|
||
"""
|
||
from flask import Blueprint, jsonify, request
|
||
|
||
from db import get_db
|
||
from routes.auth import get_current_user
|
||
import subscribe as sub
|
||
|
||
bp = Blueprint("subscribe", __name__)
|
||
|
||
|
||
def _rule_row(row: dict, locations_by_id: dict) -> dict:
|
||
loc = locations_by_id.get(row.get("location_id"))
|
||
flt = sub.rule_filters(dict(row))
|
||
return {
|
||
"id": row["id"],
|
||
"location_id": row.get("location_id"),
|
||
"location_name": loc["name"] if loc else None,
|
||
"weekday": row["weekday"],
|
||
"minute_of_day": row["minute_of_day"],
|
||
"notify_enabled": bool(row["notify_enabled"]),
|
||
"auto_unlock": bool(row["auto_unlock"]),
|
||
"enabled": bool(row["enabled"]),
|
||
"last_fired_on": row.get("last_fired_on") or "",
|
||
"last_run_at": row.get("last_run_at"),
|
||
"last_run_status": row.get("last_run_status"),
|
||
"last_run_message": row.get("last_run_message"),
|
||
# 自动开锁筛选配置
|
||
"kinds": flt["kinds"],
|
||
"min_electric": flt["min_electric"],
|
||
"max_electric": flt["max_electric"],
|
||
"sort_by": flt["sort_by"],
|
||
"retry_times": flt["retry_times"],
|
||
"sort_by_label": sub.SORT_OPTIONS.get(flt["sort_by"], flt["sort_by"]),
|
||
"kind_labels": [{"small": "小车", "big": "大车", "red": "红车"}[k]
|
||
for k in flt["kinds"]],
|
||
}
|
||
|
||
|
||
@bp.route("/api/subscribe/rules")
|
||
def rules_list():
|
||
user = get_current_user()
|
||
if not user:
|
||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||
conn = get_db()
|
||
rows = [dict(r) for r in conn.execute(
|
||
"SELECT * FROM subscribe_rules WHERE user_id = ? ORDER BY id",
|
||
(user["id"],)).fetchall()]
|
||
conn.close()
|
||
from campus import load_locations
|
||
locations_by_id = {l["id"]: l for l in load_locations()}
|
||
return jsonify({"rtn_code": 0,
|
||
"data": [_rule_row(r, locations_by_id) for r in rows]})
|
||
|
||
|
||
@bp.route("/api/subscribe/rules", methods=["POST"])
|
||
def rules_create():
|
||
user = get_current_user()
|
||
if not user:
|
||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||
if sub.count_user_rules(user["id"]) >= sub.MAX_RULES_PER_USER:
|
||
return jsonify({"rtn_code": 400,
|
||
"message": f"最多 {sub.MAX_RULES_PER_USER} 条规则,请先删除不需要的"})
|
||
try:
|
||
fields = sub.normalize_rule(request.get_json(silent=True) or {})
|
||
except ValueError as exc:
|
||
return jsonify({"rtn_code": 400, "message": str(exc)})
|
||
from campus import get_location
|
||
loc = get_location(fields["location_id"])
|
||
if not loc:
|
||
return jsonify({"rtn_code": 400, "message": "所选停车点不存在(可能已被管理员删除)"})
|
||
if (loc.get("kind") or "") != "parking":
|
||
return jsonify({"rtn_code": 400,
|
||
"message": "订阅只能选择「停车点」(楼/兴趣点只用于起终点归属)"})
|
||
conn = get_db()
|
||
conn.execute("""
|
||
INSERT INTO subscribe_rules (user_id, location_id, weekday, minute_of_day,
|
||
notify_enabled, auto_unlock, enabled,
|
||
kinds, min_electric, max_electric, sort_by, retry_times)
|
||
VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?)
|
||
""", (user["id"], fields["location_id"], fields["weekday"], fields["minute_of_day"],
|
||
1 if fields["notify_enabled"] else 0, 1 if fields["auto_unlock"] else 0,
|
||
fields["kinds"], fields["min_electric"], fields["max_electric"],
|
||
fields["sort_by"], fields["retry_times"]))
|
||
conn.commit()
|
||
conn.close()
|
||
return jsonify({"rtn_code": 0, "message": "订阅规则已添加"})
|
||
|
||
|
||
@bp.route("/api/subscribe/rules/<int:rule_id>", methods=["PUT"])
|
||
def rules_update(rule_id: int):
|
||
user = get_current_user()
|
||
if not user:
|
||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||
data = request.get_json(silent=True) or {}
|
||
conn = get_db()
|
||
row = conn.execute("SELECT * FROM subscribe_rules WHERE id = ? AND user_id = ?",
|
||
(rule_id, user["id"])).fetchone()
|
||
if not row:
|
||
conn.close()
|
||
return jsonify({"rtn_code": 404, "message": "规则不存在"})
|
||
current = dict(row)
|
||
allowed = {"enabled", "notify_enabled", "auto_unlock", "location_id", "weekday", "time",
|
||
"kinds", "min_electric", "max_electric", "sort_by", "retry_times"}
|
||
if not data or not set(data).intersection(allowed):
|
||
conn.close()
|
||
return jsonify(rtn_code=400, message="没有需要更新的字段"), 400
|
||
filters = sub.rule_filters(current)
|
||
merged = {**filters, "location_id": current["location_id"], "weekday": current["weekday"],
|
||
"time": "%02d:%02d" % divmod(current["minute_of_day"], 60),
|
||
"notify_enabled": bool(current["notify_enabled"]), "auto_unlock": bool(current["auto_unlock"])}
|
||
merged.update({k: v for k, v in data.items() if k in allowed})
|
||
try:
|
||
fields = sub.normalize_rule(merged)
|
||
from campus import get_location
|
||
location = get_location(fields["location_id"])
|
||
if not location or location.get("kind") != "parking":
|
||
raise ValueError("订阅只能选择有效停车点")
|
||
enabled = data.get("enabled", bool(current["enabled"]))
|
||
if enabled not in (True, False, 0, 1, "0", "1", "true", "false"):
|
||
raise ValueError("启用状态无效")
|
||
enabled = int(enabled in (True, 1, "1", "true"))
|
||
except (TypeError, ValueError) as exc:
|
||
conn.close()
|
||
return jsonify(rtn_code=400, message=str(exc)), 400
|
||
columns = ("location_id", "weekday", "minute_of_day", "notify_enabled", "auto_unlock",
|
||
"kinds", "min_electric", "max_electric", "sort_by", "retry_times")
|
||
values = [int(fields[k]) if k in ("notify_enabled", "auto_unlock") else fields[k] for k in columns]
|
||
conn.execute("UPDATE subscribe_rules SET " + ", ".join(k + " = ?" for k in columns) +
|
||
", enabled = ? WHERE id = ? AND user_id = ?", (*values, enabled, rule_id, user["id"]))
|
||
conn.commit()
|
||
conn.close()
|
||
return jsonify(rtn_code=0, message="规则已更新")
|
||
|
||
|
||
@bp.route("/api/subscribe/rules/<int:rule_id>", methods=["DELETE"])
|
||
def rules_delete(rule_id: int):
|
||
user = get_current_user()
|
||
if not user:
|
||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||
conn = get_db()
|
||
conn.execute("DELETE FROM subscribe_rules WHERE id = ? AND user_id = ?",
|
||
(rule_id, user["id"]))
|
||
conn.commit()
|
||
conn.close()
|
||
return jsonify({"rtn_code": 0, "message": "规则已删除"})
|
||
|
||
|
||
@bp.route("/api/subscribe/options")
|
||
def subscribe_options():
|
||
"""订阅可选项(车型/排序),供前端渲染下拉与说明。"""
|
||
return jsonify({"rtn_code": 0, "data": {
|
||
"kinds": [{"key": "small", "label": "小车"},
|
||
{"key": "big", "label": "大车"},
|
||
{"key": "red", "label": "红车"}],
|
||
"sort_by": [{"key": k, "label": v} for k, v in sub.SORT_OPTIONS.items()],
|
||
"auto_unlock_enabled": sub.AUTO_UNLOCK_ENABLED,
|
||
}})
|