diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..aa50047 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,24 @@ +.git +.gitignore +__pycache__ +**/__pycache__ +.pytest_cache +node_modules +*.db +*.db-* +*.sqlite* +*.zip +*.log +*.pem +*.key +*.crt +*config.txt* +server_config.json +secret_key.txt +backups +downloads +artifacts +temp +tests +test_*.py +.reasonix diff --git a/Dockerfile.preview b/Dockerfile.preview new file mode 100644 index 0000000..f810a75 --- /dev/null +++ b/Dockerfile.preview @@ -0,0 +1,10 @@ +FROM python:3.11-slim +ENV TZ=Asia/Shanghai PYTHONUNBUFFERED=1 XBNIU_PREVIEW=1 XBNIU_DB_PATH=/data/preview.db PIP_INDEX_URL=https://pypi.tuna.tsinghua.edu.cn/simple +WORKDIR /app +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt gunicorn==23.0.0 +COPY . . +RUN mkdir -p /data +EXPOSE 8080 +HEALTHCHECK --interval=20s --timeout=5s --start-period=20s --retries=3 CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/healthz', timeout=3)" +CMD ["gunicorn", "--bind", "0.0.0.0:8080", "--workers", "1", "--threads", "4", "--timeout", "60", "preview_server:app"] diff --git a/README.md b/README.md index 1927192..123a8ae 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ - **历史轨迹**:记录每辆车的位置历史,支持按车牌查询轨迹 - **数据分析**:状态分布、24 小时趋势、活跃车辆 Top10、热力图 - **租赁管理**:订单到期倒计时,邮件提醒(10/5/3/2/1/0 分钟多级通知) -- **自动清理**:3 天前历史数据自动归档,定期 VACUUM 释放空间 +- **自动清理**:30 天前历史数据自动归档,定期 VACUUM 释放空间 ## 技术栈 @@ -19,7 +19,7 @@ - **数据源**:微信小程序接口(需用户授权 `token_id` + `wx_signature`) - **采集调度**:threading 后台线程 + 自适应间隔 - **通知**:SMTP 邮件 + 内部计时器 -- **前端**:Jinja2 模板 + Leaflet 地图 + ECharts 图表 +- **前端**:Jinja2 模板 + 百度 BMapGL 地图 + ECharts 图表 ## 项目结构 @@ -127,7 +127,7 @@ def get_adaptive_interval(): ### 数据清理 -每 23 小时执行一次:删除 3 天前的 `bike_history` 与过期 `sessions`,并执行 `VACUUM` 压缩 SQLite 文件。 +每 23 小时执行一次:删除 30 天前的 `bike_history` 与过期 `sessions`,并执行 `VACUUM` 压缩 SQLite 文件。 ### 订单到期提醒 @@ -151,3 +151,33 @@ def get_adaptive_interval(): - HTTPS 证书文件(`*.pem` `*.crt` `*.key`)若损坏会导致小程序接口无法访问 - 服务监听端口默认 98(非特权端口) + + +## preview 分支(v1.7.0) + +本分支完善了地图状态与电量的一致性、5/8 位车牌查询、定位重试与地图中心查找、最近可用车辆推荐、地图快捷筛选、附近车辆列表、校园地点搜索及常用地点、手机操作与弹窗焦点、订阅规则编辑/复制/最近执行结果、订单筛选与分页、首次使用引导及浅色/深色/跟随系统主题。不包含步行导航。 + +### 预览环境 + +使用 `Dockerfile.preview`,监听 8080,健康检查 `GET /healthz`。容器以一个 Gunicorn worker、四个线程运行,保持订单与计时器状态一致;预览启动入口会恢复该环境的计时器并启动订阅和凭证告警调度。 + +- `XBNIU_PREVIEW=1`:标识预览环境,启用演示与独立测试账号入口。 +- `XBNIU_DB_PATH=/data/preview.db`:独立数据库;将独立持久卷挂载到 `/data`,不要挂载生产数据库。 +- **演示体验**:`demo@preview.local` / `preview123`,车辆与开锁、还车等操作使用模拟数据。演示账号不能保存真实微信凭证。 +- **创建独立测试账号**:每个浏览器获得独立账号和登录令牌;在“微信凭证”中配置自己的 Token ID / AccessToken 后使用真实上游接口,开锁、还车和支付也会真实执行。切换演示体验后再次点击测试账号入口可恢复当前浏览器的测试账号。清理浏览器存储会丢失该入口的登录状态。 +- 普通账号的真实请求没有全局外发拦截;各账号分别使用自己的微信凭证,预览地图按账号和车型缓存 60 秒,失败退避 5 秒。 +- 测试账号可在凭证页填写真实告警邮箱。邮件配置支持 `SMTP_HOST`、`SMTP_PORT`、`SMTP_USER`、`SMTP_PASS`、`SMTP_STARTTLS` 环境变量;未配置 SMTP 时不会宣称邮件发送成功。 +- `.dockerignore` 排除数据库、证书、密钥、配置凭据、备份、下载与截图,镜像不携带本地生产数据。 + +### 前端结构 + +`bike-data.js` 管理车辆规则;`map.js` 管理地图渲染与定位;`map-account.js`、`map-orders.js`、`map-history.js`、`map-subscriptions.js`、`map-rental.js`、`map-sharing.js` 分别管理业务功能;`map-discovery.js` 管理筛选、附近列表与常用地点;`api-client.js` 处理请求超时与提交锁;`ui-preferences.js` 和 `ui-dialogs.js` 处理主题及弹窗焦点;`map-boot.js` 负责启动。所有地图资源共用内容哈希版本,更新任一依赖会使整个资源包失效。 + +### 验证 + +```powershell +python -X utf8 -m pytest tests -q +node --test tests/test_api_client.cjs tests/test_bike_data.cjs tests/test_bike_clusters.cjs tests/test_map_refresh.cjs tests/test_order_return.cjs tests/test_settings_navigation.cjs +``` + +浏览器验收采用演示账号;真实上游链路用替身请求验证路由与账号隔离,不在自动化验收中执行真实车辆操作。 diff --git a/app.py b/app.py index c03e710..cae40ac 100644 --- a/app.py +++ b/app.py @@ -34,6 +34,7 @@ import random import threading import urllib3 from pathlib import Path +from runtime_mode import PREVIEW_MODE from flask import Flask, jsonify, request, render_template, session urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) @@ -50,6 +51,9 @@ def _load_or_create_secret_key() -> str: """secret_key 不再写死在源码:优先环境变量,否则随机生成一次并持久化到 secret_key.txt(已 gitignore)。key 变化只会使管理员后台 session 失效, 普通用户登录态存数据库(sessions 表),不受影响。""" + if PREVIEW_MODE: + import secrets + return os.environ.get("XBNIU_SECRET_KEY") or secrets.token_hex(32) env_key = os.environ.get("XBNIU_SECRET_KEY", "").strip() if env_key: return env_key @@ -93,6 +97,14 @@ app.register_blueprint(share_bp) app.register_blueprint(download_bp) app.register_blueprint(export_bp) app.register_blueprint(subscribe_bp) +if PREVIEW_MODE: + from preview_data import install_preview + install_preview(app) + +@app.get("/healthz") +def healthz(): + return jsonify(status="ok", mode="preview" if PREVIEW_MODE else "production") + # ========== 未认证数据接口限速 ========== @@ -392,31 +404,12 @@ def api_analysis_heatmap(): # 数据分析页/批量车辆轨迹全部 404。以下实现与前端 analysis.html 期望的 JSON 结构对齐。 # 状态分类(与 map.html / analysis.html 图例一致) -_HISTORY_STATES = ["available", "used", "locked", "reserved", "low"] +_HISTORY_STATES = ["available", "used", "locked", "reserved", "low", "unknown"] def _classify_bike_state(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) @app.route("/api/history/stats") @@ -660,6 +653,12 @@ if __name__ == "__main__": # 初始化数据库 init_db() + if PREVIEW_MODE: + from preview_data import seed_preview + seed_preview() + app.run(host=os.environ.get("XBCR_HOST", "127.0.0.1"), port=int(os.environ.get("XBCR_PORT", 9989)), debug=False) + sys.exit(0) + # 恢复未过期的计时器 restore_active_timers() diff --git a/bike_data.py b/bike_data.py new file mode 100644 index 0000000..61d0511 --- /dev/null +++ b/bike_data.py @@ -0,0 +1,31 @@ +"""Vehicle state contract shared by statistics and exports; mirrors BikeData.state.""" +import math + + +def battery(value): + if value is None or isinstance(value, bool) or (isinstance(value, str) and not value.strip()): + return None + try: + n = float(value) + except (TypeError, ValueError): + return None + return n if math.isfinite(n) and 0 <= n <= 100 else None + + +def classify(state, status, electric): + try: + state, status = int(state), int(status) + except (TypeError, ValueError): + return "unknown" + electric = battery(electric) + if state == 1 and status == 1: + return "used" + if state == 4: + return "locked" + if state == 2: + return "reserved" + if state == 10 or (electric is not None and electric < 20): + return "low" + if state == 1 and status == 0: + return "available" + return "unknown" diff --git a/db.py b/db.py index 519615a..07af363 100644 --- a/db.py +++ b/db.py @@ -4,7 +4,12 @@ import sqlite3 from pathlib import Path -DB_PATH = Path(__file__).parent / "users.db" +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, @@ -363,6 +368,12 @@ def init_db(): 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 ( diff --git a/email_utils.py b/email_utils.py index f61445a..c970925 100644 --- a/email_utils.py +++ b/email_utils.py @@ -106,10 +106,17 @@ def _load_smtp_config() -> dict: cfg[k] = v.strip() except Exception as e: print(f"[SMTP配置] 读取失败: {e}") + import os + for key in cfg: + if os.environ.get(key.upper()) is not None: + cfg[key] = os.environ[key.upper()] return cfg def send_email(to_email: str, subject: str, body: str, html_body: str = None) -> bool: + from runtime_mode import PREVIEW_MODE + if PREVIEW_MODE and str(to_email).lower() in ("demo@preview.local", "friend@preview.local"): + return True # Demonstration recipients are synthetic; real alert emails use SMTP. """发送邮件,可同时提供纯文本和 HTML 版本,返回是否成功。""" cfg = _load_smtp_config() if not cfg["smtp_user"] or not cfg["smtp_pass"]: diff --git a/preview_data.py b/preview_data.py new file mode 100644 index 0000000..9192c49 --- /dev/null +++ b/preview_data.py @@ -0,0 +1,223 @@ +"""Preview fixtures for the demo account; independent test accounts use real APIs.""" +import copy +import datetime as dt +import secrets +import threading +import time +from flask import jsonify, request + +DEMO_EMAIL = "demo@preview.local" +DEMO_PASSWORD = "preview123" +_lock = threading.RLock() +_rides = {} +_live_maps = {} + + +def sample_bikes(): + bikes = [] + for n in range(28): + code = str(30000193 + n) if n % 5 == 0 else str((50300 if n % 3 == 0 else 51200) + n) + state, status = ((4, 0) if n % 11 == 0 else (2, 0) if n % 13 == 0 else (1, 1) if n % 7 == 0 else (1, 0)) + bikes.append({"code": code, "id": code, "state": state, "status": status, + "latitude": 36.53182 + (n // 7 - 1) * .00105, + "longitude": 116.7817 + (n % 7 - 3) * .0008, + "electric_quantity": None if n == 3 else 10 if n == 4 else 25 + (n * 13) % 75}) + return bikes + + +def seed_preview(): + from db import get_db + from routes.auth import hash_password + conn = get_db() + if conn.execute("SELECT id FROM users WHERE email=?", (DEMO_EMAIL,)).fetchone(): + conn.close() + return + user_id = conn.execute("INSERT INTO users (email, password_hash) VALUES (?, ?)", + (DEMO_EMAIL, hash_password(DEMO_PASSWORD))).lastrowid + peer_id = conn.execute("INSERT INTO users (email, password_hash) VALUES (?, ?)", + ("friend@preview.local", hash_password(secrets.token_urlsafe(24)))).lastrowid + places = [("图书馆", "poi", 36.5325, 116.7812), ("第一教学楼", "poi", 36.5319, 116.7824), + ("学生食堂", "poi", 36.5308, 116.7801), ("宿舍区停车点", "parking", 36.5330, 116.7820), + ("图书馆停车点", "parking", 36.5321, 116.7808)] + for name, kind, lat, lng in places: + conn.execute("INSERT INTO campus_locations (name,kind,latitude,longitude,radius) VALUES (?,?,?,?,150)", + (name, kind, lat, lng)) + now = dt.datetime.now(dt.timezone(dt.timedelta(hours=8))).replace(tzinfo=None) + for n in range(68): + start = now - dt.timedelta(hours=n * 3 + 1) + end = start + dt.timedelta(minutes=12 + n % 6) + conn.execute("""INSERT INTO rentals (order_id,bike_code,email,user_id,rider_user_id,start_time, + end_time,returned_at,expired,source,start_label,end_label) + VALUES (?,?,?,?,?,?,?,?,1,'wechat',?,?)""", + (f"DEMO-{n:04}", str(51200 + n % 20), DEMO_EMAIL, user_id, + peer_id if n % 3 == 0 else None, start.strftime("%Y-%m-%d %H:%M:%S"), + end.strftime("%Y-%m-%d %H:%M:%S"), end.strftime("%Y-%m-%d %H:%M:%S"), + "宿舍区附近", "图书馆附近")) + for n in range(72): + when = (now - dt.timedelta(minutes=n * 10)).strftime("%Y-%m-%d %H:%M:%S") + for bike in sample_bikes(): + conn.execute("""INSERT INTO bike_history (bike_code,latitude,longitude,state,status,electric,recorded_at) + VALUES (?,?,?,?,?,?,?)""", (bike["code"], bike["latitude"], bike["longitude"], + bike["state"], bike["status"], bike["electric_quantity"], when)) + parking = conn.execute("SELECT id FROM campus_locations WHERE kind='parking' ORDER BY id LIMIT 1").fetchone()[0] + 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,last_run_at,last_run_status,last_run_message) + VALUES (?,?,0,715,1,0,0,'small,big,red',20,100,'distance_asc',3,?,'success',?)""", + (user_id, parking, now.strftime("%Y-%m-%d %H:%M:%S"), "演示:停车点附近有 6 辆符合条件的车辆")) + conn.commit() + conn.close() + + +def install_preview(app): + app.config["PREVIEW_MODE"] = True + + @app.post("/api/preview/session") + def create_test_session(): + from db import get_db + from rate_limit import hit + from routes.auth import _client_ip, hash_password + if not hit(("preview_session", _client_ip()), 10, 3600): + return jsonify(rtn_code=429, message="创建测试账号过于频繁,请稍后再试"), 429 + conn = get_db() + email = "tester-" + secrets.token_hex(6) + "@preview.local" + uid = conn.execute("INSERT INTO users (email,password_hash) VALUES (?,?)", + (email, hash_password(secrets.token_urlsafe(32)))).lastrowid + token = secrets.token_urlsafe(32) + conn.execute("""INSERT INTO sessions (user_id,token,expires_at,device_name,last_active) + VALUES (?,?,datetime('now','+8 hours','+30 days'),'预览测试浏览器',datetime('now','+8 hours'))""", (uid, token)) + conn.commit() + conn.close() + return jsonify(rtn_code=0, data={"token": token, "email": email}) + + @app.before_request + def preview_requests(): + from routes.auth import get_current_user + from db import get_db, get_user_rental_settings + path = request.path + if path == "/api/config": + return jsonify(center_lat=36.531820, center_lng=116.780180, scale=17, + school_name="山东管理学院", type_names={"1": "单车", "3": "电动车", "6": "助力车"}, preview=True) + if not path.startswith("/api/") or path == "/api/preview/session": + return None + user = get_current_user() + if not user: + return None + if user["email"] != DEMO_EMAIL: + # The preview container has no production global token. Use this private + # test account's explicitly supplied WeChat credentials for map queries. + from wechat import request_with_user_auth + if path == "/api/auth/save_token": + with _lock: + for key in [key for key in _live_maps if key[0] == user["id"]]: + _live_maps.pop(key, None) + if path == "/api/map": + bike_type = request.args.get("type", "3") + if bike_type not in ("1", "3", "6"): + return jsonify(rtn_code=400, message="不支持的车辆类型"), 400 + key = (user["id"], bike_type) + with _lock: + cached = _live_maps.get(key) + if not cached or cached[0] <= time.time(): + now = time.time() + result = request_with_user_auth(user["id"], "GET", "/project/map", params={"type": bike_type}) + if result.get("rtn_code") == 401: + result = {**result, "rtn_code": 400, "message": "请先在设置中填写微信凭证,再刷新车辆数据"} + ttl = 60 if result.get("rtn_code") == 0 else 5 + result["map_snapshot"] = {"fetched_at": now if result.get("rtn_code") == 0 else None, + "expires_at": now + ttl, "status": "fresh" if result.get("rtn_code") == 0 else "error"} + _live_maps[key] = (now + ttl, result) + if len(_live_maps) > 200: + for expired in [k for k, v in _live_maps.items() if v[0] < now]: + _live_maps.pop(expired, None) + cached = _live_maps[key] + response = jsonify(copy.deepcopy(cached[1])) + response.headers["X-Map-Server-Time"] = str(time.time()) + response.headers["Cache-Control"] = "private, no-store" + return response + if path == "/api/bicycle": + return jsonify(request_with_user_auth(user["id"], "POST", "/project/bicycle", data=request.get_json(silent=True) or {})) + if path == "/api/find_bike": + from urllib.parse import urlsplit + from wechat import SEARCH_BIKE_URL + return jsonify(request_with_user_auth(user["id"], "POST", urlsplit(SEARCH_BIKE_URL).path, data=request.get_json(silent=True) or {})) + return None + # Demo operations stay synthetic, even after live testing is enabled. + if path.startswith("/api/subscribe/") or path in ("/api/campus/locations", "/api/auth/status", "/api/auth/logout", "/api/user/orders") or path.startswith("/api/auth/sessions"): + return None + if path == "/api/auth/rental_settings": + if request.method == "POST": + from db import normalize_rental_settings, save_user_rental_settings + try: + settings = normalize_rental_settings(request.get_json(silent=True) or {}) + except ValueError as exc: + return jsonify(rtn_code=400, message=str(exc)), 400 + save_user_rental_settings(user["id"], settings) + return jsonify(rtn_code=0, data=get_user_rental_settings(user["id"])) + if path == "/api/auth/profile": + return jsonify(rtn_code=0, data={"email": DEMO_EMAIL, "has_auth": True, "token_id": "", "access_token": "", "strict_mode": False, + "rental_settings": get_user_rental_settings(user["id"]), "alert_email": DEMO_EMAIL}) + if path in ("/api/auth/user_info", "/api/user/info"): + return jsonify(rtn_code=0, data={"has_auth": True, "true_name": "演示同学", "out_money": 12.5, "save_money": 86.0}) + if path == "/api/auth/packages": + return jsonify(rtn_code=0, data={"has_auth": True, "packages": [{"name": "演示骑行月卡", "remain": 12, "remaining": 12, "expire_time": "2026-12-31"}]}) + if path.startswith("/api/auth/"): + return jsonify(rtn_code=403, message="演示账号使用模拟数据;请创建独立测试账号后填写真实凭证"), 403 + if path == "/api/map": + now = time.time() + response = jsonify(rtn_code=0, data={"bicycleStation": sample_bikes(), "driverArea": [], "parkeArea": []}, + map_snapshot={"fetched_at": now, "expires_at": now + 60, "status": "fresh"}) + response.headers["X-Map-Server-Time"] = str(now) + response.headers["Cache-Control"] = "private, no-store" + return response + if path == "/api/bicycle": + code = str((request.get_json(silent=True) or {}).get("code", "")) + bike = next((b for b in sample_bikes() if b["code"] == code), None) + return jsonify(rtn_code=0, data=bike) if bike else jsonify(rtn_code=404, message="演示数据中没有这辆车,请从附近列表选择") + if path == "/api/find_bike": + return jsonify(rtn_code=0, message="模拟寻车成功", data={}) + token = request.headers.get("Authorization", "") + with _lock: + ride = _rides.get(token) + if path == "/api/order/status": + return jsonify(rtn_code=0, has_credentials=True, has_order=bool(ride), order=ride) + if path == "/api/rental/status": + settings = get_user_rental_settings(user["id"]) + end = ride.get("deadline") if ride else time.time() + return jsonify(rtn_code=0, data={"active": bool(ride), "remaining_seconds": max(0, int(end - time.time())), + "current_round": 1, "total_rounds": ride.get("rounds", 1) if ride else 1, + "auto_return": settings["auto_return_enabled"], + "final_end_time": dt.datetime.fromtimestamp(end, dt.timezone(dt.timedelta(hours=8))).strftime("%Y-%m-%d %H:%M:%S")}) + if path == "/api/order/unlock": + if ride: + return jsonify(rtn_code=400, message="请先结束当前演示订单") + data = request.get_json(silent=True) or {} + code = str(data.get("code") or data.get("bike_code") or "51201") + ride = {"order_id": "DEMO-LIVE-" + secrets.token_hex(4), "code": code, "status": 2, "deadline": time.time() + 19 * 60, "rounds": 1} + _rides[token] = ride + return jsonify(rtn_code=0, message="模拟开锁成功", data={**ride, "rental_id": 0, "duration_minutes": 19}) + if path == "/api/order/add_round": + if ride: + ride["deadline"] += 19 * 60 + ride["rounds"] += 1 + return jsonify(rtn_code=0, message="演示订单已追加一轮") + if path in ("/api/order/return", "/api/rental/return", "/api/share/return"): + _rides.pop(token, None) + return jsonify(rtn_code=0, message="模拟还车成功", data={"returned": True, "paid": True}) + if path == "/api/order/preview": + return jsonify(rtn_code=0, data={"has_card": True, "cards": [{"name": "演示骑行月卡", "remain": 12}], + "auto_return": True, "rounds_planned": 1, "duration_minutes": 19, "est_end_time": "19 分钟后"}) + if path == "/api/share/sources": + return jsonify(rtn_code=0, data={"sources": [], "hidden_count": 0}) + if path == "/api/share/active": + return jsonify(rtn_code=0, data=[]) + if path.startswith("/api/share/"): + return jsonify(rtn_code=0, data=[], pending=[], usable=[], mine=[]) + if path == "/api/rental/sync": + return jsonify(rtn_code=0, data={"active": False}) + if path.startswith("/api/order/"): + return jsonify(rtn_code=0, message="模拟操作成功", data={"paid": True}) + if path.startswith("/api/history/") or path.startswith("/api/analysis/") or path == "/api/bike_history": + return None # Read-only seeded history through the real analysis code. + if path == "/api/user/orders/trajectory": + return jsonify(rtn_code=0, data={"points": [], "bike_code": "51201", "hint": "演示订单无完整轨迹"}) + return jsonify(rtn_code=403, message="演示模式暂不提供此操作"), 403 diff --git a/preview_server.py b/preview_server.py new file mode 100644 index 0000000..441fd87 --- /dev/null +++ b/preview_server.py @@ -0,0 +1,21 @@ +"""Dedicated preview entry point. Starts no collectors, schedulers or real timers.""" +from runtime_mode import PREVIEW_MODE + +if not PREVIEW_MODE: + raise RuntimeError("preview_server requires XBNIU_PREVIEW=1") + +from app import app +from db import init_db +from preview_data import seed_preview + +init_db() +seed_preview() + +# Real test accounts use the normal timers and notifications in this isolated database. +from timer import restore_active_timers, start_all_order_checkers +from subscribe import start_subscribe_scheduler +from alerts import start_alert_scheduler +restore_active_timers() +start_all_order_checkers() +start_subscribe_scheduler() +start_alert_scheduler() diff --git a/routes/export.py b/routes/export.py index d749e44..5a45682 100644 --- a/routes/export.py +++ b/routes/export.py @@ -6,7 +6,7 @@ 返回 /export/csv/ 直链(免登录,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): diff --git a/routes/map_api.py b/routes/map_api.py index 4e21f7b..9a56e16 100644 --- a/routes/map_api.py +++ b/routes/map_api.py @@ -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 diff --git a/routes/rental.py b/routes/rental.py index 60e2446..48239bb 100644 --- a/routes/rental.py +++ b/routes/rental.py @@ -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)) # ========== 开锁前预览(月卡余量 + 自动续租轮次预估) ========== diff --git a/routes/subscribe.py b/routes/subscribe.py index 4a64942..3ed9233 100644 --- a/routes/subscribe.py +++ b/routes/subscribe.py @@ -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/", 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, - }}) \ No newline at end of file + }}) diff --git a/runtime_mode.py b/runtime_mode.py new file mode 100644 index 0000000..5c95900 --- /dev/null +++ b/runtime_mode.py @@ -0,0 +1,4 @@ +"""An explicit process-level switch, never controlled by an HTTP request.""" +import os + +PREVIEW_MODE = os.environ.get("XBNIU_PREVIEW", "").strip().lower() in ("1", "true", "yes") diff --git a/scripts/pack_zip.ps1 b/scripts/pack_zip.ps1 index 39aac69..e442bdd 100644 --- a/scripts/pack_zip.ps1 +++ b/scripts/pack_zip.ps1 @@ -6,7 +6,8 @@ $zip = Join-Path $src '1.zip' $pendingZip = Join-Path $src '1.zip.tmp' $include = @( - '.gitignore','LICENSE','README.md','app.py','db.py','campus.py','alerts.py','subscribe.py', + '.gitignore','.dockerignore','Dockerfile','Dockerfile.preview','LICENSE','README.md','app.py','db.py','campus.py','alerts.py','subscribe.py', + 'bike_data.py','runtime_mode.py','preview_data.py','preview_server.py', 'email_utils.py','email_verify.py','generate_icons.py','map_cache.py','pytest.ini','rate_limit.py', 'rental_mail.py','requirements.txt','server_config.json','timer.py', 'update_creds_from_capture.py','wechat.py' @@ -62,4 +63,4 @@ try { Write-Host "1.zip 完成:$($names.Count) 个文件,$sizeKB KB(仅源码与必要资源)" } finally { if (Test-Path -LiteralPath $pendingZip) { Remove-Item -LiteralPath $pendingZip -Force } -} +} diff --git a/static/css/map-discovery.css b/static/css/map-discovery.css new file mode 100644 index 0000000..eb94e51 --- /dev/null +++ b/static/css/map-discovery.css @@ -0,0 +1,96 @@ +/* Discovery tools reuse the existing porcelain / charcoal theme. */ +.discovery-toolbar { position:absolute; z-index:130; top:12px; left:12px; width:min(400px, calc(100% - 140px)); padding:10px; border:1px solid var(--ui-line-strong); border-radius:16px; background:var(--ui-surface); box-shadow:var(--ui-shadow-md); font-size:13px; } +.place-search-wrap { position:relative; } +.place-search-row { display:flex; align-items:center; gap:6px; } +.place-search-row input { min-width:0; flex:1; width:100%; background:var(--ui-surface-raised); color:var(--ui-ink); border:1px solid var(--ui-line-strong); border-radius:9px; padding:10px; font-size:14px; } +.discovery-toolbar button,.discovery-toolbar summary,.nearby-panel button,.location-status button,.theme-options button,.order-filters button,.order-load-more,.sub-rule button { min-height:44px; border:1px solid var(--ui-line-strong); border-radius:9px; padding:8px 10px; background:var(--ui-surface-raised); color:var(--ui-ink); font:inherit; cursor:pointer; } +.discovery-actions { display:flex; gap:6px; align-items:center; margin-top:6px; } +.discovery-actions > button { flex:1; white-space:nowrap; } +.discovery-actions details > summary { list-style:none; display:flex; align-items:center; justify-content:center; } +.discovery-actions details > summary::-webkit-details-marker { display:none; } +.discovery-filter-fields { position:absolute; left:0; right:0; top:100%; margin-top:7px; padding:14px; background:var(--ui-surface); border:1px solid var(--ui-line-strong); border-radius:14px; box-shadow:var(--ui-shadow-md); display:grid; grid-template-columns:1fr 1fr; gap:12px; } +.discovery-filter-fields label { display:flex; flex-direction:column; gap:7px; color:var(--ui-muted); } +.discovery-filter-fields .checkbox-label { flex-direction:row; align-items:center; grid-column:1/-1; color:var(--ui-ink); min-height:36px; } +.discovery-filter-fields select,.nearby-sort select,.order-filters input,.order-filters select { min-height:44px; width:100%; min-width:0; background:var(--ui-surface-raised); color:var(--ui-ink); border:1px solid var(--ui-line-strong); border-radius:8px; padding:7px; font:inherit; } +.discovery-filter-fields input[type=checkbox] { width:20px; height:20px; } +.discovery-origin { width:100%; text-align:left; border:0!important; background:transparent!important; color:var(--ui-muted)!important; padding:7px 2px 0!important; min-height:30px!important; font-size:12px!important; } +.place-results { position:absolute; z-index:3; top:calc(100% + 6px); width:100%; max-height:280px; overflow-y:auto; border-radius:12px; border:1px solid var(--ui-line-strong); background:var(--ui-surface); box-shadow:var(--ui-shadow-md); } +.place-results button { display:flex; justify-content:space-between; align-items:center; width:100%; border:0; border-radius:0; border-bottom:1px solid var(--ui-line); background:transparent; text-align:left; gap:12px; } +.place-results small,.discovery-muted { color:var(--ui-muted); font-size:12px; } +.favorite-places { display:flex; gap:6px; overflow-x:auto; scrollbar-width:thin; padding-top:6px; } +.favorite-place { display:flex; flex:none; border:1px solid var(--ui-line); border-radius:9px; overflow:hidden; } +.favorite-place button { border:0; border-radius:0; background:transparent; white-space:nowrap; min-height:36px; } +.favorite-place button:last-child { min-width:36px; padding:6px; color:var(--ui-muted); } +.nearby-panel { position:absolute; z-index:155; left:12px; bottom:12px; width:min(400px,calc(100% - 24px)); max-height:52%; display:flex; flex-direction:column; padding:14px; border:1px solid var(--ui-line-strong); border-radius:18px; background:var(--ui-surface); box-shadow:var(--ui-shadow-lg); font-size:13px; } +[hidden] { display:none!important; } +.nearby-heading { display:flex; align-items:center; justify-content:space-between; gap:10px; } +.nearby-heading h2 { font-size:17px; letter-spacing:-.3px; } +.nearby-heading button { min-width:44px; } +.nearby-summary { color:var(--ui-muted); padding:5px 0 10px; font-size:12px; line-height:1.6; } +.nearby-sort { display:flex; align-items:center; gap:10px; padding-bottom:8px; } +.nearby-sort select { width:auto; flex:1; } +.nearby-list { overflow-y:auto; min-height:80px; overscroll-behavior:contain; } +.nearby-row { display:flex; justify-content:space-between; width:100%; text-align:left; gap:12px; background:transparent!important; border-width:0 0 1px!important; border-radius:0!important; padding:12px 2px!important; } +.nearby-row strong { font-size:15px; font-variant-numeric:tabular-nums; } +.nearby-row-meta { display:block; margin-top:5px; color:var(--ui-muted); font-size:12px; } +.nearby-row-end { display:flex; flex-direction:column; align-items:flex-end; gap:5px; color:var(--ui-muted); font-size:12px; } +.vehicle-status { color:var(--ui-ink); font-weight:600; } +.vehicle-status.available { color:var(--discovery-available,#237947); } +.vehicle-status.lowbattery,.vehicle-status.locked { color:var(--discovery-warning,#9a5a08); } +.discovery-empty { padding:15px 4px; line-height:1.8; color:var(--ui-muted); } +.discovery-empty strong { color:var(--ui-ink); } +.discovery-empty button { margin-top:10px; } +.location-status { position:absolute; z-index:125; bottom:14px; left:50%; transform:translateX(-50%); width:min(400px,calc(100% - 130px)); padding:10px 12px; border:1px solid var(--ui-line-strong); border-radius:12px; background:var(--ui-surface); color:var(--ui-ink); box-shadow:var(--ui-shadow-sm); font-size:12px; line-height:1.6; } +.location-status-actions { display:flex; gap:8px; margin-top:5px; } +.stats-card { top:auto!important; bottom:14px; } +.legend summary { cursor:pointer; min-height:32px; font-size:12px; color:var(--ui-muted); } +.legend:not([open]) .legend-item { display:none; } +.theme-options { display:flex; gap:8px; padding:12px 0; } +.theme-options button { flex:1; } +.theme-options button[aria-pressed=true] { background:var(--ui-solid); color:var(--ui-on-solid); } +.order-filters { display:grid; grid-template-columns:1fr 1fr; gap:10px; margin:10px 0 14px; } +.order-filters label { display:flex; flex-direction:column; gap:6px; color:var(--ui-muted); font-size:12px; min-width:0; } +.order-filter-actions { display:flex; gap:8px; grid-column:1/-1; } +.order-load-more { margin-top:12px; } +.sub-rule { border-bottom:1px solid var(--ui-line); padding:12px 0; font-size:13px; line-height:1.7; } +.sub-rule-head { display:flex; justify-content:space-between; align-items:flex-start; gap:10px; } +.sub-rule-meta,.sub-rule-result { color:var(--ui-muted); font-size:12px; margin-top:4px; } +.sub-rule-actions { display:flex; gap:6px; flex-wrap:wrap; margin-top:8px; } +.sub-rule-actions button { min-height:40px; padding:6px 12px; } +.sub-rule-actions .danger { color:var(--danger); } +.sub-editor-heading { display:flex; justify-content:space-between; align-items:center; margin-bottom:10px; } +.sub-editor-heading button { min-height:40px; padding:6px 10px; border:1px solid var(--ui-line); border-radius:8px; background:var(--ui-surface); color:var(--ui-ink); } +.preview-notice { display:flex; align-items:center; justify-content:space-between; padding:6px 16px; gap:12px; background:#f6edd6; color:#624608; font-size:12px; line-height:1.6; z-index:170; flex-shrink:0; } +.preview-notice button,.preview-login { border:1px solid currentColor; border-radius:8px; padding:7px 12px; color:inherit; background:transparent; min-height:40px; cursor:pointer; } +.preview-login { display:block; width:100%; margin-top:12px; color:var(--ui-ink); border-color:var(--ui-line-strong); } +.preview-notice a { color:inherit; } +.discovery-welcome { display:flex; gap:12px; padding:14px; margin:10px 0; background:var(--ui-surface-raised); border-radius:12px; color:var(--ui-muted); font-size:13px; line-height:1.7; } +.discovery-welcome strong { color:var(--ui-ink); } +.bike-card:not(.show) { visibility:hidden; pointer-events:none; } +.bike-card.show { visibility:visible; } +.auth-modal:not(.show),.qr-modal:not(.show),.unlock-confirm-modal:not(.show),.return-confirm-modal:not(.show),.token-expired-modal:not(.show),.lost-modal:not(.show),.return-modal:not(.show),.bell-modal:not(.show) { visibility:hidden; } +html,body { overflow:clip; } +body { animation:none!important; } +.locate-btn.locate-fab { min-width:44px; min-height:44px; } +.auth-close,.bike-card-close,.qr-close { min-width:44px; min-height:44px; } +.sr-only { position:absolute; width:1px; height:1px; padding:0; margin:-1px; overflow:hidden; clip-path:inset(50%); white-space:nowrap; border:0; } +button:disabled { cursor:wait; opacity:.65; } +@media (max-width:768px) { + .discovery-toolbar { width:calc(100% - 24px); padding:8px; } + .legend { top:auto!important; bottom:74px!important; right:12px!important; padding:7px 10px!important; } + .legend summary { min-height:30px; } + .stats-card { bottom:12px; left:12px!important; } + .location-status { bottom:65px; width:calc(100% - 24px); } + .nearby-panel { max-height:56%; } + .locate-btn.locate-fab { width:auto; height:44px; padding:8px 12px; bottom:92px; right:12px; } + .locate-fab-label { display:inline!important; font-size:12px; } + .favorite-places { max-height:46px; } + .preview-notice { padding:5px 12px; } + .preview-notice button { min-height:32px; padding:4px 8px; } +} +@media (prefers-reduced-motion:reduce) { .nearby-panel,.discovery-toolbar { transition:none; } } + +.battery-unknown .battery-unit { display:none; } +body:has(#nearby-panel:not([hidden])) .locate-fab { display:none; } +.preview-notice > span { flex:1; } +@media(max-width:768px){ .preview-notice { flex-wrap:wrap; gap:4px 8px; } .preview-notice > span { flex-basis:100%; } .preview-notice button { min-height:32px; } } diff --git a/static/css/theme-modes.css b/static/css/theme-modes.css new file mode 100644 index 0000000..88f1595 --- /dev/null +++ b/static/css/theme-modes.css @@ -0,0 +1,114 @@ +/* Explicit light / dark modes, selected before first paint. */ +:root[data-theme="light"] { + --bg-primary: #ffffff; + --bg-secondary: #f5f5f7; + --bg-card: #ffffff; + --text-primary: #1d1d1f; + --text-secondary: #6e6e73; + --text-tertiary: #86868b; + --border-color: #e5e5ea; + --accent-color: #0071e3; + --accent-hover: #0077ed; + --accent-soft: rgba(0, 113, 227, 0.10); + --success: #34c759; + --success-press: #2fb950; + --warning: #ff9f0a; + --danger: #ff3b30; + --error-color: #ff3b30; + --overlay: rgba(0, 0, 0, 0.45); + --shadow-sm: 0 2px 8px rgba(0,0,0,0.08); + --shadow-md: 0 4px 20px rgba(0,0,0,0.12); + --shadow-lg: 0 8px 32px rgba(0,0,0,0.16); + --shadow-up: 0 -4px 20px rgba(0,0,0,0.08); + --radius-sm: 8px; + --radius-md: 12px; + --radius-lg: 16px; + --radius-xl: 20px; + --transition: 0.3s cubic-bezier(0.4, 0, 0.2, 1); + --ease-spring: cubic-bezier(0.34, 1.3, 0.5, 1); + --ui-canvas: #f6f6f4; + --ui-surface: #fbfbfa; + --ui-surface-raised: #f0f0ee; + --ui-ink: #171719; + --ui-muted: #68686f; + --ui-faint: #929299; + --ui-line: rgba(23, 23, 25, .09); + --ui-line-strong: rgba(23, 23, 25, .15); + --ui-solid: #1c1c1f; + --ui-on-solid: #f8f8f6; + --ui-acrylic: color-mix(in srgb, var(--ui-surface) 68%, transparent); + --ui-acrylic-soft: color-mix(in srgb, var(--ui-surface) 46%, transparent); + --ui-header-acrylic: rgba(251, 251, 250, .64); + --ui-overlay: rgba(12, 12, 14, .52); + --ui-focus: rgba(23, 23, 25, .24); + --ui-shadow-sm: 0 1px 2px rgba(18, 18, 20, .04), 0 8px 24px rgba(18, 18, 20, .05); + --ui-shadow-md: 0 18px 52px rgba(18, 18, 20, .11); + --ui-shadow-lg: 0 32px 90px rgba(18, 18, 20, .16); + --ui-r-sm: 8px; + --ui-r-md: 12px; + --ui-r-lg: 16px; + --ui-r-xl: 20px; + --ui-r-2xl: 24px; + --ui-ease: cubic-bezier(.16, 1, .3, 1); + --ui-fast: 160ms; + --ui-normal: 280ms; + --discovery-available: #237947; + --discovery-warning: #915807; +} +:root[data-theme="dark"] { + --bg-primary: #000000; + --bg-secondary: #1c1c1e; + --bg-card: #2c2c2e; + --text-primary: #f5f5f7; + --text-secondary: #b0b0b7; + --text-tertiary: #636366; + --border-color: #38383a; + --accent-color: #0a84ff; + --accent-hover: #409cff; + --accent-soft: rgba(10, 132, 255, 0.16); + --success: #30d158; + --success-press: #28bd4d; + --warning: #ff9f0a; + --danger: #ff453a; + --error-color: #ff453a; + --overlay: rgba(0, 0, 0, 0.6); + --shadow-sm: 0 2px 8px rgba(0,0,0,0.3); + --shadow-md: 0 4px 20px rgba(0,0,0,0.4); + --shadow-lg: 0 8px 32px rgba(0,0,0,0.5); + --shadow-up: 0 -4px 20px rgba(0,0,0,0.4); + --radius-sm: 8px; + --radius-md: 12px; + --radius-lg: 16px; + --radius-xl: 20px; + --transition: 0.3s cubic-bezier(0.4, 0, 0.2, 1); + --ease-spring: cubic-bezier(0.34, 1.3, 0.5, 1); + --ui-canvas: #101011; + --ui-surface: #18181a; + --ui-surface-raised: #222225; + --ui-ink: #f1f1ef; + --ui-muted: #b0b0b7; + --ui-faint: #77777f; + --ui-line: rgba(241, 241, 239, .09); + --ui-line-strong: rgba(241, 241, 239, .16); + --ui-solid: #eeeeec; + --ui-on-solid: #151517; + --ui-acrylic: color-mix(in srgb, var(--ui-surface) 68%, transparent); + --ui-acrylic-soft: color-mix(in srgb, var(--ui-surface) 46%, transparent); + --ui-header-acrylic: rgba(238, 238, 236, .07); + --ui-overlay: rgba(3, 3, 4, .68); + --ui-focus: rgba(241, 241, 239, .28); + --ui-shadow-sm: 0 1px 2px rgba(2, 2, 3, .22), 0 10px 28px rgba(2, 2, 3, .18); + --ui-shadow-md: 0 20px 56px rgba(2, 2, 3, .32); + --ui-shadow-lg: 0 36px 100px rgba(2, 2, 3, .46); + --ui-r-sm: 8px; + --ui-r-md: 12px; + --ui-r-lg: 16px; + --ui-r-xl: 20px; + --ui-r-2xl: 24px; + --ui-ease: cubic-bezier(.16, 1, .3, 1); + --ui-fast: 160ms; + --ui-normal: 280ms; + --discovery-available: #78d99e; + --discovery-warning: #f3c57b; +} +:root[data-theme="dark"] .preview-notice { background:#352d1d; color:#f3cf85; } diff --git a/static/js/api-client.js b/static/js/api-client.js new file mode 100644 index 0000000..98421e6 --- /dev/null +++ b/static/js/api-client.js @@ -0,0 +1,32 @@ +/* Bounded requests; mutation requests are never retried automatically. */ +(function () { + 'use strict'; + const pending = new Map(); + async function request(url, options = {}) { + const controller = new AbortController(); + const abort = () => controller.abort(); + if (options.signal?.aborted) controller.abort(); + else options.signal?.addEventListener('abort', abort, { once: true }); + const timer = setTimeout(abort, options.timeout || 15000); + try { + return await fetch(url, { ...options, signal: controller.signal }); + } catch (error) { + if (error.name === 'AbortError') throw new Error('请求超时或已取消,请刷新状态后重试'); + throw error; + } finally { + clearTimeout(timer); + options.signal?.removeEventListener('abort', abort); + } + } + async function run(key, button, action) { + if (pending.has(key)) return pending.get(key); + if (button) { button.disabled = true; button.setAttribute('aria-busy', 'true'); } + const task = Promise.resolve().then(action).finally(() => { + pending.delete(key); + if (button) { button.disabled = false; button.removeAttribute('aria-busy'); } + }); + pending.set(key, task); + return task; + } + window.AppAPI = { fetch: request, run }; +})(); diff --git a/static/js/bike-data.js b/static/js/bike-data.js new file mode 100644 index 0000000..19d3e2e --- /dev/null +++ b/static/js/bike-data.js @@ -0,0 +1,41 @@ +/* Shared vehicle rules. Unknown battery data is never invented. */ +(function (root) { + 'use strict'; + function electric(bike) { + const raw = bike?.electric_quantity ?? bike?.electricQuantity ?? bike?.electric; + if (raw === null || raw === undefined || typeof raw === 'boolean' || String(raw).trim() === '') return null; + const n = Number(raw); + return Number.isFinite(n) && n >= 0 && n <= 100 ? n : null; + } + function state(bike) { + const s = Number(bike?.state), occupied = Number(bike?.status), e = electric(bike); + if (s === 1 && occupied === 1) return 'inuse'; + if (s === 4) return 'locked'; + if (s === 2) return 'reserved'; + if (s === 10 || (e !== null && e < 20)) return 'lowbattery'; + if (s === 1 && occupied === 0) return 'available'; + return 'unknown'; + } + const labels = { available: '可用', inuse: '使用中', locked: '欠压', reserved: '损坏', lowbattery: '低电量', unknown: '状态未知' }; + function kind(bike) { + const code = String(bike?.code ?? bike?.bike_code ?? ''); + if (/^\d{8}$/.test(code)) return 'red'; + return Number(code.slice(0, 3)) >= 511 ? 'big' : 'small'; + } + function validCode(code) { return /^(?:\d{5}|\d{8})$/.test(String(code)); } + function distance(a, b) { + if (!a || !b || ![a.lat, a.lng, b.lat, b.lng].every(Number.isFinite)) return null; + const rad = Math.PI / 180, dlat = (b.lat - a.lat) * rad, dlng = (b.lng - a.lng) * rad; + const h = Math.sin(dlat / 2) ** 2 + Math.cos(a.lat * rad) * Math.cos(b.lat * rad) * Math.sin(dlng / 2) ** 2; + return 12742000 * Math.asin(Math.sqrt(Math.min(1, h))); + } + function matches(bike, filters) { + const e = electric(bike); + return (!filters.onlyAvailable || state(bike) === 'available') && + (!filters.kind || filters.kind === 'all' || kind(bike) === filters.kind) && + (!(filters.minElectric > 0) || (e !== null && e >= filters.minElectric)); + } + const api = { electric, state, labels, kind, validCode, distance, matches }; + if (typeof module !== 'undefined' && module.exports) module.exports = api; + root.BikeData = api; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/static/js/map-account.js b/static/js/map-account.js new file mode 100644 index 0000000..08b89ac --- /dev/null +++ b/static/js/map-account.js @@ -0,0 +1,1279 @@ + // ========== 登录认证 ========== + function handleAuthBtnClick() { + if (currentUser) { + // 已登录,显示个人中心 + showProfileModal(); + } else { + // 未登录,显示登录弹窗 + showLoginModal(); + } + } + + function showLoginModal() { + closeAllModals(); + document.getElementById("login-modal").classList.add("show"); + document.getElementById("login-email").focus(); + } + + function closeLoginModal() { + document.getElementById("login-modal").classList.remove("show"); + document.getElementById("login-tip").textContent = ""; + } + + function showRegisterModal() { + closeLoginModal(); + closeRegisterModal(); + document.getElementById("register-modal").classList.add("show"); + document.getElementById("register-email").focus(); + } + + function closeRegisterModal() { + document.getElementById("register-modal").classList.remove("show"); + document.getElementById("register-tip").textContent = ""; + } + + function openSettingsPage() { + closeAllModals(); + document.getElementById("settings-clustering").checked = bikeClusteringEnabled; + document.getElementById("settings-save-status").textContent = "地图偏好自动保存在当前设备,即时生效。"; + SettingsPages.open("settings-modal"); + loadProfileData(); + } + + function closeSettingsPage() { SettingsPages.back(); } + + function saveMapClusteringSetting(enabled) { + if (typeof BikeClusters === "undefined") { + showToast("地图组件未加载,请刷新页面后重试"); + return; + } + bikeClusteringEnabled = !!enabled; + if (bikeBubbleLayer) bikeBubbleLayer.setClusteringEnabled(bikeClusteringEnabled); + const saved = BikeClusters.writeClusteringPreference(localStorage, bikeClusteringEnabled); + document.getElementById("settings-save-status").textContent = saved + ? (bikeClusteringEnabled ? "已开启车辆聚类,设置已保存。" : "已关闭聚类,所有车辆单独显示。设置已保存。") + : "设置已生效,当前浏览器无法保存,刷新后会恢复默认。"; + } + + window.addEventListener("storage", event => { + if (typeof BikeClusters === "undefined") return; + if (event.key !== BikeClusters.PREFERENCE_KEY && event.key !== null) return; + bikeClusteringEnabled = BikeClusters.readClusteringPreference(localStorage); + if (bikeBubbleLayer) bikeBubbleLayer.setClusteringEnabled(bikeClusteringEnabled); + document.getElementById("settings-clustering").checked = bikeClusteringEnabled; + }); + + function showProfileModal() { openSettingsPage(); } + + function closeProfileModal() { SettingsPages.close(); } + + function closeAllModals() { + if (typeof SettingsPages !== "undefined") SettingsPages.hide(); + document.getElementById("login-modal").classList.remove("show"); + document.getElementById("register-modal").classList.remove("show"); + document.getElementById("settings-modal").classList.remove("show"); + document.getElementById("rental-settings-modal").classList.remove("show"); + document.getElementById("devices-modal").classList.remove("show"); + document.getElementById("auth-modal").classList.remove("show"); + document.getElementById("packages-modal").classList.remove("show"); + const forgot = document.getElementById("forgot-modal"); + if (forgot) forgot.classList.remove("show"); + const orders = document.getElementById("orders-modal"); + if (orders) orders.classList.remove("show"); + const subscribe = document.getElementById("subscribe-modal"); + if (subscribe) subscribe.classList.remove("show"); + const traj = document.getElementById("order-traj-modal"); + if (traj) traj.classList.remove("show"); + const _armc = document.getElementById("add-round-modal"); + if (_armc) _armc.classList.remove("show"); + const _srm = document.getElementById("share-return-modal"); + if (_srm) _srm.classList.remove("show"); + appConfirmClose(); // 视为「取消」,避免 Promise 悬空 + } + + async function loadProfileData() { + if (!authToken) return; + + try { + const resp = await apiFetch("/api/auth/profile", { + headers: { "Authorization": `Bearer ${authToken}` } + }); + const data = await resp.json(); + + if (data.rtn_code === 0 && data.data) { + const email = data.data.email || ""; + document.getElementById("profile-email").textContent = email; + const firstChar = email.charAt(0).toUpperCase(); + document.getElementById("profile-avatar").textContent = firstChar; + + maybeStrictGuide(data.data); + + // 微信凭据(accessToken JWT)有效期,实时倒计时展示 + _savedTokenExpiry = data.data.access_token_expiry && data.data.access_token_expiry.parseable + ? { expireAt: data.data.access_token_expiry.expire_at, + source: data.data.access_token_expiry.source } : null; + updateTokenExpiryDisplays(); + + // 隐藏/显示消费统计和提示 + const hasAuth = data.data.has_auth; + document.getElementById("profile-stats").style.display = hasAuth ? "flex" : "none"; + document.getElementById("profile-auth-hint").style.display = hasAuth ? "none" : "flex"; + document.getElementById("profile-name").textContent = "--"; + document.getElementById("profile-out-money").textContent = "--"; + document.getElementById("profile-save-money").textContent = "--"; + } + } catch (err) { + console.error("加载用户信息失败:", err); + } + + // 加载姓名和消费信息 + loadUserInfo(); + } + + async function loadUserInfo() { + if (!authToken) return; + + try { + const resp = await apiFetch("/api/auth/user_info", { + headers: { "Authorization": `Bearer ${authToken}` } + }); + const data = await resp.json(); + + if (data.rtn_code === 0 && data.data) { + const info = data.data; + + // 显示姓名 + if (info.true_name) { + document.getElementById("profile-name").textContent = info.true_name; + document.getElementById("profile-avatar").textContent = info.true_name.charAt(0); + } + + // 显示消费统计 + if (info.out_money !== null) { + document.getElementById("profile-out-money").textContent = (info.out_money || 0).toFixed(1); + } + if (info.save_money !== null) { + document.getElementById("profile-save-money").textContent = (info.save_money || 0).toFixed(1); + } + } + } catch (err) { + console.error("加载用户详情失败:", err); + } + } + + // ========== AccessToken 有效期解析 ========== + // accessToken 是上游登录响应中的 JWT(RS256),payload 带 iat/nbf/exp, + // 实测有效期 30 天。此处只解码展示,不做签名校验。 + function parseJwtExpiry(token) { + token = (token || "").trim(); + if (!token || token.indexOf(".") < 0) return null; + const parts = token.split("."); + if (parts.length !== 3 || parts[1].length < 8) return null; + try { + let b64 = parts[1].replace(/-/g, "+").replace(/_/g, "/"); + while (b64.length % 4) b64 += "="; + const payload = JSON.parse(decodeURIComponent(escape(atob(b64)))); + let exp = payload.exp ? parseInt(payload.exp) : null; + let iat = payload.iat ? parseInt(payload.iat) : null; + if (!exp && iat) exp = iat + 30 * 86400; // 与上游实测一致:30 天有效期 + if (!exp) return null; + return { expireAt: exp, source: payload.exp ? "exp" : "iat+30d" }; + } catch (e) { return null; } + } + function fmtLocalTime(ts) { + const d = new Date(ts * 1000); + const p = n => String(n).padStart(2, "0"); + return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`; + } + function describeTokenExpiry(expiry) { + const remain = expiry.expireAt - Math.floor(Date.now() / 1000); + const when = fmtLocalTime(expiry.expireAt); + const left = remain <= 0 ? "已过期" : `约剩 ${fmtRemainShort(remain)}`; + const note = expiry.source === "iat+30d" ? "(按签发时间 +30 天推算)" : ""; + return { text: `该凭据(登录态)有效期至 ${when}${note},${left}`, remain }; + } + function fmtRemainShort(remain) { + const dd = Math.floor(remain / 86400), hh = Math.floor((remain % 86400) / 3600), + mm = Math.floor((remain % 3600) / 60); + if (dd >= 1) return `${dd} 天${hh ? " " + hh + " 小时" : ""}`; + if (hh >= 1) return `${hh} 小时${mm ? " " + mm + " 分" : ""}`; + return `${Math.max(1, mm)} 分钟`; + } + function renderTokenExpiry(el, expiry) { + if (!el) return; + if (!expiry) { el.style.display = "none"; el.innerHTML = ""; return; } + const { text, remain } = describeTokenExpiry(expiry); + let color = "#34c759", bg = "#eafaf0"; + if (remain <= 0) { color = "#e02020"; bg = "#fdecec"; } + else if (remain <= 259200) { color = "#e02020"; bg = "#fdecec"; } // ≤3 天 + else if (remain <= 604800) { color = "#e67e22"; bg = "#fdf3e7"; } // ≤7 天 + el.style.display = "block"; + el.style.color = color; + el.style.background = bg; + el.textContent = text; + } + function updateTokenExpiryDisplays() { + // “填写凭证”弹窗:粘贴中的新 token 优先实时预览,否则显示已保存凭据 + const authEl = document.getElementById("auth-token-expiry"); + if (authEl) { + const pasted = document.getElementById("profile-token").value.trim(); + if (pasted) { + const expiry = parseJwtExpiry(pasted); + if (expiry) { + renderTokenExpiry(authEl, expiry); + } else { + authEl.style.display = "block"; + authEl.style.color = "#e67e22"; + authEl.style.background = "#fdf3e7"; + authEl.textContent = "无法解析该 AccessToken 的有效期(不是标准 JWT,仍可保存使用)"; + } + } else { + renderTokenExpiry(authEl, _savedTokenExpiry); + } + } + // 个人中心:始终实时显示 + const pEl = document.getElementById("profile-token-expiry"); + if (pEl) renderTokenExpiry(pEl, _savedTokenExpiry); + renderAuthExpiryBanner(); + } + let _savedTokenExpiry = null; + + // ========== 登录态到期横幅 ========== + // 有效期不足 2 天时在主页面顶部常驻提醒,避免用户毫无预警地遇到上游凭据失效。 + const AUTH_EXPIRY_BANNER_THRESHOLD = 2 * 86400; // 2 天 + const AUTH_EXPIRY_BANNER_URGENT = 86400; // 不足 1 天转红 + function renderAuthExpiryBanner() { + const banner = document.getElementById("auth-expiry-banner"); + if (!banner) return; + const text = document.getElementById("auth-expiry-banner-text"); + if (!authToken || !_savedTokenExpiry) { + banner.classList.remove("show", "urgent"); + return; + } + const { remain } = describeTokenExpiry(_savedTokenExpiry); + if (remain > AUTH_EXPIRY_BANNER_THRESHOLD) { + banner.classList.remove("show", "urgent"); + return; + } + const when = fmtLocalTime(_savedTokenExpiry.expireAt); + text.textContent = remain <= 0 + ? "登录态已过期,为不影响使用请尽快抓包" + : `登录态剩 ${fmtRemainShort(remain)},为不影响使用请尽快抓包`; + banner.title = `有效期至 ${when}`; + banner.classList.toggle("urgent", remain <= AUTH_EXPIRY_BANNER_URGENT); + banner.classList.add("show"); + } + // 拉取服务端解析出的有效期(profile 接口),成功后刷新横幅 + async function refreshAuthExpiry() { + if (!authToken) { _savedTokenExpiry = null; renderAuthExpiryBanner(); return; } + try { + const resp = await apiFetch("/api/auth/profile", { + headers: { "Authorization": `Bearer ${authToken}` } + }); + const data = await resp.json(); + if (data.rtn_code === 0 && data.data) { + const e = data.data.access_token_expiry; + _savedTokenExpiry = e && e.parseable + ? { expireAt: e.expire_at, source: e.source } : null; + } else { + _savedTokenExpiry = null; + } + } catch (err) { + console.error("获取登录态有效期失败:", err); + } + updateTokenExpiryDisplays(); + } + setInterval(updateTokenExpiryDisplays, 30000); // 实时倒计时:每 30 秒刷新 + + // 打开凭证填写弹窗 + function openAuthModal() { + closeAllModals(); + SettingsPages.open("auth-modal"); + // 填充现有值 + apiFetch("/api/auth/profile", { + headers: { "Authorization": `Bearer ${authToken}` } + }).then(r => r.json()).then(data => { + if (data.rtn_code === 0 && data.data) { + document.getElementById("profile-token").value = data.data.token || ""; + document.getElementById("profile-token-id").value = data.data.token_id || ""; + const alertEl = document.getElementById("profile-alert-email"); + if (alertEl) { + // 未自定义时显示账号邮箱占位(提交空串即回退账号邮箱) + alertEl.value = data.data.alert_email || ""; + alertEl.placeholder = data.data.email || "留空则使用账号邮箱"; + } + _savedTokenExpiry = data.data.access_token_expiry && data.data.access_token_expiry.parseable + ? { expireAt: data.data.access_token_expiry.expire_at, + source: data.data.access_token_expiry.source } : null; + updateTokenExpiryDisplays(); + } + }); + } + + function closeAuthModal() { + SettingsPages.back(); + } + + // ========== 强签名验证引导 ========== + let _strictGuideShown = false; + function maybeStrictGuide(info) { + if (info && info.strict_mode && info.has_access_token === false && !_strictGuideShown) { + _strictGuideShown = true; + showTokenExpiredModal( + "需要补充 AccessToken", + "管理员已开启强签名验证,您的账号尚未填写 AccessToken,填写前无法调用用车功能。请按教程抓包获取 accessToken(登录响应中的 JWT)并保存。" + ); + } + } + async function checkStrictGuide() { + if (!authToken) return; + try { + const resp = await apiFetch("/api/auth/profile", { + headers: { "Authorization": `Bearer ${authToken}` } + }); + const data = await resp.json(); + if (data.rtn_code === 0 && data.data) maybeStrictGuide(data.data); + } catch (err) { console.error("强验证检测失败:", err); } + } + + // ========== 登录设备管理(多设备) ========== + // 生成本设备持久标识:同一浏览器/设备保持不变,用于区分不同登录设备 + function getDeviceId() { + let id = localStorage.getItem("xbniu_device_id"); + if (!id) { + id = Date.now().toString(36) + Math.random().toString(36).slice(2, 8); + try { localStorage.setItem("xbniu_device_id", id); } catch (e) {} + } + return id; + } + function getDeviceName() { + const ua = navigator.userAgent || ""; + // 与服务端 routes/auth.py _ua_label 保持同一套识别规则 + if (/xbniu-native/i.test(ua)) return "Native App"; + let os; + if (/Windows NT/.test(ua)) os = "Windows"; + else if (/iPhone|iPad|iPod/.test(ua)) os = "iOS"; + else if (/OpenHarmony|HarmonyOS|ArkWeb/.test(ua)) os = "鸿蒙"; + else if (/Android/.test(ua)) os = "Android"; + else if (/Mac OS X/.test(ua)) os = "macOS"; + else if (/Linux/.test(ua)) os = "Linux"; + else os = /Mobile/.test(ua) ? "移动设备" : "电脑"; + let browser = "浏览器"; + if (/MicroMessenger/i.test(ua)) browser = "微信"; + else if (/HuaweiBrowser/.test(ua)) browser = "华为浏览器"; + else if (/Edg\//.test(ua)) browser = "Edge"; + else if (/QQBrowser/.test(ua)) browser = "QQ浏览器"; + else if (/MiuiBrowser/.test(ua)) browser = "小米浏览器"; + else if (/Chrome\//.test(ua)) browser = "Chrome"; + else if (/Firefox\//.test(ua)) browser = "Firefox"; + else if (/Safari\//.test(ua)) browser = "Safari"; + let label = os + " · " + browser; + if (window.screen && screen.width) label += " · " + screen.width + "x" + screen.height; + return label; + } + function escHtml(s) { + return String(s == null ? "" : s).replace(/[&<>"']/g, + c => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); + } + function fmtTime(t) { + if (!t) return ""; + return escHtml(String(t).replace("T", " ").slice(0, 16)); + } + function openDevicesModal() { + closeAllModals(); + SettingsPages.open("devices-modal"); + loadDevicesList(); + } + function closeDevicesModal() { + SettingsPages.back(); + } + async function loadDevicesList() { + const box = document.getElementById("devices-list"); + if (!authToken) { box.innerHTML = '
请先登录
'; return; } + box.innerHTML = '
加载中...
'; + try { + const resp = await apiFetch("/api/auth/sessions", { + headers: { "Authorization": `Bearer ${authToken}` } + }); + const data = await resp.json(); + if (data.rtn_code !== 0) { + box.innerHTML = '
' + escHtml(data.message || "加载失败") + '
'; + return; + } + const list = data.data.sessions || []; + if (!list.length) { + box.innerHTML = '
暂无其他登录设备
'; + return; + } + box.innerHTML = list.map(s => { + const isCur = !!s.is_current; + const meta = "登录 " + fmtTime(s.created_at) + + (s.last_active ? " · 活跃 " + fmtTime(s.last_active) : ""); + return `
+
+
${escHtml(s.device_name || "未知设备")}${isCur ? ' 当前' : ""}
+
${meta}
+
+ ${isCur ? "" : ``} +
`; + }).join(""); + } catch (err) { + box.innerHTML = '
加载失败
'; + } + } + async function kickDevice(id) { + if (!(await appConfirm("确认将该设备下线?该设备需要重新登录。", { title: "下线设备", okText: "下线" }))) return; + try { + const resp = await apiFetch("/api/auth/sessions/kick", { + method: "POST", + headers: { "Authorization": `Bearer ${authToken}`, "Content-Type": "application/json" }, + body: JSON.stringify({ session_id: id }) + }); + const data = await resp.json(); + if (data.rtn_code === 0) { showToast("已下线该设备"); loadDevicesList(); } + else showToast(data.message || "下线失败"); + } catch (e) { showToast("网络错误"); } + } + async function logoutAllOtherDevices() { + if (!(await appConfirm("确认下线当前账号其他所有设备?\n本设备会保留登录。", { title: "下线其他设备", okText: "全部下线" }))) return; + try { + const resp = await apiFetch("/api/auth/sessions/logout_all", { + method: "POST", + headers: { "Authorization": `Bearer ${authToken}` } + }); + const data = await resp.json(); + if (data.rtn_code === 0) { showToast("已下线其他所有设备"); loadDevicesList(); } + else showToast(data.message || "操作失败"); + } catch (e) { showToast("网络错误"); } + } + + // 打开卡包弹窗 + function openPackagesModal() { + closeAllModals(); + SettingsPages.open("packages-modal"); + loadPackagesList(); + } + + function closePackagesModal() { + SettingsPages.back(); + } + + // 加载卡包列表(用于卡包弹窗) + async function loadPackagesList() { + if (!authToken) { + document.getElementById("packages-list-2").innerHTML = '
请先登录
'; + return; + } + + try { + const resp = await apiFetch("/api/auth/packages", { + headers: { "Authorization": `Bearer ${authToken}` } + }); + const data = await resp.json(); + const container = document.getElementById("packages-list-2"); + + if (!data.data || !data.data.has_auth) { + container.innerHTML = '
请先填写 Token ID(AccessToken 选填)
'; + return; + } + + const packages = data.data.packages || []; + if (packages.length === 0) { + container.innerHTML = '
暂无优惠卡
'; + return; + } + + container.innerHTML = packages.map(pkg => ` +
+
${pkg.name}
+
${pkg.bikeTypeName || ''} · ${pkg.useTypeName || ''}
+
有效期至 ${pkg.endTime || '无限'}
+
剩余 ${pkg.remainTimes ?? '∞'} 次
+
+ `).join(''); + } catch (err) { + console.error("加载卡包失败:", err); + document.getElementById("packages-list-2").innerHTML = '
加载失败
'; + } + } + + async function saveProfileToken() { + if (!authToken) { + showToast("请先登录"); + return; + } + + const access_token = document.getElementById("profile-token").value.trim(); + const token_id = document.getElementById("profile-token-id").value.trim(); + const alertEmailEl = document.getElementById("profile-alert-email"); + const alert_email = alertEmailEl ? alertEmailEl.value.trim().toLowerCase() : null; + + // 如果填了任意一个字段,需要先验证 + if (access_token || token_id) { + if (!token_id) { + showToast("Token ID 必填;AccessToken 选填"); + return; + } + + // 先验证(必须带登录态,否则 verify_token 返回 401) + try { + const verifyResp = await apiFetch("/api/auth/verify_token", { + method: "POST", + headers: { "Content-Type": "application/json", + "Authorization": `Bearer ${authToken}` }, + body: JSON.stringify({ access_token, token_id }) + }); + const verifyData = await verifyResp.json(); + + if (!verifyData.valid) { + showToast(verifyData.message || "凭据验证失败,请检查 Token ID 是否正确"); + return; + } + } catch (err) { + showToast("验证失败"); + return; + } + } + + // 验证通过或没填字段,直接保存 + try { + const resp = await apiFetch("/api/auth/save_token", { + method: "POST", + headers: { + "Authorization": `Bearer ${authToken}`, + "Content-Type": "application/json" + }, + body: JSON.stringify({ access_token, token_id }) + }); + const data = await resp.json(); + + if (data.rtn_code === 0) { + // 告警邮箱单独保存(可与凭据一起提交,失败不阻断) + if (alert_email !== null) { + apiFetch("/api/auth/alert_email", { + method: "POST", + headers: { "Content-Type": "application/json", + "Authorization": `Bearer ${authToken}` }, + body: JSON.stringify({ email: alert_email }) + }).catch(() => {}); + } + showToast("保存成功"); + closeAuthModal(); // 关闭凭证弹窗 + loadProfileData(); // 刷新个人中心数据 + refreshAuthExpiry(); // 新凭据可能已换有效期,重算顶部提醒 + } else { + showToast(data.message || "保存失败"); + } + } catch (err) { + showToast("保存失败"); + } + } + + // ========== 批量响铃相关状态 ========== + let currentBellTab = 'all'; // 当前选项卡 + let selectedRadius = 200; // 选中的半径(米) + let selectedLocation = null; // 选中的地点 {lat, lng} + let selectedStatuses = {available: true, used: true, locked: true, low: true, reserved: true}; // 选中的状态 + let rangeCircleOverlay = null; // 范围圆覆盖物 + + function showBellPasswordModal() { + if (!canUseBatchRing()) { + showToast("批量寻铃仅对指定用户开放"); + return; + } + document.getElementById("bell-modal").classList.add("show"); + // 重置所有输入 + document.getElementById("bell-password").value = ""; + document.getElementById("bell-password-range").value = ""; + document.getElementById("bell-password-status").value = ""; + document.getElementById("bell-error").textContent = ""; + document.getElementById("bell-error-range").textContent = ""; + document.getElementById("bell-error-status").textContent = ""; + document.getElementById("bell-progress").textContent = ""; + + // 更新状态计数 + updateStatusCounts(); + + // 重置范围相关 + selectedLocation = null; + document.getElementById("range-point-text").textContent = "--"; + document.getElementById("range-hint").classList.remove("active"); + document.getElementById("range-hint").innerHTML = ` + + + + + 点击地图选择地点,或使用当前位置 + `; + + // 更新筛选信息 + updateFilterInfo(); + + document.getElementById("bell-password").focus(); + } + + // 切换选项卡 + function switchBellTab(tab) { + currentBellTab = tab; + + // 更新选项卡样式 + document.querySelectorAll('.bell-tab').forEach(t => { + t.classList.toggle('active', t.dataset.tab === tab); + }); + + // 更新内容区 + document.querySelectorAll('.bell-section').forEach(s => { + s.classList.toggle('active', s.id === `bell-section-${tab}`); + }); + + // 切换到范围模式时清除之前的选择 + if (tab !== 'range') { + if (rangeCircleOverlay) { + map.removeOverlay(rangeCircleOverlay); + rangeCircleOverlay = null; + } + } + } + + // 选择半径 + function selectRadius(radius) { + selectedRadius = radius; + document.querySelectorAll('.radius-btn').forEach(btn => { + btn.classList.toggle('active', parseInt(btn.dataset.radius) === radius); + }); + // 更新范围圆 + updateRangeCircle(); + updateFilterInfo(); + } + + // 使用当前位置 + function useCurrentLocation() { + if (!autoLocationMarker) { + showToast("请先开启定位(点击底部定位按钮)"); + return; + } + + const point = autoLocationMarker.getPosition(); + const lat = point.lat; + const lng = point.lng; + + selectedLocation = { lat, lng }; + + document.getElementById("range-point-text").textContent = `${lat.toFixed(5)}, ${lng.toFixed(5)}`; + document.getElementById("range-hint").classList.add("active"); + document.getElementById("range-hint").innerHTML = ` + + + + 已选择:${lat.toFixed(5)}, ${lng.toFixed(5)} + `; + + updateRangeCircle(); + updateFilterInfo(); + + showToast(`已选择地点,范围内 ${getFilteredBikes().length} 辆车`); + } + + // 使用地图中心 + function useCenterLocation() { + const center = map.getCenter(); + const lat = center.lat; + const lng = center.lng; + + selectedLocation = { lat, lng }; + + document.getElementById("range-point-text").textContent = `${lat.toFixed(5)}, ${lng.toFixed(5)}`; + document.getElementById("range-hint").classList.add("active"); + document.getElementById("range-hint").innerHTML = ` + + + + 已选择:${lat.toFixed(5)}, ${lng.toFixed(5)} + `; + + updateRangeCircle(); + updateFilterInfo(); + + showToast(`已选择地点,范围内 ${getFilteredBikes().length} 辆车`); + } + + // 更新范围圆覆盖物 + function updateRangeCircle() { + if (!selectedLocation) return; + + // 清除旧的 + if (rangeCircleOverlay) { + map.removeOverlay(rangeCircleOverlay); + } + + const point = new BMapGL.Point(selectedLocation.lng, selectedLocation.lat); + rangeCircleOverlay = new BMapGL.Circle(point, selectedRadius, { + strokeColor: "#007AFF", + strokeWeight: 2, + strokeOpacity: 0.6, + fillColor: "#007AFF", + fillOpacity: 0.1 + }); + map.addOverlay(rangeCircleOverlay); + } + + // 切换状态筛选 + function toggleStatusFilter(state) { + selectedStatuses[state] = !selectedStatuses[state]; + + const item = document.querySelector(`.bell-status-item[data-state="${state}"]`); + if (item) { + item.classList.toggle('selected', selectedStatuses[state]); + item.querySelector('.bell-status-check').textContent = selectedStatuses[state] ? '✓' : ''; + } + + updateFilterInfo(); + } + + // 更新状态计数 + function updateStatusCounts() { + const bikes = Object.values(markersData); + const counts = {available: 0, used: 0, locked: 0, low: 0, reserved: 0}; + + bikes.forEach(bike => { + const state = getBikeState(bike); + if (state === 'available') counts.available++; + else if (state === 'inuse') counts.used++; + else if (state === 'locked') counts.locked++; + else if (state === 'lowbattery') counts.low++; + else if (state === 'reserved') counts.reserved++; + }); + + document.getElementById('count-available-filter').textContent = counts.available; + document.getElementById('count-used-filter').textContent = counts.used; + document.getElementById('count-locked-filter').textContent = counts.locked; + document.getElementById('count-low-filter').textContent = counts.low; + document.getElementById('count-reserved-filter').textContent = counts.reserved; + } + + // 计算两点之间的距离(米) + function calcDistance(lat1, lng1, lat2, lng2) { + const R = 6371000; // 地球半径(米) + const dLat = (lat2 - lat1) * Math.PI / 180; + const dLng = (lng2 - lng1) * Math.PI / 180; + const a = Math.sin(dLat/2) * Math.sin(dLat/2) + + Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * + Math.sin(dLng/2) * Math.sin(dLng/2); + const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); + return R * c; + } + + // 根据当前模式筛选车辆 + function getFilteredBikes() { + const allBikes = Object.values(markersData); + + if (currentBellTab === 'all') { + return allBikes; + } + + if (currentBellTab === 'range') { + if (!selectedLocation) { + return []; // 没有选择地点 + } + return allBikes.filter(bike => { + if (!bike.latitude || !bike.longitude) return false; + // 车辆在地图上显示的位置(偏移后) + const c = offsetCoord(bike.latitude, bike.longitude); + const dist = calcDistance( + selectedLocation.lat, selectedLocation.lng, + c.lat, c.lng + ); + return dist <= selectedRadius; + }); + } + + if (currentBellTab === 'status') { + return allBikes.filter(bike => { + const state = getBikeState(bike); + if (state === 'available' && selectedStatuses.available) return true; + if (state === 'inuse' && selectedStatuses.used) return true; + if (state === 'locked' && selectedStatuses.locked) return true; + if (state === 'lowbattery' && selectedStatuses.low) return true; + if (state === 'reserved' && selectedStatuses.reserved) return true; + return false; + }); + } + + return allBikes; + } + + // 更新筛选信息显示 + function updateFilterInfo() { + const bikes = getFilteredBikes(); + + if (currentBellTab === 'range') { + const infoEl = document.getElementById('range-filter-info'); + if (selectedLocation) { + infoEl.textContent = `范围内车辆:${bikes.length} 辆`; + } else { + infoEl.textContent = ''; + } + } + + if (currentBellTab === 'status') { + const infoEl = document.getElementById('status-filter-info'); + const selectedCount = Object.values(selectedStatuses).filter(v => v).length; + infoEl.textContent = `已选 ${selectedCount} 种状态,共 ${bikes.length} 辆车`; + } + } + + function closeBellModal() { + document.getElementById("bell-modal").classList.remove("show"); + } + + async function submitBellPassword() { + // 根据当前选项卡获取密码和错误元素 + let pwd, errEl; + if (currentBellTab === 'all') { + pwd = document.getElementById("bell-password").value; + errEl = document.getElementById("bell-error"); + } else if (currentBellTab === 'range') { + pwd = document.getElementById("bell-password-range").value; + errEl = document.getElementById("bell-error-range"); + if (!selectedLocation) { + errEl.textContent = "请先选择地点(点击地图或使用当前位置/地图中心)"; + return; + } + } else { + pwd = document.getElementById("bell-password-status").value; + errEl = document.getElementById("bell-error-status"); + } + + if (pwd !== "070517") { + errEl.textContent = "密码错误"; + return; + } + + // 根据模式筛选车辆 + const bikes = getFilteredBikes(); + + if (bikes.length === 0) { + if (currentBellTab === 'range') { + errEl.textContent = "范围内没有车辆,请调整半径或选择其他地点"; + } else if (currentBellTab === 'status') { + errEl.textContent = "没有符合条件的车,请调整状态筛选"; + } else { + errEl.textContent = "暂无车辆数据,请先刷新地图"; + } + return; + } + + errEl.textContent = "启动中..."; + + try { + const res = await apiFetch("/api/ring_all", { + method: "POST", + headers: { + "Content-Type": "application/json", + "Authorization": `Bearer ${authToken}` + }, + body: JSON.stringify({ codes: bikes.map(b => b.code) }) + }); + const data = await res.json(); + if (data.rtn_code === 401) { + errEl.textContent = "登录已失效,请重新登录"; + showLoginGate(); + return; + } + if (data.rtn_code !== 0) { + errEl.textContent = data.message || "启动失败"; + return; + } + + closeBellModal(); + + // 清除范围圆 + if (rangeCircleOverlay) { + map.removeOverlay(rangeCircleOverlay); + rangeCircleOverlay = null; + } + + // 打开新窗口显示进度 + const progressWin = window.open( + `/ring_progress.html?task_id=${data.task_id}&total=${data.total}`, + "ring_progress", + "width=450,height=520,menubar=no,toolbar=no,location=no,status=no" + ); + if (!progressWin) { + showToast("请允许弹出窗口以查看进度"); + } + } catch (e) { + errEl.textContent = "请求失败: " + friendlyError(e); + } + } + + // ========== 全屏登录门 ========== + function showLoginGate() { + document.getElementById("login-gate").classList.add("show"); + } + function hideLoginGate() { + document.getElementById("login-gate").classList.remove("show"); + } + + async function doLogin(email, password, tip, submitBtn) { + const btnText = submitBtn.textContent; + tip.textContent = ""; + submitBtn.disabled = true; + submitBtn.textContent = "登录中..."; + try { + const resp = await apiFetch("/api/auth/login", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ email, password, device_id: getDeviceId(), device_name: getDeviceName() }) + }); + const data = await resp.json(); + + if (data.rtn_code === 0) { + if (currentUser?.email !== data.data.email) resetMapForAccount(); + authToken = data.data.token; + localStorage.setItem("auth_token", authToken); + currentUser = { email: data.data.email }; + authKickToastShown = false; + updateAuthButton(); + hideLoginGate(); + closeLoginModal(); + showToast("登录成功"); + shareAfterLogin(); + checkOrderStatus(); + checkRentalStatus(); + refreshAuthExpiry(); // 登录态有效期不足 2 天时挂顶部提醒 + if (map) { loadMapData(currentType, false); startAutoLocation(); } + } else { + tip.textContent = data.message || "登录失败"; + } + } catch (err) { + tip.textContent = "网络错误,请重试"; + } finally { + submitBtn.disabled = false; + submitBtn.textContent = btnText; + } + } + + async function handleLoginSubmit(e) { + e.preventDefault(); + doLogin( + document.getElementById("login-email").value.trim().toLowerCase(), + document.getElementById("login-password").value, + document.getElementById("login-tip"), + e.target.querySelector("button[type='submit']") + ); + } + + document.getElementById("gate-login-form").addEventListener("submit", function (e) { + e.preventDefault(); + doLogin( + document.getElementById("gate-email").value.trim().toLowerCase(), + document.getElementById("gate-password").value, + document.getElementById("gate-tip"), + this.querySelector("button[type='submit']") + ); + }); + + let registerCodeCountdown = 0; + let registerCodeTimer = null; + function setRegisterCodeBtn(text, disabled) { + const btn = document.getElementById("register-code-btn"); + if (!btn) return; + btn.disabled = disabled; + btn.textContent = text; + } + async function sendRegisterCode() { + const email = document.getElementById("register-email").value.trim().toLowerCase(); + const tip = document.getElementById("register-tip"); + if (!email) { tip.textContent = "请先填写邮箱"; return; } + if (registerCodeCountdown > 0) return; + setRegisterCodeBtn("发送中...", true); + try { + const resp = await apiFetch("/api/auth/send_code", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ email }) + }); + const data = await resp.json(); + tip.textContent = data.message || ""; + if (data.rtn_code === 0) { + registerCodeCountdown = 60; + setRegisterCodeBtn(`${registerCodeCountdown}s`, true); + registerCodeTimer = setInterval(() => { + registerCodeCountdown--; + if (registerCodeCountdown <= 0) { + clearInterval(registerCodeTimer); + setRegisterCodeBtn("发送验证码", false); + } else { + setRegisterCodeBtn(`${registerCodeCountdown}s`, true); + } + }, 1000); + } else { + setRegisterCodeBtn("发送验证码", false); + } + } catch (err) { + tip.textContent = "网络错误,请重试"; + setRegisterCodeBtn("发送验证码", false); + } + } + + async function handleRegisterSubmit(e) { + e.preventDefault(); + const email = document.getElementById("register-email").value.trim().toLowerCase(); + const password = document.getElementById("register-password").value; + const code = document.getElementById("register-code").value.trim(); + const invite_code = document.getElementById("register-invite").value.trim(); + const token_id = document.getElementById("register-token-id").value.trim(); + const access_token = document.getElementById("register-token").value.trim(); + const tip = document.getElementById("register-tip"); + const submitBtn = e.target.querySelector("button[type='submit']"); + + tip.textContent = ""; + submitBtn.disabled = true; + submitBtn.textContent = "注册中..."; + + // 凭据字段的基础格式检查;上游有效性由 /api/auth/register 在服务端权威校验 + // (注册时还没有登录态,verify_token 接口需要 Authorization,前端预检必然 401) + if (access_token || token_id) { + if (!token_id) { + tip.textContent = "Token ID 必填;AccessToken 选填"; + submitBtn.disabled = false; + submitBtn.textContent = "注册"; + return; + } + } + + try { + const resp = await apiFetch("/api/auth/register", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + email, + password, + code, + invite_code, + token_id: token_id || "", + access_token, + device_id: getDeviceId(), + device_name: getDeviceName() + }) + }); + const data = await resp.json(); + + if (data.rtn_code === 0) { + authToken = data.data.token; + localStorage.setItem("auth_token", authToken); + currentUser = { email: data.data.email }; + authKickToastShown = false; + updateAuthButton(); + closeRegisterModal(); + hideLoginGate(); + showToast("注册成功"); + shareAfterLogin(); + refreshAuthExpiry(); // 注册时可能已填凭证,立即评估有效期 + if (map) loadMapData(currentType, false); + } else { + tip.textContent = data.message || "注册失败"; + } + } catch (err) { + tip.textContent = "网络错误,请重试"; + } finally { + submitBtn.disabled = false; + submitBtn.textContent = "注册"; + } + } + + async function handleLogout() { + clearTimeout(mapRefreshTimer); + if (authToken) { + try { + await apiFetch("/api/auth/logout", { + method: "POST", + headers: { "Authorization": `Bearer ${authToken}` } + }); + } catch (err) {} + } + authToken = null; + currentUser = null; + localStorage.removeItem("auth_token"); + authKickToastShown = false; + _savedTokenExpiry = null; + renderAuthExpiryBanner(); // 登出后隐藏登录态到期提醒 + updateAuthButton(); + closeProfileModal(); + showToast("已登出"); + showLoginGate(); + const sb = document.getElementById("share-banners"); + if (sb) sb.innerHTML = ""; + shareAskQueue = []; + shareAskActive = false; + const askModal = document.getElementById("share-ask-modal"); + if (askModal) askModal.classList.remove("show"); + } + + function updateAuthButton() { + const btn = document.getElementById("auth-btn"); + const btnText = document.getElementById("auth-btn-text"); + const avatar = document.getElementById("auth-avatar"); + + if (currentUser) { + btn.classList.add("logged-in"); + btnText.style.display = "none"; + avatar.style.display = "flex"; + avatar.textContent = currentUser.email.charAt(0).toUpperCase(); + } else { + btn.classList.remove("logged-in"); + btnText.style.display = "inline"; + avatar.style.display = "none"; + btnText.textContent = "登录"; + } + updateBellBtnVisibility(); + } + + // ========== 批量寻铃入口权限 ========== + // 仅指定用户可见/可用;服务端 /api/ring_all 同步校验 + const BATCH_RING_ALLOWED_EMAILS = ["3146527494@qq.com"]; + function canUseBatchRing() { + return !!(currentUser && BATCH_RING_ALLOWED_EMAILS.includes((currentUser.email || "").toLowerCase())); + } + function updateBellBtnVisibility() { + const btn = document.getElementById("bell-btn"); + if (btn) btn.style.display = canUseBatchRing() ? "flex" : "none"; + } + + async function checkAuthStatus() { + if (!authToken) return; + + try { + const resp = await apiFetch("/api/auth/status", { + headers: { "Authorization": `Bearer ${authToken}` } + }); + const data = await resp.json(); + + if (data.rtn_code === 0 && data.data.logged_in) { + currentUser = { email: data.data.email }; + updateAuthButton(); + } else { + // token无效(可能被本设备或其他设备下线),清除登录状态 + const hadToken = !!authToken; + authToken = null; + currentUser = null; + localStorage.removeItem("auth_token"); + updateAuthButton(); + if (hadToken && !authKickToastShown) { + authKickToastShown = true; + showToast("登录状态已失效,请重新登录"); + showLoginGate(); + } + } + } catch (err) { + console.error("检查登录状态失败:", err); + } + } + + // ========== 忘记密码 ========== + // 忘记密码可从两处打开:弹窗登录(login-modal)与全屏登录门(login-gate)。 + // 用 _forgotFromGate 记住入口,重置成功后回到原处,避免用户被"换页面"。 + let _forgotFromGate = false; + function showForgotModal() { + _forgotFromGate = false; + closeAllModals(); + document.getElementById("forgot-modal").classList.add("show"); + } + function showForgotFromGate() { + _forgotFromGate = true; + closeAllModals(); + // 带上登录门里已填的邮箱,省去用户重复输入 + const field = document.getElementById("gate-email"); + const emailInput = document.getElementById("forgot-email"); + if (field && emailInput && field.value.trim() && !emailInput.value.trim()) { + emailInput.value = field.value.trim(); + } + document.getElementById("forgot-modal").classList.add("show"); + } + function closeForgotModal() { + document.getElementById("forgot-modal").classList.remove("show"); + document.getElementById("forgot-tip").textContent = ""; + _forgotFromGate = false; + } + function backToLoginFromForgot() { + const fromGate = _forgotFromGate; + closeForgotModal(); + if (fromGate) showLoginGate(); + else showLoginModal(); + } + let forgotTimer = null; + function setForgotCodeBtn(seconds) { + const btn = document.getElementById("forgot-code-btn"); + if (forgotTimer) { clearInterval(forgotTimer); forgotTimer = null; } + if (seconds > 0) { + btn.disabled = true; + btn.textContent = `${seconds}s 后重发`; + forgotTimer = setInterval(() => { + seconds--; + if (seconds <= 0) { + clearInterval(forgotTimer); forgotTimer = null; + btn.disabled = false; btn.textContent = "发送验证码"; + } else { + btn.textContent = `${seconds}s 后重发`; + } + }, 1000); + } else { + btn.disabled = false; btn.textContent = "发送验证码"; + } + } + async function sendForgotCode() { + const email = document.getElementById("forgot-email").value.trim(); + const tip = document.getElementById("forgot-tip"); + if (!email) { tip.textContent = "请先填写注册邮箱"; return; } + tip.textContent = "发送中..."; + try { + const resp = await apiFetch("/api/auth/send_code", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ email: email, purpose: "reset" }) + }); + const data = await resp.json(); + tip.textContent = data.message || ""; + if (data.rtn_code === 0) setForgotCodeBtn(60); + } catch (err) { + tip.textContent = "发送失败,请检查网络"; + } + } + async function handleForgotSubmit(event) { + event.preventDefault(); + const email = document.getElementById("forgot-email").value.trim(); + const code = document.getElementById("forgot-code").value.trim(); + const password = document.getElementById("forgot-password").value; + const tip = document.getElementById("forgot-tip"); + if (password.length < 6) { tip.textContent = "新密码至少 6 位"; return; } + tip.textContent = "提交中..."; + try { + const resp = await apiFetch("/api/auth/reset_password", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ email: email, code: code, password: password }) + }); + const data = await resp.json(); + tip.textContent = data.message || ""; + if (data.rtn_code === 0) { + // 回到用户进来的那个登录界面:登录门 → 回登录门;弹窗 → 回登录弹窗 + const fromGate = _forgotFromGate; + setTimeout(() => { + closeForgotModal(); + if (fromGate) { + showLoginGate(); + const gateEmail = document.getElementById("gate-email"); + const gatePwd = document.getElementById("gate-password"); + if (gateEmail) gateEmail.value = email; + if (gatePwd) { gatePwd.value = ""; gatePwd.focus(); } + } else { + showLoginModal(); + document.getElementById("login-email").value = email; + } + }, 900); + } + } catch (err) { + tip.textContent = "提交失败,请检查网络"; + } + } diff --git a/static/js/map-boot.js b/static/js/map-boot.js new file mode 100644 index 0000000..dc58d80 --- /dev/null +++ b/static/js/map-boot.js @@ -0,0 +1,54 @@ + // ========== 启动 ========== + // 启动时检查登录状态,然后检查租车 + checkAuthStatus().then(() => { + if (authToken && typeof SettingsPages !== "undefined") SettingsPages.restore(); + checkRentalStatus(); + if (authToken) shareAfterLogin(); + }); + + // 未登录:全屏登录门覆盖地图(后端 /api/map 同样有登录门禁) + if (!authToken) showLoginGate(); + + document.addEventListener("DOMContentLoaded", initMap); + window.addEventListener("xbniu-map-ready", initMap); + document.getElementById("scan-input").addEventListener("keydown", e => { + if (e.key === "Enter") scanCode(); + }); + // Refresh at the shared snapshot's expiry, not 60 seconds after an old cache hit. + setInterval(updateMapFreshnessBadge, 1000); + + // 进行中订单:每 2 分钟主动刷新一次(与上游对账 + 重算剩余时长/预计还车) + setInterval(async () => { + if (!authToken || document.visibilityState !== "visible") return; + if (!currentOrder || Number(currentOrder.status) !== 2) return; + try { + await syncWechatOrder(); // 上游可能已被还车/换单 + checkOrderStatus(); // 刷新横幅状态 + if (currentOrder && currentOrder.order_id) { + fetchOrderCountdown(currentOrder.order_id); // 重算剩余 + 预计还车 + } + } catch (e) { + console.error("[订单2分钟刷新] 失败:", e); + } + }, 120000); + + // 页面重新可见时检查租车状态 + document.addEventListener("visibilitychange", () => { + if (document.visibilityState === "visible") { + if (authToken && map) loadMapData(currentType, false, true); + checkAuthStatus().then(async () => { + // 从微信或其他端回到页面时,先主动对账,再刷新本地横幅。 + if (authToken) await syncWechatOrder(); + // 如果有租车计时横幅,同步服务端时间 + const rentalBar = document.getElementById("rental-bar"); + console.log("[visibilitychange] 同步服务端用车状态"); + checkRentalStatus(); + // 如果有订单横幅且在进行中,同步倒计时 + const orderBanner = document.getElementById("order-banner"); + if (orderBanner && orderBanner.classList.contains("show") && currentOrder && currentOrder.status === 2) { + console.log("[visibilitychange] order-banner 进行中,同步倒计时"); + fetchOrderCountdown(currentOrder.order_id); + } + }); + } + }); diff --git a/static/js/map-discovery.js b/static/js/map-discovery.js new file mode 100644 index 0000000..91ecdf1 --- /dev/null +++ b/static/js/map-discovery.js @@ -0,0 +1,175 @@ +/* Find vehicles by location, availability, battery and kind. Coordinates here are BD09. */ +(function () { + 'use strict'; + const storageKey = 'xbniu_discovery', favoriteKey = 'xbniu_places'; + let filters = { onlyAvailable: false, minElectric: 0, kind: 'all', radius: 500, sort: 'distance' }; + let favorites = [], locations = [], origin = null, originName = '', initialized = false, renderFrame = null; + const byId = id => document.getElementById(id); + const escape = text => String(text ?? '').replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); + try { + const saved = JSON.parse(localStorage.getItem(storageKey) || '{}'); + filters.onlyAvailable = saved.onlyAvailable === true; + if ([0,20,40,60,80].includes(saved.minElectric)) filters.minElectric = saved.minElectric; + if (['all','small','big','red'].includes(saved.kind)) filters.kind = saved.kind; + if ([200,500,1000,0].includes(saved.radius)) filters.radius = saved.radius; + if (['distance','electric'].includes(saved.sort)) filters.sort = saved.sort; + const stored = JSON.parse(localStorage.getItem(favoriteKey) || '[]'); + if (Array.isArray(stored)) favorites = stored.filter(p => p && typeof p.name === 'string' && Number.isFinite(p.lat) && Number.isFinite(p.lng) && Math.abs(p.lat) <= 90 && Math.abs(p.lng) <= 180).slice(0, 12); + } catch (_) {} + function center() { + if (origin) return origin; + if (autoLocationMarker) return autoLocationMarker.getPosition(); + return map?.getCenter() || null; + } + function items(availableOnly = false) { + const point = center(); + return Object.values(markersData).filter(b => BikeData.matches(b, { ...filters, onlyAvailable: availableOnly || filters.onlyAvailable })) + .map(b => ({ bike: b, id: BikeClusters.bikeId(b), distance: BikeData.distance(point, offsetCoord(b.latitude, b.longitude)), electric: BikeData.electric(b) })) + .filter(row => !filters.radius || row.distance === null || row.distance <= filters.radius) + .sort((a, b) => filters.sort === 'electric' + ? (b.electric ?? -1) - (a.electric ?? -1) || (a.distance ?? Infinity) - (b.distance ?? Infinity) + : (a.distance ?? Infinity) - (b.distance ?? Infinity) || (b.electric ?? -1) - (a.electric ?? -1)); + } + function visibleBikes(bikes) { return bikes.filter(b => BikeData.matches(b, filters)); } + function persist() { try { localStorage.setItem(storageKey, JSON.stringify(filters)); } catch (_) {} } + function render() { + if (!initialized) return; + const rows = items(); + byId('nearby-count').textContent = rows.length; + byId('discovery-origin').textContent = originName || (autoLocationMarker ? '以我的位置查找' : '以地图中心查找'); + byId('nearby-summary').textContent = `${filters.radius ? filters.radius + ' 米内' : '全部范围'} · ${rows.length} 辆符合条件 · 距离为直线距离`; + const batteryText = e => e === null ? '电量未知' : `${Math.round(e)}% 电量`; + byId('nearby-list').innerHTML = rows.length ? rows.slice(0, 100).map(row => { + const s = BikeData.state(row.bike), k = { small:'小车', big:'大车', red:'红车' }[BikeData.kind(row.bike)]; + const distance = row.distance === null ? '距离待确认' : row.distance < 1000 ? `${Math.round(row.distance)} 米` : `${(row.distance / 1000).toFixed(1)} 公里`; + return ``; + }).join('') : '
这里暂时没有符合条件的车辆

可以扩大范围、降低电量要求或切换车型。

'; + if (rows.length > 100) byId('nearby-summary').textContent += ',先展示前 100 辆,请缩小范围'; + } + function refresh() { + if (!initialized) return; + persist(); + rebuildMarkersForZoom(); + render(); + } + function relax() { + filters = { onlyAvailable: true, minElectric: 0, kind: 'all', radius: 0, sort: 'distance' }; + fillControls(); refresh(); + showToast('已扩大至全部范围,保留可用车辆'); + } + function fillControls() { + byId('filter-available').checked = filters.onlyAvailable; + byId('filter-electric').value = filters.minElectric; + byId('filter-kind').value = filters.kind; + byId('filter-radius').value = filters.radius; + byId('nearby-sort').value = filters.sort; + } + function showList(open = true) { + byId('nearby-panel').hidden = !open; + byId('nearby-toggle').setAttribute('aria-expanded', String(open)); + if (open) { render(); byId('nearby-close').focus({ preventScroll: true }); } + else byId('nearby-toggle').focus({ preventScroll: true }); + } + function choosePlace(point, name) { + if (!map) { showToast('地图正在加载,请稍后重试'); return; } + origin = { lat: point.lat, lng: point.lng }; originName = name; + map.panTo(new BMapGL.Point(point.lng, point.lat)); + byId('place-search').value = name; + byId('place-results').hidden = true; + render(); showList(); + } + function searchPlaces() { + const q = byId('place-search').value.trim().toLocaleLowerCase(); + const selected = locations.filter(p => !q || p.name.toLocaleLowerCase().includes(q)).slice(0, 8); + byId('place-results').hidden = false; + byId('place-results').innerHTML = selected.length ? selected.map(p => ``).join('') : '

未找到地点,可拖动地图后收藏当前位置。

'; + } + function renderFavorites() { + byId('favorite-places').innerHTML = favorites.length ? favorites.map((p, index) => ``).join('') : '常用地点保存在这台设备'; + } + function savePlace() { + const p = origin || map?.getCenter(); + if (!p) { showToast('地图加载后可收藏地点'); return; } + const name = byId('place-search').value.trim().slice(0, 24) || originName || `地图位置 ${favorites.length + 1}`; + if (favorites.length >= 12) { showToast('最多收藏 12 个地点,请先移除不需要的'); return; } + if (favorites.some(f => f.name === name)) { showToast('已收藏同名地点'); return; } + favorites.push({ name, lat: p.lat, lng: p.lng }); + try { localStorage.setItem(favoriteKey, JSON.stringify(favorites)); } catch (_) { showToast('浏览器未允许保存常用地点'); return; } + renderFavorites(); showToast('已收藏当前查找地点'); + } + function locationStatus(message, retry = false) { + const box = byId('location-status'); if (!box) return; + box.hidden = false; + byId('location-message').textContent = message; + byId('location-retry').hidden = !retry; + } + async function nearest(point) { + if (!authToken) { showLoginGate(); return; } + if (point) { origin = { lat: point.lat, lng: point.lng }; originName = '我的位置'; } + const candidates = items(true).filter(row => row.electric !== null && row.electric >= 20); + if (!candidates.length) { + showList(); locationStatus('没有符合当前条件的可用车,可在列表中放宽筛选。'); + return; + } + candidates.sort((a, b) => (a.distance ?? Infinity) - (b.distance ?? Infinity)); + const row = candidates[0]; + nearestBikeId = row.id; showList(false); showBikeDetail(row.id); + showToast(`最近可用:#${row.bike.code},${Math.round(row.distance || 0)} 米,电量 ${row.electric}%`); + } + async function init() { + if (initialized) return; + initialized = true; fillControls(); renderFavorites(); + ['filter-available','filter-electric','filter-kind','filter-radius','nearby-sort'].forEach(id => byId(id).addEventListener('change', () => { + filters.onlyAvailable = byId('filter-available').checked; + filters.minElectric = Number(byId('filter-electric').value); + filters.kind = byId('filter-kind').value; + filters.radius = Number(byId('filter-radius').value); + filters.sort = byId('nearby-sort').value; refresh(); + })); + byId('nearby-toggle').addEventListener('click', () => showList(byId('nearby-panel').hidden)); + byId('discovery-filters').addEventListener('toggle', () => { + if (byId('discovery-filters').open && !byId('nearby-panel').hidden) showList(false); + }); + byId('nearby-close').addEventListener('click', () => showList(false)); + byId('nearby-panel').addEventListener('keydown', e => { if (e.key === 'Escape') showList(false); }); + byId('nearby-list').addEventListener('click', event => { + const row = event.target.closest('[data-bike-id]'); + if (row) { showList(false); showBikeDetail(row.dataset.bikeId); } + if (event.target.closest('[data-relax]')) relax(); + }); + byId('place-search').addEventListener('input', searchPlaces); + byId('place-search').addEventListener('focus', searchPlaces); + byId('place-search').addEventListener('keydown', e => { + if (e.key === 'Escape') byId('place-results').hidden = true; + if (e.key === 'ArrowDown') { e.preventDefault(); byId('place-results').querySelector('button')?.focus(); } + if (e.key === 'Enter') { e.preventDefault(); byId('place-results').querySelector('button')?.click(); } + }); + byId('place-results').addEventListener('click', e => { + const button = e.target.closest('[data-place-id]'); + const place = locations.find(p => String(p.id) === button?.dataset.placeId); + if (place) { const p = offsetCoord(place.latitude, place.longitude); choosePlace(p, place.name); } + }); + byId('favorite-save').addEventListener('click', savePlace); + byId('favorite-places').addEventListener('click', e => { + const remove = e.target.closest('[data-remove-favorite]'); + if (remove) { favorites.splice(Number(remove.dataset.removeFavorite), 1); try { localStorage.setItem(favoriteKey, JSON.stringify(favorites)); } catch (_) {} renderFavorites(); return; } + const button = e.target.closest('[data-favorite]'); + if (button) { const place = favorites[Number(button.dataset.favorite)]; if (place) choosePlace(place, place.name); } + }); + byId('location-center').addEventListener('click', () => { origin = null; originName = ''; if (autoLocationMarker) { const p = map.getCenter(); origin = {lat:p.lat,lng:p.lng}; originName='地图中心'; } render(); showList(); locationStatus('已按地图中心查找,无需定位权限。'); }); + byId('location-retry').addEventListener('click', () => { origin = null; originName = ''; startAutoLocation(); }); + byId('discovery-origin').addEventListener('click', () => { origin = null; originName = ''; byId('place-search').value = ''; refresh(); }); + document.addEventListener('click', e => { if (!e.target.closest('.place-search-wrap')) byId('place-results').hidden = true; }); + map.addEventListener('moveend', () => { if (!renderFrame) renderFrame = requestAnimationFrame(() => { renderFrame = null; render(); }); }); + map.addEventListener('dragend', () => { + const point = map.getCenter(); origin = {lat:point.lat,lng:point.lng}; originName = '地图中心'; + byId('place-search').value = ''; render(); + }); + try { + const response = await AppAPI.fetch('/api/campus/locations'); const data = await response.json(); + locations = Array.isArray(data.data) ? data.data : []; + } catch (_) { locationStatus('校园地点加载失败,可拖动地图查找或重试刷新。'); } + render(); + } + window.BikeDiscovery = { init, render, visibleBikes, locationStatus, nearest, showList }; +})(); diff --git a/static/js/map-history.js b/static/js/map-history.js new file mode 100644 index 0000000..bda76dc --- /dev/null +++ b/static/js/map-history.js @@ -0,0 +1,191 @@ + // ========== 订单历史(我的 → 订单历史) ========== + function fmtDuration(seconds) { + if (seconds === null || seconds === undefined) return "--"; + const mins = Math.round(seconds / 60); + if (mins < 60) return `${mins} 分钟`; + return `${Math.floor(mins / 60)} 小时 ${mins % 60} 分钟`; + } + function fmtOrderTime(s) { + if (!s) return "--"; + return String(s).replace("T", " ").slice(5, 16); // MM-DD HH:MM + } + function fmtClock(s) { + if (!s) return "--"; + return String(s).slice(11, 16); // HH:MM + } + function orderCardHtml(o) { + const badge = o.returned + ? '已完成' + : '进行中'; + const sharedRow = o.shared + ? `
${o.role === "owner" ? "共享给" : "使用"} ${escHtml(o.partner || "--")} 的车
` : ""; + // 多轮续租合并显示:共 N 轮 · 总用时 · 起止时钟 + const roundsRow = (o.rounds && o.rounds > 1) + ? `
共 ${o.rounds} 轮 · 总用时 ${fmtDuration(o.duration_seconds)}
` : ""; + const timeRow = `${fmtOrderTime(o.start_time)} → ${fmtOrderTime(o.end_time)}`; + return ` +
+
+ #${escHtml(o.bike_code)} + + ${o.duration_seconds !== null ? fmtDuration(o.duration_seconds) : ""} + ${badge} + +
+
+
${timeRow}
+
${escHtml(o.start_label || "起点未知")} → ${escHtml(o.end_label || (o.returned ? "终点未知" : "骑行中"))}
+ ${roundsRow} + ${sharedRow} +
+
+ +
+
`; + } + // ========== 订单骑行轨迹 ========== + let orderTrajMap = null; + let orderTrajOverlays = []; + async function openOrderTrajectory(rentalId){ + SettingsPages.open("order-traj-modal"); + document.getElementById("order-traj-summary").textContent = "加载轨迹中..."; + document.getElementById("order-traj-hint").textContent = "轨迹来自每 5-10 分钟一次的车辆定位采集。"; + try{ + const resp = await apiFetch(`/api/user/orders/trajectory?rental_id=${encodeURIComponent(rentalId)}`, { + headers: { "Authorization": `Bearer ${authToken}` } + }); + const data = await resp.json(); + if (data.rtn_code !== 0) { + document.getElementById("order-traj-summary").textContent = data.message || "轨迹加载失败"; + return; + } + renderOrderTrajectory(data.data); + }catch(e){ + document.getElementById("order-traj-summary").textContent = "网络错误,请重试"; + } + } + function closeOrderTrajModal(){ + SettingsPages.back(); + // 保留地图实例,下次复用;只清理覆盖物 + if (orderTrajMap) { + try { orderTrajMap.clearOverlays(); } catch(e) {} + } + orderTrajOverlays = []; + } + function renderOrderTrajectory(t){ + const pts = t.points || []; + // textContent 不解析 HTML,这里不能用 escHtml(会把 & 显示成 &) + document.getElementById("order-traj-summary").textContent = + `#${t.bike_code} · ${fmtOrderTime(t.start_time)} → ${fmtOrderTime(t.end_time)} · ` + + `${t.start_label || "起点未知"} → ${t.end_label || (t.returned ? "终点未知" : "骑行中")}`; + + const initMap = () => { + if (!orderTrajMap) { + orderTrajMap = new BMapGL.Map("order-traj-map"); + orderTrajMap.enableScrollWheelZoom(true); + } + const overlayPts = []; + try { orderTrajMap.clearOverlays(); } catch(e) {} + const toBd = (lat, lng) => offsetCoord(lat, lng); + + // 轨迹线(GCJ02 → BD09 逐点转换) + const linePts = pts.map(p => { + const c = toBd(p.lat, p.lng); + return new BMapGL.Point(c.lng, c.lat); + }); + // 采集缺失时用订单起终点兜底成两点直线 + if (linePts.length < 2 && (t.start_point || t.end_point)) { + const s = t.start_point, e = t.end_point || t.start_point; + const cs = toBd(s.lat, s.lng), ce = toBd(e.lat, e.lng); + linePts.push(new BMapGL.Point(cs.lng, cs.lat), new BMapGL.Point(ce.lng, ce.lat)); + } + if (linePts.length >= 2) { + const poly = new BMapGL.Polyline(linePts, { + strokeColor: "#0a84ff", strokeWeight: 5, strokeOpacity: 0.85, + }); + orderTrajMap.addOverlay(poly); + overlayPts.push(...linePts); + } + // 起终点标记 + const mark = (pt, color, text) => { + if (!pt) return; + const c = toBd(pt.lat, pt.lng); + const p = new BMapGL.Point(c.lng, c.lat); + const canvas = document.createElement("canvas"); + canvas.width = canvas.height = 26; + const ctx = canvas.getContext("2d"); + ctx.beginPath(); ctx.arc(13, 13, 10, 0, Math.PI * 2); + ctx.fillStyle = color; ctx.fill(); + ctx.fillStyle = "#fff"; ctx.font = "bold 12px Arial"; + ctx.textAlign = "center"; ctx.textBaseline = "middle"; + ctx.fillText(text, 13, 13); + const marker = new BMapGL.Marker(p, { + icon: new BMapGL.Icon(canvas.toDataURL(), new BMapGL.Size(26, 26), new BMapGL.Size(13, 13)) + }); + orderTrajMap.addOverlay(marker); + overlayPts.push(p); + }; + mark(t.start_point, "#34c759", "起"); + mark(t.end_point, "#ff3b30", "终"); + + if (overlayPts.length) { + try { + orderTrajMap.setViewport(overlayPts, { margins: [30, 30, 30, 30] }); + } catch (e) { + orderTrajMap.centerAndZoom(overlayPts[0], 18); + } + } else { + apiFetch("/api/config").then(r => r.json()).then(cfg => { + const c = offsetCoord(cfg.center_lat, cfg.center_lng); + orderTrajMap.centerAndZoom(new BMapGL.Point(c.lng, c.lat), 17); + }); + } + document.getElementById("order-traj-hint").textContent = pts.length + ? `共 ${pts.length} 个定位点` + : "该时间段没有采集到定位点(采集间隔 5-10 分钟),已用订单起终点示意"; + }; + + // 弹窗刚显示,等一帧再初始化,避免容器尺寸为 0 + setTimeout(initMap, 60); + } + let orderHistoryRows = [], orderHistorySerial = 0, orderHistoryController = null; + async function openOrdersModal() { + closeAllModals(); SettingsPages.open("orders-modal"); + await loadOrderPage(true); + } + function closeOrdersModal() { SettingsPages.back(); } + function resetOrderFilters() { + ["orders-from", "orders-to", "orders-code"].forEach(id => document.getElementById(id).value = ""); + document.getElementById("orders-source").value = "all"; + loadOrderPage(true); + } + async function loadOrderPage(reset) { + const from = document.getElementById("orders-from").value, to = document.getElementById("orders-to").value; + const code = document.getElementById("orders-code").value.trim(); + if (from && to && from > to) { showToast("开始日期不能晚于结束日期"); return; } + if (code && !/^\d{1,8}$/.test(code)) { showToast("车牌筛选只能包含最多8位数字"); return; } + const serial = ++orderHistorySerial; + orderHistoryController?.abort(); orderHistoryController = new AbortController(); + const box = document.getElementById("orders-list"), more = document.getElementById("orders-more"); + if (reset) { orderHistoryRows = []; box.innerHTML = '
正在查询记录...
'; } + more.disabled = true; + document.getElementById("orders-search").disabled = true; + const query = new URLSearchParams({limit:"20", offset:String(orderHistoryRows.length), from, to, code, source:document.getElementById("orders-source").value}); + try { + const response = await apiFetch(`/api/user/orders?${query}`, { headers:{Authorization:`Bearer ${authToken}`}, signal:orderHistoryController.signal }); + const data = await response.json(); + if (serial !== orderHistorySerial) return; + if (data.rtn_code !== 0) throw new Error(data.message || "查询失败"); + orderHistoryRows.push(...(data.data || [])); + document.getElementById("orders-summary").textContent = `共 ${data.total ?? orderHistoryRows.length} 条记录,已显示 ${orderHistoryRows.length} 条`; + box.innerHTML = orderHistoryRows.length ? orderHistoryRows.map(orderCardHtml).join("") : '
没有符合条件的订单,可调整日期、车牌或来源后重试。
'; + more.hidden = !data.has_more; + } catch (error) { + if (serial !== orderHistorySerial) return; + if (reset) box.innerHTML = `
${escHtml(error.message)},请点击“查询记录”重试。
`; + else showToast(error.message || "加载失败,请重试"); + } finally { + if (serial === orderHistorySerial) { more.disabled = false; document.getElementById("orders-search").disabled = false; } + } + } diff --git a/static/js/map-orders.js b/static/js/map-orders.js new file mode 100644 index 0000000..377f374 --- /dev/null +++ b/static/js/map-orders.js @@ -0,0 +1,976 @@ + // ========== 订单状态检测 ========== + let currentOrder = null; // 当前订单信息 + + async function checkOrderStatus() { + if (!authToken) { + hideOrderBanner(); + return; + } + + try { + const resp = await apiFetch("/api/order/status", { + headers: { "Authorization": `Bearer ${authToken}` } + }); + const data = await resp.json(); + + if (data.rtn_code === 0) { + if (!data.has_credentials) { + // 用户没有配置凭据 + hideOrderBanner(); + return; + } + + if (data.has_order && data.order) { + currentOrder = data.order; + // 仅当“当前微信订单本身就是我共享出去的这笔订单”时隐藏普通横幅。 + // 骑行者自己账号另有待支付/进行中订单时,必须与借用中的共享横幅同时保留。 + if (data.order.shared) { + hideOrderBanner(); + } else { + showOrderBanner(data.order); + } + } else { + currentOrder = null; + hideOrderBanner(); + } + } else if (data.rtn_code === 102001 || data.token_invalid) { + // token_id 已失效(小程序重新登录会踢掉旧会话):弹窗引导重新配置(带冷却,避免每20秒轮询骚扰) + notifyCredentialInvalid(data.message); + } + } catch (err) { + console.error("检查订单状态失败:", err); + } + } + + function showOrderBanner(order) { + const banner = document.getElementById("order-banner"); + const icon = document.getElementById("order-banner-icon"); + const text = document.getElementById("order-banner-text"); + const btn = document.getElementById("order-banner-btn"); + + banner.classList.remove("warning", "riding"); + + if (Number(order.status) === 1) { + // 待支付 + banner.classList.add("warning"); + icon.innerHTML = ''; + text.textContent = `待支付订单 #${order.code || order.order_id.slice(-6)}`; + btn.textContent = "去支付"; + hideOrderCountdown(); + const progress = document.getElementById("order-final-time"); + progress.textContent = "待支付 · 骑行已结束"; + progress.style.display = "inline"; + } else if (Number(order.status) === 2) { + // 进行中 - 获取倒计时 + banner.classList.add("riding"); + icon.innerHTML = ''; + if (order.shared) { + const sName = partnerLabel(order.shared.rider_name, order.shared.rider_email, order.shared.remark); + text.textContent = ("共享中 #" + (order.code || order.order_id.slice(-6)) + " · " + sName + "使用中"); +} else { + text.textContent = `进行中 #${order.code || order.order_id.slice(-6)}`; + } + btn.textContent = "还车"; + if (String(orderCountdownOrderId) !== String(order.order_id)) { + hideOrderCountdown(); + const progress = document.getElementById("order-final-time"); + progress.textContent = "骑行中 · 正在同步计时"; + progress.style.display = "inline"; + } + // 从后端获取剩余时间并启动倒计时 + fetchOrderCountdown(order.order_id); + } + + banner.classList.add("show"); + } + + let orderCountdownTimer = null; + let orderCountdownSeconds = 0; + let orderCountdownDeadline = null; + let orderCountdownOrderId = null; + + function rideProgressText(summary) { + const current = Math.max(1, Number(summary.current_round) || 1); + const total = Math.max(current, Number(summary.total_rounds) || current); + const end = String(summary.final_end_time || summary.end_time || "").match(/(?:T|\s)(\d{2}:\d{2})/); + const phase = summary.auto_return ? "自动还车已开启" : "手动还车"; + return `第 ${current}/${total} 轮 · ${phase}` + (end ? ` · 预计 ${end[1]} 结束` : ""); + } + + function remainingTimeText(seconds) { + const remaining = Math.max(0, Math.ceil(Number(seconds) || 0)); + return `${Math.floor(remaining / 60)}:${String(remaining % 60).padStart(2, "0")}`; + } + + function fetchOrderCountdown(orderId) { + if (!authToken || !orderId) return; + + apiFetch(`/api/rental/status?order_id=${encodeURIComponent(orderId)}`, { + headers: { "Authorization": `Bearer ${authToken}` } + }) + .then(r => r.json()) + .then(data => { + if (!currentOrder || String(currentOrder.order_id) !== String(orderId) || Number(currentOrder.status) !== 2) return; + if (data.rtn_code === 0 && data.data && data.data.active) { + orderCountdownSeconds = Math.max(0, Number(data.data.remaining_seconds) || 0); + orderCountdownDeadline = performance.now() + orderCountdownSeconds * 1000; + orderCountdownOrderId = orderId; + // 多轮适配:展示计划总轮数与最终预计还车时间 + const finalEl = document.getElementById("order-final-time"); + const addBtn = document.getElementById("order-banner-add-round-btn"); + if (finalEl) { + finalEl.textContent = rideProgressText(data.data); + finalEl.style.display = "inline"; + } + if (addBtn) { + // 真实订单才可加轮; reminder 计时不显示 + const eligible = data.data.order_id && String(data.data.source) !== "reminder"; + addBtn.style.display = eligible ? "inline-block" : "none"; + } + showOrderCountdown(); + startOrderCountdown(); + } else if (data.rtn_code === 0) { + hideOrderCountdown(); + const progress = document.getElementById("order-final-time"); + progress.textContent = "骑行中 · 计时同步中"; + progress.style.display = "inline"; + } + }) + .catch(err => console.error("获取倒计时失败:", err)); + } + + function showOrderCountdown() { + const el = document.getElementById("order-countdown"); + el.style.display = "inline"; + updateOrderCountdownText(); + } + + function hideOrderCountdown() { + orderCountdownDeadline = null; + orderCountdownOrderId = null; + document.getElementById("order-banner-add-round-btn").style.display = "none"; + document.getElementById("order-final-time").style.display = "none"; + const el = document.getElementById("order-countdown"); + el.style.display = "none"; + if (orderCountdownTimer) { + clearInterval(orderCountdownTimer); + orderCountdownTimer = null; + } + } + + function updateOrderCountdownText() { + const el = document.getElementById("order-countdown"); + const remaining = Math.max(0, orderCountdownSeconds); + const mins = Math.floor(remaining / 60); + const secs = remaining % 60; + el.textContent = remaining > 0 ? `本轮剩余 ${mins}:${secs.toString().padStart(2, "0")}` : "本轮到期 · 同步状态中"; + + // 变色提示 + if (remaining <= 60) { + el.style.color = "#ff3b30"; + } else if (remaining <= 300) { + el.style.color = "#ffcc00"; + } else { + el.style.color = "white"; + } + } + + function startOrderCountdown() { + if (orderCountdownTimer) clearInterval(orderCountdownTimer); + orderCountdownTimer = setInterval(() => { + orderCountdownSeconds = Math.max(0, Math.ceil((orderCountdownDeadline - performance.now()) / 1000)); + updateOrderCountdownText(); + if (orderCountdownSeconds <= 0) { + clearInterval(orderCountdownTimer); + // 倒计时结束,刷新订单状态 + checkOrderStatus(); + } + }, 1000); + } + + function hideOrderBanner() { + document.getElementById("order-banner").classList.remove("show"); + hideOrderCountdown(); + closeOrderActionsModal(); + } + + function isOrderActionEligible(order) { + if (!order) return false; + const type = String(order.type || "").toLowerCase(); + const source = String(order.source || "").toLowerCase(); + return type !== "reminder" && source !== "reminder"; + } + + function handleOrderBannerSurfaceClick(event) { + // 横幅右侧已有的两个按钮继续走原有行为,不触发全屏面板。 + if (event && event.target && event.target.closest && event.target.closest("button")) return; + if (!isOrderActionEligible(currentOrder)) return; + showOrderActionsModal(); + } + + function showOrderActionsModal() { + if (!isOrderActionEligible(currentOrder)) return; + + const modal = document.getElementById("order-actions-modal"); + const meta = document.getElementById("order-actions-meta"); + const status = document.getElementById("order-actions-status"); + const hint = document.getElementById("order-actions-hint"); + const code = currentOrder.code || currentOrder.order_id || "未知"; + const pending = Number(currentOrder.status) === 1; + + meta.textContent = `车辆 #${code}`; + status.textContent = pending ? "待支付订单" : "订单进行中"; + status.classList.toggle("warning", pending); + status.classList.toggle("riding", !pending); + hint.textContent = pending + ? "当前订单尚未支付,请先完成支付后再使用车辆操作。" + : "临时锁车不会结束订单,确认车辆停放安全后再操作。"; + + // 待支付订单明确不展示临时锁车/临时开车。 + ["order-action-lock", "order-action-unlock"].forEach(id => { + const button = document.getElementById(id); + if (button) button.style.display = pending ? "none" : "flex"; + }); + const pay = document.getElementById("order-action-pay"); + const ret = document.getElementById("order-action-return"); + if (pay) pay.style.display = pending ? "flex" : "none"; + if (ret) ret.style.display = pending ? "none" : "flex"; + + modal.classList.add("show"); + modal.setAttribute("aria-hidden", "false"); + document.body.classList.add("order-actions-open"); + window.setTimeout(() => document.getElementById("order-actions-close")?.focus(), 0); + } + + function closeOrderActionsModal() { + const modal = document.getElementById("order-actions-modal"); + if (!modal) return; + modal.classList.remove("show"); + modal.setAttribute("aria-hidden", "true"); + document.body.classList.remove("order-actions-open"); + } + + function viewBikeDetailFromOrderModal() { + closeOrderActionsModal(); + viewBikeDetailFromOrder(); + } + + async function findCurrentOrderBike() { + if (!isOrderActionEligible(currentOrder)) return; + const code = (currentOrder.code || "").toString().trim(); + if (!code) { + showToast("该订单没有车牌信息"); + return; + } + + const button = document.getElementById("order-action-find"); + if (button) { + button.disabled = true; + button.querySelector("strong").textContent = "发送中..."; + } + + try { + const data = await _doFindBikeRequest(code); + if (data && (data.rtn_code === 0 || data.success)) { + showToast("寻车指令已发送,请听声音"); + } else { + showToast((data && data.message) || "寻车失败"); + } + } catch (err) { + console.error("订单寻车失败:", err); + showToast("寻车失败,请重试"); + } finally { + if (button) { + button.disabled = false; + button.querySelector("strong").textContent = "寻车"; + } + } + } + + function payCurrentOrderFromModal() { + closeOrderActionsModal(); + tryCardPayOrRedirect(); + } + + function returnCurrentOrderFromModal() { + closeOrderActionsModal(); + showReturnConfirm(); + } + + function handleOrderBannerClick() { + if (!currentOrder) { + showToast("订单状态已变化,正在刷新,请稍后重试"); + checkOrderStatus(); + return; + } + + if (Number(currentOrder.status) === 1) { + // 待支付 - 先检查是否有月卡/周卡 + tryCardPayOrRedirect(); + } else if (Number(currentOrder.status) === 2) { + // 进行中 - 显示还车确认弹窗 + showReturnConfirm(); + } else { + showToast("订单状态已变化,正在刷新,请稍后重试"); + checkOrderStatus(); + } + } + + // 查看详情:等同在搜索框输入当前订单车牌并点击查询,直接弹出车辆详情 + function viewBikeDetailFromOrder() { + if (!currentOrder) { showToast("当前没有进行中的订单"); return; } + const code = (currentOrder.code || "").toString().trim(); + if (!code) { showToast("该订单没有车牌信息"); return; } + document.getElementById("scan-input").value = code; + scanCode(); + } + + document.addEventListener("keydown", event => { + if (event.key !== "Escape") return; + // 确认弹窗优先响应 ESC(原生壳没有系统对话框,全靠页面内弹窗) + const _cm = document.getElementById("app-confirm-modal"); + if (_cm && _cm.classList.contains("show")) { appConfirmClose(); return; } + const _arm = document.getElementById("add-round-modal"); + if (_arm && _arm.classList.contains("show")) { closeAddRoundModal(); return; } + const _oam = document.getElementById("order-actions-modal"); + if (_oam && _oam.classList.contains("show")) { closeOrderActionsModal(); return; } + }); + + // ========== 月卡/周卡自动支付 ========== + let cardPayLoading = false; + + async function tryCardPayOrRedirect() { + if (cardPayLoading || !currentOrder) return; + + const btn = document.getElementById("order-banner-btn"); + cardPayLoading = true; + btn.textContent = "检测中…"; + btn.disabled = true; + + try { + // 1. 查询可用支付方式 + const methodsResp = await apiFetch( + `/api/order/pay_methods?code=${encodeURIComponent(currentOrder.code || "")}`, + { headers: { "Authorization": `Bearer ${authToken}` } } + ); + const methodsData = await methodsResp.json(); + + if (methodsData.rtn_code !== 0) { + // 接口失败,降级提示跳转 + showToast("请到小白超人小程序支付订单"); + return; + } + + const cardMethods = methodsData.data?.card_methods || []; + + if (cardMethods.length === 0) { + // 没有月卡/周卡 → 原来逻辑 + showToast("未找到月卡,请到小白超人小程序支付"); + return; + } + + // 2. 优先选 get_type=2(推荐/激活)的卡,否则取第一个 + const preferred = cardMethods.find(m => m.get_type === 2) || cardMethods[0]; + const cardTypeName = preferred.type === "3" || preferred.type === 3 ? "月卡" : "周卡"; + + // 3. 更新按钮状态 + btn.textContent = `${cardTypeName}支付中…`; + + // 4. 调用月卡支付接口 + const payResp = await apiFetch("/api/order/pay_with_card", { + method: "POST", + headers: { + "Authorization": `Bearer ${authToken}`, + "Content-Type": "application/json" + }, + body: JSON.stringify({ + order_id: currentOrder.order_id, + code: currentOrder.code || "", + type: String(preferred.type), + package_id: String(preferred.package_id) + }) + }); + const payData = await payResp.json(); + + if (payData.rtn_code === 0 && payData.data?.paid) { + // 月卡支付成功 + showToast(`${cardTypeName}支付成功 ✓`); + currentOrder = null; + hideOrderBanner(); + refreshMap(); + } else if (payData.rtn_code === 0 && payData.data?.need_wechat_pay) { + // 月卡不足,需要微信支付 + showToast("月卡余额不足,请到小白超人小程序完成支付"); + } else { + showToast(payData.message || "支付失败,请到小白超人小程序支付"); + } + + } catch (err) { + console.error("月卡支付失败:", err); + showToast("请到小白超人小程序支付订单"); + } finally { + cardPayLoading = false; + btn.textContent = "去支付"; + btn.disabled = false; + } + } + + // ========== 还车确认 ========== + let returnLoading = false; + let pendingReturnOrder = null; + + async function getOrderOperationLocation() { + let position = null; + if (navigator.geolocation) { + position = await new Promise(resolve => { + navigator.geolocation.getCurrentPosition( + pos => resolve(pos), + err => { + console.error("获取位置失败:", err); + resolve(null); + }, + { timeout: 5000 } + ); + }); + } + + const latitude = Number.isFinite(position?.coords?.latitude) + ? position.coords.latitude : 36.67; + const longitude = Number.isFinite(position?.coords?.longitude) + ? position.coords.longitude : 116.98; + return { latitude, longitude }; + } + + function showReturnConfirm() { + if (returnLoading) return; + if (!currentOrder || Number(currentOrder.status) !== 2) { + showToast("当前没有可还车的进行中订单,正在刷新"); + checkOrderStatus(); + return; + } + pendingReturnOrder = { ...currentOrder }; + document.getElementById("return-confirm-text").textContent = + `车辆 #${currentOrder.code || currentOrder.order_id} 正在骑行,确认要还车吗?`; + document.getElementById("return-confirm-modal").classList.add("show"); + document.getElementById("return-confirm-btn").disabled = false; + document.getElementById("return-confirm-btn").textContent = "确认还车"; + } + + function closeReturnConfirm() { + document.getElementById("return-confirm-modal").classList.remove("show"); + pendingReturnOrder = null; + } + + async function doReturnBike() { + if (returnLoading) return; + const order = pendingReturnOrder; + if (!order) { + showToast("请重新点击还车并确认订单"); + return; + } + + returnLoading = true; + const btn = document.getElementById("return-confirm-btn"); + btn.disabled = true; + btn.textContent = "还车中..."; + + try { + // 还车和临时锁车共用同一套当前位置获取逻辑。 + const { latitude, longitude } = await getOrderOperationLocation(); + + const resp = await apiFetch("/api/order/return", { + method: "POST", + headers: { + "Authorization": `Bearer ${authToken}`, + "Content-Type": "application/json" + }, + body: JSON.stringify({ + order_id: order.order_id, + code: order.code, + latitude: latitude, + longitude: longitude + }) + }); + + const data = await resp.json(); + + if (data.rtn_code === 0) { + let msg = data.used_nearest ? "还车成功(已切换至最近停车点)" : "还车成功"; + // 显示月卡支付结果 + if (data.card_pay) { + msg += data.card_pay.success ? `,${data.card_pay.message}` : `,${data.card_pay.message}`; + } + showToast(msg); + closeReturnConfirm(); + if (!currentOrder || String(currentOrder.order_id) === String(order.order_id)) { + currentOrder = null; + hideOrderBanner(); + } + // 刷新地图 + refreshMap(); + refreshShareBanners(); + } else { + showToast(data.message || "还车失败"); + } + } catch (err) { + showToast("还车失败,请重试"); + } finally { + returnLoading = false; + btn.disabled = false; + btn.textContent = "确认还车"; + } + } + + let orderTempActionLoading = false; + + async function tempLockCurrentOrder() { + if (orderTempActionLoading || !isOrderActionEligible(currentOrder) || Number(currentOrder.status) !== 2) return; + const button = document.getElementById("order-action-lock"); + orderTempActionLoading = true; + if (button) { + button.disabled = true; + button.querySelector("strong").textContent = "锁车中..."; + } + + try { + const { latitude, longitude } = await getOrderOperationLocation(); + const resp = await apiFetch("/api/order/temp_lock", { + method: "POST", + headers: { + "Authorization": `Bearer ${authToken}`, + "Content-Type": "application/json" + }, + body: JSON.stringify({ + order_id: currentOrder.order_id, + code: currentOrder.code, + latitude, + longitude + }) + }); + const data = await resp.json(); + if (data.rtn_code === 0) { + showToast(data.used_nearest ? "临时锁车成功(已切换至最近停车点)" : "临时锁车成功"); + const status = document.getElementById("order-actions-status"); + if (status) status.textContent = "车辆已临时锁定,订单仍在进行中"; + } else { + showToast(data.message || "临时锁车失败"); + } + } catch (err) { + console.error("临时锁车失败:", err); + showToast("临时锁车失败,请重试"); + } finally { + orderTempActionLoading = false; + if (button) { + button.disabled = false; + button.querySelector("strong").textContent = "临时锁车"; + } + } + } + + async function tempUnlockCurrentOrder() { + if (orderTempActionLoading || !isOrderActionEligible(currentOrder) || Number(currentOrder.status) !== 2) return; + const button = document.getElementById("order-action-unlock"); + orderTempActionLoading = true; + if (button) { + button.disabled = true; + button.querySelector("strong").textContent = "开车中..."; + } + + try { + const resp = await apiFetch("/api/order/temp_unlock", { + method: "POST", + headers: { + "Authorization": `Bearer ${authToken}`, + "Content-Type": "application/json" + }, + body: JSON.stringify({ order_id: currentOrder.order_id }) + }); + const data = await resp.json(); + if (data.rtn_code === 0) { + showToast(data.message || "临时开车成功"); + const status = document.getElementById("order-actions-status"); + if (status) status.textContent = "车辆正在解锁,请稍候"; + } else { + showToast(data.message || "临时开车失败"); + } + } catch (err) { + console.error("临时开车失败:", err); + showToast("临时开车失败,请重试"); + } finally { + orderTempActionLoading = false; + if (button) { + button.disabled = false; + button.querySelector("strong").textContent = "临时开车"; + } + } + } + + // ========== 一键开锁 ========== + let unlockPendingCode = null; // 待开锁的车牌 + let unlockPendingPosition = null; // 待开锁的位置 + + function handleQuickUnlock() { + const qrBox = document.getElementById("qrcode-box"); + const code = qrBox.dataset.bikeCode; + + if (!code) { + showToast("无法获取车辆编码"); + return; + } + + if (!currentUser) { + showToast("请先登录"); + return; + } + + // 保存待开锁信息(用车辆自身坐标 + 随机抖动 ±0.0001,不依赖用户真实定位) + const baseLat = parseFloat(selectedBike?.latitude) || 36.67; + const baseLng = parseFloat(selectedBike?.longitude) || 116.98; + const jit = 0.0001; + unlockPendingCode = code; + unlockPendingPosition = { + lat: baseLat + (Math.random() * 2 - 1) * jit, + lng: baseLng + (Math.random() * 2 - 1) * jit + }; + + // 有共享绑定 → 先选开锁账号;否则直接确认 + openUnlockAccountChooser(); + } + + // ===== 开锁账号选择(自己 / 共享者列表) ===== + let unlockChoice = { mode: "own", owner_user_id: null, owner_email: null, owner_display: "" }; + let unlockSrcList = []; + let unlockSrcShowAll = false; + + function openUnlockAccountChooser() { + unlockChoice = { mode: "own", owner_user_id: null, owner_email: null, owner_display: "" }; + unlockSrcShowAll = false; + if (!authToken || !currentUser) { proceedToUnlockConfirm(); return; } + apiFetch("/api/share/sources", { headers: { "Authorization": "Bearer " + authToken } }) + .then(r => r.json()) + .then(data => { + if (data.rtn_code !== 0 || !data.data) { proceedToUnlockConfirm(); return; } + const d = data.data; + if (!d.has_any) { proceedToUnlockConfirm(); return; } + renderUnlockSrcList(d); + document.getElementById("unlock-src-modal").classList.add("show"); + }) + .catch(() => proceedToUnlockConfirm()); + } + + function renderUnlockSrcList(d) { + const box = document.getElementById("unlock-src-list"); + let html = ""; + html += ''; + const srcs = d.sources || []; + unlockSrcList = srcs.slice(); + if (srcs.length === 0 && d.hidden_count > 0) { + html += ''; + } + srcs.forEach(s => { + const dis = s.can_use ? "" : "unavailable"; + const tagTxt = s.can_use ? ("剩余可用 " + s.remaining_today + " 次") : (s.reasons && s.reasons.length ? s.reasons.join(" / ") : "不可用"); + const label = partnerLabel(s.owner_name, s.owner_email, s.remark); + html += ''; + }); + if (d.hidden_count > 0) { + html += '还有 ' + d.hidden_count + ' 位共享者今日次数已用完(点击查看)'; + } + box.innerHTML = html; + } + + function loadUnlockSrcShowAll() { + unlockSrcShowAll = true; + apiFetch("/api/share/sources?show_unavailable=1", { headers: { "Authorization": "Bearer " + authToken } }) + .then(r => r.json()) + .then(data => { if (data.rtn_code === 0) renderUnlockSrcList(data.data); }); + } + + function chooseUnlockSrc(ownerId) { + ownerId = ownerId || 0; + const rec = unlockSrcList.find(x => Number(x.owner_user_id) === Number(ownerId)); + if (ownerId && !rec) { closeUnlockSrc(); return; } + unlockChoice = rec + ? { mode: "shared", owner_user_id: rec.owner_user_id, owner_email: rec.owner_email, + owner_display: partnerLabel(rec.owner_name, rec.owner_email, rec.remark) } + : { mode: "own", owner_user_id: null, owner_email: null, owner_display: "" }; + closeUnlockSrc(); + proceedToUnlockConfirm(); + } + + function closeUnlockSrc() { + document.getElementById("unlock-src-modal").classList.remove("show"); + } + + function proceedToUnlockConfirm() { + if (!unlockPendingCode) return; + const btn = document.getElementById("unlock-confirm-btn"); + btn.disabled = false; + btn.textContent = unlockChoice.mode === "shared" + ? ("确认用 " + (unlockChoice.owner_display || "对方") + " 的共享开锁") + : "确认开锁"; + // 开锁前预览:月卡余量 + 自动续租轮次预估(共享单用车主的卡) + loadUnlockPreview(unlockPendingCode, + unlockChoice.mode === "shared" ? unlockChoice.owner_user_id : null); + document.getElementById("unlock-confirm-modal").classList.add("show"); + } + + function closeUnlockConfirm() { + document.getElementById("unlock-confirm-modal").classList.remove("show"); + unlockPendingCode = null; + unlockPendingPosition = null; + } + + async function doUnlockBike() { + if (!unlockPendingCode || !authToken) { + closeUnlockConfirm(); + return; + } + + const btn = document.getElementById("unlock-confirm-btn"); + btn.disabled = true; + btn.textContent = "开锁中..."; + const isShared = unlockChoice && unlockChoice.mode === "shared"; + + try { + const payload = { + code: unlockPendingCode, + latitude: unlockPendingPosition.lat, + longitude: unlockPendingPosition.lng + }; + if (isShared) payload.owner_user_id = unlockChoice.owner_user_id; + + const resp = await apiFetch(isShared ? "/api/order/shared_unlock" : "/api/order/unlock", { + method: "POST", + headers: { + "Authorization": `Bearer ${authToken}`, + "Content-Type": "application/json" + }, + body: JSON.stringify(payload) + }); + const data = await resp.json(); + console.log("[开锁] 响应:", data); + + closeUnlockConfirm(); + + if (data.rtn_code === 0) { + showToast(data.message || "开锁成功!"); + closeQrModal(); + + if (isShared) { + // 共享开锁:横幅由后端订单状态驱动,不启动本地计时 + refreshShareBanners(); + checkOrderStatus(); + } else { + // 启动前端计时器;end_time/轮次预估取自后端开锁响应 + const _ud = data.data || {}; + startRentalFromServer(data.order_id, unlockPendingCode, 19, + _ud.end_time, _ud); + // 刷新订单状态 + checkOrderStatus(); + } + } else if (data.need_pay) { + // 未支付订单月卡也付不了 → 提示用户并刷新订单横幅 + showToast(data.message || "存在未支付订单,请先支付"); + checkOrderStatus(); // 刷新横幅显示待支付 + } else { + showToast(data.message || "开锁失败"); + } + } catch (err) { + console.error("[开锁] 请求失败:", err); + showToast("开锁失败,请重试"); + } finally { + btn.disabled = false; + btn.textContent = isShared ? "确认共享开锁" : "确认开锁"; + unlockPendingCode = null; + unlockPendingPosition = null; + unlockChoice = { mode: "own", owner_user_id: null, owner_email: null }; + } + } + + async function quickUnlock(code, latitude, longitude) { + if (!authToken) { + showToast("请先登录"); + return; + } + + try { + const resp = await apiFetch("/api/order/unlock", { + method: "POST", + headers: { + "Authorization": `Bearer ${authToken}`, + "Content-Type": "application/json" + }, + body: JSON.stringify({ + code: code, + latitude: latitude, + longitude: longitude + }) + }); + const data = await resp.json(); + console.log("[开锁] 响应:", data); // 调试日志 + + if (data.rtn_code === 0) { + showToast(data.message || "开锁成功!"); + closeQrModal(); + + // 启动前端计时器;end_time/轮次预估取自后端开锁响应 + const _qd = data.data || {}; + startRentalFromServer(data.order_id, code, 19, _qd.end_time, _qd); + + // 刷新订单状态 + checkOrderStatus(); + } else { + showToast(data.message || "开锁失败"); + } + } catch (err) { + console.error("[开锁] 请求失败:", err); // 调试日志 + showToast("开锁失败,请重试"); + } + } + + // 从后端计时器启动前端计时器(隐藏横幅,由后端控制邮件通知) + function startRentalFromServer(rentalId, bikeCode, durationMinutes, endTime, summary) { + // 启动本地计时器(不显示横幅,由后端统一管理) + const remaining = durationMinutes * 60; + activeRental = { + rental_id: rentalId, + bike_code: bikeCode, + remaining_seconds: remaining, + source: "unlock", // 网页开锁 → 真实订单,+1轮可用 + end_time: endTime || null, + final_end_time: (summary && summary.final_end_time) || endTime || null, + current_round: (summary && summary.current_round) || 1, + total_rounds: (summary && summary.total_rounds) || null, + auto_return: true + }; + localStorage.setItem(RENTAL_KEY, JSON.stringify(activeRental)); + + // 启动倒计时更新(每秒) + if (rentalCountdownTimer) clearInterval(rentalCountdownTimer); + rentalCountdownTimer = setInterval(() => { + if (activeRental && activeRental.remaining_seconds > 0) { + activeRental.remaining_seconds--; + localStorage.setItem(RENTAL_KEY, JSON.stringify(activeRental)); + + // 到期动作由后端依据订单类型及用户设置执行 + // 这里不需要做任何操作 + } + }, 1000); + } + + // ========== 开锁前预览(月卡余量 + 轮次预估) ========== + function renderUnlockPreview(p) { + const box = document.getElementById("unlock-preview"); + if (!box) return; + if (!p) { box.style.display = "none"; box.innerHTML = ""; return; } + const lines = []; + lines.push(`
${p.shared ? "共享预览(用车主的卡与轮次)" : "本次用车预览"}
`); + if (p.has_card) { + const cardText = (p.cards || []).slice(0, 3).map(c => + `${escHtml(c.name)}${c.remain === null ? "(不限次)" : ` 剩 ${c.remain} 次`}`).join(","); + lines.push(`
优惠卡:${cardText}${p.card_note ? ` · ${escHtml(p.card_note)}` : ""}
`); + } else { + lines.push(`
未检测到优惠卡:本次费用将按小程序计费(还车后需支付)
`); + } + if (p.auto_return) { + lines.push(`
自动续租:计划 ${p.rounds_planned} 轮 × ${p.duration_minutes} 分钟,预计 ${escHtml(p.est_end_time)} 前还车
`); + } else { + lines.push(`
自动还车未开启:本轮 ${p.duration_minutes} 分钟,请留意到期手动还车
`); + } + box.innerHTML = lines.join(""); + box.style.display = "block"; + } + async function loadUnlockPreview(code, ownerUserId) { + const box = document.getElementById("unlock-preview"); + if (box) { box.style.display = "block"; box.innerHTML = '
预览加载中...
'; } + try { + const q = new URLSearchParams({ code: String(code) }); + if (ownerUserId) q.set("owner_user_id", ownerUserId); + const resp = await apiFetch(`/api/order/preview?${q.toString()}`, { + headers: { "Authorization": `Bearer ${authToken}` } + }); + const data = await resp.json(); + renderUnlockPreview(data.rtn_code === 0 ? data.data : null); + } catch (err) { + renderUnlockPreview(null); + } + } + + // ========== 手动 +1 轮 ========== + // ========== 手动 +1 轮(带确认弹窗) ========== + // 语义:只把「计划轮数」+1。当前这一轮照常到点 → 自动还车 → 优惠卡支付 + // → 立刻重新开锁同一辆车进入下一轮(绝不延长本轮时长)。 + let _addRoundTarget = null; + function showAddRoundConfirm(target) { + _addRoundTarget = target; + const remainSec = target.kind === "rental" + ? (activeRental && activeRental.remaining_seconds) || orderCountdownSeconds || 0 + : orderCountdownSeconds || 0; + const mins = Math.max(1, Math.round(remainSec / 60)); + const btn = document.getElementById("add-round-confirm-btn"); + if (btn) { btn.disabled = false; btn.textContent = "确认加 1 轮"; } + const text = document.getElementById("add-round-text"); + if (text) { + text.innerHTML = + `当前这一轮还剩约 ${mins} 分钟,不会延长。
` + + `到点后系统会自动:还车 → 用优惠卡支付 → 立刻重新开锁同一辆车,进入下一轮。`; + } + document.getElementById("add-round-modal").classList.add("show"); + } + function closeAddRoundModal() { + document.getElementById("add-round-modal").classList.remove("show"); + _addRoundTarget = null; + } + async function confirmAddRound() { + if (!_addRoundTarget || !authToken) { closeAddRoundModal(); return; } + const btn = document.getElementById("add-round-confirm-btn"); + if (btn) { btn.disabled = true; btn.textContent = "提交中..."; } + const payload = _addRoundTarget.kind === "rental" + ? { rental_id: _addRoundTarget.value } + : { order_id: _addRoundTarget.value }; + try { + const resp = await apiFetch("/api/order/add_round", { + method: "POST", + headers: { "Authorization": `Bearer ${authToken}`, "Content-Type": "application/json" }, + body: JSON.stringify(payload) + }); + const data = await resp.json(); + if (data.rtn_code === 0) { + showToast(data.message || "已加 1 轮"); + // 本轮剩余不变,只更新计划轮数与预计还车时间 + if (activeRental) { + activeRental.total_rounds = data.data.total_rounds; + activeRental.final_end_time = data.data.final_end_time; + localStorage.setItem(RENTAL_KEY, JSON.stringify(activeRental)); + updateRentalFinalTime(); + } + if (currentOrder && currentOrder.order_id) fetchOrderCountdown(currentOrder.order_id); + checkOrderStatus(); + } else { + showToast(data.message || "加轮失败"); + } + } catch (err) { + showToast("网络错误,请重试"); + } finally { + closeAddRoundModal(); + } + } + function addRoundForCurrent() { + if (!activeRental || !authToken) { showToast("当前没有进行中的订单"); return; } + showAddRoundConfirm({ kind: "rental", value: activeRental.rental_id }); + } + function addRoundFromBanner() { + if (!currentOrder || !currentOrder.order_id) { showToast("当前没有进行中的订单"); return; } + showAddRoundConfirm({ kind: "order", value: currentOrder.order_id }); + } + // 页面加载时检查订单状态和租车状态 + document.addEventListener("DOMContentLoaded", async () => { + if (authToken) { + await syncWechatOrder(); // 先同步微信订单状态 + checkOrderStatus(); + checkRentalStatus(); // 再恢复租车横幅 + checkStrictGuide(); // 强签名验证:缺 AccessToken 进页面立即引导 + refreshAuthExpiry(); // 登录态有效期:不足 2 天在主页面挂提醒横幅 + } + }); diff --git a/static/js/map-rental.js b/static/js/map-rental.js new file mode 100644 index 0000000..8cee75a --- /dev/null +++ b/static/js/map-rental.js @@ -0,0 +1,499 @@ + // ========== 用车计时相关 ========== + function clearRentalState() { + if (rentalCountdownTimer) { + clearInterval(rentalCountdownTimer); + rentalCountdownTimer = null; + } + activeRental = null; + localStorage.removeItem(RENTAL_KEY); + const bar = document.getElementById("rental-bar"); + if (bar) bar.classList.remove("show"); + } + + async function openRentalSettingsModal() { + closeAllModals(); + SettingsPages.open("rental-settings-modal"); + try { + const resp = await apiFetch("/api/auth/rental_settings", { + headers: { "Authorization": `Bearer ${authToken}` } + }); + const result = await resp.json(); + if (result.rtn_code !== 0) throw new Error(result.message || "加载失败"); + const settings = result.data; + document.getElementById("rs-reminder-enabled").checked = !!settings.reminder_enabled; + document.getElementById("rs-duration").value = settings.rental_duration_minutes || 19; + document.getElementById("rs-auto-return").checked = !!settings.auto_return_enabled; + document.getElementById("rs-rounds").value = settings.rental_rounds || 1; + document.getElementById("rs-protect-card").checked = settings.protect_card !== false; + const selected = new Set((settings.reminder_minutes || []).map(String)); + document.querySelectorAll("#rs-minute-options input").forEach(el => el.checked = selected.has(el.value)); + } catch (err) { + showToast("设置加载失败:" + friendlyError(err)); + } + } + + function closeRentalSettingsModal() { SettingsPages.back(); } + + async function saveRentalSettings() { + const reminderMinutes = [...document.querySelectorAll("#rs-minute-options input:checked")].map(el => Number(el.value)); + const payload = { + reminder_enabled: document.getElementById("rs-reminder-enabled").checked, + reminder_minutes: reminderMinutes, + rental_duration_minutes: Number(document.getElementById("rs-duration").value), + auto_return_enabled: document.getElementById("rs-auto-return").checked, + rental_rounds: Number(document.getElementById("rs-rounds").value), + protect_card: document.getElementById("rs-protect-card").checked + }; + try { + const resp = await apiFetch("/api/auth/rental_settings", { + method: "POST", + headers: { "Authorization": `Bearer ${authToken}`, "Content-Type": "application/json" }, + body: JSON.stringify(payload) + }); + const result = await resp.json(); + if (result.rtn_code !== 0) throw new Error(result.message || "保存失败"); + closeRentalSettingsModal(); + showToast("用车设置已保存"); + } catch (err) { + showToast("保存失败:" + friendlyError(err)); + } + } + + async function syncWechatOrder() { + if (!authToken) return; + try { + const resp = await apiFetch("/api/rental/sync", { + method: "POST", + headers: { + "Authorization": `Bearer ${authToken}`, + "Content-Type": "application/json" + } + }); + const data = await resp.json(); + console.log("[syncWechatOrder] 同步结果:", data); + if (data.rtn_code === 0 && data.data && data.data.active && data.data.source === "reminder") { + const r = data.data; + activeRental = { + rental_id: r.rental_id, + bike_code: r.bike_code, + end_time: r.end_time, + source: r.source || "reminder", + remaining_seconds: r.remaining_seconds + }; + localStorage.setItem(RENTAL_KEY, JSON.stringify(activeRental)); + } else if (data.rtn_code === 0 && data.data) { + // 真实订单走订单横幅(checkOrderStatus / fetchOrderCountdown 驱动), + // 本地计时条只承载 reminder 计时 + clearRentalState(); + } + } catch (err) { + console.error("[syncWechatOrder] 同步失败:", err); + } + } + + function checkRentalStatus() { + // 已登录才查询 + if (!authToken) { + console.log("[checkRentalStatus] 无token,跳过"); + return; + } + + apiFetch("/api/rental/status", { + headers: { "Authorization": `Bearer ${authToken}` } + }) + .then(r => r.json()) + .then(data => { + console.log("[checkRentalStatus] 响应:", data); + if (data.rtn_code === 0 && data.data && data.data.active) { + const r = data.data; + + // 剩余时间 <= 0 也视为无活跃 + if (r.remaining_seconds <= 0) { + clearRentalState(); + return; + } + + // 既然后端已按用户过滤,有记录就直接显示状态栏 + activeRental = { + rental_id: r.rental_id, + order_id: r.order_id || null, + bike_code: r.bike_code, + email: r.email, + end_time: r.end_time, + final_end_time: r.final_end_time || null, + current_round: r.current_round || 1, + total_rounds: r.total_rounds || null, + source: r.source || null, + remaining_seconds: r.remaining_seconds + }; + localStorage.setItem(RENTAL_KEY, JSON.stringify(activeRental)); + showRentalBar(); + } else { + // 无活跃租车,清空 + console.log("[checkRentalStatus] 无活跃租车"); + clearRentalState(); + } + }) + .catch(err => console.error("检查租车状态失败:", err)); + } + + function startRental(bikeCode) { + // 先显示二维码,用户体验更好 + showQrModal(bikeCode); + closeCard(); + + console.log("[startRental] authToken:", authToken, "currentUser:", currentUser); + + if (!currentUser) { + showToast("登录后可开启用车计时提醒"); + return; + } + + // 调后端开启计时 + apiFetch("/api/rental/start", { + method: "POST", + headers: { + "Content-Type": "application/json", + "Authorization": `Bearer ${authToken}` + }, + body: JSON.stringify({ bike_code: bikeCode }) + }) + .then(r => r.json()) + .then(data => { + if (data.rtn_code === 0) { + const now = new Date(); + const endTime = new Date(now.getTime() + data.data.remaining_seconds * 1000); + activeRental = { + rental_id: data.data.rental_id, + bike_code: bikeCode, + email: currentUser.email, + remaining_seconds: data.data.remaining_seconds, + end_time: endTime.toISOString().slice(0, 19).replace('T', ' ') + }; + localStorage.setItem(RENTAL_KEY, JSON.stringify(activeRental)); + showRentalBar(); + showToast("提醒计时已开始;未绑定微信订单,请到期前手动还车"); + } else { + showToast(data.message || "计时启动失败"); + } + }) + .catch(err => { + showToast("计时未开启,请检查网络"); + console.error("启动计时失败:", err); + }); + } + + function showRentalBar() { + if (!activeRental) return; + const bar = document.getElementById("rental-bar"); + document.getElementById("rental-bike-code").textContent = `#${activeRental.bike_code}`; + // +1轮 按钮仅对真实微信订单展示(reminder 计时不支持) + const addBtn = document.getElementById("rental-add-round-btn"); + if (addBtn) { + const realOrder = activeRental.source ? activeRental.source !== "reminder" + : !!activeRental.order_id; + addBtn.style.display = realOrder ? "inline-flex" : "none"; + } + updateRentalFinalTime(); + bar.classList.add("show"); + updateRentalCountdown(); + // 每秒更新倒计时 + if (rentalCountdownTimer) clearInterval(rentalCountdownTimer); + rentalCountdownTimer = setInterval(updateRentalCountdown, 1000); + } + + function updateRentalFinalTime() { + const el = document.getElementById("rental-final-time"); + if (!el) return; + if (activeRental && activeRental.final_end_time) { + const hhmm = String(activeRental.final_end_time).slice(11, 16); + const total = activeRental.total_rounds || activeRental.rounds_planned; + el.textContent = total ? ` · 共${total}轮 预计${hhmm}还车` : ` · 预计${hhmm}还车`; + el.style.display = "inline"; + } else { + el.style.display = "none"; + } + } + + function updateRentalCountdown() { + if (!activeRental) return; + const el = document.getElementById("rental-time"); + const remaining = Math.max(0, activeRental.remaining_seconds - 1); + activeRental.remaining_seconds = remaining; + localStorage.setItem(RENTAL_KEY, JSON.stringify(activeRental)); + + const mins = Math.floor(remaining / 60); + const secs = remaining % 60; + el.textContent = `${mins}:${secs.toString().padStart(2, "0")}`; + + // 变色提示 + if (remaining <= 60) { + el.style.color = "#ff3b30"; + } else if (remaining <= 300) { + el.style.color = "#ff9f0a"; + } else { + el.style.color = "white"; + } + + if (remaining <= 0) { + clearInterval(rentalCountdownTimer); + // 超时后每分钟查一次后端确认状态 + rentalCountdownTimer = setInterval(checkRentalStatus, 60000); + } + } + + function showReturnModal() { + if (!activeRental) return; + document.getElementById("return-bike-code").textContent = `#${activeRental.bike_code}`; + document.getElementById("return-modal").classList.add("show"); + } + + function closeReturnModal() { + document.getElementById("return-modal").classList.remove("show"); + } + + async function confirmReturn() { + closeReturnModal(); + if (!activeRental) return; + + try { + const response = await apiFetch("/api/rental/return", { + method: "POST", + headers: { + "Content-Type": "application/json", + "Authorization": `Bearer ${authToken}` + }, + body: JSON.stringify({ rental_id: activeRental.rental_id }) + }); + const data = await response.json(); + + // 只有后端返回成功才清除本地状态 + if (data.rtn_code === 0) { + clearRentalState(); + showToast("已确认还车,祝您使用愉快!"); + } else { + // 后端返回错误,保持本地状态,提示用户 + showToast(data.message || "还车失败,请重试"); + console.error("还车失败:", data); + } + } catch (err) { + console.error("确认还车失败:", err); + showToast("网络错误,请检查网络后重试"); + } + } + + // 原生壳(Android)判定:UA 由 Android WebView 注入 xbniu-native,head 脚本已给 加 in-native-shell + function isNativeShell() { + return document.documentElement && document.documentElement.classList.contains('in-native-shell'); + } + // 网页点“开锁用车”时,把开锁交给安卓原生(原生里选账号/共享并开锁);返回 true 表示已交给原生 + function nativeUnlockBike(code) { + try { + if (isNativeShell() && window.xbniuAndroid && typeof window.xbniuAndroid.unlock === 'function') { + window.xbniuAndroid.unlock(String(code)); + return true; + } + } catch (e) { console.error("[原生桥] 调用失败:", e); } + return false; + } + + function unlockBike() { + if (!selectedBike) return; + + // 检查车辆状态 + const bikeState = getBikeState(selectedBike); + if (bikeState === 'inuse') { + showToast("该车正在使用中,请稍后再试"); + closeCard(); + return; + } + if (bikeState === 'locked') { + showToast("该车已锁定,无法使用"); + closeCard(); + return; + } + if (bikeState === 'reserved') { + showToast("该车已被预约"); + closeCard(); + return; + } + + // 原生壳:点击即交给安卓原生开锁(账号选择在原生 BikeDetailActivity),不在此出网页二维码 + if (nativeUnlockBike(selectedBike.code)) { + return; + } + + // 网页端默认:显示二维码弹窗(长按二维码才开始计时) + showQrModal(selectedBike.code); + } + + // 显示二维码弹窗(适配微信扫码 - img格式) + let currentQrPosition = null; // 当前二维码对应的位置 + + function showQrModal(code) { + const modal = document.getElementById("qr-modal"); + const qrBox = document.getElementById("qrcode-box"); + const quickBtn = document.getElementById("quick-unlock-btn"); + + // 清空旧的二维码 + qrBox.innerHTML = ""; + + // 获取当前位置 + currentQrPosition = null; + if (navigator.geolocation) { + navigator.geolocation.getCurrentPosition( + pos => { + currentQrPosition = { + lat: pos.coords.latitude, + lng: pos.coords.longitude + }; + }, + err => console.error("获取位置失败:", err), + { timeout: 5000 } + ); + } + + // 生成新二维码 + const url = "http://bike.sdlongren.com/bicycle?code=" + code; + + // 判断暗色模式 + const isDark = UIPreferences.isDark(); + const dark = isDark ? '#ffffff' : '#000000'; + const light = isDark ? '#1a1a1a' : '#ffffff'; + + // 生成 img 格式二维码(参考 xbcr.html) + createQrImage(url, dark, light, function(dataUrl) { + qrBox.innerHTML = ""; // 清空旧内容 + if (!dataUrl) { + // 二维码库不可用:明确告知并保留一键开锁入口,避免“点了没反应” + qrBox.innerHTML = '
二维码生成组件加载失败,
可直接使用下方一键开锁。
'; + modal.classList.add("show"); + quickBtn.style.display = (authToken && currentUser) ? "block" : "none"; + showToast("二维码组件加载失败,可一键开锁"); + return; + } + const img = document.createElement('img'); + img.src = dataUrl; + img.alt = '用车二维码'; + img.style.cssText = 'width:160px;height:160px;border-radius:4px;box-shadow:rgba(0,0,0,0.4) 2px 2px 8px;display:block;'; + qrBox.appendChild(img); + qrBox.dataset.bikeCode = code; // 存车牌,长按时用 + modal.classList.add("show"); + + // 如果用户已登录,显示一键开锁按钮 + if (authToken && currentUser) { + quickBtn.style.display = "block"; + } else { + quickBtn.style.display = "none"; + } + }); + } + + // 生成高质量二维码图片(img格式,适配微信长按识别) + function createQrImage(text, dark, light, callback) { + const size = 160; + const padding = 20; + const canvas = document.createElement('canvas'); + canvas.width = canvas.height = size + padding * 2; + const ctx = canvas.getContext('2d'); + + // 白色背景 + ctx.fillStyle = light; + ctx.fillRect(0, 0, canvas.width, canvas.height); + + // 生成二维码到临时容器 + const tmp = document.createElement('div'); + tmp.style.display = 'none'; + document.body.appendChild(tmp); + + // qrcodejs 加载失败时(如外链 CDN 不可达)给出明确提示,而不是无声无息 + if (typeof QRCode === "undefined") { + document.body.removeChild(tmp); + callback(null); + return; + } + + new QRCode(tmp, { + text: text, + width: size, + height: size, + colorDark: dark, + colorLight: light, + correctLevel: QRCode.CorrectLevel.L + }); + + // 从临时容器提取 canvas 并画到带padding的画布上 + setTimeout(function() { + var qrCanvas = tmp.querySelector('canvas'); + if (qrCanvas) { + ctx.drawImage(qrCanvas, padding, padding); + } + document.body.removeChild(tmp); + callback(qrCanvas ? canvas.toDataURL('image/png', 1) : null); + }, 0); + } + + // 关闭二维码弹窗 + function closeQrModal() { + document.getElementById("qr-modal").classList.remove("show"); + document.getElementById("quick-unlock-btn").style.display = "none"; + // 清除长按定时器 + longPressTimer = null; + longPressTarget = null; + currentQrPosition = null; + } + + // 长按检测变量 + let longPressTimer = null; + let longPressTarget = null; + let qrModalBikeCode = null; // 当前二维码对应的车牌 + + // 二维码弹窗的二维码区域长按检测 + function setupQrLongPress() { + const qrBox = document.getElementById("qrcode-box"); + + // 统一用 pointer 事件(兼容触摸和鼠标) + qrBox.addEventListener("pointerdown", function(e) { + if (!currentUser) return; + e.preventDefault(); // 阻止右键菜单等默认行为 + qrModalBikeCode = qrBox.dataset.bikeCode || ""; + longPressTimer = setTimeout(() => { + longPressTimer = null; + if (qrModalBikeCode && currentUser) { + // 视觉反馈 + qrBox.style.backgroundColor = "rgba(52,199,89,0.2)"; + setTimeout(() => { qrBox.style.backgroundColor = "white"; }, 500); + startRental(qrModalBikeCode); + } + }, 300); + }); + + qrBox.addEventListener("pointerup", function(e) { + if (longPressTimer) { + clearTimeout(longPressTimer); + longPressTimer = null; + } + }); + + qrBox.addEventListener("pointerleave", function(e) { + if (longPressTimer) { + clearTimeout(longPressTimer); + longPressTimer = null; + } + }); + + qrBox.addEventListener("pointercancel", function(e) { + if (longPressTimer) { + clearTimeout(longPressTimer); + longPressTimer = null; + } + }); + } + + // 页面加载时初始化长按检测 + setupQrLongPress(); + + // 点击遮罩关闭 + document.getElementById("qr-modal").addEventListener("click", function(e) { + if (e.target === this) closeQrModal(); + }); diff --git a/static/js/map-sharing.js b/static/js/map-sharing.js new file mode 100644 index 0000000..3151ff3 --- /dev/null +++ b/static/js/map-sharing.js @@ -0,0 +1,345 @@ + // ================= 共享电动车 ================= + function shareApi(url, method, body) { + const opts = { method: method || "GET", headers: {} }; + if (authToken) opts.headers["Authorization"] = `Bearer ${authToken}`; + if (body !== undefined) { + opts.headers["Content-Type"] = "application/json"; + opts.body = JSON.stringify(body); + } + return apiFetch(url, opts).then(r => r.json()); + } + + // ===== 私密备注(昵称) 工具 ===== + // 显示对方时:优先用“我给他起的备注(昵称)”,其次显示名,最后退回邮箱 + function partnerLabel(name, email, remark) { + return (remark && String(remark).trim()) || name || email || ""; + } + // share_id -> {email,name,remark},备注编辑用(不把用户文本嵌进 HTML 属性/JS 字面量) + let shareRec = {}; + + // ---------- 管理弹窗 ---------- + let shareTabNow = "usable"; + function openShareModal() { + if (!authToken || !currentUser) { showToast("请先登录"); return; } + SettingsPages.open("share-modal"); + switchShareTab(shareTabNow); + loadShareData(); + } + function closeShareModal() { + SettingsPages.back(); + } + function switchShareTab(tab) { + shareTabNow = tab; + document.getElementById("share-tab-usable").classList.toggle("active", tab === "usable"); + document.getElementById("share-tab-mine").classList.toggle("active", tab === "mine"); + document.getElementById("share-list-usable").style.display = tab === "usable" ? "flex" : "none"; + document.getElementById("share-list-mine").style.display = tab === "mine" ? "flex" : "none"; + loadShareData(); + } + function sharePendingHtml(pending) { + if (!pending || !pending.length) { document.getElementById("share-pending-box").style.display = "none"; return; } + const rows = pending.map(p => + `
等待接受:${escHtml(p.from_email||'')} + + + +
`).join(""); + const box = document.getElementById("share-pending-box"); + box.innerHTML = `
待处理的共享申请
${rows}`; + box.style.display = "block"; + } + async function loadShareData() { + if (!authToken) return; + try { + const data = await shareApi("/api/share/list"); + if (data.rtn_code !== 0) { showToast(data.message || "加载失败"); return; } + const d = data.data || { usable: [], shared: [] }; + shareRec = {}; + + document.getElementById("share-list-usable").innerHTML = d.usable.map(u => { + const uLabel = partnerLabel(u.owner_name, u.owner_email, u.remark); + shareRec[u.share_id] = { email: u.owner_email || "", name: u.owner_name || "", remark: u.remark || "" }; + const state = u.can_use + ? ('') + : (''); + return ''; + }).join(""); + + document.getElementById("share-list-mine").innerHTML = d.shared.map(sr => { + const sLabel = partnerLabel(sr.rider_name, sr.rider_email, sr.remark); + shareRec[sr.share_id] = { email: sr.rider_email || "", name: sr.rider_name || "", remark: sr.remark || "" }; + return ''; + }).join(""); + + const pending = await shareApi("/api/share/pending"); + if (pending.rtn_code === 0) sharePendingHtml(pending.data || []); + } catch (e) { console.error("[share] load失败", e); } + } + async function sendShareRequest() { + if (!authToken) { showToast("请先登录"); return; } + const email = document.getElementById("share-req-email").value.trim(); + if (!email) { showToast("请输入对方邮箱"); return; } + const btn = document.querySelector(".share-req-row button"); + if (btn) { btn.disabled = true; } + try { + const data = await shareApi("/api/share/request", "POST", { to_email: email }); + showToast(data.message || (data.rtn_code === 0 ? "已发送" : "发送失败")); + if (data.rtn_code === 0) document.getElementById("share-req-email").value = ""; + } finally { + if (btn) { btn.disabled = false; } + } + } + + async function acceptShareRequest(reqId, fromEmail) { + const askM = document.getElementById("share-ask-modal"); + if (askM) askM.classList.remove("show"); + shareAskActive = false; + try { + const data = await shareApi("/api/share/respond", "POST", { request_id: reqId, accept: true }); + if (data.rtn_code === 0 && data.data) { + showToast("已接受,请设置权限"); + openShareConfig(data.data.share_id, data.data.daily_limit, data.data.require_card, data.data.card_min_times, data.data.rider_email); + } else { + showToast(data.message || "操作失败"); + } + } finally { + loadShareData(); + checkPendingShareRequests(); + } + } + async function rejectShareRequest(reqId) { + const askM = document.getElementById("share-ask-modal"); + if (askM) askM.classList.remove("show"); + shareAskActive = false; + try { + const data = await shareApi("/api/share/respond", "POST", { request_id: reqId, accept: false }); + showToast(data.message || "已拒绝"); + } finally { + loadShareData(); + checkPendingShareRequests(); + } + } + + // ---------- 权限设置 ---------- + let shareCfg = { share_id: null }; + function openShareConfig(shareId, daily, requireCard, minTimes, email) { + shareCfg = { share_id: shareId }; + document.getElementById("share-config-title").textContent = email ? `为 ${email} 设置共享权限` : ""; + document.getElementById("sharecfg-daily").value = daily ?? 3; + document.getElementById("sharecfg-card").checked = !!requireCard; + document.getElementById("sharecfg-mintimes").value = minTimes ?? 0; + SettingsPages.open("share-config-modal"); + } + function closeShareConfig() { + SettingsPages.back(); + setTimeout(() => checkPendingShareRequests(), 0); + } + async function saveShareConfig() { + if (!shareCfg.share_id) return; + const daily = parseInt(document.getElementById("sharecfg-daily").value, 10) || 0; + const require_card = document.getElementById("sharecfg-card").checked ? 1 : 0; + const minTimes = parseInt(document.getElementById("sharecfg-mintimes").value, 10) || 0; + const data = await shareApi("/api/share/config", "POST", { + share_id: shareCfg.share_id, daily_limit: daily, require_card, card_min_times: minTimes + }); + showToast(data.message || (data.rtn_code === 0 ? "权限已保存" : "保存失败")); + if (data.rtn_code === 0) closeShareConfig(); + loadShareData(); + checkPendingShareRequests(); + } + + async function unbindShare(shareId) { + if (!(await appConfirm("解绑后对方将无法再用你的共享额度开锁,可随时重新申请。", { title: "解绑共享关系", okText: "解绑", danger: true }))) return; + const data = await shareApi("/api/share/unbind", "POST", { share_id: shareId }); + showToast(data.message || "已解绑"); + loadShareData(); + refreshShareBanners(); + } + + // ---------- 给对方的私密备注(昵称) ---------- + let shareRemarkCfg = { share_id: null }; + function openShareRemark(shareId) { + const rec = shareRec[shareId]; + if (!rec) return; + shareRemarkCfg.share_id = shareId; + document.getElementById("share-remark-input").value = rec.remark || ""; + const shown = partnerLabel(rec.name, rec.email, rec.remark); + document.getElementById("share-remark-desc").innerHTML = + '给 ' + escHtml(shown) + ' 起一个昵称备注,仅自己可见;未设置时对 TA 的显示退回邮箱 (' + escHtml(rec.email || "") + ')。'; + SettingsPages.open("share-remark-modal"); + } + function closeShareRemark() { + SettingsPages.back(); + shareRemarkCfg.share_id = null; + } + async function saveShareRemark() { + if (!shareRemarkCfg.share_id) return; + const remark = document.getElementById("share-remark-input").value.trim(); + const btn = document.querySelector("#share-remark-modal .auth-submit"); + if (btn) btn.disabled = true; + try { + const data = await shareApi("/api/share/remark", "POST", { share_id: shareRemarkCfg.share_id, remark: remark }); + showToast(data.message || (data.rtn_code === 0 ? "备注已保存" : "保存失败")); + if (data.rtn_code === 0) closeShareRemark(); + loadShareData(); + refreshShareBanners(); + } catch (e) { console.error("[share] remark失败", e); showToast("保存失败"); } + finally { if (btn) btn.disabled = false; } + } + + // ---------- 全屏接收申请 ---------- + let shareAskQueue = []; + let shareAskActive = false; + let shareAskCur = null; + async function checkPendingShareRequests() { + if (!authToken || shareAskActive) return; + try { + const data = await shareApi("/api/share/pending"); + if (data.rtn_code === 0 && data.data && data.data.length) { + shareAskQueue = data.data.slice(); + nextShareAskIfQueue(); + } + } catch (e) { /* 忽略 */ } + } + function nextShareAskIfQueue() { + if (shareAskQueue.length > 0) { + shareAskCur = shareAskQueue.shift(); + shareAskActive = true; + document.getElementById("share-ask-from").textContent = shareAskCur.from_email || ""; + document.getElementById("share-ask-modal").classList.add("show"); + } else if (shareAskActive) { + shareAskActive = false; + document.getElementById("share-ask-modal").classList.remove("show"); + } + } + async function acceptCurrentShareAsk() { + if (!shareAskCur) return; + await acceptShareRequest(shareAskCur.id, shareAskCur.from_email); + // 接受后弹权限设置由 acceptShareRequest 处理;队列推进 + } + async function rejectCurrentShareAsk() { + if (!shareAskCur) return; + await rejectShareRequest(shareAskCur.id); + } + + // ---------- 共享横幅(车主:共享中 / 骑行者:使用中) ---------- + let shareActiveList = []; + let pendingShareReturn = null; + async function refreshShareBanners() { + const cont = document.getElementById("share-banners"); + if (!cont) return; + if (!authToken || !currentUser) { cont.innerHTML = ""; return; } + try { + const data = await shareApi("/api/share/active"); + if (data.rtn_code !== 0) return; + shareActiveList = data.data || []; + shareActiveList.forEach(it => { it._countdownDeadline = performance.now() + Math.max(0, Number(it.remaining_seconds) || 0) * 1000; }); + let html = ""; + shareActiveList.forEach((it, idx) => { + const isOwner = it.role === "owner"; + const label = partnerLabel(it.partner_name, it.partner_email, it.remark); + const esc = escHtml(label); + const bike = escHtml(it.bike_code || ""); + let text; + if (isOwner) { + text = '共享中#' + bike + '' + esc + ' 使用中'; + } else { + text = '使用 ' + esc + ' 的车中#' + bike + ''; + } + html += ''; + }); + cont.innerHTML = html; + } catch (e) { console.error("[share] banners失败", e); } + } + function openShareReturnByIdx(idx) { + const it = shareActiveList[idx]; + if (!it) return; + pendingShareReturn = it; + const isOwner = it.role === "owner"; + const label = partnerLabel(it.partner_name, it.partner_email, it.remark); + const esc = escHtml(label); + const bike = escHtml(it.bike_code || ""); + const box = document.getElementById("share-return-text"); + box.innerHTML = isOwner + ? ('你的共享电动车 #' + bike + ' 正被 ' + esc + ' 使用,确认替他/她还车?') + : ('你正在使用 ' + esc + ' 的车 #' + bike + ',确认还车?'); + document.getElementById("share-return-modal").classList.add("show"); + } + function updateShareCountdowns() { + shareActiveList.forEach((it, idx) => { + const el = document.getElementById('share-countdown-' + idx); + if (!el) return; + const seconds = Math.max(0, Math.ceil((it._countdownDeadline - performance.now()) / 1000)); + el.textContent = seconds > 0 ? '本轮剩余 ' + remainingTimeText(seconds) : '本轮到期 · 同步状态中'; + }); + } + setInterval(updateShareCountdowns, 1000); + // HTML 的 ✕ / 取消 / 遮罩都调用它(此前漏了定义 → 点击直接 ReferenceError,弹窗关不掉) + function closeShareReturnModal() { + const modal = document.getElementById("share-return-modal"); + if (modal) modal.classList.remove("show"); + pendingShareReturn = null; + } + async function confirmShareReturn() { + if (!pendingShareReturn) return; + const it = pendingShareReturn; + const btn = document.querySelector("#share-return-modal .auth-submit"); + if (btn) { btn.disabled = true; btn.textContent = "还车中..."; } + try { + let position = null; + if (navigator.geolocation) { + position = await new Promise(resolve => { + navigator.geolocation.getCurrentPosition( + pos => resolve(pos), + () => resolve(null), + { timeout: 5000 }); + }); + } + const latitude = position?.coords?.latitude || 36.67; + const longitude = position?.coords?.longitude || 116.98; + const data = await shareApi("/api/share/return", "POST", { + order_id: it.order_id, latitude, longitude + }); + showToast(data.message || (data.rtn_code === 0 ? "还车成功" : "还车失败")); + if (data.rtn_code === 0) { + closeShareReturnModal(); + pendingShareReturn = null; + await Promise.all([refreshShareBanners(), checkOrderStatus(), refreshMap()]); + } + } catch (e) { + showToast("还车失败,请重试"); + } finally { + if (btn) { btn.disabled = false; btn.textContent = "确认还车"; } + } + } + + // ---------- 初始化(登录后/页面加载) ---------- + function shareAfterLogin() { + refreshShareBanners(); + setTimeout(() => checkPendingShareRequests(), 800); + } + document.addEventListener("DOMContentLoaded", () => { + if (authToken) shareAfterLogin(); + setInterval(() => { if (authToken) { checkAuthStatus(); checkOrderStatus(); refreshShareBanners(); } }, 20000); + setInterval(() => { if (authToken) checkPendingShareRequests(); }, 30000); + setTimeout(maybeAutoShowVersion, 1200); + }); diff --git a/static/js/map-subscriptions.js b/static/js/map-subscriptions.js new file mode 100644 index 0000000..ba06a57 --- /dev/null +++ b/static/js/map-subscriptions.js @@ -0,0 +1,96 @@ + // ========== 订阅提醒(编辑、复制与最近执行结果) ========== + let subscribeLocations = [], subscribeRuleCache = [], subscribeEditId = null; + const SUB_WEEKDAYS = {0:"每天",1:"周一",2:"周二",3:"周三",4:"周四",5:"周五",6:"周六",7:"周日"}; + async function openSubscribeModal() { + closeAllModals(); SettingsPages.open("subscribe-modal"); + await loadSubscribeLocations(); resetSubscribeEditor(); await loadSubscribeRules(); + } + function closeSubscribeModal() { SettingsPages.back(); } + async function loadSubscribeLocations() { + const select = document.getElementById("sub-location"); + try { + const response = await apiFetch("/api/campus/locations"); const data = await response.json(); + subscribeLocations = (data.data || []).filter(p => p.kind === "parking"); + select.innerHTML = subscribeLocations.length ? subscribeLocations.map(p => ``).join("") : ''; + } catch (error) { select.innerHTML = ''; } + } + function subRuleRowHtml(rule) { + const time = `${String(Math.floor(rule.minute_of_day / 60)).padStart(2,"0")}:${String(rule.minute_of_day % 60).padStart(2,"0")}`; + const status = {success:"执行成功", failed:"执行失败", no_match:"没有符合条件的车辆", running:"执行中"}[rule.last_run_status] || "尚未执行"; + return `
${escHtml(rule.location_name || "停车点已删除")}${SUB_WEEKDAYS[rule.weekday]} ${time}
${rule.enabled ? "已启用" : "已停用"} · ${(rule.kind_labels || []).join("/")} · 电量 ${rule.min_electric}-${rule.max_electric}% · ${rule.auto_unlock ? "自动开锁" : "仅提醒"}
${status}${rule.last_run_at ? " · " + escHtml(rule.last_run_at) : ""}${rule.last_run_message ? "
" + escHtml(rule.last_run_message) : ""}
`; + } + async function loadSubscribeRules() { + const box = document.getElementById("subscribe-list"); + box.innerHTML = '
正在加载订阅...
'; + try { + const response = await apiFetch("/api/subscribe/rules", {headers:{Authorization:`Bearer ${authToken}`}}); const data = await response.json(); + if (data.rtn_code !== 0) throw new Error(data.message || "加载失败"); + subscribeRuleCache = data.data || []; + box.innerHTML = subscribeRuleCache.length ? subscribeRuleCache.map(subRuleRowHtml).join("") : '
暂无订阅,可以在下方添加停车点和用车时间。
'; + } catch (error) { box.innerHTML = `
${escHtml(error.message)},请返回后重试。
`; } + } + function toggleSubAdvanced() { const box = document.getElementById("sub-advanced"); box.style.display = box.style.display === "none" ? "block" : "none"; } + function resetSubscribeEditor() { + subscribeEditId = null; + document.getElementById("sub-editor-title").textContent = "新增规则"; + document.getElementById("sub-save").textContent = "添加规则"; + document.getElementById("sub-cancel-edit").hidden = true; + document.getElementById("sub-weekday").value = "0"; + document.getElementById("sub-time").value = "11:55"; + document.getElementById("sub-notify").checked = true; + document.getElementById("sub-auto").checked = false; + document.getElementById("sub-min-e").value = 0; + document.getElementById("sub-max-e").value = 100; + document.getElementById("sub-sort").value = "electric_desc"; + document.getElementById("sub-retry").value = 3; + document.querySelectorAll(".sub-kind").forEach(el => el.checked = true); + } + function editSubscribeRule(id, copy) { + const rule = subscribeRuleCache.find(r => r.id === id); if (!rule) return; + subscribeEditId = copy ? null : id; + document.getElementById("sub-editor-title").textContent = copy ? "复制规则(保存后新增)" : "编辑规则"; + document.getElementById("sub-save").textContent = copy ? "添加副本" : "保存修改"; + document.getElementById("sub-cancel-edit").hidden = false; + document.getElementById("sub-location").value = rule.location_id; + document.getElementById("sub-weekday").value = rule.weekday; + document.getElementById("sub-time").value = `${String(Math.floor(rule.minute_of_day / 60)).padStart(2,"0")}:${String(rule.minute_of_day % 60).padStart(2,"0")}`; + document.getElementById("sub-notify").checked = rule.notify_enabled; + document.getElementById("sub-auto").checked = rule.auto_unlock; + document.getElementById("sub-min-e").value = rule.min_electric; + document.getElementById("sub-max-e").value = rule.max_electric; + document.getElementById("sub-sort").value = rule.sort_by; + document.getElementById("sub-retry").value = rule.retry_times; + document.querySelectorAll(".sub-kind").forEach(el => el.checked = rule.kinds.includes(el.value)); + document.getElementById("sub-advanced").style.display = "block"; + document.getElementById("sub-time").focus({preventScroll:true}); + document.getElementById("sub-editor-title").scrollIntoView({block:"nearest"}); + } + async function addSubscribeRule() { + return AppAPI.run("subscription-save", document.getElementById("sub-save"), async () => { + const payload = {location_id:Number(document.getElementById("sub-location").value), weekday:Number(document.getElementById("sub-weekday").value), time:document.getElementById("sub-time").value, + notify_enabled:document.getElementById("sub-notify").checked, auto_unlock:document.getElementById("sub-auto").checked, + kinds:[...document.querySelectorAll(".sub-kind:checked")].map(el => el.value), min_electric:Number(document.getElementById("sub-min-e").value), max_electric:Number(document.getElementById("sub-max-e").value), sort_by:document.getElementById("sub-sort").value, retry_times:Number(document.getElementById("sub-retry").value)}; + if (!payload.location_id || !payload.time || !payload.kinds.length) { showToast("请选择停车点、时间和至少一种车型"); return; } + if (payload.min_electric < 0 || payload.max_electric > 100 || payload.min_electric > payload.max_electric) { showToast("电量区间应在0-100且下限不高于上限"); return; } + if (!payload.notify_enabled && !payload.auto_unlock) { showToast("请至少开启邮件提醒或自动开锁"); return; } + if (payload.auto_unlock && !await appConfirm("命中规则后将使用当前账号真实开锁车辆。请核对停车点、时间与筛选条件。", {title:"确认自动开锁规则",okText:subscribeEditId ? "确认保存" : "确认添加"})) return; + try { + const response = await apiFetch(subscribeEditId ? `/api/subscribe/rules/${subscribeEditId}` : "/api/subscribe/rules", {method:subscribeEditId ? "PUT" : "POST", headers:{Authorization:`Bearer ${authToken}`,"Content-Type":"application/json"},body:JSON.stringify(payload)}); + const data = await response.json(); if (data.rtn_code !== 0) throw new Error(data.message || "保存失败"); + resetSubscribeEditor(); await loadSubscribeRules(); showToast("订阅规则已保存"); + } catch (error) { showToast(error.message || "保存失败,请重试"); } + }); + } + async function toggleSubscribeRule(id, enabled) { + return AppAPI.run(`subscription-${id}`, null, async () => { + try { const response = await apiFetch(`/api/subscribe/rules/${id}`, {method:"PUT",headers:{Authorization:`Bearer ${authToken}`,"Content-Type":"application/json"},body:JSON.stringify({enabled:!!enabled})}); const data = await response.json(); if (data.rtn_code !== 0) throw new Error(data.message); await loadSubscribeRules(); } + catch (error) { showToast(error.message || "操作失败"); } + }); + } + async function deleteSubscribeRule(id) { + if (!await appConfirm("确定删除这条订阅规则吗?", {title:"删除订阅",okText:"删除"})) return; + return AppAPI.run(`subscription-${id}`, null, async () => { + try { const response = await apiFetch(`/api/subscribe/rules/${id}`, {method:"DELETE",headers:{Authorization:`Bearer ${authToken}`}}); const data = await response.json(); if (data.rtn_code !== 0) throw new Error(data.message); if (subscribeEditId === id) resetSubscribeEditor(); await loadSubscribeRules(); } + catch (error) { showToast(error.message || "删除失败"); } + }); + } diff --git a/static/js/map-utils.js b/static/js/map-utils.js new file mode 100644 index 0000000..d67c841 --- /dev/null +++ b/static/js/map-utils.js @@ -0,0 +1,457 @@ + // ========== 通用确认弹窗(替换 window.confirm) ========== + // 为什么不用 confirm:原生壳是 Android WebView,WebView 默认不弹 JS 原生对话框 + // (Chromium 需要宿主实现 onJsConfirm,未实现时 confirm 直接返回 false,用户点不到"确认")。 + // 这里用页面内弹窗,行为一致但任何环境都能用。 + let _appConfirmResolve = null; + function appConfirm(message, opts) { + const o = opts || {}; + const modal = document.getElementById("app-confirm-modal"); + const titleEl = document.getElementById("app-confirm-title"); + const textEl = document.getElementById("app-confirm-text"); + const okBtn = document.getElementById("app-confirm-ok"); + const cancelBtn = document.getElementById("app-confirm-cancel"); + if (!modal || !textEl) { // 极老页面兜底 + return Promise.resolve(window.confirm ? window.confirm(message) : true); + } + titleEl.textContent = o.title || "确认操作"; + // 支持换行(保留 \n 的排版) + textEl.innerHTML = String(message || "") + .split("\n") + .map(line => escHtml(line)) + .join("
"); + okBtn.textContent = o.okText || "确认"; + cancelBtn.textContent = o.cancelText || "取消"; + okBtn.classList.toggle("danger", !!o.danger); + + return new Promise(resolve => { + _appConfirmResolve = resolve; + const finish = (val) => { + modal.classList.remove("show"); + okBtn.onclick = null; + cancelBtn.onclick = null; + modal.onclick = null; + _appConfirmResolve = null; + resolve(val); + }; + okBtn.onclick = (e) => { e.stopPropagation(); finish(true); }; + cancelBtn.onclick = (e) => { e.stopPropagation(); finish(false); }; + modal.onclick = (e) => { if (e.target === modal) finish(false); }; + modal.classList.add("show"); + }); + } + function appConfirmClose() { + if (_appConfirmResolve) { + const r = _appConfirmResolve; + _appConfirmResolve = null; + document.getElementById("app-confirm-modal").classList.remove("show"); + r(false); + } + } + + function mapSnapshotNow() { + return renderedMapSnapshot + ? renderedMapSnapshot.serverTime + (performance.now() - renderedMapSnapshot.receivedAt) / 1000 + : Date.now() / 1000; + } + + function updateMapFreshnessBadge() { + const el = document.getElementById("update-time"); + if (!el) return; + const stamp = Number(renderedMapSnapshot?.fetched_at); + if (renderedMapSnapshot && Number.isFinite(stamp) && renderedMapSnapshot.fetched_at !== null) { + el.textContent = new Date(stamp * 1000).toLocaleTimeString('zh-CN', { + timeZone: 'Asia/Shanghai', hour: '2-digit', minute: '2-digit' + }); + const expired = mapSnapshotNow() >= Number(renderedMapSnapshot.expires_at); + el.classList.toggle("stale", expired || mapRefreshFailed); + } else if (mapRefreshFailed) { + el.textContent = "更新失败"; + el.classList.add("stale"); + } + el.onclick = showFreshnessDetail; + el.style.cursor = "pointer"; + } + + function updateTime() { + if (renderedMapSnapshot) { updateMapFreshnessBadge(); return; } + // Compatibility for a server without snapshot metadata; never show client time. + apiFetch(`/api/map/freshness?type=${encodeURIComponent(currentType)}`, { cache: "no-store" }) + .then(r => r.json()) + .then(result => { + if (result.rtn_code !== 0 || !result.data?.latest) return; + const el = document.getElementById("update-time"); + if (!el) return; + el.textContent = String(result.data.latest).slice(11, 16); + el.classList.toggle("stale", result.data.status === "stale" || result.data.stale_seconds >= 60); + el.onclick = showFreshnessDetail; + el.style.cursor = "pointer"; + }) + .catch(() => {}); + } + + function showFreshnessDetail() { + if (renderedMapSnapshot && renderedMapSnapshot.fetched_at !== null) { + const seconds = Math.max(0, Math.floor(mapSnapshotNow() - renderedMapSnapshot.fetched_at)); + const when = new Date(renderedMapSnapshot.fetched_at * 1000).toLocaleTimeString('zh-CN', { timeZone: 'Asia/Shanghai' }); + const age = seconds < 60 ? `${seconds} 秒前` : `${Math.floor(seconds / 60)} 分钟前`; + showToast(`车辆数据更新于 ${when}(${age})${mapRefreshFailed ? ',更新暂时失败,正在自动重试' : ''}`); + return; + } + showToast(mapRefreshFailed ? "地图数据暂时不可用,正在自动重试" : "正在获取最新车辆数据"); + } + + function showToast(msg) { + const t = document.getElementById("toast"); + t.textContent = msg; + t.classList.add("show"); + setTimeout(() => t.classList.remove("show"), 2500); + } + + // ========== 抓包工具下载 ========== + // 安装包是 Windows exe,任何手机/平板都跑不了;微信、QQ、支付宝等内置 + // WebView 还会直接拦截 exe 下载。这两类情况都改为提示复制链接到电脑浏览器。 + const CAPTURE_TOOL_PATH = "/download/capture-tool.exe"; + + // 鸿蒙 UA 有两种:老版 HarmonyOS + Android 兼容层,新版纯 OpenHarmony/ArkWeb; + // 微信鸿蒙版仍带 MicroMessenger,但部分版本 UA 精简后只剩 HarmonyOS。 + function detectHarmony() { + const ua = navigator.userAgent || ""; + return /OpenHarmony|HarmonyOS|ArkWeb|HMSCore/i.test(ua); + } + function detectMobile() { + const ua = navigator.userAgent || ""; + const touchPoints = navigator.maxTouchPoints || 0; + // iPadOS 13+ 默认「请求桌面网站」,UA 伪装成 macOS; + // 靠触点数区分真正的 Mac(0)与 iPad(>1) + if (/Macintosh/.test(ua) && touchPoints > 1) return "iPad"; + // 鸿蒙平板也常带 Tablet,先于手机判断 + if (/OpenHarmony|HarmonyOS|ArkWeb/.test(ua)) { + return /Tablet/i.test(ua) ? "鸿蒙平板" : "鸿蒙手机"; + } + if (/iPhone|iPod/.test(ua)) return "iPhone"; + if (/iPad/.test(ua)) return "iPad"; + if (/Android/.test(ua)) return /Tablet/i.test(ua) ? "安卓平板" : "安卓手机"; + // 兜底:UA 明确标了 Mobile 但没给出具体平台 + if (/Mobile/i.test(ua)) return "手机"; + return null; + } + // 返回需要拦截的"环境名",null 表示可以直接下载 + function detectInAppBrowser() { + const ua = navigator.userAgent || ""; + // 原生壳优先判断:它是最外层容器,UA 里可能同时带 Android + if (/xbniu-native/i.test(ua)) return "APP"; + if (/MicroMessenger/i.test(ua)) return detectHarmony() ? "鸿蒙微信" : "微信"; + if (/\bQQ\/|QQBrowser/i.test(ua)) return "QQ"; + if (/AlipayClient/i.test(ua)) return "支付宝"; + if (/DingTalk/i.test(ua)) return "钉钉"; + if (/Weibo/i.test(ua)) return "微博"; + if (/aweme|ByteDance/i.test(ua)) return "抖音"; + return null; + } + function captureToolUrl() { + return new URL(CAPTURE_TOOL_PATH, window.location.href).href; + } + // 返回 true 时放行 的原生下载 + function onDownloadCaptureTool(event) { + const app = detectInAppBrowser(); + const mobile = app ? null : detectMobile(); // 内嵌环境优先,文案更具体 + if (!app && !mobile) return true; + if (event) event.preventDefault(); + showDownloadTipModal(app, mobile); + return false; + } + function showDownloadTipModal(appName, mobileName) { + const title = document.getElementById("download-tip-title"); + const desc = document.getElementById("download-tip-desc"); + const hint = document.getElementById("download-tip-hint"); + title.textContent = "请在电脑上下载安装"; + if (appName) { + desc.textContent = `${appName}内无法直接下载安装包。请复制下面的链接,在电脑浏览器中打开下载。`; + hint.textContent = "安装包为 Windows 程序,手机端下载后无法运行。"; + } else { + // 普通移动端浏览器:能下载但装了也用不了,引导去电脑 + desc.textContent = `当前是${mobileName || "移动设备"},安装包为 Windows 程序,在此设备上无法运行。请复制下面的链接,在电脑浏览器中打开下载。`; + hint.textContent = ""; + } + hint.style.display = hint.textContent ? "block" : "none"; + document.getElementById("download-tip-link").value = captureToolUrl(); + document.getElementById("download-tip-modal").classList.add("show"); + } + function closeDownloadTipModal() { + document.getElementById("download-tip-modal").classList.remove("show"); + } + + // ========== 数据导出(CSV 直链,1 小时有效) ========== + // 流程:POST /api/export/create(登录态)→ 拿到免登录直链。 + // UA 复用 detectInAppBrowser:微信/QQ/支付宝/钉钉/微博/抖音/原生壳内无法直接下载, + // 弹「复制链接到外部浏览器」提示;普通浏览器直接触发下载。 + function closeExportTipModal() { + document.getElementById("export-tip-modal").classList.remove("show"); + } + async function copyExportLink() { + const url = document.getElementById("export-tip-link").value; + const input = document.getElementById("export-tip-link"); + try { + if (navigator.clipboard && window.isSecureContext) { + await navigator.clipboard.writeText(url); + showToast("链接已复制,请在浏览器中打开"); + return; + } + throw new Error("clipboard unavailable"); + } catch (e) { + try { + input.removeAttribute("readonly"); + input.select(); + document.execCommand("copy"); + input.setAttribute("readonly", ""); + showToast("链接已复制,请在浏览器中打开"); + } catch (e2) { + showToast("复制失败,请长按链接手动复制"); + } + } + } + async function exportHistoryCsv() { + if (!authToken) { showToast("请先登录"); return; } + showToast("正在生成导出链接..."); + try { + const resp = await apiFetch("/api/export/create", { + method: "POST", + headers: { "Content-Type": "application/json", + "Authorization": `Bearer ${authToken}` }, + body: JSON.stringify({ type: "history_csv" }) + }); + const data = await resp.json(); + if (data.rtn_code !== 0) { + showToast(data.message || "生成导出链接失败"); + return; + } + const url = new URL(data.data.url, window.location.href).href; + const app = detectInAppBrowser(); + if (app) { + // 微信/原生壳等内嵌环境:给直链,复制到外部浏览器下载(直链免登录,1小时有效) + document.getElementById("export-tip-desc").textContent = + `${app}内无法直接下载文件。请复制下面的链接到系统浏览器打开(免登录,${data.data.ttl_hours} 小时内有效)。`; + document.getElementById("export-tip-link").value = url; + document.getElementById("export-tip-modal").classList.add("show"); + return; + } + // 普通浏览器:直接下载,同时保留直链以便换浏览器使用 + const a = document.createElement("a"); + a.href = url; + a.download = ""; + document.body.appendChild(a); + a.click(); + a.remove(); + showToast(`已开始下载(直链 ${data.data.ttl_hours} 小时内有效)`); + } catch (err) { + showToast("导出失败,请重试"); + } + } + async function copyDownloadLink() { + const url = captureToolUrl(); + const input = document.getElementById("download-tip-link"); + // 微信等 WebView 常禁用 navigator.clipboard(非安全上下文或权限拒绝), + // 回退到选中 + execCommand 的老办法 + try { + if (navigator.clipboard && window.isSecureContext) { + await navigator.clipboard.writeText(url); + showToast("链接已复制"); + return; + } + throw new Error("clipboard unavailable"); + } catch (e) { + try { + input.removeAttribute("readonly"); + input.select(); + input.setSelectionRange(0, url.length); + const ok = document.execCommand("copy"); + input.setAttribute("readonly", "readonly"); + showToast(ok ? "链接已复制" : "复制失败,请长按链接手动复制"); + } catch (e2) { + showToast("复制失败,请长按链接手动复制"); + } + } + } + + // 底层异常转用户提示:网关/错误页返回 HTML 时 resp.json() 会抛 + // "Unexpected token '<' ... is not valid JSON",直接展示既难懂又含 token 字样易引起误解 + function friendlyError(e) { + const msg = (e && e.message) || ""; + if (/Unexpected token|is not valid JSON|JSON\.parse/i.test(msg)) { + return "服务响应异常,请稍后重试"; + } + return msg || "网络错误,请重试"; + } + + // ========== Token失效弹窗 ========== + // 仅在真正检测到微信凭据失效时调用;带冷却时间,避免轮询/刷新反复打扰 + let _credInvalidLastShownAt = 0; + const CRED_INVALID_MODAL_COOLDOWN = 10 * 60 * 1000; // 10 分钟内不重复弹出 + function notifyCredentialInvalid(message) { + const modal = document.getElementById("token-expired-modal"); + if (!modal || modal.classList.contains("show")) return; + if (Date.now() - _credInvalidLastShownAt < CRED_INVALID_MODAL_COOLDOWN) return; + _credInvalidLastShownAt = Date.now(); + showTokenExpiredModal(null, message); + } + function showTokenExpiredModal(customTitle, customDesc) { + document.getElementById("token-expired-title").textContent = customTitle || "token已失效,请重新登录"; + document.getElementById("token-expired-desc").textContent = customDesc || "您的微信凭据已过期,请重新抓包获取最新的 Token ID(及 AccessToken)"; + document.getElementById("token-expired-modal").classList.add("show"); + // 预填当前用户已有的token信息 + loadExpiredTokenFields(); + } + function closeTokenExpiredModal() { + document.getElementById("token-expired-modal").classList.remove("show"); + document.getElementById("expired-tip").textContent = ""; + } + async function loadExpiredTokenFields() { + if (!authToken) return; + try { + const resp = await apiFetch("/api/auth/profile", { + headers: { "Authorization": `Bearer ${authToken}` } + }); + const data = await resp.json(); + if (data.rtn_code === 0 && data.data) { + document.getElementById("expired-token-id").value = data.data.token_id || ""; + document.getElementById("expired-signature").value = data.data.token || ""; + } + } catch (e) { /* ignore */ } + } + async function saveExpiredToken() { + if (!authToken) { + document.getElementById("expired-tip").textContent = "请先登录"; + return; + } + const token_id = document.getElementById("expired-token-id").value.trim(); + const access_token = document.getElementById("expired-signature").value.trim(); + const tip = document.getElementById("expired-tip"); + + if (!token_id) { + tip.textContent = "Token ID 必填;AccessToken 选填"; + return; + } + + tip.textContent = "验证中..."; + try { + const verifyResp = await apiFetch("/api/auth/verify_token", { + method: "POST", + headers: { "Content-Type": "application/json", + "Authorization": `Bearer ${authToken}` }, + body: JSON.stringify({ access_token, token_id }) + }); + const verifyData = await verifyResp.json(); + if (!verifyData.valid) { + tip.textContent = verifyData.message || "凭据验证失败,请检查 Token ID 是否正确"; + return; + } + } catch (err) { + tip.textContent = "验证失败"; + return; + } + + try { + const resp = await apiFetch("/api/auth/save_token", { + method: "POST", + headers: { + "Content-Type": "application/json", + "Authorization": `Bearer ${authToken}` + }, + body: JSON.stringify({ access_token, token_id }) + }); + const data = await resp.json(); + if (data.rtn_code === 0) { + tip.textContent = ""; + closeTokenExpiredModal(); + showToast("凭证已更新 ✓"); + } else { + tip.textContent = data.message || "保存失败"; + } + } catch (err) { + tip.textContent = "保存失败"; + } + } + + // ================= 版本号 & 更新说明 ================= + const VERSION_TAG = "v1.7.0-preview"; + const VERSION_LOGS = [ + { v: "v1.7.0 预览", items: ["新增附近列表、车型与电量筛选、校园地点搜索和常用地点", "完善定位失败引导、订阅编辑与执行结果、历史订单筛选和分页", "统一车辆状态,支持5位和8位车牌,增加浅色、深色和跟随系统"] }, + { v: "v1.6.0", items: [ + "新增用车设置:可独立开启或关闭邮件提醒,并多选到期前 10、5、3、2、1 分钟及到期时提醒", + "支持实时调整用车到期时间,当前订单也会立即按新时长更新;默认 19 分钟,月卡前 20 分钟免费并预留 1 分钟容错", + "新增自动还车开关;关闭后到期邮件只提醒手动还车,不再显示已自动还车或自动还车失败", + "共享用车按实际骑行人的到期与自动还车设置执行,车主和骑行人分别按各自设置接收美化后的 HTML 邮件及一键还车入口", + "修复共享车主重复显示订单横幅,并修复普通/共享车辆已锁车但接口响应异常时误报还车失败的问题" + ] }, + { v: "v1.5.0", items: [ + "新增共享电动车自定义昵称" + ] }, + { v: "v1.4.0", items: [ + "支持多设备同时登录:同一账号可在多台设备/多个浏览器同时在线,不再相互顶下线", + "个人中心新增“登录设备管理”:可查看当前账号各登录设备(记录系统/浏览器与最近活跃),随时下线其它设备或一键下线其它所有设备", + "统一个人中心/凭证/设备管理的深浅色模式适配" + ] }, + { v: "v1.3.0", items: [ + "新增「共享电动车」功能:向车主申请共享其电动车;接受后可设置每天可用次数、是否需要车主持有优惠卡、优惠卡剩余次数下限(低于则不能用)", + "开锁时可选择“用自己的账号”或“用共享者的账号”(附实时可用次数;今日次数用完的共享者默认隐藏)", + "用车横幅区分“共享中/使用XX的车中”,车主与被共享者都能还车", + "个人中心新增“共享电动车”入口,双Tab管理(可使用的/我共享的),双方都可解绑" + ] }, + { v: "v1.2.0", items: [ + "修复远程扫码被拦截:开锁上报车辆附近随机位置", + "请求头对齐当前版本微信环境" + ] } + ]; + // 右下角版本徽标始终跟随 VERSION_TAG,避免与更新说明不一致 + (function () { + var b = document.getElementById("version-badge"); + if (b) b.textContent = VERSION_TAG; + })(); + let versionModalInited = false; + let versionAutoTries = 0; + function openVersionModal() { + if (!versionModalInited) { + const el = document.getElementById("version-content"); + el.innerHTML = VERSION_LOGS.map(l => + `

${l.v}

    ${l.items.map(i => `
  • ${i}
  • `).join("")}
` + ).join(""); + versionModalInited = true; + } + // 记录已查看当前版本,避免每次打开都弹 + try { localStorage.setItem("version_seen", VERSION_TAG); } catch (e) {} + document.getElementById("version-modal").classList.add("show"); + } + function closeVersionModal() { + document.getElementById("version-modal").classList.remove("show"); + } + // 新版本/首次打开自动弹当前版本更新说明(每版本每浏览器只自动弹一次) + function maybeAutoShowVersion() { + // Update notes are available from Settings; first visits stay focused on finding a bike. + } + + async function previewLogin() { + const button = document.querySelector(".preview-login") || document.getElementById("auth-btn"); + await doLogin("demo@preview.local", "preview123", document.getElementById("gate-tip"), button); + } + async function createPreviewSession() { + return AppAPI.run("preview-session", null, async () => { + try { + let result = null; + const saved = localStorage.getItem("xbniu_preview_live_token"); + if (saved) { + const status = await (await apiFetch("/api/auth/status", {headers:{Authorization:`Bearer ${saved}`}})).json(); + if (status.data?.logged_in) result = {rtn_code:0,data:{token:saved,email:status.data.email}}; + } + if (!result) result = await (await apiFetch("/api/preview/session", {method:"POST"})).json(); + if (result.rtn_code !== 0) throw new Error(result.message || "创建失败"); + if (currentUser?.email !== result.data.email) resetMapForAccount(); + authToken = result.data.token; currentUser = {email:result.data.email}; localStorage.setItem("auth_token",authToken); + localStorage.setItem("xbniu_preview_live_token", authToken); + updateAuthButton(); hideLoginGate(); closeAllModals(); clearRentalState(); hideOrderBanner(); + currentOrder = null; + if (map) loadMapData(currentType, false); + showToast("独立测试账号已创建,请填写微信凭证后测试真实接口"); + openSettingsPage(); openAuthModal(); + } catch (error) { showToast(error.message || "创建失败,请重试"); } + }); + } diff --git a/static/js/map.js b/static/js/map.js index 6b6b8d4..32bf2f3 100644 --- a/static/js/map.js +++ b/static/js/map.js @@ -1,3 +1,4 @@ + function apiFetch(url, options) { return typeof AppAPI !== "undefined" ? AppAPI.fetch(url, options) : fetch(url, options); } // ========== 全局变量 ========== let map = null; let currentType = "3"; @@ -92,7 +93,7 @@ ctx.font = isHighlighted ? "bold 60px Arial" : "bold 44px Arial"; ctx.textAlign = "center"; ctx.textBaseline = "middle"; - ctx.fillText(isHighlighted ? (bikeCode + "") : (Math.round(electric) + ""), centerX, centerY); + ctx.fillText(isHighlighted ? (bikeCode + "") : (electric === null ? "?" : Math.round(electric) + ""), centerX, centerY); return canvas.toDataURL("image/png"); } @@ -158,22 +159,7 @@ // state=10: 低电量车辆 // state=4: 欠压车辆 // state=2: 损坏车辆 - function getBikeState(bike) { - const state = bike.state; - const status = bike.status; - const electric = Number(bike.electric_quantity ?? bike.electricQuantity ?? 100); - // 使用中:被占用 - if (state === 1 && status === 1) return 'inuse'; - // 低电量:state=10 或电量<20(与后端 _classify_bike_state 同序) - if (state === 10 || electric < 20) return 'lowbattery'; - // 空闲可用 - if (state === 1) return 'available'; - // 欠压车辆 - if (state === 4) return 'locked'; - // 损坏车辆 - if (state === 2) return 'reserved'; - return 'unknown'; - } + function getBikeState(bike) { return BikeData.state(bike); } // ========== 电池绘制 ========== function updateRingProgress(percent, color) { @@ -259,7 +245,7 @@ } function getBikeIcon(bike, isHighlighted = false) { - const electric = Number(bike.electric_quantity ?? bike.electricQuantity ?? 100); + const electric = BikeData.electric(bike); const bikeState = getBikeState(bike); // 车辆类型只影响弹起卡片上的标注,地图电量球保持原有「按状态配色」 @@ -270,12 +256,12 @@ color = "#FF9F0A"; // 橙色-欠压车辆 } else if (bikeState === 'reserved') { color = "#5856D6"; // 紫色-损坏车辆 - } else if (bikeState === 'lowbattery' || electric < 20) { + } else if (bikeState === 'lowbattery' || bikeState === 'unknown' || electric === null) { color = "#8E8E93"; // 灰色-低电量 } // 生成缓存 key - const electricLevel = Math.floor(electric / 5) * 5; + const electricLevel = electric === null ? "unknown" : Math.floor(electric / 5) * 5; const cacheKey = isHighlighted ? `${electricLevel}|${color}|1|${bike.code}` : `${electricLevel}|${color}|0`; @@ -289,7 +275,7 @@ const displaySize = isHighlighted ? 48 : 36; // 显示尺寸不变 // 非高亮模式:尝试使用预创建的图标 - if (!isHighlighted && prebuiltIcons.size > 0) { + if (electric !== null && !isHighlighted && prebuiltIcons.size > 0) { // 找到最接近的电量档位 const levels = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]; let closestLevel = levels[0]; @@ -488,7 +474,7 @@ }, 100); } } - + // ========== 初始化地图 ========== let mapInitializationStarted = false; function initMap() { @@ -508,2599 +494,12 @@ } waitForBMap(); } - - // ========== 登录认证 ========== - function handleAuthBtnClick() { - if (currentUser) { - // 已登录,显示个人中心 - showProfileModal(); - } else { - // 未登录,显示登录弹窗 - showLoginModal(); - } - } - - function showLoginModal() { - closeAllModals(); - document.getElementById("login-modal").classList.add("show"); - document.getElementById("login-email").focus(); - } - - function closeLoginModal() { - document.getElementById("login-modal").classList.remove("show"); - document.getElementById("login-tip").textContent = ""; - } - - function showRegisterModal() { - closeLoginModal(); - closeRegisterModal(); - document.getElementById("register-modal").classList.add("show"); - document.getElementById("register-email").focus(); - } - - function closeRegisterModal() { - document.getElementById("register-modal").classList.remove("show"); - document.getElementById("register-tip").textContent = ""; - } - function openSettingsPage() { - closeAllModals(); - document.getElementById("settings-clustering").checked = bikeClusteringEnabled; - document.getElementById("settings-save-status").textContent = "地图偏好自动保存在当前设备,即时生效。"; - SettingsPages.open("settings-modal"); - loadProfileData(); - } - - function closeSettingsPage() { SettingsPages.back(); } - - function saveMapClusteringSetting(enabled) { - if (typeof BikeClusters === "undefined") { - showToast("地图组件未加载,请刷新页面后重试"); - return; - } - bikeClusteringEnabled = !!enabled; - if (bikeBubbleLayer) bikeBubbleLayer.setClusteringEnabled(bikeClusteringEnabled); - const saved = BikeClusters.writeClusteringPreference(localStorage, bikeClusteringEnabled); - document.getElementById("settings-save-status").textContent = saved - ? (bikeClusteringEnabled ? "已开启车辆聚类,设置已保存。" : "已关闭聚类,所有车辆单独显示。设置已保存。") - : "设置已生效,当前浏览器无法保存,刷新后会恢复默认。"; - } - - window.addEventListener("storage", event => { - if (typeof BikeClusters === "undefined") return; - if (event.key !== BikeClusters.PREFERENCE_KEY && event.key !== null) return; - bikeClusteringEnabled = BikeClusters.readClusteringPreference(localStorage); - if (bikeBubbleLayer) bikeBubbleLayer.setClusteringEnabled(bikeClusteringEnabled); - document.getElementById("settings-clustering").checked = bikeClusteringEnabled; - }); - - function showProfileModal() { openSettingsPage(); } - - function closeProfileModal() { SettingsPages.close(); } - - function closeAllModals() { - if (typeof SettingsPages !== "undefined") SettingsPages.hide(); - document.getElementById("login-modal").classList.remove("show"); - document.getElementById("register-modal").classList.remove("show"); - document.getElementById("settings-modal").classList.remove("show"); - document.getElementById("rental-settings-modal").classList.remove("show"); - document.getElementById("devices-modal").classList.remove("show"); - document.getElementById("auth-modal").classList.remove("show"); - document.getElementById("packages-modal").classList.remove("show"); - const forgot = document.getElementById("forgot-modal"); - if (forgot) forgot.classList.remove("show"); - const orders = document.getElementById("orders-modal"); - if (orders) orders.classList.remove("show"); - const subscribe = document.getElementById("subscribe-modal"); - if (subscribe) subscribe.classList.remove("show"); - const traj = document.getElementById("order-traj-modal"); - if (traj) traj.classList.remove("show"); - const _armc = document.getElementById("add-round-modal"); - if (_armc) _armc.classList.remove("show"); - const _srm = document.getElementById("share-return-modal"); - if (_srm) _srm.classList.remove("show"); - appConfirmClose(); // 视为「取消」,避免 Promise 悬空 - } - - async function loadProfileData() { - if (!authToken) return; - - try { - const resp = await fetch("/api/auth/profile", { - headers: { "Authorization": `Bearer ${authToken}` } - }); - const data = await resp.json(); - - if (data.rtn_code === 0 && data.data) { - const email = data.data.email || ""; - document.getElementById("profile-email").textContent = email; - const firstChar = email.charAt(0).toUpperCase(); - document.getElementById("profile-avatar").textContent = firstChar; - - maybeStrictGuide(data.data); - - // 微信凭据(accessToken JWT)有效期,实时倒计时展示 - _savedTokenExpiry = data.data.access_token_expiry && data.data.access_token_expiry.parseable - ? { expireAt: data.data.access_token_expiry.expire_at, - source: data.data.access_token_expiry.source } : null; - updateTokenExpiryDisplays(); - - // 隐藏/显示消费统计和提示 - const hasAuth = data.data.has_auth; - document.getElementById("profile-stats").style.display = hasAuth ? "flex" : "none"; - document.getElementById("profile-auth-hint").style.display = hasAuth ? "none" : "flex"; - document.getElementById("profile-name").textContent = "--"; - document.getElementById("profile-out-money").textContent = "--"; - document.getElementById("profile-save-money").textContent = "--"; - } - } catch (err) { - console.error("加载用户信息失败:", err); - } - - // 加载姓名和消费信息 - loadUserInfo(); - } - - async function loadUserInfo() { - if (!authToken) return; - - try { - const resp = await fetch("/api/auth/user_info", { - headers: { "Authorization": `Bearer ${authToken}` } - }); - const data = await resp.json(); - - if (data.rtn_code === 0 && data.data) { - const info = data.data; - - // 显示姓名 - if (info.true_name) { - document.getElementById("profile-name").textContent = info.true_name; - document.getElementById("profile-avatar").textContent = info.true_name.charAt(0); - } - - // 显示消费统计 - if (info.out_money !== null) { - document.getElementById("profile-out-money").textContent = (info.out_money || 0).toFixed(1); - } - if (info.save_money !== null) { - document.getElementById("profile-save-money").textContent = (info.save_money || 0).toFixed(1); - } - } - } catch (err) { - console.error("加载用户详情失败:", err); - } - } - - // ========== AccessToken 有效期解析 ========== - // accessToken 是上游登录响应中的 JWT(RS256),payload 带 iat/nbf/exp, - // 实测有效期 30 天。此处只解码展示,不做签名校验。 - function parseJwtExpiry(token) { - token = (token || "").trim(); - if (!token || token.indexOf(".") < 0) return null; - const parts = token.split("."); - if (parts.length !== 3 || parts[1].length < 8) return null; - try { - let b64 = parts[1].replace(/-/g, "+").replace(/_/g, "/"); - while (b64.length % 4) b64 += "="; - const payload = JSON.parse(decodeURIComponent(escape(atob(b64)))); - let exp = payload.exp ? parseInt(payload.exp) : null; - let iat = payload.iat ? parseInt(payload.iat) : null; - if (!exp && iat) exp = iat + 30 * 86400; // 与上游实测一致:30 天有效期 - if (!exp) return null; - return { expireAt: exp, source: payload.exp ? "exp" : "iat+30d" }; - } catch (e) { return null; } - } - function fmtLocalTime(ts) { - const d = new Date(ts * 1000); - const p = n => String(n).padStart(2, "0"); - return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`; - } - function describeTokenExpiry(expiry) { - const remain = expiry.expireAt - Math.floor(Date.now() / 1000); - const when = fmtLocalTime(expiry.expireAt); - const left = remain <= 0 ? "已过期" : `约剩 ${fmtRemainShort(remain)}`; - const note = expiry.source === "iat+30d" ? "(按签发时间 +30 天推算)" : ""; - return { text: `该凭据(登录态)有效期至 ${when}${note},${left}`, remain }; - } - function fmtRemainShort(remain) { - const dd = Math.floor(remain / 86400), hh = Math.floor((remain % 86400) / 3600), - mm = Math.floor((remain % 3600) / 60); - if (dd >= 1) return `${dd} 天${hh ? " " + hh + " 小时" : ""}`; - if (hh >= 1) return `${hh} 小时${mm ? " " + mm + " 分" : ""}`; - return `${Math.max(1, mm)} 分钟`; - } - function renderTokenExpiry(el, expiry) { - if (!el) return; - if (!expiry) { el.style.display = "none"; el.innerHTML = ""; return; } - const { text, remain } = describeTokenExpiry(expiry); - let color = "#34c759", bg = "#eafaf0"; - if (remain <= 0) { color = "#e02020"; bg = "#fdecec"; } - else if (remain <= 259200) { color = "#e02020"; bg = "#fdecec"; } // ≤3 天 - else if (remain <= 604800) { color = "#e67e22"; bg = "#fdf3e7"; } // ≤7 天 - el.style.display = "block"; - el.style.color = color; - el.style.background = bg; - el.textContent = text; - } - function updateTokenExpiryDisplays() { - // “填写凭证”弹窗:粘贴中的新 token 优先实时预览,否则显示已保存凭据 - const authEl = document.getElementById("auth-token-expiry"); - if (authEl) { - const pasted = document.getElementById("profile-token").value.trim(); - if (pasted) { - const expiry = parseJwtExpiry(pasted); - if (expiry) { - renderTokenExpiry(authEl, expiry); - } else { - authEl.style.display = "block"; - authEl.style.color = "#e67e22"; - authEl.style.background = "#fdf3e7"; - authEl.textContent = "无法解析该 AccessToken 的有效期(不是标准 JWT,仍可保存使用)"; - } - } else { - renderTokenExpiry(authEl, _savedTokenExpiry); - } - } - // 个人中心:始终实时显示 - const pEl = document.getElementById("profile-token-expiry"); - if (pEl) renderTokenExpiry(pEl, _savedTokenExpiry); - renderAuthExpiryBanner(); - } - let _savedTokenExpiry = null; - - // ========== 登录态到期横幅 ========== - // 有效期不足 2 天时在主页面顶部常驻提醒,避免用户毫无预警地遇到上游凭据失效。 - const AUTH_EXPIRY_BANNER_THRESHOLD = 2 * 86400; // 2 天 - const AUTH_EXPIRY_BANNER_URGENT = 86400; // 不足 1 天转红 - function renderAuthExpiryBanner() { - const banner = document.getElementById("auth-expiry-banner"); - if (!banner) return; - const text = document.getElementById("auth-expiry-banner-text"); - if (!authToken || !_savedTokenExpiry) { - banner.classList.remove("show", "urgent"); - return; - } - const { remain } = describeTokenExpiry(_savedTokenExpiry); - if (remain > AUTH_EXPIRY_BANNER_THRESHOLD) { - banner.classList.remove("show", "urgent"); - return; - } - const when = fmtLocalTime(_savedTokenExpiry.expireAt); - text.textContent = remain <= 0 - ? "登录态已过期,为不影响使用请尽快抓包" - : `登录态剩 ${fmtRemainShort(remain)},为不影响使用请尽快抓包`; - banner.title = `有效期至 ${when}`; - banner.classList.toggle("urgent", remain <= AUTH_EXPIRY_BANNER_URGENT); - banner.classList.add("show"); - } - // 拉取服务端解析出的有效期(profile 接口),成功后刷新横幅 - async function refreshAuthExpiry() { - if (!authToken) { _savedTokenExpiry = null; renderAuthExpiryBanner(); return; } - try { - const resp = await fetch("/api/auth/profile", { - headers: { "Authorization": `Bearer ${authToken}` } - }); - const data = await resp.json(); - if (data.rtn_code === 0 && data.data) { - const e = data.data.access_token_expiry; - _savedTokenExpiry = e && e.parseable - ? { expireAt: e.expire_at, source: e.source } : null; - } else { - _savedTokenExpiry = null; - } - } catch (err) { - console.error("获取登录态有效期失败:", err); - } - updateTokenExpiryDisplays(); - } - setInterval(updateTokenExpiryDisplays, 30000); // 实时倒计时:每 30 秒刷新 - - // 打开凭证填写弹窗 - function openAuthModal() { - closeAllModals(); - SettingsPages.open("auth-modal"); - // 填充现有值 - fetch("/api/auth/profile", { - headers: { "Authorization": `Bearer ${authToken}` } - }).then(r => r.json()).then(data => { - if (data.rtn_code === 0 && data.data) { - document.getElementById("profile-token").value = data.data.token || ""; - document.getElementById("profile-token-id").value = data.data.token_id || ""; - const alertEl = document.getElementById("profile-alert-email"); - if (alertEl) { - // 未自定义时显示账号邮箱占位(提交空串即回退账号邮箱) - alertEl.value = data.data.alert_email || ""; - alertEl.placeholder = data.data.email || "留空则使用账号邮箱"; - } - _savedTokenExpiry = data.data.access_token_expiry && data.data.access_token_expiry.parseable - ? { expireAt: data.data.access_token_expiry.expire_at, - source: data.data.access_token_expiry.source } : null; - updateTokenExpiryDisplays(); - } - }); - } - - function closeAuthModal() { - SettingsPages.back(); - } - - // ========== 强签名验证引导 ========== - let _strictGuideShown = false; - function maybeStrictGuide(info) { - if (info && info.strict_mode && info.has_access_token === false && !_strictGuideShown) { - _strictGuideShown = true; - showTokenExpiredModal( - "需要补充 AccessToken", - "管理员已开启强签名验证,您的账号尚未填写 AccessToken,填写前无法调用用车功能。请按教程抓包获取 accessToken(登录响应中的 JWT)并保存。" - ); - } - } - async function checkStrictGuide() { - if (!authToken) return; - try { - const resp = await fetch("/api/auth/profile", { - headers: { "Authorization": `Bearer ${authToken}` } - }); - const data = await resp.json(); - if (data.rtn_code === 0 && data.data) maybeStrictGuide(data.data); - } catch (err) { console.error("强验证检测失败:", err); } - } - - // ========== 登录设备管理(多设备) ========== - // 生成本设备持久标识:同一浏览器/设备保持不变,用于区分不同登录设备 - function getDeviceId() { - let id = localStorage.getItem("xbniu_device_id"); - if (!id) { - id = Date.now().toString(36) + Math.random().toString(36).slice(2, 8); - try { localStorage.setItem("xbniu_device_id", id); } catch (e) {} - } - return id; - } - function getDeviceName() { - const ua = navigator.userAgent || ""; - // 与服务端 routes/auth.py _ua_label 保持同一套识别规则 - if (/xbniu-native/i.test(ua)) return "Native App"; - let os; - if (/Windows NT/.test(ua)) os = "Windows"; - else if (/iPhone|iPad|iPod/.test(ua)) os = "iOS"; - else if (/OpenHarmony|HarmonyOS|ArkWeb/.test(ua)) os = "鸿蒙"; - else if (/Android/.test(ua)) os = "Android"; - else if (/Mac OS X/.test(ua)) os = "macOS"; - else if (/Linux/.test(ua)) os = "Linux"; - else os = /Mobile/.test(ua) ? "移动设备" : "电脑"; - let browser = "浏览器"; - if (/MicroMessenger/i.test(ua)) browser = "微信"; - else if (/HuaweiBrowser/.test(ua)) browser = "华为浏览器"; - else if (/Edg\//.test(ua)) browser = "Edge"; - else if (/QQBrowser/.test(ua)) browser = "QQ浏览器"; - else if (/MiuiBrowser/.test(ua)) browser = "小米浏览器"; - else if (/Chrome\//.test(ua)) browser = "Chrome"; - else if (/Firefox\//.test(ua)) browser = "Firefox"; - else if (/Safari\//.test(ua)) browser = "Safari"; - let label = os + " · " + browser; - if (window.screen && screen.width) label += " · " + screen.width + "x" + screen.height; - return label; - } - function escHtml(s) { - return String(s == null ? "" : s).replace(/[&<>"']/g, - c => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); - } - function fmtTime(t) { - if (!t) return ""; - return escHtml(String(t).replace("T", " ").slice(0, 16)); - } - function openDevicesModal() { - closeAllModals(); - SettingsPages.open("devices-modal"); - loadDevicesList(); - } - function closeDevicesModal() { - SettingsPages.back(); - } - async function loadDevicesList() { - const box = document.getElementById("devices-list"); - if (!authToken) { box.innerHTML = '
请先登录
'; return; } - box.innerHTML = '
加载中...
'; - try { - const resp = await fetch("/api/auth/sessions", { - headers: { "Authorization": `Bearer ${authToken}` } - }); - const data = await resp.json(); - if (data.rtn_code !== 0) { - box.innerHTML = '
' + escHtml(data.message || "加载失败") + '
'; - return; - } - const list = data.data.sessions || []; - if (!list.length) { - box.innerHTML = '
暂无其他登录设备
'; - return; - } - box.innerHTML = list.map(s => { - const isCur = !!s.is_current; - const meta = "登录 " + fmtTime(s.created_at) + - (s.last_active ? " · 活跃 " + fmtTime(s.last_active) : ""); - return `
-
-
${escHtml(s.device_name || "未知设备")}${isCur ? ' 当前' : ""}
-
${meta}
-
- ${isCur ? "" : ``} -
`; - }).join(""); - } catch (err) { - box.innerHTML = '
加载失败
'; - } - } - async function kickDevice(id) { - if (!(await appConfirm("确认将该设备下线?该设备需要重新登录。", { title: "下线设备", okText: "下线" }))) return; - try { - const resp = await fetch("/api/auth/sessions/kick", { - method: "POST", - headers: { "Authorization": `Bearer ${authToken}`, "Content-Type": "application/json" }, - body: JSON.stringify({ session_id: id }) - }); - const data = await resp.json(); - if (data.rtn_code === 0) { showToast("已下线该设备"); loadDevicesList(); } - else showToast(data.message || "下线失败"); - } catch (e) { showToast("网络错误"); } - } - async function logoutAllOtherDevices() { - if (!(await appConfirm("确认下线当前账号其他所有设备?\n本设备会保留登录。", { title: "下线其他设备", okText: "全部下线" }))) return; - try { - const resp = await fetch("/api/auth/sessions/logout_all", { - method: "POST", - headers: { "Authorization": `Bearer ${authToken}` } - }); - const data = await resp.json(); - if (data.rtn_code === 0) { showToast("已下线其他所有设备"); loadDevicesList(); } - else showToast(data.message || "操作失败"); - } catch (e) { showToast("网络错误"); } - } - - // 打开卡包弹窗 - function openPackagesModal() { - closeAllModals(); - SettingsPages.open("packages-modal"); - loadPackagesList(); - } - - function closePackagesModal() { - SettingsPages.back(); - } - - // 加载卡包列表(用于卡包弹窗) - async function loadPackagesList() { - if (!authToken) { - document.getElementById("packages-list-2").innerHTML = '
请先登录
'; - return; - } - - try { - const resp = await fetch("/api/auth/packages", { - headers: { "Authorization": `Bearer ${authToken}` } - }); - const data = await resp.json(); - const container = document.getElementById("packages-list-2"); - - if (!data.data || !data.data.has_auth) { - container.innerHTML = '
请先填写 Token ID(AccessToken 选填)
'; - return; - } - - const packages = data.data.packages || []; - if (packages.length === 0) { - container.innerHTML = '
暂无优惠卡
'; - return; - } - - container.innerHTML = packages.map(pkg => ` -
-
${pkg.name}
-
${pkg.bikeTypeName || ''} · ${pkg.useTypeName || ''}
-
有效期至 ${pkg.endTime || '无限'}
-
剩余 ${pkg.remainTimes ?? '∞'} 次
-
- `).join(''); - } catch (err) { - console.error("加载卡包失败:", err); - document.getElementById("packages-list-2").innerHTML = '
加载失败
'; - } - } - - async function saveProfileToken() { - if (!authToken) { - showToast("请先登录"); - return; - } - - const access_token = document.getElementById("profile-token").value.trim(); - const token_id = document.getElementById("profile-token-id").value.trim(); - const alertEmailEl = document.getElementById("profile-alert-email"); - const alert_email = alertEmailEl ? alertEmailEl.value.trim().toLowerCase() : null; - - // 如果填了任意一个字段,需要先验证 - if (access_token || token_id) { - if (!token_id) { - showToast("Token ID 必填;AccessToken 选填"); - return; - } - - // 先验证(必须带登录态,否则 verify_token 返回 401) - try { - const verifyResp = await fetch("/api/auth/verify_token", { - method: "POST", - headers: { "Content-Type": "application/json", - "Authorization": `Bearer ${authToken}` }, - body: JSON.stringify({ access_token, token_id }) - }); - const verifyData = await verifyResp.json(); - - if (!verifyData.valid) { - showToast(verifyData.message || "凭据验证失败,请检查 Token ID 是否正确"); - return; - } - } catch (err) { - showToast("验证失败"); - return; - } - } - - // 验证通过或没填字段,直接保存 - try { - const resp = await fetch("/api/auth/save_token", { - method: "POST", - headers: { - "Authorization": `Bearer ${authToken}`, - "Content-Type": "application/json" - }, - body: JSON.stringify({ access_token, token_id }) - }); - const data = await resp.json(); - - if (data.rtn_code === 0) { - // 告警邮箱单独保存(可与凭据一起提交,失败不阻断) - if (alert_email !== null) { - fetch("/api/auth/alert_email", { - method: "POST", - headers: { "Content-Type": "application/json", - "Authorization": `Bearer ${authToken}` }, - body: JSON.stringify({ email: alert_email }) - }).catch(() => {}); - } - showToast("保存成功"); - closeAuthModal(); // 关闭凭证弹窗 - loadProfileData(); // 刷新个人中心数据 - refreshAuthExpiry(); // 新凭据可能已换有效期,重算顶部提醒 - } else { - showToast(data.message || "保存失败"); - } - } catch (err) { - showToast("保存失败"); - } - } - - // ========== 批量响铃相关状态 ========== - let currentBellTab = 'all'; // 当前选项卡 - let selectedRadius = 200; // 选中的半径(米) - let selectedLocation = null; // 选中的地点 {lat, lng} - let selectedStatuses = {available: true, used: true, locked: true, low: true, reserved: true}; // 选中的状态 - let rangeCircleOverlay = null; // 范围圆覆盖物 - - function showBellPasswordModal() { - if (!canUseBatchRing()) { - showToast("批量寻铃仅对指定用户开放"); - return; - } - document.getElementById("bell-modal").classList.add("show"); - // 重置所有输入 - document.getElementById("bell-password").value = ""; - document.getElementById("bell-password-range").value = ""; - document.getElementById("bell-password-status").value = ""; - document.getElementById("bell-error").textContent = ""; - document.getElementById("bell-error-range").textContent = ""; - document.getElementById("bell-error-status").textContent = ""; - document.getElementById("bell-progress").textContent = ""; - - // 更新状态计数 - updateStatusCounts(); - - // 重置范围相关 - selectedLocation = null; - document.getElementById("range-point-text").textContent = "--"; - document.getElementById("range-hint").classList.remove("active"); - document.getElementById("range-hint").innerHTML = ` - - - - - 点击地图选择地点,或使用当前位置 - `; - - // 更新筛选信息 - updateFilterInfo(); - - document.getElementById("bell-password").focus(); - } - - // 切换选项卡 - function switchBellTab(tab) { - currentBellTab = tab; - - // 更新选项卡样式 - document.querySelectorAll('.bell-tab').forEach(t => { - t.classList.toggle('active', t.dataset.tab === tab); - }); - - // 更新内容区 - document.querySelectorAll('.bell-section').forEach(s => { - s.classList.toggle('active', s.id === `bell-section-${tab}`); - }); - - // 切换到范围模式时清除之前的选择 - if (tab !== 'range') { - if (rangeCircleOverlay) { - map.removeOverlay(rangeCircleOverlay); - rangeCircleOverlay = null; - } - } - } - - // 选择半径 - function selectRadius(radius) { - selectedRadius = radius; - document.querySelectorAll('.radius-btn').forEach(btn => { - btn.classList.toggle('active', parseInt(btn.dataset.radius) === radius); - }); - // 更新范围圆 - updateRangeCircle(); - updateFilterInfo(); - } - - // 使用当前位置 - function useCurrentLocation() { - if (!autoLocationMarker) { - showToast("请先开启定位(点击底部定位按钮)"); - return; - } - - const point = autoLocationMarker.getPosition(); - const lat = point.lat; - const lng = point.lng; - - selectedLocation = { lat, lng }; - - document.getElementById("range-point-text").textContent = `${lat.toFixed(5)}, ${lng.toFixed(5)}`; - document.getElementById("range-hint").classList.add("active"); - document.getElementById("range-hint").innerHTML = ` - - - - 已选择:${lat.toFixed(5)}, ${lng.toFixed(5)} - `; - - updateRangeCircle(); - updateFilterInfo(); - - showToast(`已选择地点,范围内 ${getFilteredBikes().length} 辆车`); - } - - // 使用地图中心 - function useCenterLocation() { - const center = map.getCenter(); - const lat = center.lat; - const lng = center.lng; - - selectedLocation = { lat, lng }; - - document.getElementById("range-point-text").textContent = `${lat.toFixed(5)}, ${lng.toFixed(5)}`; - document.getElementById("range-hint").classList.add("active"); - document.getElementById("range-hint").innerHTML = ` - - - - 已选择:${lat.toFixed(5)}, ${lng.toFixed(5)} - `; - - updateRangeCircle(); - updateFilterInfo(); - - showToast(`已选择地点,范围内 ${getFilteredBikes().length} 辆车`); - } - - // 更新范围圆覆盖物 - function updateRangeCircle() { - if (!selectedLocation) return; - - // 清除旧的 - if (rangeCircleOverlay) { - map.removeOverlay(rangeCircleOverlay); - } - - const point = new BMapGL.Point(selectedLocation.lng, selectedLocation.lat); - rangeCircleOverlay = new BMapGL.Circle(point, selectedRadius, { - strokeColor: "#007AFF", - strokeWeight: 2, - strokeOpacity: 0.6, - fillColor: "#007AFF", - fillOpacity: 0.1 - }); - map.addOverlay(rangeCircleOverlay); - } - - // 切换状态筛选 - function toggleStatusFilter(state) { - selectedStatuses[state] = !selectedStatuses[state]; - - const item = document.querySelector(`.bell-status-item[data-state="${state}"]`); - if (item) { - item.classList.toggle('selected', selectedStatuses[state]); - item.querySelector('.bell-status-check').textContent = selectedStatuses[state] ? '✓' : ''; - } - - updateFilterInfo(); - } - - // 更新状态计数 - function updateStatusCounts() { - const bikes = Object.values(markersData); - const counts = {available: 0, used: 0, locked: 0, low: 0, reserved: 0}; - - bikes.forEach(bike => { - const state = getBikeState(bike); - if (state === 'available') counts.available++; - else if (state === 'inuse') counts.used++; - else if (state === 'locked') counts.locked++; - else if (state === 'lowbattery') counts.low++; - else if (state === 'reserved') counts.reserved++; - }); - - document.getElementById('count-available-filter').textContent = counts.available; - document.getElementById('count-used-filter').textContent = counts.used; - document.getElementById('count-locked-filter').textContent = counts.locked; - document.getElementById('count-low-filter').textContent = counts.low; - document.getElementById('count-reserved-filter').textContent = counts.reserved; - } - - // 计算两点之间的距离(米) - function calcDistance(lat1, lng1, lat2, lng2) { - const R = 6371000; // 地球半径(米) - const dLat = (lat2 - lat1) * Math.PI / 180; - const dLng = (lng2 - lng1) * Math.PI / 180; - const a = Math.sin(dLat/2) * Math.sin(dLat/2) + - Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * - Math.sin(dLng/2) * Math.sin(dLng/2); - const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); - return R * c; - } - - // 根据当前模式筛选车辆 - function getFilteredBikes() { - const allBikes = Object.values(markersData); - - if (currentBellTab === 'all') { - return allBikes; - } - - if (currentBellTab === 'range') { - if (!selectedLocation) { - return []; // 没有选择地点 - } - return allBikes.filter(bike => { - if (!bike.latitude || !bike.longitude) return false; - // 车辆在地图上显示的位置(偏移后) - const c = offsetCoord(bike.latitude, bike.longitude); - const dist = calcDistance( - selectedLocation.lat, selectedLocation.lng, - c.lat, c.lng - ); - return dist <= selectedRadius; - }); - } - - if (currentBellTab === 'status') { - return allBikes.filter(bike => { - const state = getBikeState(bike); - if (state === 'available' && selectedStatuses.available) return true; - if (state === 'inuse' && selectedStatuses.used) return true; - if (state === 'locked' && selectedStatuses.locked) return true; - if (state === 'lowbattery' && selectedStatuses.low) return true; - if (state === 'reserved' && selectedStatuses.reserved) return true; - return false; - }); - } - - return allBikes; - } - - // 更新筛选信息显示 - function updateFilterInfo() { - const bikes = getFilteredBikes(); - - if (currentBellTab === 'range') { - const infoEl = document.getElementById('range-filter-info'); - if (selectedLocation) { - infoEl.textContent = `范围内车辆:${bikes.length} 辆`; - } else { - infoEl.textContent = ''; - } - } - - if (currentBellTab === 'status') { - const infoEl = document.getElementById('status-filter-info'); - const selectedCount = Object.values(selectedStatuses).filter(v => v).length; - infoEl.textContent = `已选 ${selectedCount} 种状态,共 ${bikes.length} 辆车`; - } - } - - function closeBellModal() { - document.getElementById("bell-modal").classList.remove("show"); - } - - async function submitBellPassword() { - // 根据当前选项卡获取密码和错误元素 - let pwd, errEl; - if (currentBellTab === 'all') { - pwd = document.getElementById("bell-password").value; - errEl = document.getElementById("bell-error"); - } else if (currentBellTab === 'range') { - pwd = document.getElementById("bell-password-range").value; - errEl = document.getElementById("bell-error-range"); - if (!selectedLocation) { - errEl.textContent = "请先选择地点(点击地图或使用当前位置/地图中心)"; - return; - } - } else { - pwd = document.getElementById("bell-password-status").value; - errEl = document.getElementById("bell-error-status"); - } - - if (pwd !== "070517") { - errEl.textContent = "密码错误"; - return; - } - - // 根据模式筛选车辆 - const bikes = getFilteredBikes(); - - if (bikes.length === 0) { - if (currentBellTab === 'range') { - errEl.textContent = "范围内没有车辆,请调整半径或选择其他地点"; - } else if (currentBellTab === 'status') { - errEl.textContent = "没有符合条件的车,请调整状态筛选"; - } else { - errEl.textContent = "暂无车辆数据,请先刷新地图"; - } - return; - } - - errEl.textContent = "启动中..."; - - try { - const res = await fetch("/api/ring_all", { - method: "POST", - headers: { - "Content-Type": "application/json", - "Authorization": `Bearer ${authToken}` - }, - body: JSON.stringify({ codes: bikes.map(b => b.code) }) - }); - const data = await res.json(); - if (data.rtn_code === 401) { - errEl.textContent = "登录已失效,请重新登录"; - showLoginGate(); - return; - } - if (data.rtn_code !== 0) { - errEl.textContent = data.message || "启动失败"; - return; - } - - closeBellModal(); - - // 清除范围圆 - if (rangeCircleOverlay) { - map.removeOverlay(rangeCircleOverlay); - rangeCircleOverlay = null; - } - - // 打开新窗口显示进度 - const progressWin = window.open( - `/ring_progress.html?task_id=${data.task_id}&total=${data.total}`, - "ring_progress", - "width=450,height=520,menubar=no,toolbar=no,location=no,status=no" - ); - if (!progressWin) { - showToast("请允许弹出窗口以查看进度"); - } - } catch (e) { - errEl.textContent = "请求失败: " + friendlyError(e); - } - } - - // ========== 全屏登录门 ========== - function showLoginGate() { - document.getElementById("login-gate").classList.add("show"); - } - function hideLoginGate() { - document.getElementById("login-gate").classList.remove("show"); - } - - async function doLogin(email, password, tip, submitBtn) { - const btnText = submitBtn.textContent; - tip.textContent = ""; - submitBtn.disabled = true; - submitBtn.textContent = "登录中..."; - try { - const resp = await fetch("/api/auth/login", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ email, password, device_id: getDeviceId(), device_name: getDeviceName() }) - }); - const data = await resp.json(); - - if (data.rtn_code === 0) { - authToken = data.data.token; - localStorage.setItem("auth_token", authToken); - currentUser = { email: data.data.email }; - authKickToastShown = false; - updateAuthButton(); - hideLoginGate(); - closeLoginModal(); - showToast("登录成功"); - shareAfterLogin(); - checkOrderStatus(); - checkRentalStatus(); - refreshAuthExpiry(); // 登录态有效期不足 2 天时挂顶部提醒 - if (map) loadMapData(currentType, false); - } else { - tip.textContent = data.message || "登录失败"; - } - } catch (err) { - tip.textContent = "网络错误,请重试"; - } finally { - submitBtn.disabled = false; - submitBtn.textContent = btnText; - } - } - - async function handleLoginSubmit(e) { - e.preventDefault(); - doLogin( - document.getElementById("login-email").value.trim().toLowerCase(), - document.getElementById("login-password").value, - document.getElementById("login-tip"), - e.target.querySelector("button[type='submit']") - ); - } - - document.getElementById("gate-login-form").addEventListener("submit", function (e) { - e.preventDefault(); - doLogin( - document.getElementById("gate-email").value.trim().toLowerCase(), - document.getElementById("gate-password").value, - document.getElementById("gate-tip"), - this.querySelector("button[type='submit']") - ); - }); - - let registerCodeCountdown = 0; - let registerCodeTimer = null; - function setRegisterCodeBtn(text, disabled) { - const btn = document.getElementById("register-code-btn"); - if (!btn) return; - btn.disabled = disabled; - btn.textContent = text; - } - async function sendRegisterCode() { - const email = document.getElementById("register-email").value.trim().toLowerCase(); - const tip = document.getElementById("register-tip"); - if (!email) { tip.textContent = "请先填写邮箱"; return; } - if (registerCodeCountdown > 0) return; - setRegisterCodeBtn("发送中...", true); - try { - const resp = await fetch("/api/auth/send_code", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ email }) - }); - const data = await resp.json(); - tip.textContent = data.message || ""; - if (data.rtn_code === 0) { - registerCodeCountdown = 60; - setRegisterCodeBtn(`${registerCodeCountdown}s`, true); - registerCodeTimer = setInterval(() => { - registerCodeCountdown--; - if (registerCodeCountdown <= 0) { - clearInterval(registerCodeTimer); - setRegisterCodeBtn("发送验证码", false); - } else { - setRegisterCodeBtn(`${registerCodeCountdown}s`, true); - } - }, 1000); - } else { - setRegisterCodeBtn("发送验证码", false); - } - } catch (err) { - tip.textContent = "网络错误,请重试"; - setRegisterCodeBtn("发送验证码", false); - } - } - - async function handleRegisterSubmit(e) { - e.preventDefault(); - const email = document.getElementById("register-email").value.trim().toLowerCase(); - const password = document.getElementById("register-password").value; - const code = document.getElementById("register-code").value.trim(); - const invite_code = document.getElementById("register-invite").value.trim(); - const token_id = document.getElementById("register-token-id").value.trim(); - const access_token = document.getElementById("register-token").value.trim(); - const tip = document.getElementById("register-tip"); - const submitBtn = e.target.querySelector("button[type='submit']"); - - tip.textContent = ""; - submitBtn.disabled = true; - submitBtn.textContent = "注册中..."; - - // 凭据字段的基础格式检查;上游有效性由 /api/auth/register 在服务端权威校验 - // (注册时还没有登录态,verify_token 接口需要 Authorization,前端预检必然 401) - if (access_token || token_id) { - if (!token_id) { - tip.textContent = "Token ID 必填;AccessToken 选填"; - submitBtn.disabled = false; - submitBtn.textContent = "注册"; - return; - } - } - - try { - const resp = await fetch("/api/auth/register", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - email, - password, - code, - invite_code, - token_id: token_id || "", - access_token, - device_id: getDeviceId(), - device_name: getDeviceName() - }) - }); - const data = await resp.json(); - - if (data.rtn_code === 0) { - authToken = data.data.token; - localStorage.setItem("auth_token", authToken); - currentUser = { email: data.data.email }; - authKickToastShown = false; - updateAuthButton(); - closeRegisterModal(); - hideLoginGate(); - showToast("注册成功"); - shareAfterLogin(); - refreshAuthExpiry(); // 注册时可能已填凭证,立即评估有效期 - if (map) loadMapData(currentType, false); - } else { - tip.textContent = data.message || "注册失败"; - } - } catch (err) { - tip.textContent = "网络错误,请重试"; - } finally { - submitBtn.disabled = false; - submitBtn.textContent = "注册"; - } - } - - async function handleLogout() { - clearTimeout(mapRefreshTimer); - if (authToken) { - try { - await fetch("/api/auth/logout", { - method: "POST", - headers: { "Authorization": `Bearer ${authToken}` } - }); - } catch (err) {} - } - authToken = null; - currentUser = null; - localStorage.removeItem("auth_token"); - authKickToastShown = false; - _savedTokenExpiry = null; - renderAuthExpiryBanner(); // 登出后隐藏登录态到期提醒 - updateAuthButton(); - closeProfileModal(); - showToast("已登出"); - showLoginGate(); - const sb = document.getElementById("share-banners"); - if (sb) sb.innerHTML = ""; - shareAskQueue = []; - shareAskActive = false; - const askModal = document.getElementById("share-ask-modal"); - if (askModal) askModal.classList.remove("show"); - } - - function updateAuthButton() { - const btn = document.getElementById("auth-btn"); - const btnText = document.getElementById("auth-btn-text"); - const avatar = document.getElementById("auth-avatar"); - - if (currentUser) { - btn.classList.add("logged-in"); - btnText.style.display = "none"; - avatar.style.display = "flex"; - avatar.textContent = currentUser.email.charAt(0).toUpperCase(); - } else { - btn.classList.remove("logged-in"); - btnText.style.display = "inline"; - avatar.style.display = "none"; - btnText.textContent = "登录"; - } - updateBellBtnVisibility(); - } - - // ========== 批量寻铃入口权限 ========== - // 仅指定用户可见/可用;服务端 /api/ring_all 同步校验 - const BATCH_RING_ALLOWED_EMAILS = ["3146527494@qq.com"]; - function canUseBatchRing() { - return !!(currentUser && BATCH_RING_ALLOWED_EMAILS.includes((currentUser.email || "").toLowerCase())); - } - function updateBellBtnVisibility() { - const btn = document.getElementById("bell-btn"); - if (btn) btn.style.display = canUseBatchRing() ? "flex" : "none"; - } - - async function checkAuthStatus() { - if (!authToken) return; - - try { - const resp = await fetch("/api/auth/status", { - headers: { "Authorization": `Bearer ${authToken}` } - }); - const data = await resp.json(); - - if (data.rtn_code === 0 && data.data.logged_in) { - currentUser = { email: data.data.email }; - updateAuthButton(); - } else { - // token无效(可能被本设备或其他设备下线),清除登录状态 - const hadToken = !!authToken; - authToken = null; - currentUser = null; - localStorage.removeItem("auth_token"); - updateAuthButton(); - if (hadToken && !authKickToastShown) { - authKickToastShown = true; - showToast("登录状态已失效,请重新登录"); - showLoginGate(); - } - } - } catch (err) { - console.error("检查登录状态失败:", err); - } - } - - // ========== 订单状态检测 ========== - let currentOrder = null; // 当前订单信息 - - async function checkOrderStatus() { - if (!authToken) { - hideOrderBanner(); - return; - } - - try { - const resp = await fetch("/api/order/status", { - headers: { "Authorization": `Bearer ${authToken}` } - }); - const data = await resp.json(); - - if (data.rtn_code === 0) { - if (!data.has_credentials) { - // 用户没有配置凭据 - hideOrderBanner(); - return; - } - - if (data.has_order && data.order) { - currentOrder = data.order; - // 仅当“当前微信订单本身就是我共享出去的这笔订单”时隐藏普通横幅。 - // 骑行者自己账号另有待支付/进行中订单时,必须与借用中的共享横幅同时保留。 - if (data.order.shared) { - hideOrderBanner(); - } else { - showOrderBanner(data.order); - } - } else { - currentOrder = null; - hideOrderBanner(); - } - } else if (data.rtn_code === 102001 || data.token_invalid) { - // token_id 已失效(小程序重新登录会踢掉旧会话):弹窗引导重新配置(带冷却,避免每20秒轮询骚扰) - notifyCredentialInvalid(data.message); - } - } catch (err) { - console.error("检查订单状态失败:", err); - } - } - - function showOrderBanner(order) { - const banner = document.getElementById("order-banner"); - const icon = document.getElementById("order-banner-icon"); - const text = document.getElementById("order-banner-text"); - const btn = document.getElementById("order-banner-btn"); - - banner.classList.remove("warning", "riding"); - - if (Number(order.status) === 1) { - // 待支付 - banner.classList.add("warning"); - icon.innerHTML = ''; - text.textContent = `待支付订单 #${order.code || order.order_id.slice(-6)}`; - btn.textContent = "去支付"; - hideOrderCountdown(); - const progress = document.getElementById("order-final-time"); - progress.textContent = "待支付 · 骑行已结束"; - progress.style.display = "inline"; - } else if (Number(order.status) === 2) { - // 进行中 - 获取倒计时 - banner.classList.add("riding"); - icon.innerHTML = ''; - if (order.shared) { - const sName = partnerLabel(order.shared.rider_name, order.shared.rider_email, order.shared.remark); - text.textContent = ("共享中 #" + (order.code || order.order_id.slice(-6)) + " · " + sName + "使用中"); -} else { - text.textContent = `进行中 #${order.code || order.order_id.slice(-6)}`; - } - btn.textContent = "还车"; - if (String(orderCountdownOrderId) !== String(order.order_id)) { - hideOrderCountdown(); - const progress = document.getElementById("order-final-time"); - progress.textContent = "骑行中 · 正在同步计时"; - progress.style.display = "inline"; - } - // 从后端获取剩余时间并启动倒计时 - fetchOrderCountdown(order.order_id); - } - - banner.classList.add("show"); - } - - let orderCountdownTimer = null; - let orderCountdownSeconds = 0; - let orderCountdownDeadline = null; - let orderCountdownOrderId = null; - - function rideProgressText(summary) { - const current = Math.max(1, Number(summary.current_round) || 1); - const total = Math.max(current, Number(summary.total_rounds) || current); - const end = String(summary.final_end_time || summary.end_time || "").match(/(?:T|\s)(\d{2}:\d{2})/); - const phase = summary.auto_return ? "自动还车已开启" : "手动还车"; - return `第 ${current}/${total} 轮 · ${phase}` + (end ? ` · 预计 ${end[1]} 结束` : ""); - } - - function remainingTimeText(seconds) { - const remaining = Math.max(0, Math.ceil(Number(seconds) || 0)); - return `${Math.floor(remaining / 60)}:${String(remaining % 60).padStart(2, "0")}`; - } - - function fetchOrderCountdown(orderId) { - if (!authToken || !orderId) return; - - fetch(`/api/rental/status?order_id=${encodeURIComponent(orderId)}`, { - headers: { "Authorization": `Bearer ${authToken}` } - }) - .then(r => r.json()) - .then(data => { - if (!currentOrder || String(currentOrder.order_id) !== String(orderId) || Number(currentOrder.status) !== 2) return; - if (data.rtn_code === 0 && data.data && data.data.active) { - orderCountdownSeconds = Math.max(0, Number(data.data.remaining_seconds) || 0); - orderCountdownDeadline = performance.now() + orderCountdownSeconds * 1000; - orderCountdownOrderId = orderId; - // 多轮适配:展示计划总轮数与最终预计还车时间 - const finalEl = document.getElementById("order-final-time"); - const addBtn = document.getElementById("order-banner-add-round-btn"); - if (finalEl) { - finalEl.textContent = rideProgressText(data.data); - finalEl.style.display = "inline"; - } - if (addBtn) { - // 真实订单才可加轮; reminder 计时不显示 - const eligible = data.data.order_id && String(data.data.source) !== "reminder"; - addBtn.style.display = eligible ? "inline-block" : "none"; - } - showOrderCountdown(); - startOrderCountdown(); - } else if (data.rtn_code === 0) { - hideOrderCountdown(); - const progress = document.getElementById("order-final-time"); - progress.textContent = "骑行中 · 计时同步中"; - progress.style.display = "inline"; - } - }) - .catch(err => console.error("获取倒计时失败:", err)); - } - - function showOrderCountdown() { - const el = document.getElementById("order-countdown"); - el.style.display = "inline"; - updateOrderCountdownText(); - } - - function hideOrderCountdown() { - orderCountdownDeadline = null; - orderCountdownOrderId = null; - document.getElementById("order-banner-add-round-btn").style.display = "none"; - document.getElementById("order-final-time").style.display = "none"; - const el = document.getElementById("order-countdown"); - el.style.display = "none"; - if (orderCountdownTimer) { - clearInterval(orderCountdownTimer); - orderCountdownTimer = null; - } - } - - function updateOrderCountdownText() { - const el = document.getElementById("order-countdown"); - const remaining = Math.max(0, orderCountdownSeconds); - const mins = Math.floor(remaining / 60); - const secs = remaining % 60; - el.textContent = remaining > 0 ? `本轮剩余 ${mins}:${secs.toString().padStart(2, "0")}` : "本轮到期 · 同步状态中"; - - // 变色提示 - if (remaining <= 60) { - el.style.color = "#ff3b30"; - } else if (remaining <= 300) { - el.style.color = "#ffcc00"; - } else { - el.style.color = "white"; - } - } - - function startOrderCountdown() { - if (orderCountdownTimer) clearInterval(orderCountdownTimer); - orderCountdownTimer = setInterval(() => { - orderCountdownSeconds = Math.max(0, Math.ceil((orderCountdownDeadline - performance.now()) / 1000)); - updateOrderCountdownText(); - if (orderCountdownSeconds <= 0) { - clearInterval(orderCountdownTimer); - // 倒计时结束,刷新订单状态 - checkOrderStatus(); - } - }, 1000); - } - - function hideOrderBanner() { - document.getElementById("order-banner").classList.remove("show"); - hideOrderCountdown(); - closeOrderActionsModal(); - } - - function isOrderActionEligible(order) { - if (!order) return false; - const type = String(order.type || "").toLowerCase(); - const source = String(order.source || "").toLowerCase(); - return type !== "reminder" && source !== "reminder"; - } - - function handleOrderBannerSurfaceClick(event) { - // 横幅右侧已有的两个按钮继续走原有行为,不触发全屏面板。 - if (event && event.target && event.target.closest && event.target.closest("button")) return; - if (!isOrderActionEligible(currentOrder)) return; - showOrderActionsModal(); - } - - function showOrderActionsModal() { - if (!isOrderActionEligible(currentOrder)) return; - - const modal = document.getElementById("order-actions-modal"); - const meta = document.getElementById("order-actions-meta"); - const status = document.getElementById("order-actions-status"); - const hint = document.getElementById("order-actions-hint"); - const code = currentOrder.code || currentOrder.order_id || "未知"; - const pending = Number(currentOrder.status) === 1; - - meta.textContent = `车辆 #${code}`; - status.textContent = pending ? "待支付订单" : "订单进行中"; - status.classList.toggle("warning", pending); - status.classList.toggle("riding", !pending); - hint.textContent = pending - ? "当前订单尚未支付,请先完成支付后再使用车辆操作。" - : "临时锁车不会结束订单,确认车辆停放安全后再操作。"; - - // 待支付订单明确不展示临时锁车/临时开车。 - ["order-action-lock", "order-action-unlock"].forEach(id => { - const button = document.getElementById(id); - if (button) button.style.display = pending ? "none" : "flex"; - }); - const pay = document.getElementById("order-action-pay"); - const ret = document.getElementById("order-action-return"); - if (pay) pay.style.display = pending ? "flex" : "none"; - if (ret) ret.style.display = pending ? "none" : "flex"; - - modal.classList.add("show"); - modal.setAttribute("aria-hidden", "false"); - document.body.classList.add("order-actions-open"); - window.setTimeout(() => document.getElementById("order-actions-close")?.focus(), 0); - } - - function closeOrderActionsModal() { - const modal = document.getElementById("order-actions-modal"); - if (!modal) return; - modal.classList.remove("show"); - modal.setAttribute("aria-hidden", "true"); - document.body.classList.remove("order-actions-open"); - } - - function viewBikeDetailFromOrderModal() { - closeOrderActionsModal(); - viewBikeDetailFromOrder(); - } - - async function findCurrentOrderBike() { - if (!isOrderActionEligible(currentOrder)) return; - const code = (currentOrder.code || "").toString().trim(); - if (!code) { - showToast("该订单没有车牌信息"); - return; - } - - const button = document.getElementById("order-action-find"); - if (button) { - button.disabled = true; - button.querySelector("strong").textContent = "发送中..."; - } - - try { - const data = await _doFindBikeRequest(code); - if (data && (data.rtn_code === 0 || data.success)) { - showToast("寻车指令已发送,请听声音"); - } else { - showToast((data && data.message) || "寻车失败"); - } - } catch (err) { - console.error("订单寻车失败:", err); - showToast("寻车失败,请重试"); - } finally { - if (button) { - button.disabled = false; - button.querySelector("strong").textContent = "寻车"; - } - } - } - - function payCurrentOrderFromModal() { - closeOrderActionsModal(); - tryCardPayOrRedirect(); - } - - function returnCurrentOrderFromModal() { - closeOrderActionsModal(); - showReturnConfirm(); - } - - function handleOrderBannerClick() { - if (!currentOrder) { - showToast("订单状态已变化,正在刷新,请稍后重试"); - checkOrderStatus(); - return; - } - - if (Number(currentOrder.status) === 1) { - // 待支付 - 先检查是否有月卡/周卡 - tryCardPayOrRedirect(); - } else if (Number(currentOrder.status) === 2) { - // 进行中 - 显示还车确认弹窗 - showReturnConfirm(); - } else { - showToast("订单状态已变化,正在刷新,请稍后重试"); - checkOrderStatus(); - } - } - - // 查看详情:等同在搜索框输入当前订单车牌并点击查询,直接弹出车辆详情 - function viewBikeDetailFromOrder() { - if (!currentOrder) { showToast("当前没有进行中的订单"); return; } - const code = (currentOrder.code || "").toString().trim(); - if (!code) { showToast("该订单没有车牌信息"); return; } - document.getElementById("scan-input").value = code; - scanCode(); - } - - document.addEventListener("keydown", event => { - if (event.key !== "Escape") return; - // 确认弹窗优先响应 ESC(原生壳没有系统对话框,全靠页面内弹窗) - const _cm = document.getElementById("app-confirm-modal"); - if (_cm && _cm.classList.contains("show")) { appConfirmClose(); return; } - const _arm = document.getElementById("add-round-modal"); - if (_arm && _arm.classList.contains("show")) { closeAddRoundModal(); return; } - const _oam = document.getElementById("order-actions-modal"); - if (_oam && _oam.classList.contains("show")) { closeOrderActionsModal(); return; } - }); - - // ========== 月卡/周卡自动支付 ========== - let cardPayLoading = false; - - async function tryCardPayOrRedirect() { - if (cardPayLoading || !currentOrder) return; - - const btn = document.getElementById("order-banner-btn"); - cardPayLoading = true; - btn.textContent = "检测中…"; - btn.disabled = true; - - try { - // 1. 查询可用支付方式 - const methodsResp = await fetch( - `/api/order/pay_methods?code=${encodeURIComponent(currentOrder.code || "")}`, - { headers: { "Authorization": `Bearer ${authToken}` } } - ); - const methodsData = await methodsResp.json(); - - if (methodsData.rtn_code !== 0) { - // 接口失败,降级提示跳转 - showToast("请到小白超人小程序支付订单"); - return; - } - - const cardMethods = methodsData.data?.card_methods || []; - - if (cardMethods.length === 0) { - // 没有月卡/周卡 → 原来逻辑 - showToast("未找到月卡,请到小白超人小程序支付"); - return; - } - - // 2. 优先选 get_type=2(推荐/激活)的卡,否则取第一个 - const preferred = cardMethods.find(m => m.get_type === 2) || cardMethods[0]; - const cardTypeName = preferred.type === "3" || preferred.type === 3 ? "月卡" : "周卡"; - - // 3. 更新按钮状态 - btn.textContent = `${cardTypeName}支付中…`; - - // 4. 调用月卡支付接口 - const payResp = await fetch("/api/order/pay_with_card", { - method: "POST", - headers: { - "Authorization": `Bearer ${authToken}`, - "Content-Type": "application/json" - }, - body: JSON.stringify({ - order_id: currentOrder.order_id, - code: currentOrder.code || "", - type: String(preferred.type), - package_id: String(preferred.package_id) - }) - }); - const payData = await payResp.json(); - - if (payData.rtn_code === 0 && payData.data?.paid) { - // 月卡支付成功 - showToast(`${cardTypeName}支付成功 ✓`); - currentOrder = null; - hideOrderBanner(); - refreshMap(); - } else if (payData.rtn_code === 0 && payData.data?.need_wechat_pay) { - // 月卡不足,需要微信支付 - showToast("月卡余额不足,请到小白超人小程序完成支付"); - } else { - showToast(payData.message || "支付失败,请到小白超人小程序支付"); - } - - } catch (err) { - console.error("月卡支付失败:", err); - showToast("请到小白超人小程序支付订单"); - } finally { - cardPayLoading = false; - btn.textContent = "去支付"; - btn.disabled = false; - } - } - - // ========== 还车确认 ========== - let returnLoading = false; - let pendingReturnOrder = null; - - async function getOrderOperationLocation() { - let position = null; - if (navigator.geolocation) { - position = await new Promise(resolve => { - navigator.geolocation.getCurrentPosition( - pos => resolve(pos), - err => { - console.error("获取位置失败:", err); - resolve(null); - }, - { timeout: 5000 } - ); - }); - } - - const latitude = Number.isFinite(position?.coords?.latitude) - ? position.coords.latitude : 36.67; - const longitude = Number.isFinite(position?.coords?.longitude) - ? position.coords.longitude : 116.98; - return { latitude, longitude }; - } - - function showReturnConfirm() { - if (returnLoading) return; - if (!currentOrder || Number(currentOrder.status) !== 2) { - showToast("当前没有可还车的进行中订单,正在刷新"); - checkOrderStatus(); - return; - } - pendingReturnOrder = { ...currentOrder }; - document.getElementById("return-confirm-text").textContent = - `车辆 #${currentOrder.code || currentOrder.order_id} 正在骑行,确认要还车吗?`; - document.getElementById("return-confirm-modal").classList.add("show"); - document.getElementById("return-confirm-btn").disabled = false; - document.getElementById("return-confirm-btn").textContent = "确认还车"; - } - - function closeReturnConfirm() { - document.getElementById("return-confirm-modal").classList.remove("show"); - pendingReturnOrder = null; - } - - async function doReturnBike() { - if (returnLoading) return; - const order = pendingReturnOrder; - if (!order) { - showToast("请重新点击还车并确认订单"); - return; - } - - returnLoading = true; - const btn = document.getElementById("return-confirm-btn"); - btn.disabled = true; - btn.textContent = "还车中..."; - - try { - // 还车和临时锁车共用同一套当前位置获取逻辑。 - const { latitude, longitude } = await getOrderOperationLocation(); - - const resp = await fetch("/api/order/return", { - method: "POST", - headers: { - "Authorization": `Bearer ${authToken}`, - "Content-Type": "application/json" - }, - body: JSON.stringify({ - order_id: order.order_id, - code: order.code, - latitude: latitude, - longitude: longitude - }) - }); - - const data = await resp.json(); - - if (data.rtn_code === 0) { - let msg = data.used_nearest ? "还车成功(已切换至最近停车点)" : "还车成功"; - // 显示月卡支付结果 - if (data.card_pay) { - msg += data.card_pay.success ? `,${data.card_pay.message}` : `,${data.card_pay.message}`; - } - showToast(msg); - closeReturnConfirm(); - if (!currentOrder || String(currentOrder.order_id) === String(order.order_id)) { - currentOrder = null; - hideOrderBanner(); - } - // 刷新地图 - refreshMap(); - refreshShareBanners(); - } else { - showToast(data.message || "还车失败"); - } - } catch (err) { - showToast("还车失败,请重试"); - } finally { - returnLoading = false; - btn.disabled = false; - btn.textContent = "确认还车"; - } - } - - let orderTempActionLoading = false; - - async function tempLockCurrentOrder() { - if (orderTempActionLoading || !isOrderActionEligible(currentOrder) || Number(currentOrder.status) !== 2) return; - const button = document.getElementById("order-action-lock"); - orderTempActionLoading = true; - if (button) { - button.disabled = true; - button.querySelector("strong").textContent = "锁车中..."; - } - - try { - const { latitude, longitude } = await getOrderOperationLocation(); - const resp = await fetch("/api/order/temp_lock", { - method: "POST", - headers: { - "Authorization": `Bearer ${authToken}`, - "Content-Type": "application/json" - }, - body: JSON.stringify({ - order_id: currentOrder.order_id, - code: currentOrder.code, - latitude, - longitude - }) - }); - const data = await resp.json(); - if (data.rtn_code === 0) { - showToast(data.used_nearest ? "临时锁车成功(已切换至最近停车点)" : "临时锁车成功"); - const status = document.getElementById("order-actions-status"); - if (status) status.textContent = "车辆已临时锁定,订单仍在进行中"; - } else { - showToast(data.message || "临时锁车失败"); - } - } catch (err) { - console.error("临时锁车失败:", err); - showToast("临时锁车失败,请重试"); - } finally { - orderTempActionLoading = false; - if (button) { - button.disabled = false; - button.querySelector("strong").textContent = "临时锁车"; - } - } - } - - async function tempUnlockCurrentOrder() { - if (orderTempActionLoading || !isOrderActionEligible(currentOrder) || Number(currentOrder.status) !== 2) return; - const button = document.getElementById("order-action-unlock"); - orderTempActionLoading = true; - if (button) { - button.disabled = true; - button.querySelector("strong").textContent = "开车中..."; - } - - try { - const resp = await fetch("/api/order/temp_unlock", { - method: "POST", - headers: { - "Authorization": `Bearer ${authToken}`, - "Content-Type": "application/json" - }, - body: JSON.stringify({ order_id: currentOrder.order_id }) - }); - const data = await resp.json(); - if (data.rtn_code === 0) { - showToast(data.message || "临时开车成功"); - const status = document.getElementById("order-actions-status"); - if (status) status.textContent = "车辆正在解锁,请稍候"; - } else { - showToast(data.message || "临时开车失败"); - } - } catch (err) { - console.error("临时开车失败:", err); - showToast("临时开车失败,请重试"); - } finally { - orderTempActionLoading = false; - if (button) { - button.disabled = false; - button.querySelector("strong").textContent = "临时开车"; - } - } - } - - // ========== 一键开锁 ========== - let unlockPendingCode = null; // 待开锁的车牌 - let unlockPendingPosition = null; // 待开锁的位置 - - function handleQuickUnlock() { - const qrBox = document.getElementById("qrcode-box"); - const code = qrBox.dataset.bikeCode; - - if (!code) { - showToast("无法获取车辆编码"); - return; - } - - if (!currentUser) { - showToast("请先登录"); - return; - } - - // 保存待开锁信息(用车辆自身坐标 + 随机抖动 ±0.0001,不依赖用户真实定位) - const baseLat = parseFloat(selectedBike?.latitude) || 36.67; - const baseLng = parseFloat(selectedBike?.longitude) || 116.98; - const jit = 0.0001; - unlockPendingCode = code; - unlockPendingPosition = { - lat: baseLat + (Math.random() * 2 - 1) * jit, - lng: baseLng + (Math.random() * 2 - 1) * jit - }; - - // 有共享绑定 → 先选开锁账号;否则直接确认 - openUnlockAccountChooser(); - } - - // ===== 开锁账号选择(自己 / 共享者列表) ===== - let unlockChoice = { mode: "own", owner_user_id: null, owner_email: null, owner_display: "" }; - let unlockSrcList = []; - let unlockSrcShowAll = false; - - function openUnlockAccountChooser() { - unlockChoice = { mode: "own", owner_user_id: null, owner_email: null, owner_display: "" }; - unlockSrcShowAll = false; - if (!authToken || !currentUser) { proceedToUnlockConfirm(); return; } - fetch("/api/share/sources", { headers: { "Authorization": "Bearer " + authToken } }) - .then(r => r.json()) - .then(data => { - if (data.rtn_code !== 0 || !data.data) { proceedToUnlockConfirm(); return; } - const d = data.data; - if (!d.has_any) { proceedToUnlockConfirm(); return; } - renderUnlockSrcList(d); - document.getElementById("unlock-src-modal").classList.add("show"); - }) - .catch(() => proceedToUnlockConfirm()); - } - - function renderUnlockSrcList(d) { - const box = document.getElementById("unlock-src-list"); - let html = ""; - html += ''; - const srcs = d.sources || []; - unlockSrcList = srcs.slice(); - if (srcs.length === 0 && d.hidden_count > 0) { - html += ''; - } - srcs.forEach(s => { - const dis = s.can_use ? "" : "unavailable"; - const tagTxt = s.can_use ? ("剩余可用 " + s.remaining_today + " 次") : (s.reasons && s.reasons.length ? s.reasons.join(" / ") : "不可用"); - const label = partnerLabel(s.owner_name, s.owner_email, s.remark); - html += ''; - }); - if (d.hidden_count > 0) { - html += '
还有 ' + d.hidden_count + ' 位共享者今日次数已用完(点击查看)'; - } - box.innerHTML = html; - } - - function loadUnlockSrcShowAll() { - unlockSrcShowAll = true; - fetch("/api/share/sources?show_unavailable=1", { headers: { "Authorization": "Bearer " + authToken } }) - .then(r => r.json()) - .then(data => { if (data.rtn_code === 0) renderUnlockSrcList(data.data); }); - } - - function chooseUnlockSrc(ownerId) { - ownerId = ownerId || 0; - const rec = unlockSrcList.find(x => Number(x.owner_user_id) === Number(ownerId)); - if (ownerId && !rec) { closeUnlockSrc(); return; } - unlockChoice = rec - ? { mode: "shared", owner_user_id: rec.owner_user_id, owner_email: rec.owner_email, - owner_display: partnerLabel(rec.owner_name, rec.owner_email, rec.remark) } - : { mode: "own", owner_user_id: null, owner_email: null, owner_display: "" }; - closeUnlockSrc(); - proceedToUnlockConfirm(); - } - - function closeUnlockSrc() { - document.getElementById("unlock-src-modal").classList.remove("show"); - } - - function proceedToUnlockConfirm() { - if (!unlockPendingCode) return; - const btn = document.getElementById("unlock-confirm-btn"); - btn.disabled = false; - btn.textContent = unlockChoice.mode === "shared" - ? ("确认用 " + (unlockChoice.owner_display || "对方") + " 的共享开锁") - : "确认开锁"; - // 开锁前预览:月卡余量 + 自动续租轮次预估(共享单用车主的卡) - loadUnlockPreview(unlockPendingCode, - unlockChoice.mode === "shared" ? unlockChoice.owner_user_id : null); - document.getElementById("unlock-confirm-modal").classList.add("show"); - } - - function closeUnlockConfirm() { - document.getElementById("unlock-confirm-modal").classList.remove("show"); - unlockPendingCode = null; - unlockPendingPosition = null; - } - - async function doUnlockBike() { - if (!unlockPendingCode || !authToken) { - closeUnlockConfirm(); - return; - } - - const btn = document.getElementById("unlock-confirm-btn"); - btn.disabled = true; - btn.textContent = "开锁中..."; - const isShared = unlockChoice && unlockChoice.mode === "shared"; - - try { - const payload = { - code: unlockPendingCode, - latitude: unlockPendingPosition.lat, - longitude: unlockPendingPosition.lng - }; - if (isShared) payload.owner_user_id = unlockChoice.owner_user_id; - - const resp = await fetch(isShared ? "/api/order/shared_unlock" : "/api/order/unlock", { - method: "POST", - headers: { - "Authorization": `Bearer ${authToken}`, - "Content-Type": "application/json" - }, - body: JSON.stringify(payload) - }); - const data = await resp.json(); - console.log("[开锁] 响应:", data); - - closeUnlockConfirm(); - - if (data.rtn_code === 0) { - showToast(data.message || "开锁成功!"); - closeQrModal(); - - if (isShared) { - // 共享开锁:横幅由后端订单状态驱动,不启动本地计时 - refreshShareBanners(); - checkOrderStatus(); - } else { - // 启动前端计时器;end_time/轮次预估取自后端开锁响应 - const _ud = data.data || {}; - startRentalFromServer(data.order_id, unlockPendingCode, 19, - _ud.end_time, _ud); - // 刷新订单状态 - checkOrderStatus(); - } - } else if (data.need_pay) { - // 未支付订单月卡也付不了 → 提示用户并刷新订单横幅 - showToast(data.message || "存在未支付订单,请先支付"); - checkOrderStatus(); // 刷新横幅显示待支付 - } else { - showToast(data.message || "开锁失败"); - } - } catch (err) { - console.error("[开锁] 请求失败:", err); - showToast("开锁失败,请重试"); - } finally { - btn.disabled = false; - btn.textContent = isShared ? "确认共享开锁" : "确认开锁"; - unlockPendingCode = null; - unlockPendingPosition = null; - unlockChoice = { mode: "own", owner_user_id: null, owner_email: null }; - } - } - - async function quickUnlock(code, latitude, longitude) { - if (!authToken) { - showToast("请先登录"); - return; - } - - try { - const resp = await fetch("/api/order/unlock", { - method: "POST", - headers: { - "Authorization": `Bearer ${authToken}`, - "Content-Type": "application/json" - }, - body: JSON.stringify({ - code: code, - latitude: latitude, - longitude: longitude - }) - }); - const data = await resp.json(); - console.log("[开锁] 响应:", data); // 调试日志 - - if (data.rtn_code === 0) { - showToast(data.message || "开锁成功!"); - closeQrModal(); - - // 启动前端计时器;end_time/轮次预估取自后端开锁响应 - const _qd = data.data || {}; - startRentalFromServer(data.order_id, code, 19, _qd.end_time, _qd); - - // 刷新订单状态 - checkOrderStatus(); - } else { - showToast(data.message || "开锁失败"); - } - } catch (err) { - console.error("[开锁] 请求失败:", err); // 调试日志 - showToast("开锁失败,请重试"); - } - } - - // 从后端计时器启动前端计时器(隐藏横幅,由后端控制邮件通知) - function startRentalFromServer(rentalId, bikeCode, durationMinutes, endTime, summary) { - // 启动本地计时器(不显示横幅,由后端统一管理) - const remaining = durationMinutes * 60; - activeRental = { - rental_id: rentalId, - bike_code: bikeCode, - remaining_seconds: remaining, - source: "unlock", // 网页开锁 → 真实订单,+1轮可用 - end_time: endTime || null, - final_end_time: (summary && summary.final_end_time) || endTime || null, - current_round: (summary && summary.current_round) || 1, - total_rounds: (summary && summary.total_rounds) || null, - auto_return: true - }; - localStorage.setItem(RENTAL_KEY, JSON.stringify(activeRental)); - - // 启动倒计时更新(每秒) - if (rentalCountdownTimer) clearInterval(rentalCountdownTimer); - rentalCountdownTimer = setInterval(() => { - if (activeRental && activeRental.remaining_seconds > 0) { - activeRental.remaining_seconds--; - localStorage.setItem(RENTAL_KEY, JSON.stringify(activeRental)); - - // 到期动作由后端依据订单类型及用户设置执行 - // 这里不需要做任何操作 - } - }, 1000); - } - - // ========== 忘记密码 ========== - // 忘记密码可从两处打开:弹窗登录(login-modal)与全屏登录门(login-gate)。 - // 用 _forgotFromGate 记住入口,重置成功后回到原处,避免用户被"换页面"。 - let _forgotFromGate = false; - function showForgotModal() { - _forgotFromGate = false; - closeAllModals(); - document.getElementById("forgot-modal").classList.add("show"); - } - function showForgotFromGate() { - _forgotFromGate = true; - closeAllModals(); - // 带上登录门里已填的邮箱,省去用户重复输入 - const field = document.getElementById("gate-email"); - const emailInput = document.getElementById("forgot-email"); - if (field && emailInput && field.value.trim() && !emailInput.value.trim()) { - emailInput.value = field.value.trim(); - } - document.getElementById("forgot-modal").classList.add("show"); - } - function closeForgotModal() { - document.getElementById("forgot-modal").classList.remove("show"); - document.getElementById("forgot-tip").textContent = ""; - _forgotFromGate = false; - } - function backToLoginFromForgot() { - const fromGate = _forgotFromGate; - closeForgotModal(); - if (fromGate) showLoginGate(); - else showLoginModal(); - } - let forgotTimer = null; - function setForgotCodeBtn(seconds) { - const btn = document.getElementById("forgot-code-btn"); - if (forgotTimer) { clearInterval(forgotTimer); forgotTimer = null; } - if (seconds > 0) { - btn.disabled = true; - btn.textContent = `${seconds}s 后重发`; - forgotTimer = setInterval(() => { - seconds--; - if (seconds <= 0) { - clearInterval(forgotTimer); forgotTimer = null; - btn.disabled = false; btn.textContent = "发送验证码"; - } else { - btn.textContent = `${seconds}s 后重发`; - } - }, 1000); - } else { - btn.disabled = false; btn.textContent = "发送验证码"; - } - } - async function sendForgotCode() { - const email = document.getElementById("forgot-email").value.trim(); - const tip = document.getElementById("forgot-tip"); - if (!email) { tip.textContent = "请先填写注册邮箱"; return; } - tip.textContent = "发送中..."; - try { - const resp = await fetch("/api/auth/send_code", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ email: email, purpose: "reset" }) - }); - const data = await resp.json(); - tip.textContent = data.message || ""; - if (data.rtn_code === 0) setForgotCodeBtn(60); - } catch (err) { - tip.textContent = "发送失败,请检查网络"; - } - } - async function handleForgotSubmit(event) { - event.preventDefault(); - const email = document.getElementById("forgot-email").value.trim(); - const code = document.getElementById("forgot-code").value.trim(); - const password = document.getElementById("forgot-password").value; - const tip = document.getElementById("forgot-tip"); - if (password.length < 6) { tip.textContent = "新密码至少 6 位"; return; } - tip.textContent = "提交中..."; - try { - const resp = await fetch("/api/auth/reset_password", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ email: email, code: code, password: password }) - }); - const data = await resp.json(); - tip.textContent = data.message || ""; - if (data.rtn_code === 0) { - // 回到用户进来的那个登录界面:登录门 → 回登录门;弹窗 → 回登录弹窗 - const fromGate = _forgotFromGate; - setTimeout(() => { - closeForgotModal(); - if (fromGate) { - showLoginGate(); - const gateEmail = document.getElementById("gate-email"); - const gatePwd = document.getElementById("gate-password"); - if (gateEmail) gateEmail.value = email; - if (gatePwd) { gatePwd.value = ""; gatePwd.focus(); } - } else { - showLoginModal(); - document.getElementById("login-email").value = email; - } - }, 900); - } - } catch (err) { - tip.textContent = "提交失败,请检查网络"; - } - } - - // ========== 订单历史(我的 → 订单历史) ========== - function fmtDuration(seconds) { - if (seconds === null || seconds === undefined) return "--"; - const mins = Math.round(seconds / 60); - if (mins < 60) return `${mins} 分钟`; - return `${Math.floor(mins / 60)} 小时 ${mins % 60} 分钟`; - } - function fmtOrderTime(s) { - if (!s) return "--"; - return String(s).replace("T", " ").slice(5, 16); // MM-DD HH:MM - } - function fmtClock(s) { - if (!s) return "--"; - return String(s).slice(11, 16); // HH:MM - } - function orderCardHtml(o) { - const badge = o.returned - ? '已完成' - : '进行中'; - const sharedRow = o.shared - ? `
${o.role === "owner" ? "共享给" : "使用"} ${escHtml(o.partner || "--")} 的车
` : ""; - // 多轮续租合并显示:共 N 轮 · 总用时 · 起止时钟 - const roundsRow = (o.rounds && o.rounds > 1) - ? `
共 ${o.rounds} 轮 · 总用时 ${fmtDuration(o.duration_seconds)}
` : ""; - const timeRow = `${fmtOrderTime(o.start_time)} ${fmtClock(o.start_time)} → ${fmtOrderTime(o.end_time)} ${fmtClock(o.end_time)}`; - return ` -
-
- #${escHtml(o.bike_code)} - - ${o.duration_seconds !== null ? fmtDuration(o.duration_seconds) : ""} - ${badge} - -
-
-
${timeRow}
-
${escHtml(o.start_label || "起点未知")} → ${escHtml(o.end_label || (o.returned ? "终点未知" : "骑行中"))}
- ${roundsRow} - ${sharedRow} -
-
- -
-
`; - } - // ========== 订单骑行轨迹 ========== - let orderTrajMap = null; - let orderTrajOverlays = []; - async function openOrderTrajectory(rentalId){ - SettingsPages.open("order-traj-modal"); - document.getElementById("order-traj-summary").textContent = "加载轨迹中..."; - document.getElementById("order-traj-hint").textContent = "轨迹来自每 5-10 分钟一次的车辆定位采集。"; - try{ - const resp = await fetch(`/api/user/orders/trajectory?rental_id=${encodeURIComponent(rentalId)}`, { - headers: { "Authorization": `Bearer ${authToken}` } - }); - const data = await resp.json(); - if (data.rtn_code !== 0) { - document.getElementById("order-traj-summary").textContent = data.message || "轨迹加载失败"; - return; - } - renderOrderTrajectory(data.data); - }catch(e){ - document.getElementById("order-traj-summary").textContent = "网络错误,请重试"; - } - } - function closeOrderTrajModal(){ - SettingsPages.back(); - // 保留地图实例,下次复用;只清理覆盖物 - if (orderTrajMap) { - try { orderTrajMap.clearOverlays(); } catch(e) {} - } - orderTrajOverlays = []; - } - function renderOrderTrajectory(t){ - const pts = t.points || []; - // textContent 不解析 HTML,这里不能用 escHtml(会把 & 显示成 &) - document.getElementById("order-traj-summary").textContent = - `#${t.bike_code} · ${fmtOrderTime(t.start_time)} → ${fmtOrderTime(t.end_time)} · ` + - `${t.start_label || "起点未知"} → ${t.end_label || (t.returned ? "终点未知" : "骑行中")}`; - - const initMap = () => { - if (!orderTrajMap) { - orderTrajMap = new BMapGL.Map("order-traj-map"); - orderTrajMap.enableScrollWheelZoom(true); - } - const overlayPts = []; - try { orderTrajMap.clearOverlays(); } catch(e) {} - const toBd = (lat, lng) => offsetCoord(lat, lng); - - // 轨迹线(GCJ02 → BD09 逐点转换) - const linePts = pts.map(p => { - const c = toBd(p.lat, p.lng); - return new BMapGL.Point(c.lng, c.lat); - }); - // 采集缺失时用订单起终点兜底成两点直线 - if (linePts.length < 2 && (t.start_point || t.end_point)) { - const s = t.start_point, e = t.end_point || t.start_point; - const cs = toBd(s.lat, s.lng), ce = toBd(e.lat, e.lng); - linePts.push(new BMapGL.Point(cs.lng, cs.lat), new BMapGL.Point(ce.lng, ce.lat)); - } - if (linePts.length >= 2) { - const poly = new BMapGL.Polyline(linePts, { - strokeColor: "#0a84ff", strokeWeight: 5, strokeOpacity: 0.85, - }); - orderTrajMap.addOverlay(poly); - overlayPts.push(...linePts); - } - // 起终点标记 - const mark = (pt, color, text) => { - if (!pt) return; - const c = toBd(pt.lat, pt.lng); - const p = new BMapGL.Point(c.lng, c.lat); - const canvas = document.createElement("canvas"); - canvas.width = canvas.height = 26; - const ctx = canvas.getContext("2d"); - ctx.beginPath(); ctx.arc(13, 13, 10, 0, Math.PI * 2); - ctx.fillStyle = color; ctx.fill(); - ctx.fillStyle = "#fff"; ctx.font = "bold 12px Arial"; - ctx.textAlign = "center"; ctx.textBaseline = "middle"; - ctx.fillText(text, 13, 13); - const marker = new BMapGL.Marker(p, { - icon: new BMapGL.Icon(canvas.toDataURL(), new BMapGL.Size(26, 26), new BMapGL.Size(13, 13)) - }); - orderTrajMap.addOverlay(marker); - overlayPts.push(p); - }; - mark(t.start_point, "#34c759", "起"); - mark(t.end_point, "#ff3b30", "终"); - - if (overlayPts.length) { - try { - orderTrajMap.setViewport(overlayPts, { margins: [30, 30, 30, 30] }); - } catch (e) { - orderTrajMap.centerAndZoom(overlayPts[0], 18); - } - } else { - fetch("/api/config").then(r => r.json()).then(cfg => { - const c = offsetCoord(cfg.center_lat, cfg.center_lng); - orderTrajMap.centerAndZoom(new BMapGL.Point(c.lng, c.lat), 17); - }); - } - document.getElementById("order-traj-hint").textContent = pts.length - ? `共 ${pts.length} 个定位点` - : "该时间段没有采集到定位点(采集间隔 5-10 分钟),已用订单起终点示意"; - }; - - // 弹窗刚显示,等一帧再初始化,避免容器尺寸为 0 - setTimeout(initMap, 60); - } - async function openOrdersModal() { - closeAllModals(); - SettingsPages.open("orders-modal"); - const box = document.getElementById("orders-list"); - box.innerHTML = '
加载中...
'; - try { - const resp = await fetch("/api/user/orders?limit=50", { - headers: { "Authorization": `Bearer ${authToken}` } - }); - const data = await resp.json(); - if (data.rtn_code !== 0) { - box.innerHTML = `
${escHtml(data.message || "加载失败")}
`; - return; - } - const orders = data.data || []; - document.getElementById("orders-summary").textContent = - orders.length ? `最近 ${orders.length} 条用车记录(含共享)` : "还没有用车记录"; - box.innerHTML = orders.length - ? orders.map(orderCardHtml).join("") - : '
暂无订单
'; - } catch (err) { - box.innerHTML = '
网络错误,请重试
'; - } - } - function closeOrdersModal() { - SettingsPages.back(); - } - - // ========== 订阅提醒(我的 → 车辆订阅) ========== - let subscribeLocations = []; - const SUB_WEEKDAYS = { 0: "每天", 1: "周一", 2: "周二", 3: "周三", 4: "周四", 5: "周五", 6: "周六", 7: "周日" }; - async function openSubscribeModal() { - closeAllModals(); - SettingsPages.open("subscribe-modal"); - await loadSubscribeLocations(); - loadSubscribeRules(); - } - function closeSubscribeModal() { - SettingsPages.back(); - } - async function loadSubscribeLocations() { - const sel = document.getElementById("sub-location"); - sel.innerHTML = ''; - try { - const resp = await fetch("/api/campus/locations"); - const data = await resp.json(); - // 订阅只针对「停车点」(楼/兴趣点只用于起终点归属) - subscribeLocations = ((data.rtn_code === 0 ? data.data : []) || []) - .filter(l => l.kind === "parking"); - } catch (err) { - subscribeLocations = []; - } - sel.innerHTML = subscribeLocations.length - ? subscribeLocations.map(l => ``).join("") - : ''; - } - function subRuleRowHtml(r) { - const loc = subscribeLocations.find(l => l.id === r.location_id); - const locName = loc ? loc.name : (r.location_name || "停车点已删除"); - const hh = String(Math.floor(r.minute_of_day / 60)).padStart(2, "0"); - const mm = String(r.minute_of_day % 60).padStart(2, "0"); - const kindText = (r.kind_labels && r.kind_labels.length) - ? r.kind_labels.join("/") : "全部车型"; - const eMin = r.min_electric != null ? r.min_electric : 0; - const eMax = r.max_electric != null ? r.max_electric : 100; - const sortLabel = r.sort_by_label || r.sort_by || ""; - const tags = []; - if (r.auto_unlock) { - tags.push(`自动开锁 · ${kindText} · 电量${eMin}-${eMax}% · ${sortLabel} · 重试${r.retry_times || 3}次`); - } - return ` -
-
-
- ${escHtml(locName)} - · ${SUB_WEEKDAYS[r.weekday] || "每周"} ${hh}:${mm} -
${r.enabled ? "已启用" : "已停用"}${r.notify_enabled ? " · 邮件提醒" : ""}
- ${tags.length ? `
${escHtml(tags[0])}
` : ""} -
-
- - -
-
-
`; - } - // 订阅表单「更多筛选」折叠开关(高级调优项默认收起) - function toggleSubAdvanced() { - const box = document.getElementById("sub-advanced"); - if (!box) return; - const show = box.style.display === "none"; - box.style.display = show ? "block" : "none"; - } - async function loadSubscribeRules() { - const box = document.getElementById("subscribe-list"); - box.innerHTML = '
加载中...
'; - try { - const resp = await fetch("/api/subscribe/rules", { - headers: { "Authorization": `Bearer ${authToken}` } - }); - const data = await resp.json(); - if (data.rtn_code !== 0) { - box.innerHTML = `
${escHtml(data.message || "加载失败")}
`; - return; - } - const rules = data.data || []; - box.innerHTML = rules.length - ? rules.map(subRuleRowHtml).join("") - : '
暂无规则,在下方添加
'; - } catch (err) { - box.innerHTML = '
网络错误,请重试
'; - } - } - async function addSubscribeRule() { - const locationId = Number(document.getElementById("sub-location").value || 0); - const weekday = Number(document.getElementById("sub-weekday").value); - const time = document.getElementById("sub-time").value; - const notify = document.getElementById("sub-notify").checked; - const auto = document.getElementById("sub-auto").checked; - const kinds = [...document.querySelectorAll(".sub-kind:checked")].map(el => el.value); - const minE = Number(document.getElementById("sub-min-e").value || 0); - const maxE = Number(document.getElementById("sub-max-e").value || 100); - const sortBy = document.getElementById("sub-sort").value; - const retry = Number(document.getElementById("sub-retry").value || 3); - - if (!locationId) { showToast("请先选择停车点(需要管理员先配置停车点)"); return; } - if (!/^\d{2}:\d{2}$/.test(time)) { showToast("请选择时间"); return; } - if (!kinds.length) { showToast("至少选择一个车型"); return; } - if (!(minE >= 0 && maxE <= 100 && minE <= maxE)) { showToast("电量区间需在 0-100 且下限≤上限"); return; } - if (auto) { - const ok = await appConfirm( - "开启自动开锁后,命中规则时系统会用你的账号直接开锁车辆。\n\n" + - `筛选:${kinds.map(k => ({small:"小车",big:"大车",red:"红车"}[k])).join("/")},` + - `电量 ${minE}%-${maxE}%,${document.getElementById("sub-sort").selectedOptions[0].textContent};` + - `被他人抢先时最多重试 ${retry} 次。`, - { title: "开启自动开锁", okText: "确认添加" }); - if (!ok) return; - } - try { - const resp = await fetch("/api/subscribe/rules", { - method: "POST", - headers: { "Authorization": `Bearer ${authToken}`, "Content-Type": "application/json" }, - body: JSON.stringify({ - location_id: locationId, weekday, time, - notify_enabled: notify, auto_unlock: auto, - kinds, min_electric: minE, max_electric: maxE, - sort_by: sortBy, retry_times: retry - }) - }); - const data = await resp.json(); - showToast(data.message || (data.rtn_code === 0 ? "已添加" : "添加失败")); - if (data.rtn_code === 0) loadSubscribeRules(); - } catch (err) { - showToast("网络错误,请重试"); - } - } - async function toggleSubscribeRule(ruleId, enable) { - try { - const resp = await fetch(`/api/subscribe/rules/${ruleId}`, { - method: "PUT", - headers: { "Authorization": `Bearer ${authToken}`, "Content-Type": "application/json" }, - body: JSON.stringify({ enabled: !!enable }) - }); - const data = await resp.json(); - if (data.rtn_code === 0) loadSubscribeRules(); - else showToast(data.message || "操作失败"); - } catch (err) { showToast("网络错误"); } - } - async function deleteSubscribeRule(ruleId) { - try { - const resp = await fetch(`/api/subscribe/rules/${ruleId}`, { - method: "DELETE", - headers: { "Authorization": `Bearer ${authToken}` } - }); - const data = await resp.json(); - if (data.rtn_code === 0) loadSubscribeRules(); - else showToast(data.message || "删除失败"); - } catch (err) { showToast("网络错误"); } - } - - // ========== 开锁前预览(月卡余量 + 轮次预估) ========== - function renderUnlockPreview(p) { - const box = document.getElementById("unlock-preview"); - if (!box) return; - if (!p) { box.style.display = "none"; box.innerHTML = ""; return; } - const lines = []; - lines.push(`
${p.shared ? "共享预览(用车主的卡与轮次)" : "本次用车预览"}
`); - if (p.has_card) { - const cardText = (p.cards || []).slice(0, 3).map(c => - `${escHtml(c.name)}${c.remain === null ? "(不限次)" : ` 剩 ${c.remain} 次`}`).join(","); - lines.push(`
优惠卡:${cardText}${p.card_note ? ` · ${escHtml(p.card_note)}` : ""}
`); - } else { - lines.push(`
未检测到优惠卡:本次费用将按小程序计费(还车后需支付)
`); - } - if (p.auto_return) { - lines.push(`
自动续租:计划 ${p.rounds_planned} 轮 × ${p.duration_minutes} 分钟,预计 ${escHtml(p.est_end_time)} 前还车
`); - } else { - lines.push(`
自动还车未开启:本轮 ${p.duration_minutes} 分钟,请留意到期手动还车
`); - } - box.innerHTML = lines.join(""); - box.style.display = "block"; - } - async function loadUnlockPreview(code, ownerUserId) { - const box = document.getElementById("unlock-preview"); - if (box) { box.style.display = "block"; box.innerHTML = '
预览加载中...
'; } - try { - const q = new URLSearchParams({ code: String(code) }); - if (ownerUserId) q.set("owner_user_id", ownerUserId); - const resp = await fetch(`/api/order/preview?${q.toString()}`, { - headers: { "Authorization": `Bearer ${authToken}` } - }); - const data = await resp.json(); - renderUnlockPreview(data.rtn_code === 0 ? data.data : null); - } catch (err) { - renderUnlockPreview(null); - } - } - - // ========== 手动 +1 轮 ========== - // ========== 手动 +1 轮(带确认弹窗) ========== - // 语义:只把「计划轮数」+1。当前这一轮照常到点 → 自动还车 → 优惠卡支付 - // → 立刻重新开锁同一辆车进入下一轮(绝不延长本轮时长)。 - let _addRoundTarget = null; - function showAddRoundConfirm(target) { - _addRoundTarget = target; - const remainSec = target.kind === "rental" - ? (activeRental && activeRental.remaining_seconds) || orderCountdownSeconds || 0 - : orderCountdownSeconds || 0; - const mins = Math.max(1, Math.round(remainSec / 60)); - const btn = document.getElementById("add-round-confirm-btn"); - if (btn) { btn.disabled = false; btn.textContent = "确认加 1 轮"; } - const text = document.getElementById("add-round-text"); - if (text) { - text.innerHTML = - `当前这一轮还剩约 ${mins} 分钟,不会延长。
` + - `到点后系统会自动:还车 → 用优惠卡支付 → 立刻重新开锁同一辆车,进入下一轮。`; - } - document.getElementById("add-round-modal").classList.add("show"); - } - function closeAddRoundModal() { - document.getElementById("add-round-modal").classList.remove("show"); - _addRoundTarget = null; - } - async function confirmAddRound() { - if (!_addRoundTarget || !authToken) { closeAddRoundModal(); return; } - const btn = document.getElementById("add-round-confirm-btn"); - if (btn) { btn.disabled = true; btn.textContent = "提交中..."; } - const payload = _addRoundTarget.kind === "rental" - ? { rental_id: _addRoundTarget.value } - : { order_id: _addRoundTarget.value }; - try { - const resp = await fetch("/api/order/add_round", { - method: "POST", - headers: { "Authorization": `Bearer ${authToken}`, "Content-Type": "application/json" }, - body: JSON.stringify(payload) - }); - const data = await resp.json(); - if (data.rtn_code === 0) { - showToast(data.message || "已加 1 轮"); - // 本轮剩余不变,只更新计划轮数与预计还车时间 - if (activeRental) { - activeRental.total_rounds = data.data.total_rounds; - activeRental.final_end_time = data.data.final_end_time; - localStorage.setItem(RENTAL_KEY, JSON.stringify(activeRental)); - updateRentalFinalTime(); - } - if (currentOrder && currentOrder.order_id) fetchOrderCountdown(currentOrder.order_id); - checkOrderStatus(); - } else { - showToast(data.message || "加轮失败"); - } - } catch (err) { - showToast("网络错误,请重试"); - } finally { - closeAddRoundModal(); - } - } - function addRoundForCurrent() { - if (!activeRental || !authToken) { showToast("当前没有进行中的订单"); return; } - showAddRoundConfirm({ kind: "rental", value: activeRental.rental_id }); - } - function addRoundFromBanner() { - if (!currentOrder || !currentOrder.order_id) { showToast("当前没有进行中的订单"); return; } - showAddRoundConfirm({ kind: "order", value: currentOrder.order_id }); - } - // 页面加载时检查订单状态和租车状态 - document.addEventListener("DOMContentLoaded", async () => { - if (authToken) { - await syncWechatOrder(); // 先同步微信订单状态 - checkOrderStatus(); - checkRentalStatus(); // 再恢复租车横幅 - checkStrictGuide(); // 强签名验证:缺 AccessToken 进页面立即引导 - refreshAuthExpiry(); // 登录态有效期:不足 2 天在主页面挂提醒横幅 - } - }); - function initMapCore() { // 预加载基础图标(在请求地图数据之前就开始) preloadBaseIcons(); - fetch("/api/config") + apiFetch("/api/config") .then(r => r.json()) .then(cfg => { document.getElementById("school-name").textContent = cfg.school_name || "山东管理学院"; @@ -3123,7 +522,8 @@ loadMapData(currentType); // 启动自动持续定位(地图加载后立即开始) - startAutoLocation(); + if (typeof BikeDiscovery !== "undefined") BikeDiscovery.init(); + if (authToken) startAutoLocation(); }) .catch(err => { console.error("初始化失败:", err); @@ -3133,7 +533,7 @@ // ========== 深色模式适配 ========== function updateMapStyle() { - const isDark = window.matchMedia('(prefers-color-scheme: dark)').matches; + const isDark = UIPreferences.isDark(); if (isDark) { // Only filter the basemap canvas; native DOM overlays retain their colours. const mapEl = document.getElementById("baidu_map"); @@ -3150,7 +550,7 @@ } // 监听系统颜色变化 - window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => { + window.addEventListener('xbniu-theme-change', e => { updateMapStyle(); }); @@ -3160,6 +560,18 @@ let renderedMapSnapshot = null; let mapRefreshFailed = false; + function resetMapForAccount() { + clearTimeout(mapRefreshTimer); + mapRequest = null; renderedMapSnapshot = null; mapRefreshFailed = false; isFirstLoad = true; + markersData = {}; selectedBike = null; highlightedBikeId = null; + if (bikeBubbleLayer) bikeBubbleLayer.setData([]); + ['available','used','locked','reserved','low'].forEach(name => { + const count = document.getElementById('count-' + name); if (count) count.textContent = '0'; + }); + const stamp = document.getElementById('update-time'); if (stamp) stamp.textContent = '--:--'; + if (typeof BikeDiscovery !== 'undefined') BikeDiscovery.render(); + } + function scheduleMapRefresh(snapshot, serverTime, retrySeconds = 5) { clearTimeout(mapRefreshTimer); const expires = Number(snapshot?.expires_at); @@ -3182,7 +594,7 @@ if (isFirstLoad && showLoading) loading.classList.remove("hidden"); const pending = { type: String(type), promise: null }; mapRequest = pending; - pending.promise = fetch(`/api/map?type=${encodeURIComponent(type)}`, { + pending.promise = apiFetch(`/api/map?type=${encodeURIComponent(type)}`, { headers: { "Authorization": `Bearer ${requestToken}` }, cache: "no-store" }) @@ -3327,18 +739,12 @@ // state=10 或 电量<20 优先判低电量,其次欠压/损坏,最后 state=1 分使用中/可用。 // 注意电量字段是 electric_quantity(上游字段名),不存在 bike.electric。 allBikes.forEach(bike => { - const electric = Number(bike.electric_quantity ?? bike.electricQuantity ?? 100); - if (bike.state === 10 || electric < 20) { - lowCount++; - } else if (bike.state === 1 && bike.status === 1) { - usedCount++; - } else if (bike.state === 1) { - availableCount++; - } else if (bike.state === 4) { - lockedCount++; - } else if (bike.state === 2) { - reservedCount++; - } + const state = getBikeState(bike); + if (state === 'available') availableCount++; + else if (state === 'inuse') usedCount++; + else if (state === 'locked') lockedCount++; + else if (state === 'reserved') reservedCount++; + else if (state === 'lowbattery') lowCount++; }); nextBikes.push(...allBikes); @@ -3353,6 +759,7 @@ document.getElementById("count-reserved").textContent = reservedCount; document.getElementById("count-low").textContent = lowCount; rebuildMarkersForZoom(nextBikes); + if (typeof BikeDiscovery !== "undefined") BikeDiscovery.render(); } // Native overlay coordinates keep markers aligned during reverse zooming. @@ -3378,7 +785,7 @@ function rebuildMarkersForZoom(bikes) { setupClusterListener(); - if (bikeBubbleLayer) bikeBubbleLayer.setData(bikes ?? Object.values(markersData)); + if (bikeBubbleLayer) { const rows = bikes ?? Object.values(markersData); bikeBubbleLayer.setData(typeof BikeDiscovery !== "undefined" ? BikeDiscovery.visibleBikes(rows) : rows); } } // ========== 车辆详情 ========== @@ -3416,8 +823,9 @@ kindEl.classList.add("kind-" + kind.key); } - const electric = parseFloat(bike.electric_quantity || bike.electricQuantity || 0); - document.getElementById("card-electric").textContent = Math.round(electric); + const electric = BikeData.electric(bike); + document.getElementById("card-electric").textContent = electric === null ? "未知" : Math.round(electric); + document.getElementById("card-electric").parentElement.classList.toggle("battery-unknown", electric === null); let ringColor = "#34c759"; const bikeState = getBikeState(bike); @@ -3427,7 +835,7 @@ ringColor = "#ff9f0a"; } else if (bikeState === 'reserved') { ringColor = "#5856D6"; - } else if (bikeState === 'lowbattery' || electric < 20) { + } else if (bikeState === 'lowbattery' || bikeState === 'unknown' || electric === null) { ringColor = "#8e8e93"; } try { @@ -3437,23 +845,10 @@ } // 状态文本:结合 state 和 status 判断 - let stateText = "--"; - if (bike.state === 1 && bike.status === 1) { - stateText = "使用中"; - } else if (bike.state === 1) { - stateText = "空闲"; - } else if (bike.state === 10) { - stateText = "低电量"; - } else if (bike.state === 4) { - stateText = "欠压车辆"; - } else if (bike.state === 2) { - stateText = "损坏车辆"; - } else { - stateText = "未知"; - } + const stateText = BikeData.labels[getBikeState(bike)]; document.getElementById("card-state").textContent = stateText; document.getElementById("card-state").className = "bike-status-value" + - (stateText === "使用中" ? " warning" : stateText === "空闲" ? " highlight" : ""); + (stateText === "使用中" ? " warning" : stateText === "可用" ? " highlight" : ""); document.getElementById("bike-card").classList.add("show"); const overlay = document.getElementById("card-overlay"); @@ -3521,10 +916,10 @@ // ========== 扫码查询 ========== function scanCode() { const code = document.getElementById("scan-input").value.trim(); - if (!code) { showToast("请输入车牌号"); return; } + if (!BikeData.validCode(code)) { showToast("请输入5位普通车牌或8位红车车牌,只能包含数字"); document.getElementById("scan-input").focus(); return; } showToast("正在查询..."); - fetch("/api/bicycle", { + apiFetch("/api/bicycle", { method: "POST", headers: { "Content-Type": "application/json", "Authorization": `Bearer ${authToken}` }, body: JSON.stringify({ code }) @@ -3538,11 +933,11 @@ if (data.rtn_code === 0 && data.data) { const bike = data.data; bike.code = code; - + // 优先用 markersData 的实时位置,其次用 API 返回的位置 const mapBike = markersData[codeNum] || markersData[code]; let hasLocation = false; - + if (mapBike && mapBike.latitude && mapBike.longitude) { bike.latitude = mapBike.latitude; bike.longitude = mapBike.longitude; @@ -3552,7 +947,7 @@ } else if (bike.latitude && bike.longitude) { hasLocation = true; } - + if (hasLocation) { const c = offsetCoord(bike.latitude, bike.longitude); map.panTo(new BMapGL.Point(c.lng, c.lat)); @@ -3560,15 +955,15 @@ } else { showToast("该车暂无实时位置,请在地图上查看"); } - + // 如果车辆在使用中,额外提示 if (bike.state === 1 && bike.status === 1) { showToast("该车正在使用中"); } - + markersData[codeNum] = bike; showBikeDetail(codeNum); - } + } // success=false 时,也尝试用 markersData 显示详情和定位 else if (data.success === false) { const mapBike = markersData[codeNum] || markersData[code]; @@ -3608,7 +1003,7 @@ /** 发送单次寻车请求(内部使用,不操作按钮状态) */ function _doFindBikeRequest(code) { - return fetch("/api/find_bike", { + return apiFetch("/api/find_bike", { method: "POST", headers: { "Content-Type": "application/json", @@ -3772,880 +1167,6 @@ btn.addEventListener("touchcancel", cancelLongPress); })(); - // ========== 用车计时相关 ========== - function clearRentalState() { - if (rentalCountdownTimer) { - clearInterval(rentalCountdownTimer); - rentalCountdownTimer = null; - } - activeRental = null; - localStorage.removeItem(RENTAL_KEY); - const bar = document.getElementById("rental-bar"); - if (bar) bar.classList.remove("show"); - } - - async function openRentalSettingsModal() { - closeAllModals(); - SettingsPages.open("rental-settings-modal"); - try { - const resp = await fetch("/api/auth/rental_settings", { - headers: { "Authorization": `Bearer ${authToken}` } - }); - const result = await resp.json(); - if (result.rtn_code !== 0) throw new Error(result.message || "加载失败"); - const settings = result.data; - document.getElementById("rs-reminder-enabled").checked = !!settings.reminder_enabled; - document.getElementById("rs-duration").value = settings.rental_duration_minutes || 19; - document.getElementById("rs-auto-return").checked = !!settings.auto_return_enabled; - document.getElementById("rs-rounds").value = settings.rental_rounds || 1; - document.getElementById("rs-protect-card").checked = settings.protect_card !== false; - const selected = new Set((settings.reminder_minutes || []).map(String)); - document.querySelectorAll("#rs-minute-options input").forEach(el => el.checked = selected.has(el.value)); - } catch (err) { - showToast("设置加载失败:" + friendlyError(err)); - } - } - - function closeRentalSettingsModal() { SettingsPages.back(); } - - async function saveRentalSettings() { - const reminderMinutes = [...document.querySelectorAll("#rs-minute-options input:checked")].map(el => Number(el.value)); - const payload = { - reminder_enabled: document.getElementById("rs-reminder-enabled").checked, - reminder_minutes: reminderMinutes, - rental_duration_minutes: Number(document.getElementById("rs-duration").value), - auto_return_enabled: document.getElementById("rs-auto-return").checked, - rental_rounds: Number(document.getElementById("rs-rounds").value), - protect_card: document.getElementById("rs-protect-card").checked - }; - try { - const resp = await fetch("/api/auth/rental_settings", { - method: "POST", - headers: { "Authorization": `Bearer ${authToken}`, "Content-Type": "application/json" }, - body: JSON.stringify(payload) - }); - const result = await resp.json(); - if (result.rtn_code !== 0) throw new Error(result.message || "保存失败"); - closeRentalSettingsModal(); - showToast("用车设置已保存"); - } catch (err) { - showToast("保存失败:" + friendlyError(err)); - } - } - - async function syncWechatOrder() { - if (!authToken) return; - try { - const resp = await fetch("/api/rental/sync", { - method: "POST", - headers: { - "Authorization": `Bearer ${authToken}`, - "Content-Type": "application/json" - } - }); - const data = await resp.json(); - console.log("[syncWechatOrder] 同步结果:", data); - if (data.rtn_code === 0 && data.data && data.data.active && data.data.source === "reminder") { - const r = data.data; - activeRental = { - rental_id: r.rental_id, - bike_code: r.bike_code, - end_time: r.end_time, - source: r.source || "reminder", - remaining_seconds: r.remaining_seconds - }; - localStorage.setItem(RENTAL_KEY, JSON.stringify(activeRental)); - } else if (data.rtn_code === 0 && data.data) { - // 真实订单走订单横幅(checkOrderStatus / fetchOrderCountdown 驱动), - // 本地计时条只承载 reminder 计时 - clearRentalState(); - } - } catch (err) { - console.error("[syncWechatOrder] 同步失败:", err); - } - } - - function checkRentalStatus() { - // 已登录才查询 - if (!authToken) { - console.log("[checkRentalStatus] 无token,跳过"); - return; - } - console.log("[checkRentalStatus] 发送请求, authToken:", authToken); - fetch("/api/rental/status", { - headers: { "Authorization": `Bearer ${authToken}` } - }) - .then(r => r.json()) - .then(data => { - console.log("[checkRentalStatus] 响应:", data); - if (data.rtn_code === 0 && data.data && data.data.active) { - const r = data.data; - - // 剩余时间 <= 0 也视为无活跃 - if (r.remaining_seconds <= 0) { - clearRentalState(); - return; - } - - // 既然后端已按用户过滤,有记录就直接显示状态栏 - activeRental = { - rental_id: r.rental_id, - order_id: r.order_id || null, - bike_code: r.bike_code, - email: r.email, - end_time: r.end_time, - final_end_time: r.final_end_time || null, - current_round: r.current_round || 1, - total_rounds: r.total_rounds || null, - source: r.source || null, - remaining_seconds: r.remaining_seconds - }; - localStorage.setItem(RENTAL_KEY, JSON.stringify(activeRental)); - showRentalBar(); - } else { - // 无活跃租车,清空 - console.log("[checkRentalStatus] 无活跃租车"); - clearRentalState(); - } - }) - .catch(err => console.error("检查租车状态失败:", err)); - } - - function startRental(bikeCode) { - // 先显示二维码,用户体验更好 - showQrModal(bikeCode); - closeCard(); - - console.log("[startRental] authToken:", authToken, "currentUser:", currentUser); - - if (!currentUser) { - showToast("登录后可开启用车计时提醒"); - return; - } - - // 调后端开启计时 - fetch("/api/rental/start", { - method: "POST", - headers: { - "Content-Type": "application/json", - "Authorization": `Bearer ${authToken}` - }, - body: JSON.stringify({ bike_code: bikeCode }) - }) - .then(r => r.json()) - .then(data => { - if (data.rtn_code === 0) { - const now = new Date(); - const endTime = new Date(now.getTime() + data.data.remaining_seconds * 1000); - activeRental = { - rental_id: data.data.rental_id, - bike_code: bikeCode, - email: currentUser.email, - remaining_seconds: data.data.remaining_seconds, - end_time: endTime.toISOString().slice(0, 19).replace('T', ' ') - }; - localStorage.setItem(RENTAL_KEY, JSON.stringify(activeRental)); - showRentalBar(); - showToast("提醒计时已开始;未绑定微信订单,请到期前手动还车"); - } else { - showToast(data.message || "计时启动失败"); - } - }) - .catch(err => { - showToast("计时未开启,请检查网络"); - console.error("启动计时失败:", err); - }); - } - - function showRentalBar() { - if (!activeRental) return; - const bar = document.getElementById("rental-bar"); - document.getElementById("rental-bike-code").textContent = `#${activeRental.bike_code}`; - // +1轮 按钮仅对真实微信订单展示(reminder 计时不支持) - const addBtn = document.getElementById("rental-add-round-btn"); - if (addBtn) { - const realOrder = activeRental.source ? activeRental.source !== "reminder" - : !!activeRental.order_id; - addBtn.style.display = realOrder ? "inline-flex" : "none"; - } - updateRentalFinalTime(); - bar.classList.add("show"); - updateRentalCountdown(); - // 每秒更新倒计时 - if (rentalCountdownTimer) clearInterval(rentalCountdownTimer); - rentalCountdownTimer = setInterval(updateRentalCountdown, 1000); - } - - function updateRentalFinalTime() { - const el = document.getElementById("rental-final-time"); - if (!el) return; - if (activeRental && activeRental.final_end_time) { - const hhmm = String(activeRental.final_end_time).slice(11, 16); - const total = activeRental.total_rounds || activeRental.rounds_planned; - el.textContent = total ? ` · 共${total}轮 预计${hhmm}还车` : ` · 预计${hhmm}还车`; - el.style.display = "inline"; - } else { - el.style.display = "none"; - } - } - - function updateRentalCountdown() { - if (!activeRental) return; - const el = document.getElementById("rental-time"); - const remaining = Math.max(0, activeRental.remaining_seconds - 1); - activeRental.remaining_seconds = remaining; - localStorage.setItem(RENTAL_KEY, JSON.stringify(activeRental)); - - const mins = Math.floor(remaining / 60); - const secs = remaining % 60; - el.textContent = `${mins}:${secs.toString().padStart(2, "0")}`; - - // 变色提示 - if (remaining <= 60) { - el.style.color = "#ff3b30"; - } else if (remaining <= 300) { - el.style.color = "#ff9f0a"; - } else { - el.style.color = "white"; - } - - if (remaining <= 0) { - clearInterval(rentalCountdownTimer); - // 超时后每分钟查一次后端确认状态 - rentalCountdownTimer = setInterval(checkRentalStatus, 60000); - } - } - - function showReturnModal() { - if (!activeRental) return; - document.getElementById("return-bike-code").textContent = `#${activeRental.bike_code}`; - document.getElementById("return-modal").classList.add("show"); - } - - function closeReturnModal() { - document.getElementById("return-modal").classList.remove("show"); - } - - async function confirmReturn() { - closeReturnModal(); - if (!activeRental) return; - - try { - const response = await fetch("/api/rental/return", { - method: "POST", - headers: { - "Content-Type": "application/json", - "Authorization": `Bearer ${authToken}` - }, - body: JSON.stringify({ rental_id: activeRental.rental_id }) - }); - const data = await response.json(); - - // 只有后端返回成功才清除本地状态 - if (data.rtn_code === 0) { - clearRentalState(); - showToast("已确认还车,祝您使用愉快!"); - } else { - // 后端返回错误,保持本地状态,提示用户 - showToast(data.message || "还车失败,请重试"); - console.error("还车失败:", data); - } - } catch (err) { - console.error("确认还车失败:", err); - showToast("网络错误,请检查网络后重试"); - } - } - - // 原生壳(Android)判定:UA 由 Android WebView 注入 xbniu-native,head 脚本已给 加 in-native-shell - function isNativeShell() { - return document.documentElement && document.documentElement.classList.contains('in-native-shell'); - } - // 网页点“开锁用车”时,把开锁交给安卓原生(原生里选账号/共享并开锁);返回 true 表示已交给原生 - function nativeUnlockBike(code) { - try { - if (isNativeShell() && window.xbniuAndroid && typeof window.xbniuAndroid.unlock === 'function') { - window.xbniuAndroid.unlock(String(code)); - return true; - } - } catch (e) { console.error("[原生桥] 调用失败:", e); } - return false; - } - - function unlockBike() { - if (!selectedBike) return; - - // 检查车辆状态 - const bikeState = getBikeState(selectedBike); - if (bikeState === 'inuse') { - showToast("该车正在使用中,请稍后再试"); - closeCard(); - return; - } - if (bikeState === 'locked') { - showToast("该车已锁定,无法使用"); - closeCard(); - return; - } - if (bikeState === 'reserved') { - showToast("该车已被预约"); - closeCard(); - return; - } - - // 原生壳:点击即交给安卓原生开锁(账号选择在原生 BikeDetailActivity),不在此出网页二维码 - if (nativeUnlockBike(selectedBike.code)) { - return; - } - - // 网页端默认:显示二维码弹窗(长按二维码才开始计时) - showQrModal(selectedBike.code); - } - - // 显示二维码弹窗(适配微信扫码 - img格式) - let currentQrPosition = null; // 当前二维码对应的位置 - - function showQrModal(code) { - const modal = document.getElementById("qr-modal"); - const qrBox = document.getElementById("qrcode-box"); - const quickBtn = document.getElementById("quick-unlock-btn"); - - // 清空旧的二维码 - qrBox.innerHTML = ""; - - // 获取当前位置 - currentQrPosition = null; - if (navigator.geolocation) { - navigator.geolocation.getCurrentPosition( - pos => { - currentQrPosition = { - lat: pos.coords.latitude, - lng: pos.coords.longitude - }; - }, - err => console.error("获取位置失败:", err), - { timeout: 5000 } - ); - } - - // 生成新二维码 - const url = "http://bike.sdlongren.com/bicycle?code=" + code; - - // 判断暗色模式 - const isDark = window.matchMedia('(prefers-color-scheme: dark)').matches; - const dark = isDark ? '#ffffff' : '#000000'; - const light = isDark ? '#1a1a1a' : '#ffffff'; - - // 生成 img 格式二维码(参考 xbcr.html) - createQrImage(url, dark, light, function(dataUrl) { - qrBox.innerHTML = ""; // 清空旧内容 - if (!dataUrl) { - // 二维码库不可用:明确告知并保留一键开锁入口,避免“点了没反应” - qrBox.innerHTML = '
二维码生成组件加载失败,
可直接使用下方一键开锁。
'; - modal.classList.add("show"); - quickBtn.style.display = (authToken && currentUser) ? "block" : "none"; - showToast("二维码组件加载失败,可一键开锁"); - return; - } - const img = document.createElement('img'); - img.src = dataUrl; - img.alt = '用车二维码'; - img.style.cssText = 'width:160px;height:160px;border-radius:4px;box-shadow:rgba(0,0,0,0.4) 2px 2px 8px;display:block;'; - qrBox.appendChild(img); - qrBox.dataset.bikeCode = code; // 存车牌,长按时用 - modal.classList.add("show"); - - // 如果用户已登录,显示一键开锁按钮 - if (authToken && currentUser) { - quickBtn.style.display = "block"; - } else { - quickBtn.style.display = "none"; - } - }); - } - - // 生成高质量二维码图片(img格式,适配微信长按识别) - function createQrImage(text, dark, light, callback) { - const size = 160; - const padding = 20; - const canvas = document.createElement('canvas'); - canvas.width = canvas.height = size + padding * 2; - const ctx = canvas.getContext('2d'); - - // 白色背景 - ctx.fillStyle = light; - ctx.fillRect(0, 0, canvas.width, canvas.height); - - // 生成二维码到临时容器 - const tmp = document.createElement('div'); - tmp.style.display = 'none'; - document.body.appendChild(tmp); - - // qrcodejs 加载失败时(如外链 CDN 不可达)给出明确提示,而不是无声无息 - if (typeof QRCode === "undefined") { - document.body.removeChild(tmp); - callback(null); - return; - } - - new QRCode(tmp, { - text: text, - width: size, - height: size, - colorDark: dark, - colorLight: light, - correctLevel: QRCode.CorrectLevel.L - }); - - // 从临时容器提取 canvas 并画到带padding的画布上 - setTimeout(function() { - var qrCanvas = tmp.querySelector('canvas'); - if (qrCanvas) { - ctx.drawImage(qrCanvas, padding, padding); - } - document.body.removeChild(tmp); - callback(qrCanvas ? canvas.toDataURL('image/png', 1) : null); - }, 0); - } - - // 关闭二维码弹窗 - function closeQrModal() { - document.getElementById("qr-modal").classList.remove("show"); - document.getElementById("quick-unlock-btn").style.display = "none"; - // 清除长按定时器 - longPressTimer = null; - longPressTarget = null; - currentQrPosition = null; - } - - // 长按检测变量 - let longPressTimer = null; - let longPressTarget = null; - let qrModalBikeCode = null; // 当前二维码对应的车牌 - - // 二维码弹窗的二维码区域长按检测 - function setupQrLongPress() { - const qrBox = document.getElementById("qrcode-box"); - - // 统一用 pointer 事件(兼容触摸和鼠标) - qrBox.addEventListener("pointerdown", function(e) { - if (!currentUser) return; - e.preventDefault(); // 阻止右键菜单等默认行为 - qrModalBikeCode = qrBox.dataset.bikeCode || ""; - longPressTimer = setTimeout(() => { - longPressTimer = null; - if (qrModalBikeCode && currentUser) { - // 视觉反馈 - qrBox.style.backgroundColor = "rgba(52,199,89,0.2)"; - setTimeout(() => { qrBox.style.backgroundColor = "white"; }, 500); - startRental(qrModalBikeCode); - } - }, 300); - }); - - qrBox.addEventListener("pointerup", function(e) { - if (longPressTimer) { - clearTimeout(longPressTimer); - longPressTimer = null; - } - }); - - qrBox.addEventListener("pointerleave", function(e) { - if (longPressTimer) { - clearTimeout(longPressTimer); - longPressTimer = null; - } - }); - - qrBox.addEventListener("pointercancel", function(e) { - if (longPressTimer) { - clearTimeout(longPressTimer); - longPressTimer = null; - } - }); - } - - // 页面加载时初始化长按检测 - setupQrLongPress(); - - // 点击遮罩关闭 - document.getElementById("qr-modal").addEventListener("click", function(e) { - if (e.target === this) closeQrModal(); - }); - - // ========== 通用确认弹窗(替换 window.confirm) ========== - // 为什么不用 confirm:原生壳是 Android WebView,WebView 默认不弹 JS 原生对话框 - // (Chromium 需要宿主实现 onJsConfirm,未实现时 confirm 直接返回 false,用户点不到"确认")。 - // 这里用页面内弹窗,行为一致但任何环境都能用。 - let _appConfirmResolve = null; - function appConfirm(message, opts) { - const o = opts || {}; - const modal = document.getElementById("app-confirm-modal"); - const titleEl = document.getElementById("app-confirm-title"); - const textEl = document.getElementById("app-confirm-text"); - const okBtn = document.getElementById("app-confirm-ok"); - const cancelBtn = document.getElementById("app-confirm-cancel"); - if (!modal || !textEl) { // 极老页面兜底 - return Promise.resolve(window.confirm ? window.confirm(message) : true); - } - titleEl.textContent = o.title || "确认操作"; - // 支持换行(保留 \n 的排版) - textEl.innerHTML = String(message || "") - .split("\n") - .map(line => escHtml(line)) - .join("
"); - okBtn.textContent = o.okText || "确认"; - cancelBtn.textContent = o.cancelText || "取消"; - okBtn.classList.toggle("danger", !!o.danger); - - return new Promise(resolve => { - _appConfirmResolve = resolve; - const finish = (val) => { - modal.classList.remove("show"); - okBtn.onclick = null; - cancelBtn.onclick = null; - modal.onclick = null; - _appConfirmResolve = null; - resolve(val); - }; - okBtn.onclick = (e) => { e.stopPropagation(); finish(true); }; - cancelBtn.onclick = (e) => { e.stopPropagation(); finish(false); }; - modal.onclick = (e) => { if (e.target === modal) finish(false); }; - modal.classList.add("show"); - }); - } - function appConfirmClose() { - if (_appConfirmResolve) { - const r = _appConfirmResolve; - _appConfirmResolve = null; - document.getElementById("app-confirm-modal").classList.remove("show"); - r(false); - } - } - - function mapSnapshotNow() { - return renderedMapSnapshot - ? renderedMapSnapshot.serverTime + (performance.now() - renderedMapSnapshot.receivedAt) / 1000 - : Date.now() / 1000; - } - - function updateMapFreshnessBadge() { - const el = document.getElementById("update-time"); - if (!el) return; - const stamp = Number(renderedMapSnapshot?.fetched_at); - if (renderedMapSnapshot && Number.isFinite(stamp) && renderedMapSnapshot.fetched_at !== null) { - el.textContent = new Date(stamp * 1000).toLocaleTimeString('zh-CN', { - timeZone: 'Asia/Shanghai', hour: '2-digit', minute: '2-digit' - }); - const expired = mapSnapshotNow() >= Number(renderedMapSnapshot.expires_at); - el.classList.toggle("stale", expired || mapRefreshFailed); - } else if (mapRefreshFailed) { - el.textContent = "更新失败"; - el.classList.add("stale"); - } - el.onclick = showFreshnessDetail; - el.style.cursor = "pointer"; - } - - function updateTime() { - if (renderedMapSnapshot) { updateMapFreshnessBadge(); return; } - // Compatibility for a server without snapshot metadata; never show client time. - fetch(`/api/map/freshness?type=${encodeURIComponent(currentType)}`, { cache: "no-store" }) - .then(r => r.json()) - .then(result => { - if (result.rtn_code !== 0 || !result.data?.latest) return; - const el = document.getElementById("update-time"); - if (!el) return; - el.textContent = String(result.data.latest).slice(11, 16); - el.classList.toggle("stale", result.data.status === "stale" || result.data.stale_seconds >= 60); - el.onclick = showFreshnessDetail; - el.style.cursor = "pointer"; - }) - .catch(() => {}); - } - - function showFreshnessDetail() { - if (renderedMapSnapshot && renderedMapSnapshot.fetched_at !== null) { - const seconds = Math.max(0, Math.floor(mapSnapshotNow() - renderedMapSnapshot.fetched_at)); - const when = new Date(renderedMapSnapshot.fetched_at * 1000).toLocaleTimeString('zh-CN', { timeZone: 'Asia/Shanghai' }); - const age = seconds < 60 ? `${seconds} 秒前` : `${Math.floor(seconds / 60)} 分钟前`; - showToast(`车辆数据更新于 ${when}(${age})${mapRefreshFailed ? ',更新暂时失败,正在自动重试' : ''}`); - return; - } - showToast(mapRefreshFailed ? "地图数据暂时不可用,正在自动重试" : "正在获取最新车辆数据"); - } - - function showToast(msg) { - const t = document.getElementById("toast"); - t.textContent = msg; - t.classList.add("show"); - setTimeout(() => t.classList.remove("show"), 2500); - } - - // ========== 抓包工具下载 ========== - // 安装包是 Windows exe,任何手机/平板都跑不了;微信、QQ、支付宝等内置 - // WebView 还会直接拦截 exe 下载。这两类情况都改为提示复制链接到电脑浏览器。 - const CAPTURE_TOOL_PATH = "/download/capture-tool.exe"; - - // 鸿蒙 UA 有两种:老版 HarmonyOS + Android 兼容层,新版纯 OpenHarmony/ArkWeb; - // 微信鸿蒙版仍带 MicroMessenger,但部分版本 UA 精简后只剩 HarmonyOS。 - function detectHarmony() { - const ua = navigator.userAgent || ""; - return /OpenHarmony|HarmonyOS|ArkWeb|HMSCore/i.test(ua); - } - function detectMobile() { - const ua = navigator.userAgent || ""; - const touchPoints = navigator.maxTouchPoints || 0; - // iPadOS 13+ 默认「请求桌面网站」,UA 伪装成 macOS; - // 靠触点数区分真正的 Mac(0)与 iPad(>1) - if (/Macintosh/.test(ua) && touchPoints > 1) return "iPad"; - // 鸿蒙平板也常带 Tablet,先于手机判断 - if (/OpenHarmony|HarmonyOS|ArkWeb/.test(ua)) { - return /Tablet/i.test(ua) ? "鸿蒙平板" : "鸿蒙手机"; - } - if (/iPhone|iPod/.test(ua)) return "iPhone"; - if (/iPad/.test(ua)) return "iPad"; - if (/Android/.test(ua)) return /Tablet/i.test(ua) ? "安卓平板" : "安卓手机"; - // 兜底:UA 明确标了 Mobile 但没给出具体平台 - if (/Mobile/i.test(ua)) return "手机"; - return null; - } - // 返回需要拦截的"环境名",null 表示可以直接下载 - function detectInAppBrowser() { - const ua = navigator.userAgent || ""; - // 原生壳优先判断:它是最外层容器,UA 里可能同时带 Android - if (/xbniu-native/i.test(ua)) return "APP"; - if (/MicroMessenger/i.test(ua)) return detectHarmony() ? "鸿蒙微信" : "微信"; - if (/\bQQ\/|QQBrowser/i.test(ua)) return "QQ"; - if (/AlipayClient/i.test(ua)) return "支付宝"; - if (/DingTalk/i.test(ua)) return "钉钉"; - if (/Weibo/i.test(ua)) return "微博"; - if (/aweme|ByteDance/i.test(ua)) return "抖音"; - return null; - } - function captureToolUrl() { - return new URL(CAPTURE_TOOL_PATH, window.location.href).href; - } - // 返回 true 时放行 的原生下载 - function onDownloadCaptureTool(event) { - const app = detectInAppBrowser(); - const mobile = app ? null : detectMobile(); // 内嵌环境优先,文案更具体 - if (!app && !mobile) return true; - if (event) event.preventDefault(); - showDownloadTipModal(app, mobile); - return false; - } - function showDownloadTipModal(appName, mobileName) { - const title = document.getElementById("download-tip-title"); - const desc = document.getElementById("download-tip-desc"); - const hint = document.getElementById("download-tip-hint"); - title.textContent = "请在电脑上下载安装"; - if (appName) { - desc.textContent = `${appName}内无法直接下载安装包。请复制下面的链接,在电脑浏览器中打开下载。`; - hint.textContent = "安装包为 Windows 程序,手机端下载后无法运行。"; - } else { - // 普通移动端浏览器:能下载但装了也用不了,引导去电脑 - desc.textContent = `当前是${mobileName || "移动设备"},安装包为 Windows 程序,在此设备上无法运行。请复制下面的链接,在电脑浏览器中打开下载。`; - hint.textContent = ""; - } - hint.style.display = hint.textContent ? "block" : "none"; - document.getElementById("download-tip-link").value = captureToolUrl(); - document.getElementById("download-tip-modal").classList.add("show"); - } - function closeDownloadTipModal() { - document.getElementById("download-tip-modal").classList.remove("show"); - } - - // ========== 数据导出(CSV 直链,1 小时有效) ========== - // 流程:POST /api/export/create(登录态)→ 拿到免登录直链。 - // UA 复用 detectInAppBrowser:微信/QQ/支付宝/钉钉/微博/抖音/原生壳内无法直接下载, - // 弹「复制链接到外部浏览器」提示;普通浏览器直接触发下载。 - function closeExportTipModal() { - document.getElementById("export-tip-modal").classList.remove("show"); - } - async function copyExportLink() { - const url = document.getElementById("export-tip-link").value; - const input = document.getElementById("export-tip-link"); - try { - if (navigator.clipboard && window.isSecureContext) { - await navigator.clipboard.writeText(url); - showToast("链接已复制,请在浏览器中打开"); - return; - } - throw new Error("clipboard unavailable"); - } catch (e) { - try { - input.removeAttribute("readonly"); - input.select(); - document.execCommand("copy"); - input.setAttribute("readonly", ""); - showToast("链接已复制,请在浏览器中打开"); - } catch (e2) { - showToast("复制失败,请长按链接手动复制"); - } - } - } - async function exportHistoryCsv() { - if (!authToken) { showToast("请先登录"); return; } - showToast("正在生成导出链接..."); - try { - const resp = await fetch("/api/export/create", { - method: "POST", - headers: { "Content-Type": "application/json", - "Authorization": `Bearer ${authToken}` }, - body: JSON.stringify({ type: "history_csv" }) - }); - const data = await resp.json(); - if (data.rtn_code !== 0) { - showToast(data.message || "生成导出链接失败"); - return; - } - const url = new URL(data.data.url, window.location.href).href; - const app = detectInAppBrowser(); - if (app) { - // 微信/原生壳等内嵌环境:给直链,复制到外部浏览器下载(直链免登录,1小时有效) - document.getElementById("export-tip-desc").textContent = - `${app}内无法直接下载文件。请复制下面的链接到系统浏览器打开(免登录,${data.data.ttl_hours} 小时内有效)。`; - document.getElementById("export-tip-link").value = url; - document.getElementById("export-tip-modal").classList.add("show"); - return; - } - // 普通浏览器:直接下载,同时保留直链以便换浏览器使用 - const a = document.createElement("a"); - a.href = url; - a.download = ""; - document.body.appendChild(a); - a.click(); - a.remove(); - showToast(`已开始下载(直链 ${data.data.ttl_hours} 小时内有效)`); - } catch (err) { - showToast("导出失败,请重试"); - } - } - async function copyDownloadLink() { - const url = captureToolUrl(); - const input = document.getElementById("download-tip-link"); - // 微信等 WebView 常禁用 navigator.clipboard(非安全上下文或权限拒绝), - // 回退到选中 + execCommand 的老办法 - try { - if (navigator.clipboard && window.isSecureContext) { - await navigator.clipboard.writeText(url); - showToast("链接已复制"); - return; - } - throw new Error("clipboard unavailable"); - } catch (e) { - try { - input.removeAttribute("readonly"); - input.select(); - input.setSelectionRange(0, url.length); - const ok = document.execCommand("copy"); - input.setAttribute("readonly", "readonly"); - showToast(ok ? "链接已复制" : "复制失败,请长按链接手动复制"); - } catch (e2) { - showToast("复制失败,请长按链接手动复制"); - } - } - } - - // 底层异常转用户提示:网关/错误页返回 HTML 时 resp.json() 会抛 - // "Unexpected token '<' ... is not valid JSON",直接展示既难懂又含 token 字样易引起误解 - function friendlyError(e) { - const msg = (e && e.message) || ""; - if (/Unexpected token|is not valid JSON|JSON\.parse/i.test(msg)) { - return "服务响应异常,请稍后重试"; - } - return msg || "网络错误,请重试"; - } - - // ========== Token失效弹窗 ========== - // 仅在真正检测到微信凭据失效时调用;带冷却时间,避免轮询/刷新反复打扰 - let _credInvalidLastShownAt = 0; - const CRED_INVALID_MODAL_COOLDOWN = 10 * 60 * 1000; // 10 分钟内不重复弹出 - function notifyCredentialInvalid(message) { - const modal = document.getElementById("token-expired-modal"); - if (!modal || modal.classList.contains("show")) return; - if (Date.now() - _credInvalidLastShownAt < CRED_INVALID_MODAL_COOLDOWN) return; - _credInvalidLastShownAt = Date.now(); - showTokenExpiredModal(null, message); - } - function showTokenExpiredModal(customTitle, customDesc) { - document.getElementById("token-expired-title").textContent = customTitle || "token已失效,请重新登录"; - document.getElementById("token-expired-desc").textContent = customDesc || "您的微信凭据已过期,请重新抓包获取最新的 Token ID(及 AccessToken)"; - document.getElementById("token-expired-modal").classList.add("show"); - // 预填当前用户已有的token信息 - loadExpiredTokenFields(); - } - function closeTokenExpiredModal() { - document.getElementById("token-expired-modal").classList.remove("show"); - document.getElementById("expired-tip").textContent = ""; - } - async function loadExpiredTokenFields() { - if (!authToken) return; - try { - const resp = await fetch("/api/auth/profile", { - headers: { "Authorization": `Bearer ${authToken}` } - }); - const data = await resp.json(); - if (data.rtn_code === 0 && data.data) { - document.getElementById("expired-token-id").value = data.data.token_id || ""; - document.getElementById("expired-signature").value = data.data.token || ""; - } - } catch (e) { /* ignore */ } - } - async function saveExpiredToken() { - if (!authToken) { - document.getElementById("expired-tip").textContent = "请先登录"; - return; - } - const token_id = document.getElementById("expired-token-id").value.trim(); - const access_token = document.getElementById("expired-signature").value.trim(); - const tip = document.getElementById("expired-tip"); - - if (!token_id) { - tip.textContent = "Token ID 必填;AccessToken 选填"; - return; - } - - tip.textContent = "验证中..."; - try { - const verifyResp = await fetch("/api/auth/verify_token", { - method: "POST", - headers: { "Content-Type": "application/json", - "Authorization": `Bearer ${authToken}` }, - body: JSON.stringify({ access_token, token_id }) - }); - const verifyData = await verifyResp.json(); - if (!verifyData.valid) { - tip.textContent = verifyData.message || "凭据验证失败,请检查 Token ID 是否正确"; - return; - } - } catch (err) { - tip.textContent = "验证失败"; - return; - } - - try { - const resp = await fetch("/api/auth/save_token", { - method: "POST", - headers: { - "Content-Type": "application/json", - "Authorization": `Bearer ${authToken}` - }, - body: JSON.stringify({ access_token, token_id }) - }); - const data = await resp.json(); - if (data.rtn_code === 0) { - tip.textContent = ""; - closeTokenExpiredModal(); - showToast("凭证已更新 ✓"); - } else { - tip.textContent = data.message || "保存失败"; - } - } catch (err) { - tip.textContent = "保存失败"; - } - } - // ========== 定位最近车辆(手动找车)========== function locateMe() { if (!navigator.geolocation) { @@ -4659,13 +1180,12 @@ // 手动找最近的车(基于当前自动定位的位置) function findNearestBikeManual() { + if (!authToken) { showLoginGate(); return; } if (!autoLocationMarker) { - showToast("请先开启定位"); - return; + BikeDiscovery.locationStatus("尚未获取位置。可重新定位,或按地图中心找车。", true); + BikeDiscovery.showList(); return; } - - const point = autoLocationMarker.getPosition(); - findNearestBike(point); + findNearestBike(autoLocationMarker.getPosition()); } // 显示我的位置(手动定位模式,带 panTo) @@ -4742,7 +1262,7 @@ // 启动自动持续定位 function startAutoLocation() { if (!navigator.geolocation) { - console.log("[自动定位] 浏览器不支持定位"); + BikeDiscovery.locationStatus("浏览器不支持定位,可以按地图中心或校园地点找车。", false); return; } @@ -4751,7 +1271,7 @@ navigator.geolocation.clearWatch(autoLocationWatchId); } - showToast("正在获取您的位置..."); + BikeDiscovery.locationStatus("正在获取位置,可先按地图中心查找车辆。", false); autoLocationWatchId = navigator.geolocation.watchPosition( (pos) => { const gpsLat = pos.coords.latitude; @@ -4776,6 +1296,8 @@ } updateAutoLocation(myPoint); hasLocationPermission = true; + BikeDiscovery.locationStatus("定位已更新,可以找最近的车。"); + BikeDiscovery.render(); // 用户授权定位时:本页首次拿到位置后,把地图居中到用户位置(仅一次) if (!initialLocationCentered) { @@ -4788,6 +1310,8 @@ (err) => { console.log("[自动定位] 定位失败:", err.message); hasLocationPermission = false; + const reason = err.code === 1 ? "定位权限未开启,请在浏览器的网站权限中允许定位。" : err.code === 3 ? "定位超时,请重试或按地图中心找车。" : "暂时无法获取位置,可重试或按地图中心找车。"; + BikeDiscovery.locationStatus(reason, true); }, { enableHighAccuracy: false, maximumAge: 5000, timeout: 10000 } ); @@ -4806,542 +1330,4 @@ } // 计算距离并找最近可用车辆(智能电量匹配) - function findNearestBike(myPoint) { - // Haversine公式计算两点距离(米) - function calcDistance(lat1, lng1, lat2, lng2) { - const R = 6371000; - const dLat = (lat2 - lat1) * Math.PI / 180; - const dLng = (lng2 - lng1) * Math.PI / 180; - const a = Math.sin(dLat/2) * Math.sin(dLat/2) + - Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * - Math.sin(dLng/2) * Math.sin(dLng/2); - return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); - } - - const myLat = myPoint.lat; - const myLng = myPoint.lng; - const NEARBY_THRESHOLD = 200; // 附近范围(米) - const LOW_BATTERY = 20; // 低电量阈值 - - // 收集所有可用车(电量>20%,非使用中) - const available = []; - for (const id in markersData) { - const bike = markersData[id]; - if (!bike.latitude || !bike.longitude) continue; - // 只把「空闲可用」的车推荐给用户:分类规则与 getBikeState / 后端一致 - // (使用中 state=1&status=1 / 低电量 state=10 或 电量<20 / 欠压 4 / 损坏 2) - const bs = getBikeState(bike); - if (bs !== 'available') continue; - const electric = parseFloat(bike.electric_quantity || bike.electricQuantity || 0); - if (electric <= LOW_BATTERY) continue; // 过滤低电量 - - const c = offsetCoord(bike.latitude, bike.longitude); - const dist = calcDistance(myLat, myLng, c.lat, c.lng); - available.push({ id, bike, dist, electric }); - } - - // 过滤:只选电量 > 40% 的车 - const enoughElec = available.filter(v => v.electric > 40); - - if (enoughElec.length === 0) { - showToast("附近没有电量足够的车辆(需要>40%)"); - return; - } - - // 直接选距离最近的 - enoughElec.sort((a, b) => a.dist - b.dist); - const selected = enoughElec[0]; - const matchType = "最近可用"; - - - nearestBikeId = selected.id; - const bike = selected.bike; - const c = offsetCoord(bike.latitude, bike.longitude); - const bikePoint = new BMapGL.Point(c.lng, c.lat); - - // 飞到这个车并放大一级 - map.panTo(bikePoint); - setTimeout(() => { - map.setZoom(map.getZoom() + 1); - }, 300); - - // 文案与 getBikeState 的分类一一对应(推荐出来的车一定是 available,正常走「空闲」) - const stateLabel = { - inuse: "使用中", available: "空闲", lowbattery: "低电量", - locked: "欠压车辆", reserved: "损坏车辆", unknown: "未知", - }[getBikeState(bike)] || "未知"; - const distText = selected.dist < 1000 ? `${Math.round(selected.dist)}米` : `${(selected.dist/1000).toFixed(1)}公里`; - showToast(`${matchType}:#${bike.code}(${stateLabel} ${selected.electric}%),${distText}`); - - setTimeout(() => showBikeDetail(selected.id), 500); - } - - // ========== 启动 ========== - // 启动时检查登录状态,然后检查租车 - checkAuthStatus().then(() => { - if (authToken && typeof SettingsPages !== "undefined") SettingsPages.restore(); - checkRentalStatus(); - if (authToken) shareAfterLogin(); - }); - - // 未登录:全屏登录门覆盖地图(后端 /api/map 同样有登录门禁) - if (!authToken) showLoginGate(); - - document.addEventListener("DOMContentLoaded", initMap); - window.addEventListener("xbniu-map-ready", initMap); - document.getElementById("scan-input").addEventListener("keydown", e => { - if (e.key === "Enter") scanCode(); - }); - // Refresh at the shared snapshot's expiry, not 60 seconds after an old cache hit. - setInterval(updateMapFreshnessBadge, 1000); - - // 进行中订单:每 2 分钟主动刷新一次(与上游对账 + 重算剩余时长/预计还车) - setInterval(async () => { - if (!authToken || document.visibilityState !== "visible") return; - if (!currentOrder || Number(currentOrder.status) !== 2) return; - try { - await syncWechatOrder(); // 上游可能已被还车/换单 - checkOrderStatus(); // 刷新横幅状态 - if (currentOrder && currentOrder.order_id) { - fetchOrderCountdown(currentOrder.order_id); // 重算剩余 + 预计还车 - } - } catch (e) { - console.error("[订单2分钟刷新] 失败:", e); - } - }, 120000); - - // 页面重新可见时检查租车状态 - document.addEventListener("visibilitychange", () => { - if (document.visibilityState === "visible") { - if (authToken && map) loadMapData(currentType, false, true); - checkAuthStatus().then(async () => { - // 从微信或其他端回到页面时,先主动对账,再刷新本地横幅。 - if (authToken) await syncWechatOrder(); - // 如果有租车计时横幅,同步服务端时间 - const rentalBar = document.getElementById("rental-bar"); - console.log("[visibilitychange] 同步服务端用车状态"); - checkRentalStatus(); - // 如果有订单横幅且在进行中,同步倒计时 - const orderBanner = document.getElementById("order-banner"); - if (orderBanner && orderBanner.classList.contains("show") && currentOrder && currentOrder.status === 2) { - console.log("[visibilitychange] order-banner 进行中,同步倒计时"); - fetchOrderCountdown(currentOrder.order_id); - } - }); - } - }); - - // ================= 版本号 & 更新说明 ================= - const VERSION_TAG = "v1.6.0"; - const VERSION_LOGS = [ - { v: "v1.6.0", items: [ - "新增用车设置:可独立开启或关闭邮件提醒,并多选到期前 10、5、3、2、1 分钟及到期时提醒", - "支持实时调整用车到期时间,当前订单也会立即按新时长更新;默认 19 分钟,月卡前 20 分钟免费并预留 1 分钟容错", - "新增自动还车开关;关闭后到期邮件只提醒手动还车,不再显示已自动还车或自动还车失败", - "共享用车按实际骑行人的到期与自动还车设置执行,车主和骑行人分别按各自设置接收美化后的 HTML 邮件及一键还车入口", - "修复共享车主重复显示订单横幅,并修复普通/共享车辆已锁车但接口响应异常时误报还车失败的问题" - ] }, - { v: "v1.5.0", items: [ - "新增共享电动车自定义昵称" - ] }, - { v: "v1.4.0", items: [ - "支持多设备同时登录:同一账号可在多台设备/多个浏览器同时在线,不再相互顶下线", - "个人中心新增“登录设备管理”:可查看当前账号各登录设备(记录系统/浏览器与最近活跃),随时下线其它设备或一键下线其它所有设备", - "统一个人中心/凭证/设备管理的深浅色模式适配" - ] }, - { v: "v1.3.0", items: [ - "新增「共享电动车」功能:向车主申请共享其电动车;接受后可设置每天可用次数、是否需要车主持有优惠卡、优惠卡剩余次数下限(低于则不能用)", - "开锁时可选择“用自己的账号”或“用共享者的账号”(附实时可用次数;今日次数用完的共享者默认隐藏)", - "用车横幅区分“共享中/使用XX的车中”,车主与被共享者都能还车", - "个人中心新增“共享电动车”入口,双Tab管理(可使用的/我共享的),双方都可解绑" - ] }, - { v: "v1.2.0", items: [ - "修复远程扫码被拦截:开锁上报车辆附近随机位置", - "请求头对齐当前版本微信环境" - ] } - ]; - // 右下角版本徽标始终跟随 VERSION_TAG,避免与更新说明不一致 - (function () { - var b = document.getElementById("version-badge"); - if (b) b.textContent = VERSION_TAG; - })(); - let versionModalInited = false; - let versionAutoTries = 0; - function openVersionModal() { - if (!versionModalInited) { - const el = document.getElementById("version-content"); - el.innerHTML = VERSION_LOGS.map(l => - `

${l.v}

    ${l.items.map(i => `
  • ${i}
  • `).join("")}
` - ).join(""); - versionModalInited = true; - } - // 记录已查看当前版本,避免每次打开都弹 - try { localStorage.setItem("version_seen", VERSION_TAG); } catch (e) {} - document.getElementById("version-modal").classList.add("show"); - } - function closeVersionModal() { - document.getElementById("version-modal").classList.remove("show"); - } - // 新版本/首次打开自动弹当前版本更新说明(每版本每浏览器只自动弹一次) - function maybeAutoShowVersion() { - if (typeof SettingsPages !== "undefined" && SettingsPages.isOpen()) return; - let seen = ""; - try { seen = localStorage.getItem("version_seen") || ""; } catch (e) {} - if (seen === VERSION_TAG) return; - const askM = document.getElementById("share-ask-modal"); - const cfgM = document.getElementById("share-config-modal"); - const busy = (askM && askM.classList.contains("show")) || - (cfgM && cfgM.classList.contains("show")); - if (busy) { - versionAutoTries++; - if (versionAutoTries < 8) setTimeout(maybeAutoShowVersion, 4000); - return; - } - openVersionModal(); - } - - // ================= 共享电动车 ================= - function shareApi(url, method, body) { - const opts = { method: method || "GET", headers: {} }; - if (authToken) opts.headers["Authorization"] = `Bearer ${authToken}`; - if (body !== undefined) { - opts.headers["Content-Type"] = "application/json"; - opts.body = JSON.stringify(body); - } - return fetch(url, opts).then(r => r.json()); - } - - // ===== 私密备注(昵称) 工具 ===== - // 显示对方时:优先用“我给他起的备注(昵称)”,其次显示名,最后退回邮箱 - function partnerLabel(name, email, remark) { - return (remark && String(remark).trim()) || name || email || ""; - } - // share_id -> {email,name,remark},备注编辑用(不把用户文本嵌进 HTML 属性/JS 字面量) - let shareRec = {}; - - // ---------- 管理弹窗 ---------- - let shareTabNow = "usable"; - function openShareModal() { - if (!authToken || !currentUser) { showToast("请先登录"); return; } - SettingsPages.open("share-modal"); - switchShareTab(shareTabNow); - loadShareData(); - } - function closeShareModal() { - SettingsPages.back(); - } - function switchShareTab(tab) { - shareTabNow = tab; - document.getElementById("share-tab-usable").classList.toggle("active", tab === "usable"); - document.getElementById("share-tab-mine").classList.toggle("active", tab === "mine"); - document.getElementById("share-list-usable").style.display = tab === "usable" ? "flex" : "none"; - document.getElementById("share-list-mine").style.display = tab === "mine" ? "flex" : "none"; - loadShareData(); - } - function sharePendingHtml(pending) { - if (!pending || !pending.length) { document.getElementById("share-pending-box").style.display = "none"; return; } - const rows = pending.map(p => - `
等待接受:${escHtml(p.from_email||'')} - - - -
`).join(""); - const box = document.getElementById("share-pending-box"); - box.innerHTML = `
待处理的共享申请
${rows}`; - box.style.display = "block"; - } - async function loadShareData() { - if (!authToken) return; - try { - const data = await shareApi("/api/share/list"); - if (data.rtn_code !== 0) { showToast(data.message || "加载失败"); return; } - const d = data.data || { usable: [], shared: [] }; - shareRec = {}; - - document.getElementById("share-list-usable").innerHTML = d.usable.map(u => { - const uLabel = partnerLabel(u.owner_name, u.owner_email, u.remark); - shareRec[u.share_id] = { email: u.owner_email || "", name: u.owner_name || "", remark: u.remark || "" }; - const state = u.can_use - ? ('') - : (''); - return ''; - }).join(""); - - document.getElementById("share-list-mine").innerHTML = d.shared.map(sr => { - const sLabel = partnerLabel(sr.rider_name, sr.rider_email, sr.remark); - shareRec[sr.share_id] = { email: sr.rider_email || "", name: sr.rider_name || "", remark: sr.remark || "" }; - return ''; - }).join(""); - - const pending = await shareApi("/api/share/pending"); - if (pending.rtn_code === 0) sharePendingHtml(pending.data || []); - } catch (e) { console.error("[share] load失败", e); } - } - async function sendShareRequest() { - if (!authToken) { showToast("请先登录"); return; } - const email = document.getElementById("share-req-email").value.trim(); - if (!email) { showToast("请输入对方邮箱"); return; } - const btn = document.querySelector(".share-req-row button"); - if (btn) { btn.disabled = true; } - try { - const data = await shareApi("/api/share/request", "POST", { to_email: email }); - showToast(data.message || (data.rtn_code === 0 ? "已发送" : "发送失败")); - if (data.rtn_code === 0) document.getElementById("share-req-email").value = ""; - } finally { - if (btn) { btn.disabled = false; } - } - } - - async function acceptShareRequest(reqId, fromEmail) { - const askM = document.getElementById("share-ask-modal"); - if (askM) askM.classList.remove("show"); - shareAskActive = false; - try { - const data = await shareApi("/api/share/respond", "POST", { request_id: reqId, accept: true }); - if (data.rtn_code === 0 && data.data) { - showToast("已接受,请设置权限"); - openShareConfig(data.data.share_id, data.data.daily_limit, data.data.require_card, data.data.card_min_times, data.data.rider_email); - } else { - showToast(data.message || "操作失败"); - } - } finally { - loadShareData(); - checkPendingShareRequests(); - } - } - async function rejectShareRequest(reqId) { - const askM = document.getElementById("share-ask-modal"); - if (askM) askM.classList.remove("show"); - shareAskActive = false; - try { - const data = await shareApi("/api/share/respond", "POST", { request_id: reqId, accept: false }); - showToast(data.message || "已拒绝"); - } finally { - loadShareData(); - checkPendingShareRequests(); - } - } - - // ---------- 权限设置 ---------- - let shareCfg = { share_id: null }; - function openShareConfig(shareId, daily, requireCard, minTimes, email) { - shareCfg = { share_id: shareId }; - document.getElementById("share-config-title").textContent = email ? `为 ${email} 设置共享权限` : ""; - document.getElementById("sharecfg-daily").value = daily ?? 3; - document.getElementById("sharecfg-card").checked = !!requireCard; - document.getElementById("sharecfg-mintimes").value = minTimes ?? 0; - SettingsPages.open("share-config-modal"); - } - function closeShareConfig() { - SettingsPages.back(); - setTimeout(() => checkPendingShareRequests(), 0); - } - async function saveShareConfig() { - if (!shareCfg.share_id) return; - const daily = parseInt(document.getElementById("sharecfg-daily").value, 10) || 0; - const require_card = document.getElementById("sharecfg-card").checked ? 1 : 0; - const minTimes = parseInt(document.getElementById("sharecfg-mintimes").value, 10) || 0; - const data = await shareApi("/api/share/config", "POST", { - share_id: shareCfg.share_id, daily_limit: daily, require_card, card_min_times: minTimes - }); - showToast(data.message || (data.rtn_code === 0 ? "权限已保存" : "保存失败")); - if (data.rtn_code === 0) closeShareConfig(); - loadShareData(); - checkPendingShareRequests(); - } - - async function unbindShare(shareId) { - if (!(await appConfirm("解绑后对方将无法再用你的共享额度开锁,可随时重新申请。", { title: "解绑共享关系", okText: "解绑", danger: true }))) return; - const data = await shareApi("/api/share/unbind", "POST", { share_id: shareId }); - showToast(data.message || "已解绑"); - loadShareData(); - refreshShareBanners(); - } - - // ---------- 给对方的私密备注(昵称) ---------- - let shareRemarkCfg = { share_id: null }; - function openShareRemark(shareId) { - const rec = shareRec[shareId]; - if (!rec) return; - shareRemarkCfg.share_id = shareId; - document.getElementById("share-remark-input").value = rec.remark || ""; - const shown = partnerLabel(rec.name, rec.email, rec.remark); - document.getElementById("share-remark-desc").innerHTML = - '给 ' + escHtml(shown) + ' 起一个昵称备注,仅自己可见;未设置时对 TA 的显示退回邮箱 (' + escHtml(rec.email || "") + ')。'; - SettingsPages.open("share-remark-modal"); - } - function closeShareRemark() { - SettingsPages.back(); - shareRemarkCfg.share_id = null; - } - async function saveShareRemark() { - if (!shareRemarkCfg.share_id) return; - const remark = document.getElementById("share-remark-input").value.trim(); - const btn = document.querySelector("#share-remark-modal .auth-submit"); - if (btn) btn.disabled = true; - try { - const data = await shareApi("/api/share/remark", "POST", { share_id: shareRemarkCfg.share_id, remark: remark }); - showToast(data.message || (data.rtn_code === 0 ? "备注已保存" : "保存失败")); - if (data.rtn_code === 0) closeShareRemark(); - loadShareData(); - refreshShareBanners(); - } catch (e) { console.error("[share] remark失败", e); showToast("保存失败"); } - finally { if (btn) btn.disabled = false; } - } - - // ---------- 全屏接收申请 ---------- - let shareAskQueue = []; - let shareAskActive = false; - let shareAskCur = null; - async function checkPendingShareRequests() { - if (!authToken || shareAskActive) return; - try { - const data = await shareApi("/api/share/pending"); - if (data.rtn_code === 0 && data.data && data.data.length) { - shareAskQueue = data.data.slice(); - nextShareAskIfQueue(); - } - } catch (e) { /* 忽略 */ } - } - function nextShareAskIfQueue() { - if (shareAskQueue.length > 0) { - shareAskCur = shareAskQueue.shift(); - shareAskActive = true; - document.getElementById("share-ask-from").textContent = shareAskCur.from_email || ""; - document.getElementById("share-ask-modal").classList.add("show"); - } else if (shareAskActive) { - shareAskActive = false; - document.getElementById("share-ask-modal").classList.remove("show"); - } - } - async function acceptCurrentShareAsk() { - if (!shareAskCur) return; - await acceptShareRequest(shareAskCur.id, shareAskCur.from_email); - // 接受后弹权限设置由 acceptShareRequest 处理;队列推进 - } - async function rejectCurrentShareAsk() { - if (!shareAskCur) return; - await rejectShareRequest(shareAskCur.id); - } - - // ---------- 共享横幅(车主:共享中 / 骑行者:使用中) ---------- - let shareActiveList = []; - let pendingShareReturn = null; - async function refreshShareBanners() { - const cont = document.getElementById("share-banners"); - if (!cont) return; - if (!authToken || !currentUser) { cont.innerHTML = ""; return; } - try { - const data = await shareApi("/api/share/active"); - if (data.rtn_code !== 0) return; - shareActiveList = data.data || []; - shareActiveList.forEach(it => { it._countdownDeadline = performance.now() + Math.max(0, Number(it.remaining_seconds) || 0) * 1000; }); - let html = ""; - shareActiveList.forEach((it, idx) => { - const isOwner = it.role === "owner"; - const label = partnerLabel(it.partner_name, it.partner_email, it.remark); - const esc = escHtml(label); - const bike = escHtml(it.bike_code || ""); - let text; - if (isOwner) { - text = '共享中#' + bike + '' + esc + ' 使用中'; - } else { - text = '使用 ' + esc + ' 的车中#' + bike + ''; - } - html += ''; - }); - cont.innerHTML = html; - } catch (e) { console.error("[share] banners失败", e); } - } - function openShareReturnByIdx(idx) { - const it = shareActiveList[idx]; - if (!it) return; - pendingShareReturn = it; - const isOwner = it.role === "owner"; - const label = partnerLabel(it.partner_name, it.partner_email, it.remark); - const esc = escHtml(label); - const bike = escHtml(it.bike_code || ""); - const box = document.getElementById("share-return-text"); - box.innerHTML = isOwner - ? ('你的共享电动车 #' + bike + ' 正被 ' + esc + ' 使用,确认替他/她还车?') - : ('你正在使用 ' + esc + ' 的车 #' + bike + ',确认还车?'); - document.getElementById("share-return-modal").classList.add("show"); - } - function updateShareCountdowns() { - shareActiveList.forEach((it, idx) => { - const el = document.getElementById('share-countdown-' + idx); - if (!el) return; - const seconds = Math.max(0, Math.ceil((it._countdownDeadline - performance.now()) / 1000)); - el.textContent = seconds > 0 ? '本轮剩余 ' + remainingTimeText(seconds) : '本轮到期 · 同步状态中'; - }); - } - setInterval(updateShareCountdowns, 1000); - // HTML 的 ✕ / 取消 / 遮罩都调用它(此前漏了定义 → 点击直接 ReferenceError,弹窗关不掉) - function closeShareReturnModal() { - const modal = document.getElementById("share-return-modal"); - if (modal) modal.classList.remove("show"); - pendingShareReturn = null; - } - async function confirmShareReturn() { - if (!pendingShareReturn) return; - const it = pendingShareReturn; - const btn = document.querySelector("#share-return-modal .auth-submit"); - if (btn) { btn.disabled = true; btn.textContent = "还车中..."; } - try { - let position = null; - if (navigator.geolocation) { - position = await new Promise(resolve => { - navigator.geolocation.getCurrentPosition( - pos => resolve(pos), - () => resolve(null), - { timeout: 5000 }); - }); - } - const latitude = position?.coords?.latitude || 36.67; - const longitude = position?.coords?.longitude || 116.98; - const data = await shareApi("/api/share/return", "POST", { - order_id: it.order_id, latitude, longitude - }); - showToast(data.message || (data.rtn_code === 0 ? "还车成功" : "还车失败")); - if (data.rtn_code === 0) { - closeShareReturnModal(); - pendingShareReturn = null; - await Promise.all([refreshShareBanners(), checkOrderStatus(), refreshMap()]); - } - } catch (e) { - showToast("还车失败,请重试"); - } finally { - if (btn) { btn.disabled = false; btn.textContent = "确认还车"; } - } - } - - // ---------- 初始化(登录后/页面加载) ---------- - function shareAfterLogin() { - refreshShareBanners(); - setTimeout(() => checkPendingShareRequests(), 800); - } - document.addEventListener("DOMContentLoaded", () => { - if (authToken) shareAfterLogin(); - setInterval(() => { if (authToken) { checkAuthStatus(); checkOrderStatus(); refreshShareBanners(); } }, 20000); - setInterval(() => { if (authToken) checkPendingShareRequests(); }, 30000); - setTimeout(maybeAutoShowVersion, 1200); - }); + function findNearestBike(myPoint) { return BikeDiscovery.nearest(myPoint); } diff --git a/static/js/ui-dialogs.js b/static/js/ui-dialogs.js new file mode 100644 index 0000000..eea596a --- /dev/null +++ b/static/js/ui-dialogs.js @@ -0,0 +1,67 @@ +/* Modal visibility, keyboard containment and focus restoration. */ +(function () { + 'use strict'; + const selector = '.auth-modal,.bell-modal,.return-modal,.qr-modal,.token-expired-modal,.return-confirm-modal,.unlock-confirm-modal,.lost-modal,#bike-card'; + const focusable = 'button:not([disabled]),a[href],input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex="0"]'; + const previous = new WeakMap(); + function containBackground() { + const open = [...document.querySelectorAll(selector)].filter(el => el.classList.contains('show')); + const modal = open.at(-1), settings = document.getElementById('settings-page'); + const active = modal || (settings && !settings.hidden ? settings : null); + for (const child of document.body.children) { + if (['SCRIPT','STYLE','LINK'].includes(child.tagName)) continue; + if (active) child.inert = !(child === active || child.contains(active) || (modal?.id === 'bike-card' && child.matches('.card-overlay.show'))); + else if (!child.matches(selector)) child.inert = false; + } + } + function sync(el) { + const open = el.classList.contains('show'); + const activeElement = document.activeElement, hadFocus = el.contains(activeElement); + el.inert = !open; + el.setAttribute('aria-hidden', String(!open)); + if (!el.hasAttribute('role')) el.setAttribute('role', 'dialog'); + el.setAttribute('aria-modal', 'true'); + if (!el.hasAttribute('aria-label') && !el.hasAttribute('aria-labelledby')) { + const title = el.querySelector('.auth-header,.unlock-confirm-title,.return-confirm-title,.bike-card-title,.qr-header'); + el.setAttribute('aria-label', title?.textContent.trim().slice(0, 60) || '操作窗口'); + } + if (open) { + previous.set(el, activeElement); + containBackground(); + queueMicrotask(() => { + if (el.classList.contains('show')) [...el.querySelectorAll(focusable)].find(node => node.getClientRects().length)?.focus({ preventScroll: true }); + }); + } else if (hadFocus) { + containBackground(); + const target = previous.get(el); + if (target?.isConnected) target.focus({ preventScroll: true }); + else document.getElementById('auth-btn')?.focus({ preventScroll: true }); + } + containBackground(); + } + document.addEventListener('DOMContentLoaded', () => { + document.querySelectorAll(selector).forEach(el => { + sync(el); + new MutationObserver(records => { if (records.some(r => r.attributeName === 'class')) sync(el); }).observe(el, { attributes: true, attributeFilter: ['class'] }); + }); + const settings = document.getElementById('settings-page'); + if (settings) new MutationObserver(containBackground).observe(settings, { attributes:true, attributeFilter:['hidden'] }); + containBackground(); + document.addEventListener('keydown', event => { + const dialogs = [...document.querySelectorAll(selector)].filter(el => el.classList.contains('show')); + const el = dialogs.at(-1); + if (!el) return; + if (event.key === 'Escape') { + const close = el.querySelector('.auth-close,.bike-card-close,.qr-close,#app-confirm-cancel,.unlock-confirm-btn.cancel,.return-confirm-btn.cancel,.return-confirm-cancel,[data-dialog-close]'); + if (close) { event.preventDefault(); close.click(); } + return; + } + if (event.key !== 'Tab') return; + const items = [...el.querySelectorAll(focusable)].filter(n => n.getClientRects().length); + if (!items.length) { event.preventDefault(); return; } + const first = items[0], last = items.at(-1); + if (event.shiftKey && (document.activeElement === first || !el.contains(document.activeElement))) { event.preventDefault(); last.focus({ preventScroll: true }); } + else if (!event.shiftKey && (document.activeElement === last || !el.contains(document.activeElement))) { event.preventDefault(); first.focus({ preventScroll: true }); } + }); + }); +})(); diff --git a/static/js/ui-preferences.js b/static/js/ui-preferences.js new file mode 100644 index 0000000..89aedaf --- /dev/null +++ b/static/js/ui-preferences.js @@ -0,0 +1,19 @@ +(function () { + 'use strict'; + const key = 'xbniu_theme', media = window.matchMedia('(prefers-color-scheme: dark)'); + let preference = 'system'; + try { preference = localStorage.getItem(key) || 'system'; } catch (_) {} + function apply(value, save) { + preference = ['light', 'dark', 'system'].includes(value) ? value : 'system'; + document.documentElement.dataset.theme = preference === 'system' ? (media.matches ? 'dark' : 'light') : preference; + document.documentElement.style.colorScheme = document.documentElement.dataset.theme; + if (save) { try { localStorage.setItem(key, preference); } catch (_) {} } + document.querySelectorAll('[data-theme-choice]').forEach(el => el.setAttribute('aria-pressed', String(el.dataset.themeChoice === preference))); + window.dispatchEvent(new Event('xbniu-theme-change')); + } + window.UIPreferences = { set: value => apply(value, true), isDark: () => document.documentElement.dataset.theme === 'dark', get: () => preference }; + apply(preference, false); + media.addEventListener('change', () => { if (preference === 'system') apply(preference, false); }); + window.addEventListener('storage', e => { if (e.key === key) apply(e.newValue || 'system', false); }); + document.addEventListener('DOMContentLoaded', () => apply(preference, false)); +})(); diff --git a/subscribe.py b/subscribe.py index b944a49..edcf6be 100644 --- a/subscribe.py +++ b/subscribe.py @@ -12,7 +12,7 @@ - 判定用最近 20 分钟内的采集点(每车取最新一条),坐标系与车辆一致(GCJ02)。 """ import datetime as dt -import math +import math import sqlite3 import random import threading @@ -414,15 +414,25 @@ def _user_email(user_id): return get_user_alert_email(user_id) +def record_rule_result(rule_id, status, message): + conn = get_db() + conn.execute("UPDATE subscribe_rules SET last_run_at=datetime('now','+8 hours'), last_run_status=?, last_run_message=? WHERE id=?", + (status, str(message)[:500], rule_id)) + conn.commit() + conn.close() + + def fire_rule(rule: dict): """执行一条规则:按筛选条件统计候选车辆;需要时自动开锁并邮件汇报。""" from db import get_user_alert_email locs = load_locations() loc = next((l for l in locs if l["id"] == rule["location_id"]), None) to_email = get_user_alert_email(rule["user_id"]) - if not to_email: + if rule.get("notify_enabled") and not to_email: + record_rule_result(rule["id"], "failed", "未配置提醒邮箱") return False if loc is None: + record_rule_result(rule["id"], "failed", "订阅停车点已删除") return False flt = rule_filters(rule) @@ -498,7 +508,11 @@ def fire_rule(rule: dict): plain = f"{title}\n\n{lead}\n\n" + "\n".join(f"{k}:{v}" for k, v in details) html_body = _render_html(title, lead, details) - return send_email(to_email, f"【小白超人】{title}", plain, html_body) + delivered = send_email(to_email, f"【小白超人】{title}", plain, html_body) if rule.get("notify_enabled") else True + status = "failed" if (unlock_result and not unlock_result.get("success")) or not delivered else "success" if candidates else "no_match" + message = title + (";邮件发送失败,请检查提醒邮箱和服务配置" if not delivered else "") + record_rule_result(rule["id"], status, message) + return status != "failed" # ========== 调度 ========== @@ -538,10 +552,12 @@ def _tick(): if not rule.get("notify_enabled") and not rule.get("auto_unlock"): continue try: + record_rule_result(rule["id"], "running", "正在检查符合条件的车辆") ok = fire_rule(rule) except Exception as e: ok = False - print(f"[订阅提醒] 规则 {rule['id']} 发送失败: {e}") + record_rule_result(rule["id"], "failed", "执行失败,请检查凭证有效期和网络后重试") + print(f"[订阅提醒] 规则 {rule['id']} 执行失败: {type(e).__name__}") print(f"[订阅提醒] 规则 {rule['id']} 已触发 (user={rule['user_id']}, 发送={ok})") diff --git a/templates/analysis.html b/templates/analysis.html index 37edc27..8c19d66 100644 --- a/templates/analysis.html +++ b/templates/analysis.html @@ -2,7 +2,8 @@ - + + 数据分析 - 小白超人 + @@ -418,7 +420,7 @@
车辆轨迹回放
- +
@@ -438,7 +440,7 @@
- + @@ -470,7 +472,7 @@ - +
@@ -523,7 +525,7 @@ 低电量
- +
@@ -733,7 +735,7 @@ used: '使用中', locked: '欠压', reserved: '损坏', - low: '低电量' + low: '低电量', unknown: '未知' }; const statusEl = document.getElementById('stat-avail'); const statusSub = document.getElementById('stat-status'); @@ -809,7 +811,7 @@ : (i) => `${String(i).padStart(2, '0')}`; // 提取各状态数据 - const states = ['available', 'used', 'locked', 'reserved', 'low']; + const states = ['available', 'used', 'locked', 'reserved', 'low', 'unknown']; const stateData = {}; const stateColors = { available: '#34c759', @@ -825,10 +827,10 @@ stateData[state].push(data[keyOf(i)]?.[state] || 0); } }); - + // 更新状态汇总(使用24小时平均数据) const summaryEl = document.getElementById('hourly-summary'); - const stateNames = { available: '可用', used: '使用中', locked: '欠压', reserved: '损坏', low: '低电量' }; + const stateNames = { available: '可用', used: '使用中', locked: '欠压', reserved: '损坏', low: '低电量', unknown: '未知' }; summaryEl.innerHTML = states.map(state => { const avg = avgData?.[state] || 0; return ` @@ -838,7 +840,7 @@
`; }).join(''); - + const option = { tooltip: { trigger: 'axis', @@ -848,7 +850,7 @@ let total = 0; params.forEach(p => { if (p.value > 0) { - const names = { available: '可用', used: '使用中', locked: '欠压', reserved: '损坏', low: '低电量' }; + const names = { available: '可用', used: '使用中', locked: '欠压', reserved: '损坏', low: '低电量', unknown: '未知' }; result += `${names[p.seriesName]}: ${p.value}
`; total += p.value; } @@ -902,9 +904,9 @@ barWidth: '35%' })) }; - + hourlyChart.setOption(option); - + // 响应窗口变化 window.addEventListener('resize', () => { if (hourlyChart) hourlyChart.resize(); @@ -938,7 +940,7 @@ // Tab切换 function switchTab(tab) { document.querySelectorAll('.tab-btn').forEach((btn, i) => { - btn.classList.toggle('active', + btn.classList.toggle('active', (tab === 'trajectory' && i === 0) || (tab === 'heatmap' && i === 1) || (tab === 'stats' && i === 2) @@ -947,7 +949,7 @@ document.getElementById('panel-trajectory').style.display = tab === 'trajectory' ? 'block' : 'none'; document.getElementById('panel-heatmap').style.display = tab === 'heatmap' ? 'block' : 'none'; document.getElementById('panel-stats').style.display = tab === 'stats' ? 'block' : 'none'; - + if (tab === 'stats') { refreshStats(); // 图表容器显示后需要手动触发 resize @@ -971,20 +973,20 @@ async function loadTrajectory() { const days = document.getElementById('traj-days').value; const bikeCode = document.getElementById('traj-bike').value; - + const mapEl = document.getElementById('traj-map'); // 只在地图从未初始化时清容器并显示loading,后续只清覆盖物不重建地图 if (!trajMapReady) { mapEl.innerHTML = '
加载中...
'; } - + try { - const url = bikeCode + const url = bikeCode ? `${API_BASE}/api/history/trajectory?bike_code=${bikeCode}&days=${days}` : `${API_BASE}/api/history/all_trajectory?days=${days}`; const resp = await fetch(url); const json = await resp.json(); - + if (json.rtn_code === 0) { currentTrajData = json.data; renderTrajectory(json.data); @@ -1032,18 +1034,12 @@ let cachedAllPts = []; // 多车模式:预排序的合并点数组(只排一次) let cachedBikePts = {}; // 多车模式:每辆车的排序后点数组(只排一次) let prevIdx = -1; // 上一次时间轴索引(用于差量更新) - + // 根据 state + electric 决定颜色,与 map.html 完全一致 function getBikeColor(p) { - const state = p.state != null ? p.state : (p.status ?? 1); - const electric = p.electric != null ? p.electric : 100; - if (state === 10 || electric < 20) return '#8e8e93'; // 低电量 灰 - if (state === 4) return '#ff9f0a'; // 欠压 橙 - if (state === 2) return '#5856D6'; // 损坏 紫 - if (state === 1 && p.status === 1) return '#ff2d55'; // 使用中 红 - return '#34c759'; // 可用 绿 + return {available:'#34c759',inuse:'#ff2d55',locked:'#ff9f0a',reserved:'#5856D6',lowbattery:'#8e8e93',unknown:'#777780'}[BikeData.state(p)]; } - + function doRenderTrajectoryData(data) { // 清除旧数据 currentTrajMarkers.forEach(m => map.removeOverlay(m)); @@ -1055,14 +1051,14 @@ prevIdx = -1; // 重置帧索引 cachedAllPts = []; // 清缓存 cachedBikePts = {}; // 清缓存 - + const allPoints = []; // 用于调整视野 trajectoryData = data; // 保存数据 - + if (data.trajectories) { // 多辆车模式:预排序所有点(只排一次,后续复用) const bikeCodes = Object.keys(data.trajectories); - + // 对每辆车单独排序并缓存 bikeCodes.forEach(code => { const pts = [...data.trajectories[code]].sort((a, b) => @@ -1070,7 +1066,7 @@ ); cachedBikePts[code] = pts; }); - + // 合并所有点用于时间轴滑动 bikeCodes.forEach(code => { cachedBikePts[code].forEach(p => { @@ -1079,19 +1075,19 @@ }); }); cachedAllPts.sort((a, b) => new Date(a.time) - new Date(b.time)); - + // 添加所有点到视野 cachedAllPts.forEach(p => { allPoints.push(new BMapGL.Point(p.c.lng, p.c.lat)); }); - + // 显示时间条 document.getElementById('traj-time').style.display = 'block'; document.getElementById('traj-slider').max = cachedAllPts.length - 1; document.getElementById('traj-slider').value = 0; document.getElementById('traj-time-start').textContent = cachedAllPts[0]?.time || '-'; document.getElementById('traj-time-end').textContent = cachedAllPts[cachedAllPts.length - 1]?.time || '-'; - + } else if (data.points) { // 单辆车模式:只显示线 const points = []; @@ -1101,11 +1097,11 @@ // 跳过位置没变化的点 if (lastCoord && c.lat === lastCoord.lat && c.lng === lastCoord.lng) return; lastCoord = c; - + points.push(new BMapGL.Point(c.lng, c.lat)); allPoints.push(points[points.length - 1]); }); - + if (points.length > 1) { trajPolyline = new BMapGL.Polyline(points, { strokeColor: '#0071e3', @@ -1114,7 +1110,7 @@ }); map.addOverlay(trajPolyline); } - + // 显示时间轴 document.getElementById('traj-time').style.display = 'block'; document.getElementById('traj-slider').max = points.length - 1; @@ -1122,7 +1118,7 @@ document.getElementById('traj-time-start').textContent = data.points?.[0]?.recorded_at || '-'; document.getElementById('traj-time-end').textContent = data.points?.[data.points.length - 1]?.recorded_at || '-'; } - + // 单辆车模式调整视野;多辆车模式只在首次加载时定位中心点 if (allPoints.length > 0) { if (!data.trajectories) { @@ -1134,18 +1130,18 @@ multiBikeFirstPan = false; } } - + onTimelineChange(); } // 时间轴变化 - 多车模式用差量更新,只动位置变化 >5m 的车 function onTimelineChange() { const idx = parseInt(document.getElementById('traj-slider').value); - + // 必须等数据和缓存都就绪 if (!trajectoryData) return; if (trajectoryData.trajectories && cachedAllPts.length === 0) return; - + if (trajectoryData.points) { // 单辆车模式:距离过滤 + 复用 marker const filteredPoints = []; @@ -1162,14 +1158,14 @@ lastCoord = c; filteredPoints.push({...p, c}); }); - + const point = filteredPoints[idx]; if (!point) return; - + const c = point.c; const color = getBikeColor(point); const bikeCode = trajectoryData.bike_code || point.bike_code || ''; - + if (currentTrajMarkers.length === 0) { // 首次:创建带标签的 marker const marker = createTrajMarker(c.lat, c.lng, color, bikeCode); @@ -1190,9 +1186,9 @@ marker.setIcon(createTrajIcon(color)); marker.setTop(true); } - + document.getElementById('traj-time-current').textContent = point.recorded_at || '-'; - + } else if (trajectoryData.trajectories) { const bikeCodes = Object.keys(cachedBikePts); const colors = ['#0071e3', '#34c759', '#ff9500', '#ff3b30', '#5856d6', '#af52de']; @@ -1264,11 +1260,11 @@ if (!heatMapReady) { mapEl.innerHTML = '
聚合数据中...
'; } - + try { const resp = await fetch(`${API_BASE}/api/history/heatmap`); const json = await resp.json(); - + if (json.rtn_code === 0) { if (!heatMapReady) { const b = json.data.bounds; @@ -1302,20 +1298,20 @@ // 渲染服务端聚合后的热力图数据 function renderServerHeatmap(data) { if (!window.heatMap || !heatmapView) return; - + const points = data.points || []; const maxCount = data.max_count || 1; - + // 清除旧热力图层 if (heatmapOverlay) { heatmapView.removeLayer(heatmapOverlay); heatmapOverlay = null; } - + if (points.length === 0) { return; } - + // 转换为 MapVGL 格式(带 count 作为强度权重,加 GPS 偏移) const mapvData = points.map(p => { const c = offsetCoord(p.lat, p.lng); @@ -1324,7 +1320,7 @@ count: p.count // 网格内落点数量作为热力强度 }; }); - + // 创建热力图层 const layer = new mapvgl.HeatmapLayer({ size: 40, // 网格半径(米) @@ -1343,9 +1339,9 @@ layer.setData(mapvData); heatmapView.addLayer(layer); heatmapOverlay = layer; - + // 更新信息 - document.getElementById('heat-info').textContent = + document.getElementById('heat-info').textContent = `共 ${data.grid_count} 个网格, ${data.total_points} 个历史位置`; } @@ -1372,7 +1368,7 @@ const el = document.getElementById(containerId); const loading = el ? el.querySelector('.loading') : null; if (loading) loading.remove(); - + const mapInstance = new BMapGL.Map(containerId); // 默认中心点(山东管理学院,与后端 /api/config 的 center_lat/lng 一致; // 此前的 36.67,117.12 不是本校区坐标,无数据时会落到错误城市的空白区) @@ -1403,7 +1399,7 @@ canvas.height = size; const ctx = canvas.getContext("2d"); const r = size / 2 - 2; - + ctx.beginPath(); ctx.arc(size/2, size/2, r, 0, Math.PI * 2); ctx.fillStyle = color; diff --git a/templates/map.html b/templates/map.html index 4ac6957..c1b3087 100644 --- a/templates/map.html +++ b/templates/map.html @@ -2,7 +2,7 @@ - + 电动车地图 + + + +{% if preview_mode %}
预览环境 · 演示账号使用模拟数据,独立测试账号可连接真实接口
{% endif %}
@@ -183,19 +187,32 @@
-
-
状态图例
+
+
+
筛选条件
+ + + + +
+ +
+
+ + +
+ 状态图例
可用 0
使用中 0
欠压 0
损坏 0
低电量 0
-
+
- +
@@ -205,14 +222,14 @@
登录 - +
- +
- +
@@ -227,7 +244,7 @@
注册 - +
@@ -303,8 +320,8 @@ 填写 Token ID 后可查看更多信息;AccessToken 选填(强验证模式下必填)
- -

地图显示

+ +

外观

地图显示

- +
@@ -539,7 +556,7 @@
请在浏览器中打开下载 - +
当前浏览器无法直接下载文件,请复制下面的链接到系统浏览器打开(1 小时内有效,换浏览器也可用)。 @@ -558,7 +575,7 @@
请在电脑上下载安装 - +
安装包为 Windows 程序,请复制下面的链接到电脑浏览器打开下载。 @@ -583,14 +600,14 @@ 批量寻铃
- +
- +
@@ -598,7 +615,7 @@
- +
@@ -633,7 +650,7 @@
- +
@@ -712,7 +729,7 @@
-
+ - --% + --%
@@ -802,7 +819,7 @@
-
+
@@ -810,7 +827,7 @@ - -
v1.6.0
+
@@ -874,7 +892,7 @@
版本更新说明 - +
@@ -908,7 +926,7 @@
选择开锁账号 - +
@@ -922,7 +940,7 @@
还车确认 - +
@@ -939,7 +957,19 @@ + + + + + + + + + + + +
diff --git a/tests/frontend-source.cjs b/tests/frontend-source.cjs new file mode 100644 index 0000000..9a304f4 --- /dev/null +++ b/tests/frontend-source.cjs @@ -0,0 +1,4 @@ +const fs = require('node:fs'); +const path = require('node:path'); +const modules = ['map.js', 'map-account.js', 'map-orders.js', 'map-history.js', 'map-subscriptions.js', 'map-rental.js', 'map-utils.js', 'map-sharing.js', 'map-boot.js']; +module.exports = modules.map(name => fs.readFileSync(path.join(__dirname, '../static/js', name), 'utf8')).join('\n'); diff --git a/tests/test_api_client.cjs b/tests/test_api_client.cjs new file mode 100644 index 0000000..5396e0b --- /dev/null +++ b/tests/test_api_client.cjs @@ -0,0 +1,27 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const vm = require('node:vm'); +const fs = require('node:fs'); +const source = fs.readFileSync(require('node:path').join(__dirname,'../static/js/api-client.js'),'utf8'); + +test('submission lock prevents duplicates while preserving the next editor state', async () => { + const context={window:{},AbortController,Promise,setTimeout,clearTimeout}; + vm.createContext(context);vm.runInContext(source,context); + let resolve, count=0; + const button={textContent:'保存修改',disabled:false,setAttribute(){},removeAttribute(){}}; + const work=()=>{count++; return new Promise(done=>{resolve=()=>{button.textContent='添加规则';done('saved');};});}; + const first=context.window.AppAPI.run('save-rule',button,work); + const second=context.window.AppAPI.run('save-rule',button,work); + await Promise.resolve();assert.equal(count,1);assert.equal(button.disabled,true); + resolve();assert.deepEqual(await Promise.all([first,second]),['saved','saved']); + assert.equal(button.disabled,false);assert.equal(button.textContent,'添加规则'); +}); +test('request deadline aborts once and never retries a mutation', async () => { + let deadline, calls=0; + const context={window:{},AbortController,Promise,setTimeout:fn=>{deadline=fn;return 1;},clearTimeout(){},fetch:(_,options)=>{ + calls++;return new Promise((_,reject)=>options.signal.addEventListener('abort',()=>{const e=new Error();e.name='AbortError';reject(e);})); + }}; + vm.createContext(context);vm.runInContext(source,context); + const result=context.window.AppAPI.fetch('/api/order/unlock',{method:'POST'}); + deadline();await assert.rejects(result,/请求超时/);assert.equal(calls,1); +}); diff --git a/tests/test_bike_data.cjs b/tests/test_bike_data.cjs new file mode 100644 index 0000000..e5c8b01 --- /dev/null +++ b/tests/test_bike_data.cjs @@ -0,0 +1,35 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const BikeData = require('../static/js/bike-data.js'); + +test('missing, empty, invalid and zero batteries remain distinct', () => { + for (const value of [null, undefined, '', ' ', true, 'NaN', Infinity, -1, 101]) { + assert.equal(BikeData.electric({electric_quantity:value}), null); + } + assert.equal(BikeData.electric({electric_quantity:0,electricQuantity:90}), 0); + assert.equal(BikeData.electric({electric_quantity:'45'}), 45); +}); +test('occupancy and faults take priority; low charge is consistent for strings and numbers', () => { + assert.equal(BikeData.state({state:'1',status:'1',electric_quantity:10}), 'inuse'); + assert.equal(BikeData.state({state:4,status:0,electric_quantity:10}), 'locked'); + assert.equal(BikeData.state({state:2,status:0,electric_quantity:10}), 'reserved'); + assert.equal(BikeData.state({state:1,status:0,electric_quantity:10}), 'lowbattery'); + assert.equal(BikeData.labels[BikeData.state({state:1,status:0,electric_quantity:10})], '低电量'); + assert.equal(BikeData.state({state:99,status:0}), 'unknown'); +}); +test('plate validation supports actual five and eight digit formats only', () => { + for (const value of ['50301','51201','30000193']) assert.equal(BikeData.validCode(value), true); + for (const value of ['1234','123456','30000193e0','-51201','51 201','12345']) assert.equal(BikeData.validCode(value), false); + assert.equal(BikeData.kind({code:'51001'}), 'small'); + assert.equal(BikeData.kind({code:'51101'}), 'big'); + assert.equal(BikeData.kind({code:'30000193'}), 'red'); +}); +test('filtering preserves unknown batteries only when no minimum is requested', () => { + const bike={state:1,status:0,code:'51201'}; + assert.equal(BikeData.matches(bike,{onlyAvailable:true,minElectric:0,kind:'big'}),true); + assert.equal(BikeData.matches(bike,{onlyAvailable:true,minElectric:20,kind:'big'}),false); + assert.equal(BikeData.matches({...bike,electric_quantity:25},{onlyAvailable:true,minElectric:20,kind:'big'}),true); + assert.equal(BikeData.matches({...bike,status:1,electric_quantity:80},{onlyAvailable:true,minElectric:20}),false); + assert.ok(BikeData.distance({lat:36.53,lng:116.78},{lat:36.531,lng:116.78}) > 110); + assert.equal(BikeData.distance(null,{lat:36.53,lng:116.78}),null); +}); diff --git a/tests/test_history_30d.py b/tests/test_history_30d.py index 9e80dd6..b71cd33 100644 --- a/tests/test_history_30d.py +++ b/tests/test_history_30d.py @@ -60,8 +60,8 @@ check("freshness stale 为数字", isinstance(d["stale_seconds"], int)) r = client.get("/api/history/stats?days=1").get_json()["data"] check("stats days=1 回显", r["days"] == 1) check("stats 24桶", "00" in r["hourly_distribution"] and "23" in r["hourly_distribution"]) -expected_states = {"available", "used", "locked", "reserved", "low"} -check("stats 桶含5状态", set(r["hourly_distribution"]["08"].keys()) == expected_states) +expected_states = {"available", "used", "locked", "reserved", "low", "unknown"} +check("stats 桶含6状态", set(r["hourly_distribution"]["08"].keys()) == expected_states) # ---- stats days=30 ---- r = client.get("/api/history/stats?days=30").get_json()["data"] @@ -100,7 +100,7 @@ check("days=0 收敛1", r["days"] == 1) Path(handle.name).unlink(missing_ok=True) print(f"RESULT: {{'FAIL' if failures else 'ALL PASS'}} ({{len(failures)}} failures)") sys.exit(1 if failures else 0) -'''.replace("{root}", str(ROOT).replace("\\", "\\\\")) +'''.replace("{root}", str(ROOT).replace("\\", "\\\\")).replace("{{", "{").replace("}}", "}") def test_history_30d_contract(): @@ -109,4 +109,4 @@ def test_history_30d_contract(): cwd=str(ROOT)) out = (r.stdout or "") + (r.stderr or "") print(out[-4000:] if len(out) > 4000 else out) - assert r.returncode == 0, "子进程契约验证失败(见上方输出)" \ No newline at end of file + assert r.returncode == 0, "子进程契约验证失败(见上方输出)" diff --git a/tests/test_map_refresh.cjs b/tests/test_map_refresh.cjs index 0978612..f772c4a 100644 --- a/tests/test_map_refresh.cjs +++ b/tests/test_map_refresh.cjs @@ -3,7 +3,7 @@ const assert = require('node:assert/strict'); const fs = require('node:fs'); const path = require('node:path'); const vm = require('node:vm'); -const source = fs.readFileSync(path.join(__dirname, '../static/js/map.js'), 'utf8'); +const source = require('./frontend-source.cjs'); const loadingCode = source.slice(source.indexOf(' let mapRequest = null;'), source.indexOf(' // ========== 手动刷新')); const badgeCode = source.slice(source.indexOf(' function mapSnapshotNow()'), source.indexOf(' function showToast(msg)')); @@ -29,6 +29,7 @@ function environment() { clearTimeout: id => timers.delete(id), renderMap: result => renders.push(result), setupClusterListener() {}, showLoginGate() {}, showToast: message => notices.push(message), friendlyError: error => error.message, + apiFetch: (...args) => context.fetch(...args), fetch: () => { context.fetchCount++; return new Promise(done => { resolve = done; }); }, fetchCount: 0 }; vm.createContext(context); vm.runInContext(loadingCode + badgeCode, context); diff --git a/tests/test_order_return.cjs b/tests/test_order_return.cjs index 84fba68..3b52b59 100644 --- a/tests/test_order_return.cjs +++ b/tests/test_order_return.cjs @@ -3,7 +3,7 @@ const assert = require('node:assert/strict'); const fs = require('node:fs'); const path = require('node:path'); const vm = require('node:vm'); -const source = fs.readFileSync(path.join(__dirname, '../static/js/map.js'), 'utf8'); +const source = require('./frontend-source.cjs'); async function environment({ dependencies = true } = {}) { const elements = new Map(), requests = [], notices = [], events = {}; diff --git a/tests/test_preview_features.py b/tests/test_preview_features.py new file mode 100644 index 0000000..eec8f12 --- /dev/null +++ b/tests/test_preview_features.py @@ -0,0 +1,69 @@ +"""Preview/live routing and authenticated editor/pagination contracts in a subprocess.""" +import os +from pathlib import Path +import subprocess +import sys +import tempfile + + +def test_preview_and_live_feature_contract(): + root = Path(__file__).resolve().parents[1] + with tempfile.TemporaryDirectory() as directory: + env = {**os.environ, "XBNIU_PREVIEW": "1", "XBNIU_DB_PATH": str(Path(directory) / "preview.db"), "PYTHONDONTWRITEBYTECODE": "1"} + script = r''' +from unittest.mock import patch +import db +db.init_db() +import app +from preview_data import seed_preview +seed_preview() +c=app.app.test_client() +assert c.get('/healthz').json == {'status':'ok','mode':'preview'} +login=c.post('/api/auth/login',json={'email':'demo@preview.local','password':'preview123'}).json +h={'Authorization':'Bearer '+login['data']['token']} +with patch('wechat.request_with_user_auth',side_effect=AssertionError('Demo called upstream')): + bikes=c.get('/api/map?type=3',headers=h).json['data']['bicycleStation'] + assert len(bikes)==28 + assert c.post('/api/order/unlock',headers=h,json={'code':'51201'}).json['rtn_code']==0 + assert c.get('/api/order/status',headers=h).json['has_order'] + assert c.post('/api/order/return',headers=h,json={}).json['rtn_code']==0 + assert not c.get('/api/order/status',headers=h).json['has_order'] + assert c.post('/api/auth/save_token',headers=h,json={'token_id':'real'}).status_code==403 +page1=c.get('/api/user/orders?limit=20',headers=h).json +page2=c.get('/api/user/orders?limit=20&offset=20',headers=h).json +assert page1['total']==68 and page1['has_more'] and len(page1['data'])==20 +assert not ({x['id'] for x in page1['data']} & {x['id'] for x in page2['data']}) +assert all(x['shared'] for x in c.get('/api/user/orders?source=shared',headers=h).json['data']) +assert c.get('/api/user/orders?from=2026-11-05&to=2026-11-01',headers=h).status_code==400 +rules=c.get('/api/subscribe/rules',headers=h).json['data'];rule=rules[0] +parking=c.get('/api/campus/locations',headers=h).json['data'] +location=next(p for p in parking if p['kind']=='parking' and p['id']!=rule['location_id']) +updated=c.put('/api/subscribe/rules/'+str(rule['id']),headers=h,json={'location_id':location['id'],'time':'12:34','weekday':3,'min_electric':40,'auto_unlock':False,'notify_enabled':True}) +assert updated.json['rtn_code']==0,updated.json +saved=c.get('/api/subscribe/rules',headers=h).json['data'][0] +assert saved['minute_of_day']==754 and saved['location_id']==location['id'] and saved['min_electric']==40 +assert saved['last_run_status']=='success' +assert c.put('/api/subscribe/rules/'+str(rule['id']),headers=h,json={'min_electric':90,'max_electric':20}).status_code==400 +session=c.post('/api/preview/session').json +live={'Authorization':'Bearer '+session['data']['token']} +assert not c.get('/api/user/orders',headers=live).json['data'] +assert not c.get('/api/subscribe/rules',headers=live).json['data'] +with patch('wechat.request_with_user_auth',return_value={'rtn_code':0,'data':{'bicycleStation':[]}}) as upstream: + assert c.get('/api/map?type=3',headers=live).json['rtn_code']==0 + assert c.get('/api/map?type=3',headers=live).json['rtn_code']==0 + assert upstream.call_count==1, 'live map cache should coalesce requests' + assert upstream.call_args.args[0] != 1, 'live requests must use private test account credentials' +assert c.put('/api/subscribe/rules/'+str(rule['id']),headers=live,json={'enabled':False}).json['rtn_code']==404 +with patch('wechat.request_with_user_auth',return_value={'rtn_code':0,'data':{'order_id':'REAL-TEST'}}) as upstream: + assert c.post('/api/bicycle',headers=live,json={'code':'51201'}).json['rtn_code']==0 + assert upstream.call_count==1 +with patch('email_utils.smtplib.SMTP',side_effect=AssertionError('Demo SMTP')): + from email_utils import send_email + assert send_email('demo@preview.local','test','body') is True +from bike_data import classify,battery +assert classify(1,0,10)=='low' and classify(1,1,10)=='used' and classify(4,0,10)=='locked' +assert battery(None) is None and battery(0)==0 +print('PASS: demo isolation, real test account routing, pagination, subscription ownership and full edits') +''' + result = subprocess.run([sys.executable, "-X", "utf8", "-c", script], cwd=root, env=env, capture_output=True, text=True, timeout=60) + assert result.returncode == 0, result.stdout + result.stderr diff --git a/tests/test_ring_all_frontend.py b/tests/test_ring_all_frontend.py index 6aaa201..a5893fb 100644 --- a/tests/test_ring_all_frontend.py +++ b/tests/test_ring_all_frontend.py @@ -4,10 +4,8 @@ import unittest class RingAllFrontendAuthTests(unittest.TestCase): def test_ring_all_request_sends_session_token(self): - source = ( - Path(__file__).resolve().parents[1] / "static" / "js" / "map.js" - ).read_text(encoding="utf-8") - request_block = source.split('fetch("/api/ring_all"', 1)[1].split(");", 1)[0] + source = (Path(__file__).resolve().parents[1] / "static/js/map-account.js").read_text(encoding="utf-8") + request_block = source.split('apiFetch("/api/ring_all"', 1)[1].split(");", 1)[0] self.assertIn('"Authorization": `Bearer ${authToken}`', request_block)