初版:小白超人(从线上实例导出)
This commit is contained in:
@@ -0,0 +1,200 @@
|
||||
#!/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 "",
|
||||
# 自动开锁筛选配置
|
||||
"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)
|
||||
updates = []
|
||||
params = []
|
||||
|
||||
def _truthy(v):
|
||||
return 1 if v in (True, 1, "1", "true") else 0
|
||||
|
||||
if "enabled" in data:
|
||||
updates.append("enabled = ?")
|
||||
params.append(_truthy(data.get("enabled")))
|
||||
if "notify_enabled" in data:
|
||||
updates.append("notify_enabled = ?")
|
||||
params.append(_truthy(data.get("notify_enabled")))
|
||||
if "auto_unlock" in data:
|
||||
updates.append("auto_unlock = ?")
|
||||
params.append(_truthy(data.get("auto_unlock")))
|
||||
|
||||
# 组合校验:任何一个筛选字段变化时,用「现值 + 新值」整体校验一次
|
||||
filter_keys = ("kinds", "min_electric", "max_electric", "sort_by", "retry_times")
|
||||
if any(k in data for k in filter_keys):
|
||||
flt = sub.rule_filters(current)
|
||||
merged = {
|
||||
"location_id": current.get("location_id"),
|
||||
"weekday": current.get("weekday"),
|
||||
"time": "%02d:%02d" % (int(current.get("minute_of_day") or 0) // 60,
|
||||
int(current.get("minute_of_day") or 0) % 60),
|
||||
"kinds": data.get("kinds", flt["kinds"]),
|
||||
"min_electric": data.get("min_electric", flt["min_electric"]),
|
||||
"max_electric": data.get("max_electric", flt["max_electric"]),
|
||||
"sort_by": data.get("sort_by", flt["sort_by"]),
|
||||
"retry_times": data.get("retry_times", flt["retry_times"]),
|
||||
"notify_enabled": True,
|
||||
"auto_unlock": bool(current.get("auto_unlock")),
|
||||
}
|
||||
try:
|
||||
fields = sub.normalize_rule(merged)
|
||||
except ValueError as exc:
|
||||
conn.close()
|
||||
return jsonify({"rtn_code": 400, "message": str(exc)})
|
||||
updates.extend(["kinds = ?", "min_electric = ?", "max_electric = ?",
|
||||
"sort_by = ?", "retry_times = ?"])
|
||||
params.extend([fields["kinds"], fields["min_electric"], fields["max_electric"],
|
||||
fields["sort_by"], fields["retry_times"]])
|
||||
|
||||
if ("time" in data and "weekday" in data) or ("time" in data or "weekday" in data):
|
||||
merged_time = {
|
||||
"location_id": current.get("location_id"),
|
||||
"weekday": data.get("weekday", current.get("weekday")),
|
||||
"time": data.get("time") or "%02d:%02d" % (
|
||||
int(current.get("minute_of_day") or 0) // 60,
|
||||
int(current.get("minute_of_day") or 0) % 60),
|
||||
}
|
||||
try:
|
||||
fields = sub.normalize_rule(merged_time)
|
||||
except ValueError as exc:
|
||||
conn.close()
|
||||
return jsonify({"rtn_code": 400, "message": str(exc)})
|
||||
updates.extend(["weekday = ?", "minute_of_day = ?"])
|
||||
params.extend([fields["weekday"], fields["minute_of_day"]])
|
||||
|
||||
if not updates:
|
||||
conn.close()
|
||||
return jsonify({"rtn_code": 400, "message": "没有需要更新的字段"})
|
||||
params.extend([rule_id, user["id"]])
|
||||
conn.execute(f"UPDATE subscribe_rules SET {', '.join(updates)} "
|
||||
f"WHERE id = ? AND user_id = ?", params)
|
||||
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,
|
||||
}})
|
||||
Reference in New Issue
Block a user