feat: improve campus bike discovery and add independent live preview

This commit is contained in:
zzy
2026-11-04 16:42:47 +08:00
parent f986c8deae
commit b6b7b3dbe5
42 changed files with 5267 additions and 4313 deletions
+4 -23
View File
@@ -6,7 +6,7 @@
返回 /export/csv/<token> 直链(免登录,1 小时有效,一次性换浏览器可继续下载)。
前端用 detectInAppBrowser 复用「复制链接到外部浏览器」提示(微信/原生壳内无法下载)。
CSV 内容:最近 3 天全部车辆点位(与库内保留策略一致)。
CSV 内容:最近 30 天全部车辆点位(与库内保留策略一致)。
"""
import csv
import datetime as dt
@@ -26,32 +26,13 @@ HISTORY_DAYS = 30
_STATE_LABELS = {
"available": "可用", "used": "使用中", "locked": "欠压",
"reserved": "损坏", "low": "低电量",
"reserved": "损坏", "low": "低电量", "unknown": "未知",
}
def _classify(state, status, electric):
try:
state = int(state)
except (TypeError, ValueError):
state = 1
try:
status = int(status)
except (TypeError, ValueError):
status = 1
try:
electric = float(electric)
except (TypeError, ValueError):
electric = 100.0
if state == 10 or electric < 20:
return "low"
if state == 4:
return "locked"
if state == 2:
return "reserved"
if state == 1 and status == 1:
return "used"
return "available"
from bike_data import classify
return classify(state, status, electric)
def _clean_expired_tokens(conn):
+26 -4
View File
@@ -377,9 +377,31 @@ def api_user_info():
# ========== 首页路由 ==========
MAP_ASSETS = (
"css/map.css", "css/bike-clusters.css", "css/map-settings.css", "css/ui-system.css",
"js/ui-motion.js", "js/qrcode.min.js", "js/coordtransform.js", "js/bike-clusters.js",
"js/settings-pages.js", "js/map.js",
"js/ui-preferences.js",
"css/map.css",
"css/bike-clusters.css",
"css/map-settings.css",
"css/ui-system.css",
"css/theme-modes.css",
"css/map-discovery.css",
"js/ui-motion.js",
"js/qrcode.min.js",
"js/coordtransform.js",
"js/bike-clusters.js",
"js/settings-pages.js",
"js/bike-data.js",
"js/api-client.js",
"js/ui-dialogs.js",
"js/map.js",
"js/map-account.js",
"js/map-orders.js",
"js/map-history.js",
"js/map-subscriptions.js",
"js/map-rental.js",
"js/map-utils.js",
"js/map-sharing.js",
"js/map-discovery.js",
"js/map-boot.js",
)
@@ -397,7 +419,7 @@ def _map_asset_version():
@bp.route("/")
def index():
response = current_app.make_response(render_template("map.html", map_asset_version=_map_asset_version()))
response = current_app.make_response(render_template("map.html", map_asset_version=_map_asset_version(), preview_mode=current_app.config.get("PREVIEW_MODE", False)))
response.headers["Cache-Control"] = "no-cache"
return response
+28 -7
View File
@@ -1157,9 +1157,23 @@ def user_orders():
if not user:
return jsonify({"rtn_code": 401, "message": "请先登录"})
try:
limit = max(1, min(500, int(request.args.get("limit", 80))))
except (TypeError, ValueError):
limit = 80
limit = max(1, min(100, int(request.args.get("limit", 20))))
offset = max(0, int(request.args.get("offset", 0)))
date_from, date_to = request.args.get("from", ""), request.args.get("to", "")
for value in (date_from, date_to):
if value:
dt.datetime.strptime(value, "%Y-%m-%d")
if date_from and date_to and date_from > date_to:
raise ValueError("开始日期不能晚于结束日期")
code = request.args.get("code", "").strip()
if code and (not code.isascii() or not code.isdigit() or len(code) > 8):
raise ValueError("车牌筛选只能输入最多8位数字")
source = request.args.get("source", "all")
if source not in ("all", "own", "shared"):
raise ValueError("无效的订单来源")
except (TypeError, ValueError) as exc:
return jsonify(rtn_code=400, message=str(exc) or "筛选参数无效"), 400
conn = get_db()
cursor = conn.cursor()
cursor.execute("""
@@ -1174,16 +1188,23 @@ def user_orders():
WHERE owner_user_id = r.user_id AND rider_user_id = r.rider_user_id)
WHERE (r.user_id = ? OR r.rider_user_id = ?)
AND COALESCE(r.source, '') != 'reminder'
ORDER BY r.id DESC LIMIT ?
""", (user["id"], user["id"], limit))
ORDER BY r.id DESC
""", (user["id"], user["id"]))
rows = [dict(r) for r in cursor.fetchall()]
conn.close()
chains = _merge_rental_chains(rows)
# 最近的在最前
chains.sort(key=lambda c: (c["rows"][-1].get("start_time") or "", c["rows"][-1]["id"]),
reverse=True)
return jsonify({"rtn_code": 0,
"data": [_chain_order_dict(c, user["id"]) for c in chains]})
records = [_chain_order_dict(c, user["id"]) for c in chains]
records = [item for item in records
if (not code or code in item["bike_code"])
and (not date_from or str(item.get("start_time") or "")[:10] >= date_from)
and (not date_to or str(item.get("start_time") or "")[:10] <= date_to)
and (source == "all" or bool(item["shared"]) == (source == "shared"))]
page = records[offset:offset + limit]
return jsonify(rtn_code=0, data=page, total=len(records), offset=offset,
has_more=offset + len(page) < len(records))
# ========== 开锁前预览(月卡余量 + 自动续租轮次预估) ==========
+32 -66
View File
@@ -30,6 +30,9 @@ def _rule_row(row: dict, locations_by_id: dict) -> dict:
"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"],
@@ -105,74 +108,37 @@ def rules_update(rule_id: int):
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:
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": "没有需要更新的字段"})
params.extend([rule_id, user["id"]])
conn.execute(f"UPDATE subscribe_rules SET {', '.join(updates)} "
f"WHERE id = ? AND user_id = ?", params)
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": "规则已更新"})
return jsonify(rtn_code=0, message="规则已更新")
@bp.route("/api/subscribe/rules/<int:rule_id>", methods=["DELETE"])
@@ -197,4 +163,4 @@ def subscribe_options():
{"key": "red", "label": "红车"}],
"sort_by": [{"key": k, "label": v} for k, v in sub.SORT_OPTIONS.items()],
"auto_unlock_enabled": sub.AUTO_UNLOCK_ENABLED,
}})
}})