Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f0537e446b |
@@ -1,24 +0,0 @@
|
||||
.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
|
||||
@@ -1,14 +0,0 @@
|
||||
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
|
||||
RUN sed -i 's|deb.debian.org|mirrors.aliyun.com|g; s|security.debian.org|mirrors.aliyun.com|g' /etc/apt/sources.list 2>/dev/null || true
|
||||
RUN sed -i 's|deb.debian.org|mirrors.aliyun.com|g' /etc/apt/sources.list.d/debian.sources 2>/dev/null || true
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends curl \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
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"]
|
||||
@@ -10,7 +10,7 @@
|
||||
- **历史轨迹**:记录每辆车的位置历史,支持按车牌查询轨迹
|
||||
- **数据分析**:状态分布、24 小时趋势、活跃车辆 Top10、热力图
|
||||
- **租赁管理**:订单到期倒计时,邮件提醒(10/5/3/2/1/0 分钟多级通知)
|
||||
- **自动清理**:30 天前历史数据自动归档,定期 VACUUM 释放空间
|
||||
- **自动清理**:3 天前历史数据自动归档,定期 VACUUM 释放空间
|
||||
|
||||
## 技术栈
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
- **数据源**:微信小程序接口(需用户授权 `token_id` + `wx_signature`)
|
||||
- **采集调度**:threading 后台线程 + 自适应间隔
|
||||
- **通知**:SMTP 邮件 + 内部计时器
|
||||
- **前端**:Jinja2 模板 + 百度 BMapGL 地图 + ECharts 图表
|
||||
- **前端**:Jinja2 模板 + Leaflet 地图 + ECharts 图表
|
||||
|
||||
## 项目结构
|
||||
|
||||
@@ -127,7 +127,7 @@ def get_adaptive_interval():
|
||||
|
||||
### 数据清理
|
||||
|
||||
每 23 小时执行一次:删除 30 天前的 `bike_history` 与过期 `sessions`,并执行 `VACUUM` 压缩 SQLite 文件。
|
||||
每 23 小时执行一次:删除 3 天前的 `bike_history` 与过期 `sessions`,并执行 `VACUUM` 压缩 SQLite 文件。
|
||||
|
||||
### 订单到期提醒
|
||||
|
||||
@@ -151,38 +151,3 @@ 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
|
||||
```
|
||||
|
||||
浏览器验收采用演示账号;真实上游链路用替身请求验证路由与账号隔离,不在自动化验收中执行真实车辆操作。
|
||||
|
||||
|
||||
### 手机界面
|
||||
|
||||
地图默认只保留找车入口、状态图例、最近车辆按钮和车牌查询。地点、常用地点、筛选与附近列表收进同一个按需展开的亚克力面板;列表与筛选互相切换,选中车辆或点击地图即可收起。定位提示不再悬浮遮挡地图,首次进入也不会主动弹出定位权限请求;已授权的设备会恢复定位。数据分析及演示/真实测试切换位于设置,预览标识缩为校名旁的小标签。
|
||||
|
||||
@@ -34,7 +34,6 @@ 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)
|
||||
@@ -51,9 +50,6 @@ 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
|
||||
@@ -97,14 +93,6 @@ 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")
|
||||
|
||||
|
||||
|
||||
# ========== 未认证数据接口限速 ==========
|
||||
@@ -404,12 +392,31 @@ def api_analysis_heatmap():
|
||||
# 数据分析页/批量车辆轨迹全部 404。以下实现与前端 analysis.html 期望的 JSON 结构对齐。
|
||||
|
||||
# 状态分类(与 map.html / analysis.html 图例一致)
|
||||
_HISTORY_STATES = ["available", "used", "locked", "reserved", "low", "unknown"]
|
||||
_HISTORY_STATES = ["available", "used", "locked", "reserved", "low"]
|
||||
|
||||
|
||||
def _classify_bike_state(state, status, electric):
|
||||
from bike_data import classify
|
||||
return 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"
|
||||
|
||||
|
||||
@app.route("/api/history/stats")
|
||||
@@ -653,12 +660,6 @@ 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()
|
||||
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
"""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"
|
||||
@@ -4,12 +4,7 @@
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
|
||||
import os
|
||||
from runtime_mode import PREVIEW_MODE
|
||||
DB_PATH = Path(os.environ.get("XBNIU_DB_PATH") or (Path(__file__).parent / ("preview.db" if PREVIEW_MODE else "users.db")))
|
||||
if PREVIEW_MODE and DB_PATH.name == "users.db":
|
||||
raise RuntimeError("Preview mode must use a separate database")
|
||||
DB_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
DB_PATH = Path(__file__).parent / "users.db"
|
||||
|
||||
DEFAULT_RENTAL_SETTINGS = {
|
||||
"reminder_enabled": True,
|
||||
@@ -368,12 +363,6 @@ 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 (
|
||||
|
||||
@@ -106,17 +106,10 @@ 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"]:
|
||||
|
||||
-223
@@ -1,223 +0,0 @@
|
||||
"""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
|
||||
@@ -1,21 +0,0 @@
|
||||
"""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()
|
||||
+2
-2
@@ -2,7 +2,7 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""抓包工具安装包下载
|
||||
|
||||
安装包体积较大(约 160MB),放在项目根的 downloads/ 目录而不是 static/,
|
||||
安装包体积较大(约 25MB),放在项目根的 downloads/ 目录而不是 static/,
|
||||
避免被 Flask 静态路由以外的缓存策略干扰,也便于单独替换升级。
|
||||
|
||||
公开访问:用户注册前就需要拿到工具,若加登录校验会形成「没工具拿不到凭据、
|
||||
@@ -18,7 +18,7 @@ bp = Blueprint("download", __name__)
|
||||
# 容易出编码问题。对外的下载文件名由 download_name 还原。
|
||||
DOWNLOADS_DIR = Path(__file__).parent.parent / "downloads"
|
||||
CAPTURE_TOOL_FILE = "xbniu-capture-tool.exe"
|
||||
CAPTURE_TOOL_NAME = "小白超人抓包工具(新版).exe"
|
||||
CAPTURE_TOOL_NAME = "HeaderCapture.exe"
|
||||
|
||||
|
||||
@bp.route("/download/capture-tool.exe", methods=["GET", "HEAD"])
|
||||
|
||||
+23
-4
@@ -6,7 +6,7 @@
|
||||
返回 /export/csv/<token> 直链(免登录,1 小时有效,一次性换浏览器可继续下载)。
|
||||
前端用 detectInAppBrowser 复用「复制链接到外部浏览器」提示(微信/原生壳内无法下载)。
|
||||
|
||||
CSV 内容:最近 30 天全部车辆点位(与库内保留策略一致)。
|
||||
CSV 内容:最近 3 天全部车辆点位(与库内保留策略一致)。
|
||||
"""
|
||||
import csv
|
||||
import datetime as dt
|
||||
@@ -26,13 +26,32 @@ HISTORY_DAYS = 30
|
||||
|
||||
_STATE_LABELS = {
|
||||
"available": "可用", "used": "使用中", "locked": "欠压",
|
||||
"reserved": "损坏", "low": "低电量", "unknown": "未知",
|
||||
"reserved": "损坏", "low": "低电量",
|
||||
}
|
||||
|
||||
|
||||
def _classify(state, status, electric):
|
||||
from bike_data import classify
|
||||
return 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"
|
||||
|
||||
|
||||
def _clean_expired_tokens(conn):
|
||||
|
||||
+4
-26
@@ -377,31 +377,9 @@ def api_user_info():
|
||||
|
||||
# ========== 首页路由 ==========
|
||||
MAP_ASSETS = (
|
||||
"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",
|
||||
"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",
|
||||
)
|
||||
|
||||
|
||||
@@ -419,7 +397,7 @@ def _map_asset_version():
|
||||
|
||||
@bp.route("/")
|
||||
def index():
|
||||
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 = current_app.make_response(render_template("map.html", map_asset_version=_map_asset_version()))
|
||||
response.headers["Cache-Control"] = "no-cache"
|
||||
return response
|
||||
|
||||
|
||||
+7
-28
@@ -1157,23 +1157,9 @@ def user_orders():
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||||
try:
|
||||
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
|
||||
|
||||
limit = max(1, min(500, int(request.args.get("limit", 80))))
|
||||
except (TypeError, ValueError):
|
||||
limit = 80
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("""
|
||||
@@ -1188,23 +1174,16 @@ 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
|
||||
""", (user["id"], user["id"]))
|
||||
ORDER BY r.id DESC LIMIT ?
|
||||
""", (user["id"], user["id"], limit))
|
||||
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)
|
||||
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))
|
||||
return jsonify({"rtn_code": 0,
|
||||
"data": [_chain_order_dict(c, user["id"]) for c in chains]})
|
||||
|
||||
|
||||
# ========== 开锁前预览(月卡余量 + 自动续租轮次预估) ==========
|
||||
|
||||
+65
-31
@@ -30,9 +30,6 @@ 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"],
|
||||
@@ -108,37 +105,74 @@ def rules_update(rule_id: int):
|
||||
conn.close()
|
||||
return jsonify({"rtn_code": 404, "message": "规则不存在"})
|
||||
current = dict(row)
|
||||
allowed = {"enabled", "notify_enabled", "auto_unlock", "location_id", "weekday", "time",
|
||||
"kinds", "min_electric", "max_electric", "sort_by", "retry_times"}
|
||||
if not data or not set(data).intersection(allowed):
|
||||
updates = []
|
||||
params = []
|
||||
|
||||
def _truthy(v):
|
||||
return 1 if v in (True, 1, "1", "true") else 0
|
||||
|
||||
if "enabled" in data:
|
||||
updates.append("enabled = ?")
|
||||
params.append(_truthy(data.get("enabled")))
|
||||
if "notify_enabled" in data:
|
||||
updates.append("notify_enabled = ?")
|
||||
params.append(_truthy(data.get("notify_enabled")))
|
||||
if "auto_unlock" in data:
|
||||
updates.append("auto_unlock = ?")
|
||||
params.append(_truthy(data.get("auto_unlock")))
|
||||
|
||||
# 组合校验:任何一个筛选字段变化时,用「现值 + 新值」整体校验一次
|
||||
filter_keys = ("kinds", "min_electric", "max_electric", "sort_by", "retry_times")
|
||||
if any(k in data for k in filter_keys):
|
||||
flt = sub.rule_filters(current)
|
||||
merged = {
|
||||
"location_id": current.get("location_id"),
|
||||
"weekday": current.get("weekday"),
|
||||
"time": "%02d:%02d" % (int(current.get("minute_of_day") or 0) // 60,
|
||||
int(current.get("minute_of_day") or 0) % 60),
|
||||
"kinds": data.get("kinds", flt["kinds"]),
|
||||
"min_electric": data.get("min_electric", flt["min_electric"]),
|
||||
"max_electric": data.get("max_electric", flt["max_electric"]),
|
||||
"sort_by": data.get("sort_by", flt["sort_by"]),
|
||||
"retry_times": data.get("retry_times", flt["retry_times"]),
|
||||
"notify_enabled": True,
|
||||
"auto_unlock": bool(current.get("auto_unlock")),
|
||||
}
|
||||
try:
|
||||
fields = sub.normalize_rule(merged)
|
||||
except ValueError as exc:
|
||||
conn.close()
|
||||
return jsonify({"rtn_code": 400, "message": str(exc)})
|
||||
updates.extend(["kinds = ?", "min_electric = ?", "max_electric = ?",
|
||||
"sort_by = ?", "retry_times = ?"])
|
||||
params.extend([fields["kinds"], fields["min_electric"], fields["max_electric"],
|
||||
fields["sort_by"], fields["retry_times"]])
|
||||
|
||||
if ("time" in data and "weekday" in data) or ("time" in data or "weekday" in data):
|
||||
merged_time = {
|
||||
"location_id": current.get("location_id"),
|
||||
"weekday": data.get("weekday", current.get("weekday")),
|
||||
"time": data.get("time") or "%02d:%02d" % (
|
||||
int(current.get("minute_of_day") or 0) // 60,
|
||||
int(current.get("minute_of_day") or 0) % 60),
|
||||
}
|
||||
try:
|
||||
fields = sub.normalize_rule(merged_time)
|
||||
except ValueError as exc:
|
||||
conn.close()
|
||||
return jsonify({"rtn_code": 400, "message": str(exc)})
|
||||
updates.extend(["weekday = ?", "minute_of_day = ?"])
|
||||
params.extend([fields["weekday"], fields["minute_of_day"]])
|
||||
|
||||
if not updates:
|
||||
conn.close()
|
||||
return jsonify(rtn_code=400, message="没有需要更新的字段"), 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"]))
|
||||
return jsonify({"rtn_code": 400, "message": "没有需要更新的字段"})
|
||||
params.extend([rule_id, user["id"]])
|
||||
conn.execute(f"UPDATE subscribe_rules SET {', '.join(updates)} "
|
||||
f"WHERE id = ? AND user_id = ?", params)
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return jsonify(rtn_code=0, message="规则已更新")
|
||||
return jsonify({"rtn_code": 0, "message": "规则已更新"})
|
||||
|
||||
|
||||
@bp.route("/api/subscribe/rules/<int:rule_id>", methods=["DELETE"])
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
"""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")
|
||||
@@ -6,8 +6,7 @@ $zip = Join-Path $src '1.zip'
|
||||
$pendingZip = Join-Path $src '1.zip.tmp'
|
||||
|
||||
$include = @(
|
||||
'.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',
|
||||
'.gitignore','LICENSE','README.md','app.py','db.py','campus.py','alerts.py','subscribe.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'
|
||||
|
||||
@@ -1,123 +0,0 @@
|
||||
/* Keep the map clear. Secondary tools open only on demand, in the original acrylic material. */
|
||||
[hidden] { display:none!important; }
|
||||
.map-tools-toggle,.discovery-toolbar,.place-results,.legend {
|
||||
background:var(--ui-header-acrylic)!important;
|
||||
border:1px solid var(--ui-line-strong);
|
||||
-webkit-backdrop-filter:blur(24px) saturate(1.4);
|
||||
backdrop-filter:blur(24px) saturate(1.4);
|
||||
box-shadow:var(--ui-shadow-sm);
|
||||
}
|
||||
.map-tools-toggle { position:absolute; z-index:130; top:12px; left:12px; min-height:44px; padding:10px 16px; border-radius:14px; color:var(--ui-ink); font:inherit; font-size:13px; cursor:pointer; }
|
||||
#map-filter-indicator { color:var(--ui-muted); font-size:11px; }
|
||||
.discovery-toolbar { position:absolute; z-index:155; bottom:12px; left:12px; width:min(360px,calc(100% - 24px)); max-height:min(68%,560px); padding:14px; border-radius:20px; overflow-y:auto; overscroll-behavior:contain; color:var(--ui-ink); font-size:13px; }
|
||||
.discovery-heading,.nearby-heading { display:flex; justify-content:space-between; align-items:center; gap:12px; margin-bottom:8px; }
|
||||
.discovery-heading h2 { font-size:17px; letter-spacing:-.3px; font-weight:650; }
|
||||
.discovery-toolbar button,.discovery-toolbar summary,.discovery-toolbar select,.discovery-toolbar input { font:inherit; }
|
||||
.discovery-toolbar button,.discovery-actions summary,.location-status button,.theme-options button,.order-filters button,.order-load-more,.sub-rule button,.preview-settings button {
|
||||
min-height:44px; border:1px solid var(--ui-line); border-radius:10px; padding:8px 12px;
|
||||
background:var(--ui-acrylic-soft); color:var(--ui-ink); cursor:pointer;
|
||||
}
|
||||
.discovery-heading button,.nearby-heading button { border:0; background:transparent; min-width:44px; padding:6px; color:var(--ui-muted); }
|
||||
.place-search-row { display:flex; align-items:center; gap:6px; }
|
||||
.place-search-row input { width:100%; min-width:0; min-height:44px; border:1px solid var(--ui-line-strong); border-radius:11px; padding:10px 12px; background:var(--ui-acrylic-soft); color:var(--ui-ink); font-size:14px; }
|
||||
.place-results { position:relative; margin-top:6px; max-height:150px; overflow-y:auto; border-radius:12px; }
|
||||
.place-results button { width:100%; display:flex; justify-content:space-between; align-items:center; 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; }
|
||||
.discovery-actions { display:flex; align-items:flex-start; gap:8px; margin-top:8px; }
|
||||
.discovery-actions > button { flex:1; }
|
||||
.discovery-actions details { flex:1; }
|
||||
.discovery-actions details[open] { flex-basis:100%; }
|
||||
.discovery-actions:has(details[open]) { flex-wrap:wrap; }
|
||||
.discovery-actions summary { list-style:none; display:flex; justify-content:center; align-items:center; }
|
||||
.discovery-actions summary::-webkit-details-marker { display:none; }
|
||||
.discovery-filter-fields { display:grid; grid-template-columns:1fr 1fr; gap:10px; padding:12px 2px 4px; }
|
||||
.discovery-filter-fields label { display:flex; flex-direction:column; gap:6px; color:var(--ui-muted); font-size:12px; }
|
||||
.discovery-filter-fields .checkbox-label { flex-direction:row; align-items:center; grid-column:1/-1; color:var(--ui-ink); }
|
||||
.discovery-filter-fields input[type=checkbox] { width:18px; height:18px; }
|
||||
.discovery-filter-fields select,.nearby-sort select,.order-filters input,.order-filters select { min-height:44px; min-width:0; width:100%; border:1px solid var(--ui-line); border-radius:9px; padding:8px; background:var(--ui-acrylic-soft); color:var(--ui-ink); }
|
||||
.discovery-origin { width:100%; min-height:32px!important; padding:8px 0!important; border:0!important; background:transparent!important; color:var(--ui-muted)!important; font-size:12px!important; text-align:left; }
|
||||
.discovery-places { border-top:1px solid var(--ui-line); padding-top:4px; }
|
||||
.discovery-places > summary { min-height:36px; color:var(--ui-muted); cursor:pointer; line-height:36px; font-size:12px; }
|
||||
.favorite-places { display:flex; flex-wrap:wrap; gap:6px; padding:4px 0 8px; }
|
||||
.favorite-place { display:flex; border:1px solid var(--ui-line); border-radius:9px; overflow:hidden; }
|
||||
.favorite-place button { border:0; border-radius:0; background:transparent; min-height:36px; padding:6px 9px; }
|
||||
.favorite-place button:last-child { min-width:36px; padding:5px; color:var(--ui-muted); }
|
||||
#favorite-save { min-height:36px; font-size:12px; margin-bottom:6px; }
|
||||
.nearby-panel { display:flex; flex-direction:column; position:static; margin-top:8px; padding-top:10px; border-top:1px solid var(--ui-line); background:transparent; }
|
||||
.nearby-heading { margin-bottom:0; }
|
||||
.nearby-heading h2 { font-size:14px; font-weight:600; }
|
||||
.nearby-summary { color:var(--ui-muted); font-size:11px; line-height:1.6; padding:2px 0 8px; }
|
||||
.nearby-sort { display:flex; align-items:center; gap:10px; padding-bottom:6px; color:var(--ui-muted); font-size:12px; }
|
||||
.nearby-sort select { flex:1; width:auto; }
|
||||
.nearby-list { overflow-y:auto; max-height:210px; overscroll-behavior:contain; }
|
||||
.nearby-row { display:flex; justify-content:space-between; gap:12px; width:100%; padding:11px 0!important; border-width:0 0 1px!important; border-radius:0!important; background:transparent!important; text-align:left; }
|
||||
.nearby-row strong { font-size:14px; font-variant-numeric:tabular-nums; }
|
||||
.nearby-row-meta { display:block; color:var(--ui-muted); font-size:12px; margin-top:4px; }
|
||||
.nearby-row-end { display:flex; flex-direction:column; align-items:flex-end; gap:4px; color:var(--ui-muted); font-size:12px; white-space:nowrap; }
|
||||
.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:12px 0; color:var(--ui-muted); line-height:1.7; }
|
||||
.discovery-empty strong { color:var(--ui-ink); }
|
||||
.discovery-empty button { margin-top:8px; }
|
||||
.location-status { position:static; padding-top:8px; border-top:1px solid var(--ui-line); color:var(--ui-muted); font-size:12px; line-height:1.6; }
|
||||
.location-status-actions { display:flex; gap:8px; margin-top:6px; }
|
||||
.location-status-actions button { min-height:36px; padding:6px 9px; font-size:12px; }
|
||||
.legend { top:12px!important; right:12px!important; bottom:auto!important; }
|
||||
.legend summary { cursor:pointer; min-height:28px; line-height:28px; font-size:12px; color:var(--ui-muted); }
|
||||
.legend:not([open]) .legend-item { display:none; }
|
||||
body:has(#discovery-drawer:not([hidden])) .locate-fab { visibility:hidden; }
|
||||
.header-school-row { display:flex; align-items:center; gap:7px; }
|
||||
.preview-tag { font-size:10px; color:var(--ui-muted); border:1px solid var(--ui-line-strong); border-radius:5px; padding:1px 4px; line-height:1.3; }
|
||||
.preview-entry { display:flex; justify-content:center; gap:10px; align-items:center; color:var(--ui-muted); margin:12px 0 2px; font-size:12px; }
|
||||
.preview-entry button { padding:5px 2px; background:transparent; color:inherit; border:0; cursor:pointer; font:inherit; min-height:32px; }
|
||||
.preview-settings { padding:14px 0; }
|
||||
.preview-settings > div { display:flex; gap:8px; margin-top:8px; }
|
||||
.preview-settings button { flex:1; font:inherit; font-size:13px; }
|
||||
.theme-options { display:flex; gap:8px; padding:10px 0 14px; }
|
||||
.theme-options button { flex:1; font:inherit; font-size:13px; }
|
||||
.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-filters input,.order-filters select { font:inherit; }
|
||||
.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; font:inherit; }
|
||||
.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-acrylic-soft); color:var(--ui-ink); }
|
||||
.settings-page { background:color-mix(in srgb,var(--ui-canvas) 82%,transparent)!important; -webkit-backdrop-filter:blur(32px) saturate(1.3); backdrop-filter:blur(32px) saturate(1.3); }
|
||||
.settings-page .settings-group { background:var(--ui-acrylic-soft)!important; }
|
||||
.bike-card:not(.show) { visibility:hidden; pointer-events:none; }
|
||||
.bike-card.show { visibility:visible; }
|
||||
.battery-unknown .battery-unit { display:none; }
|
||||
.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) {
|
||||
.map-tools-toggle { top:10px; left:10px; padding:9px 14px; border-radius:13px; }
|
||||
.legend { top:10px!important; right:10px!important; padding:6px 10px!important; }
|
||||
.discovery-toolbar { left:10px; bottom:10px; width:calc(100% - 20px); max-height:64%; padding:12px; }
|
||||
.locate-btn.locate-fab { width:44px; height:44px; padding:0; border-radius:50%; bottom:94px; right:12px; }
|
||||
.locate-fab-label { display:none!important; }
|
||||
.nearby-list { max-height:180px; }
|
||||
}
|
||||
@media(prefers-reduced-motion:reduce) { .discovery-toolbar { transition:none; } }
|
||||
|
||||
.discovery-toolbar[data-view=list] > .place-search-wrap,
|
||||
.discovery-toolbar[data-view=list] > .discovery-actions,
|
||||
.discovery-toolbar[data-view=list] > .discovery-origin,
|
||||
.discovery-toolbar[data-view=list] > .discovery-places,
|
||||
.discovery-toolbar[data-view=list] > .location-status { display:none!important; }
|
||||
.discovery-toolbar[data-view=list] .nearby-heading h2 { display:none; }
|
||||
.discovery-toolbar[data-view=list] .nearby-panel { margin-top:0; padding-top:0; border-top:0; }
|
||||
.discovery-toolbar[data-view=list] .nearby-heading { justify-content:flex-start; }
|
||||
.discovery-toolbar[data-view=list] #nearby-close { min-height:32px; padding:3px 0; color:var(--ui-muted); font-size:12px; }
|
||||
@@ -1,114 +0,0 @@
|
||||
/* 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; }
|
||||
@@ -1,32 +0,0 @@
|
||||
/* 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 };
|
||||
})();
|
||||
@@ -1,41 +0,0 @@
|
||||
/* 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);
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,54 +0,0 @@
|
||||
// ========== 启动 ==========
|
||||
// 启动时检查登录状态,然后检查租车
|
||||
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);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -1,198 +0,0 @@
|
||||
/* 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('map-filter-indicator').hidden = !(filters.onlyAvailable || filters.minElectric || filters.kind !== 'all');
|
||||
byId('discovery-origin').textContent = originName || (autoLocationMarker ? '以我的位置查找' : '以地图中心查找');
|
||||
byId('nearby-summary').textContent = `${originName || (autoLocationMarker ? '我的位置' : '地图中心')} · ${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 `<button class="nearby-row" data-bike-id="${escape(row.id)}"><span><strong>#${escape(row.bike.code)}</strong><span class="nearby-row-meta">${k} · ${batteryText(row.electric)}</span></span><span class="nearby-row-end"><span class="vehicle-status ${s}">${BikeData.labels[s]}</span><span>${distance}</span></span></button>`;
|
||||
}).join('') : '<div class="discovery-empty"><strong>这里暂时没有符合条件的车辆</strong><p>可以扩大范围、降低电量要求或切换车型。</p><button type="button" data-relax>放宽筛选条件</button></div>';
|
||||
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 openTools() {
|
||||
byId('discovery-drawer').hidden = false;
|
||||
byId('map-tools-toggle').setAttribute('aria-expanded', 'true');
|
||||
render();
|
||||
}
|
||||
function closeTools(restoreFocus = true) {
|
||||
byId('discovery-drawer').hidden = true;
|
||||
byId('discovery-drawer').dataset.view = 'tools';
|
||||
byId('discovery-title').textContent = '找车';
|
||||
byId('nearby-panel').hidden = true;
|
||||
byId('nearby-toggle').setAttribute('aria-expanded', 'false');
|
||||
byId('map-tools-toggle').setAttribute('aria-expanded', 'false');
|
||||
byId('discovery-filters').open = false;
|
||||
byId('place-results').hidden = true;
|
||||
if (restoreFocus) byId('map-tools-toggle').focus({preventScroll:true});
|
||||
}
|
||||
function showList(open = true) {
|
||||
if (open) { openTools(); byId('discovery-filters').open = false; }
|
||||
byId('nearby-panel').hidden = !open;
|
||||
byId('discovery-drawer').dataset.view = open ? 'list' : 'tools';
|
||||
byId('discovery-title').textContent = open ? '附近车辆' : '找车';
|
||||
byId('nearby-toggle').setAttribute('aria-expanded', String(open));
|
||||
if (open) render();
|
||||
}
|
||||
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 => `<button type="button" data-place-id="${p.id}"><span>${escape(p.name)}</span><small>${p.kind === 'parking' ? '停车点' : '校园地点'}</small></button>`).join('') : '<p class="discovery-empty">未找到地点,可拖动地图后收藏当前位置。</p>';
|
||||
}
|
||||
function renderFavorites() {
|
||||
byId('favorite-places').innerHTML = favorites.length ? favorites.map((p, index) => `<span class="favorite-place"><button type="button" data-favorite="${index}">${escape(p.name)}</button><button type="button" data-remove-favorite="${index}" aria-label="删除常用地点 ${escape(p.name)}">×</button></span>`).join('') : '<span class="discovery-muted">常用地点保存在这台设备</span>';
|
||||
}
|
||||
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, name = "我的位置") {
|
||||
if (!authToken) { showLoginGate(); return; }
|
||||
if (point) { origin = { lat: point.lat, lng: point.lng }; originName = name; }
|
||||
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; closeTools(false); showBikeDetail(row.id);
|
||||
showToast(`${originName || "地图中心"}最近可用:#${row.bike.code},${Math.round(row.distance || 0)} 米,电量 ${row.electric}%`);
|
||||
}
|
||||
async function init() {
|
||||
if (initialized) return;
|
||||
initialized = true; fillControls(); renderFavorites();
|
||||
byId('map-tools-toggle').addEventListener('click', () => { if (byId('discovery-drawer').hidden) openTools(); else closeTools(); });
|
||||
byId('discovery-close').addEventListener('click', () => closeTools());
|
||||
byId('discovery-drawer').addEventListener('keydown', event => { if (event.key === 'Escape') { event.preventDefault(); closeTools(); } });
|
||||
document.addEventListener('pointerdown', event => { if (!byId('discovery-drawer').hidden && !event.target.closest('#discovery-drawer,#map-tools-toggle')) closeTools(false); });
|
||||
['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) { closeTools(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, openTools, closeTools };
|
||||
})();
|
||||
@@ -1,191 +0,0 @@
|
||||
// ========== 订单历史(我的 → 订单历史) ==========
|
||||
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
|
||||
? '<span class="badge muted" style="padding:2px 8px;border-radius:8px;font-size:11px;background:var(--ui-surface-raised);color:var(--ui-muted);">已完成</span>'
|
||||
: '<span class="badge" style="padding:2px 8px;border-radius:8px;font-size:11px;background:var(--ui-surface-raised);color:var(--discovery-available);">进行中</span>';
|
||||
const sharedRow = o.shared
|
||||
? `<div style="margin-top:2px;">${o.role === "owner" ? "共享给" : "使用"} <b>${escHtml(o.partner || "--")}</b> 的车</div>` : "";
|
||||
// 多轮续租合并显示:共 N 轮 · 总用时 · 起止时钟
|
||||
const roundsRow = (o.rounds && o.rounds > 1)
|
||||
? `<div style="margin-top:2px;color:var(--ui-muted);">共 ${o.rounds} 轮 · 总用时 ${fmtDuration(o.duration_seconds)}</div>` : "";
|
||||
const timeRow = `${fmtOrderTime(o.start_time)} → ${fmtOrderTime(o.end_time)}`;
|
||||
return `
|
||||
<div class="device-item" style="display:block;padding:10px 12px;border-bottom:1px solid var(--bg-tertiary,#ececf1);">
|
||||
<div style="display:flex;justify-content:space-between;align-items:center;">
|
||||
<b style="font-size:14px;">#${escHtml(o.bike_code)}</b>
|
||||
<span style="display:flex;align-items:center;gap:6px;">
|
||||
<span style="font-size:12px;color:var(--text-secondary);">${o.duration_seconds !== null ? fmtDuration(o.duration_seconds) : ""}</span>
|
||||
${badge}
|
||||
</span>
|
||||
</div>
|
||||
<div style="font-size:12.5px;color:var(--text-secondary);margin-top:3px;line-height:1.7;">
|
||||
<div>${timeRow}</div>
|
||||
<div>${escHtml(o.start_label || "起点未知")} <span style="margin:0 3px;">→</span> ${escHtml(o.end_label || (o.returned ? "终点未知" : "骑行中"))}</div>
|
||||
${roundsRow}
|
||||
${sharedRow}
|
||||
</div>
|
||||
<div style="margin-top:6px;text-align:right;">
|
||||
<button class="btn" style="padding:4px 10px;border:none;border-radius:8px;font-size:12px;background:#e7f0fd;color:var(--ui-muted);"
|
||||
onclick="openOrderTrajectory(${o.id})">查看轨迹</button>
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
// ========== 订单骑行轨迹 ==========
|
||||
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 = '<div class="device-loading">正在查询记录...</div>'; }
|
||||
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("") : '<div class="device-loading">没有符合条件的订单,可调整日期、车牌或来源后重试。</div>';
|
||||
more.hidden = !data.has_more;
|
||||
} catch (error) {
|
||||
if (serial !== orderHistorySerial) return;
|
||||
if (reset) box.innerHTML = `<div class="device-loading">${escHtml(error.message)},请点击“查询记录”重试。</div>`;
|
||||
else showToast(error.message || "加载失败,请重试");
|
||||
} finally {
|
||||
if (serial === orderHistorySerial) { more.disabled = false; document.getElementById("orders-search").disabled = false; }
|
||||
}
|
||||
}
|
||||
@@ -1,976 +0,0 @@
|
||||
// ========== 订单状态检测 ==========
|
||||
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 = '<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg>';
|
||||
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 = '<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2"><circle cx="5.5" cy="17.5" r="3.5"/><circle cx="18.5" cy="17.5" r="3.5"/><path d="M15 6h3l2 4-2.5 1.5a8 8 0 0 1-7 3.5c-2.5 0-4.5-1.5-5.5-3.5L2 12l4-4h4"/></svg>';
|
||||
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 += '<button class="unlock-src-item" onclick="chooseUnlockSrc(0)"><span>自己的账号</span><span class="tag">自己付费</span></button>';
|
||||
const srcs = d.sources || [];
|
||||
unlockSrcList = srcs.slice();
|
||||
if (srcs.length === 0 && d.hidden_count > 0) {
|
||||
html += '<div class="share-desc">共享者今日次数都已用完,可查看或直接用自己的账号。</div>';
|
||||
}
|
||||
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 += '<button class="unlock-src-item ' + dis + '" onclick="chooseUnlockSrc(' + s.owner_user_id + ')"><span>' + escHtml(label) + '</span><span class="tag">' + escHtml(tagTxt) + '</span></button>';
|
||||
});
|
||||
if (d.hidden_count > 0) {
|
||||
html += '<a class="unlock-src-more" onclick="event.stopPropagation();loadUnlockSrcShowAll()">还有 ' + d.hidden_count + ' 位共享者今日次数已用完(点击查看)</a>';
|
||||
}
|
||||
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(`<div><b style="color:var(--text-primary);">${p.shared ? "共享预览(用车主的卡与轮次)" : "本次用车预览"}</b></div>`);
|
||||
if (p.has_card) {
|
||||
const cardText = (p.cards || []).slice(0, 3).map(c =>
|
||||
`${escHtml(c.name)}${c.remain === null ? "(不限次)" : ` 剩 ${c.remain} 次`}`).join(",");
|
||||
lines.push(`<div>优惠卡:${cardText}${p.card_note ? ` · ${escHtml(p.card_note)}` : ""}</div>`);
|
||||
} else {
|
||||
lines.push(`<div style="color:#c62828;">未检测到优惠卡:本次费用将按小程序计费(还车后需支付)</div>`);
|
||||
}
|
||||
if (p.auto_return) {
|
||||
lines.push(`<div>自动续租:计划 ${p.rounds_planned} 轮 × ${p.duration_minutes} 分钟,预计 ${escHtml(p.est_end_time)} 前还车</div>`);
|
||||
} else {
|
||||
lines.push(`<div>自动还车未开启:本轮 ${p.duration_minutes} 分钟,请留意到期手动还车</div>`);
|
||||
}
|
||||
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 = '<div style="color:var(--text-secondary);">预览加载中...</div>'; }
|
||||
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 =
|
||||
`当前这一轮还剩约 <b>${mins} 分钟</b>,<b>不会延长</b>。<br/>` +
|
||||
`到点后系统会自动:还车 → 用优惠卡支付 → 立刻重新开锁同一辆车,进入下一轮。`;
|
||||
}
|
||||
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 天在主页面挂提醒横幅
|
||||
}
|
||||
});
|
||||
@@ -1,499 +0,0 @@
|
||||
// ========== 用车计时相关 ==========
|
||||
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 脚本已给 <html> 加 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 = '<div style="padding:30px 10px;color:var(--text-secondary);font-size:13px;">二维码生成组件加载失败,<br/>可直接使用下方一键开锁。</div>';
|
||||
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();
|
||||
});
|
||||
@@ -1,345 +0,0 @@
|
||||
// ================= 共享电动车 =================
|
||||
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 =>
|
||||
`<div class="prow"><span>等待接受:<b>${escHtml(p.from_email||'')}</b></span>
|
||||
<span style="display:flex;gap:6px;flex-shrink:0">
|
||||
<button class="share-mini-btn danger" onclick="rejectShareRequest(${p.id})">拒绝</button>
|
||||
<button class="share-mini-btn primary" onclick="acceptShareRequest(${p.id}, '${(p.from_email||'').replace(/'/g,"")}')">接受</button>
|
||||
</span></div>`).join("");
|
||||
const box = document.getElementById("share-pending-box");
|
||||
box.innerHTML = `<div style="font-weight:600;margin-bottom:2px;">待处理的共享申请</div>${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
|
||||
? ('<div class="share-row-state ok">今日可用 ' + u.remaining_today + '/' + u.daily_limit + ' 次 · 对方需有优惠卡' + (u.require_card ? "是" : "否") + '</div>')
|
||||
: ('<div class="share-row-state err">不可用:' + (u.reasons && u.reasons.length ? u.reasons.join(";") : "今日次数已用完") + '</div>');
|
||||
return '<div class="share-row">'
|
||||
+ '<div class="share-row-top"><span class="share-row-email">' + escHtml(uLabel) + '</span></div>'
|
||||
+ state
|
||||
+ '<div class="share-row-btns">'
|
||||
+ '<button class="share-mini-btn primary" onclick="openShareRemark(' + u.share_id + ')">备注</button>'
|
||||
+ '<button class="share-mini-btn danger" onclick="unbindShare(' + u.share_id + ')">解绑</button>'
|
||||
+ '</div></div>';
|
||||
}).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 '<div class="share-row">'
|
||||
+ '<div class="share-row-top"><span class="share-row-email">' + escHtml(sLabel) + '</span>'
|
||||
+ '<span style="font-size:12px;color:var(--text-secondary);flex-shrink:0;">今日已用 ' + sr.rider_used_today + '/' + sr.daily_limit + '</span></div>'
|
||||
+ '<div class="share-row-state">每天 ' + sr.daily_limit + ' 次' + (sr.require_card ? (' · 需我有优惠卡且剩余 ≥ ' + sr.card_min_times) : " · 无卡要求") + '</div>'
|
||||
+ '<div class="share-row-btns">'
|
||||
+ '<button class="share-mini-btn primary" onclick="openShareRemark(' + sr.share_id + ')">备注</button>'
|
||||
+ '<button class="share-mini-btn primary" onclick="openShareConfig(' + sr.share_id + ', ' + sr.daily_limit + ', ' + (sr.require_card ? 1 : 0) + ', ' + sr.card_min_times + ', \'' + String(sr.rider_email || "").replace(/'/g, "") + '\')">修改权限</button>'
|
||||
+ '<button class="share-mini-btn danger" onclick="unbindShare(' + sr.share_id + ')">解绑</button>'
|
||||
+ '</div></div>';
|
||||
}).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 =
|
||||
'给 <b>' + escHtml(shown) + '</b> 起一个昵称备注,仅自己可见;未设置时对 TA 的显示退回邮箱 (<b>' + escHtml(rec.email || "") + '</b>)。';
|
||||
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 = '<span>共享中</span><b style="margin:0 4px;">#' + bike + '</b><span style="opacity:.85;">' + esc + ' 使用中</span>';
|
||||
} else {
|
||||
text = '<span>使用 ' + esc + ' 的车中</span><b style="margin:0 4px;">#' + bike + '</b>';
|
||||
}
|
||||
html += '<div class="share-banner show ' + (isOwner ? "" : "rider") + '">'
|
||||
+ '<div class="share-banner-copy"><div class="share-banner-title">' + text + '</div>'
|
||||
+ '<div class="banner-progress"><span id="share-countdown-' + idx + '">本轮剩余 ' + remainingTimeText(it.remaining_seconds) + '</span>'
|
||||
+ '<span>' + escHtml(rideProgressText(it)) + '</span></div></div>'
|
||||
+ '<button class="share-banner-btn" onclick="openShareReturnByIdx(' + idx + ')">还车</button>'
|
||||
+ '</div>';
|
||||
});
|
||||
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
|
||||
? ('你的共享电动车 <b>#' + bike + '</b> 正被 ' + esc + ' 使用,确认替他/她还车?')
|
||||
: ('你正在使用 <b>' + esc + '</b> 的车 <b>#' + bike + '</b>,确认还车?');
|
||||
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);
|
||||
});
|
||||
@@ -1,96 +0,0 @@
|
||||
// ========== 订阅提醒(编辑、复制与最近执行结果) ==========
|
||||
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 => `<option value="${p.id}">${escHtml(p.name)}</option>`).join("") : '<option value="">管理员尚未配置停车点</option>';
|
||||
} catch (error) { select.innerHTML = '<option value="">加载失败,请返回后重试</option>'; }
|
||||
}
|
||||
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 `<article class="sub-rule"><div class="sub-rule-head"><strong>${escHtml(rule.location_name || "停车点已删除")}</strong><span>${SUB_WEEKDAYS[rule.weekday]} ${time}</span></div><div class="sub-rule-meta">${rule.enabled ? "已启用" : "已停用"} · ${(rule.kind_labels || []).join("/")} · 电量 ${rule.min_electric}-${rule.max_electric}% · ${rule.auto_unlock ? "自动开锁" : "仅提醒"}</div><div class="sub-rule-result">${status}${rule.last_run_at ? " · " + escHtml(rule.last_run_at) : ""}${rule.last_run_message ? "<br>" + escHtml(rule.last_run_message) : ""}</div><div class="sub-rule-actions"><button onclick="editSubscribeRule(${rule.id},false)">编辑</button><button onclick="editSubscribeRule(${rule.id},true)">复制</button><button onclick="toggleSubscribeRule(${rule.id},${rule.enabled ? 0 : 1})">${rule.enabled ? "停用" : "启用"}</button><button class="danger" onclick="deleteSubscribeRule(${rule.id})">删除</button></div></article>`;
|
||||
}
|
||||
async function loadSubscribeRules() {
|
||||
const box = document.getElementById("subscribe-list");
|
||||
box.innerHTML = '<div class="device-loading">正在加载订阅...</div>';
|
||||
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("") : '<div class="device-loading">暂无订阅,可以在下方添加停车点和用车时间。</div>';
|
||||
} catch (error) { box.innerHTML = `<div class="device-loading">${escHtml(error.message)},请返回后重试。</div>`; }
|
||||
}
|
||||
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 || "删除失败"); }
|
||||
});
|
||||
}
|
||||
@@ -1,458 +0,0 @@
|
||||
// ========== 通用确认弹窗(替换 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("<br/>");
|
||||
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 时放行 <a download> 的原生下载
|
||||
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 =>
|
||||
`<h4>${l.v}</h4><ul>${l.items.map(i => `<li>${i}</li>`).join("")}</ul>`
|
||||
).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(button) {
|
||||
button = button || document.querySelector("[data-preview-demo]") || document.getElementById("auth-btn");
|
||||
await doLogin("demo@preview.local", "preview123", document.getElementById("gate-tip"), button);
|
||||
if (currentUser?.email === "demo@preview.local" && typeof SettingsPages !== "undefined") SettingsPages.close();
|
||||
}
|
||||
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 || "创建失败,请重试"); }
|
||||
});
|
||||
}
|
||||
+4069
-61
File diff suppressed because it is too large
Load Diff
@@ -1,67 +0,0 @@
|
||||
/* 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 }); }
|
||||
});
|
||||
});
|
||||
})();
|
||||
@@ -1,19 +0,0 @@
|
||||
(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));
|
||||
})();
|
||||
+3
-19
@@ -414,25 +414,15 @@ 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 rule.get("notify_enabled") and not to_email:
|
||||
record_rule_result(rule["id"], "failed", "未配置提醒邮箱")
|
||||
if not to_email:
|
||||
return False
|
||||
if loc is None:
|
||||
record_rule_result(rule["id"], "failed", "订阅停车点已删除")
|
||||
return False
|
||||
|
||||
flt = rule_filters(rule)
|
||||
@@ -508,11 +498,7 @@ 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)
|
||||
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"
|
||||
return send_email(to_email, f"【小白超人】{title}", plain, html_body)
|
||||
|
||||
# ========== 调度 ==========
|
||||
|
||||
@@ -552,12 +538,10 @@ 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
|
||||
record_rule_result(rule["id"], "failed", "执行失败,请检查凭证有效期和网络后重试")
|
||||
print(f"[订阅提醒] 规则 {rule['id']} 执行失败: {type(e).__name__}")
|
||||
print(f"[订阅提醒] 规则 {rule['id']} 发送失败: {e}")
|
||||
print(f"[订阅提醒] 规则 {rule['id']} 已触发 (user={rule['user_id']}, 发送={ok})")
|
||||
|
||||
|
||||
|
||||
+12
-8
@@ -2,8 +2,7 @@
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
|
||||
<script src="/static/js/ui-preferences.js"></script><script src="/static/js/bike-data.js"></script>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
|
||||
<title>数据分析 - 小白超人</title>
|
||||
<style>
|
||||
:root {
|
||||
@@ -372,7 +371,6 @@
|
||||
}
|
||||
</style>
|
||||
<link rel="stylesheet" href="/static/css/ui-system.css">
|
||||
<link rel="stylesheet" href="/static/css/theme-modes.css">
|
||||
<script defer src="/static/js/ui-motion.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
@@ -735,7 +733,7 @@
|
||||
used: '使用中',
|
||||
locked: '欠压',
|
||||
reserved: '损坏',
|
||||
low: '低电量', unknown: '未知'
|
||||
low: '低电量'
|
||||
};
|
||||
const statusEl = document.getElementById('stat-avail');
|
||||
const statusSub = document.getElementById('stat-status');
|
||||
@@ -811,7 +809,7 @@
|
||||
: (i) => `${String(i).padStart(2, '0')}`;
|
||||
|
||||
// 提取各状态数据
|
||||
const states = ['available', 'used', 'locked', 'reserved', 'low', 'unknown'];
|
||||
const states = ['available', 'used', 'locked', 'reserved', 'low'];
|
||||
const stateData = {};
|
||||
const stateColors = {
|
||||
available: '#34c759',
|
||||
@@ -830,7 +828,7 @@
|
||||
|
||||
// 更新状态汇总(使用24小时平均数据)
|
||||
const summaryEl = document.getElementById('hourly-summary');
|
||||
const stateNames = { available: '可用', used: '使用中', locked: '欠压', reserved: '损坏', low: '低电量', unknown: '未知' };
|
||||
const stateNames = { available: '可用', used: '使用中', locked: '欠压', reserved: '损坏', low: '低电量' };
|
||||
summaryEl.innerHTML = states.map(state => {
|
||||
const avg = avgData?.[state] || 0;
|
||||
return `
|
||||
@@ -850,7 +848,7 @@
|
||||
let total = 0;
|
||||
params.forEach(p => {
|
||||
if (p.value > 0) {
|
||||
const names = { available: '可用', used: '使用中', locked: '欠压', reserved: '损坏', low: '低电量', unknown: '未知' };
|
||||
const names = { available: '可用', used: '使用中', locked: '欠压', reserved: '损坏', low: '低电量' };
|
||||
result += `<span style="display:inline-block;margin-right:4px;border-radius:2px;width:10px;height:10px;background:${p.color};"></span>${names[p.seriesName]}: ${p.value}<br/>`;
|
||||
total += p.value;
|
||||
}
|
||||
@@ -1037,7 +1035,13 @@
|
||||
|
||||
// 根据 state + electric 决定颜色,与 map.html 完全一致
|
||||
function getBikeColor(p) {
|
||||
return {available:'#34c759',inuse:'#ff2d55',locked:'#ff9f0a',reserved:'#5856D6',lowbattery:'#8e8e93',unknown:'#777780'}[BikeData.state(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'; // 可用 绿
|
||||
}
|
||||
|
||||
function doRenderTrajectoryData(data) {
|
||||
|
||||
+47
-66
@@ -2,7 +2,7 @@
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
|
||||
<title>电动车地图</title>
|
||||
<script>
|
||||
// The SDK's async mode needs a callback; its default loader uses document.write.
|
||||
@@ -34,18 +34,14 @@
|
||||
});
|
||||
}
|
||||
</script>
|
||||
<script src="/static/js/ui-preferences.js?v={{ map_asset_version }}"></script>
|
||||
<link rel="stylesheet" href="/static/css/map.css?v={{ map_asset_version }}">
|
||||
<link rel="stylesheet" href="/static/css/bike-clusters.css?v={{ map_asset_version }}">
|
||||
<link rel="stylesheet" href="/static/css/map-settings.css?v={{ map_asset_version }}">
|
||||
<link rel="stylesheet" href="/static/css/ui-system.css?v={{ map_asset_version }}">
|
||||
<link rel="stylesheet" href="/static/css/theme-modes.css?v={{ map_asset_version }}">
|
||||
<link rel="stylesheet" href="/static/css/map-discovery.css?v={{ map_asset_version }}">
|
||||
<script defer src="/static/js/ui-motion.js?v={{ map_asset_version }}"></script>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
|
||||
<!-- 登录态(微信凭据)到期提醒横幅:有效期不足 2 天时显示 -->
|
||||
<div class="auth-expiry-banner" id="auth-expiry-banner" onclick="openAuthModal()">
|
||||
<div class="auth-expiry-banner-left">
|
||||
@@ -126,7 +122,7 @@
|
||||
<div class="header">
|
||||
<div>
|
||||
<div class="header-title">电动车地图</div>
|
||||
<div class="header-school-row"><div class="header-sub" id="school-name">加载中...</div>{% if preview_mode %}<span class="preview-tag">预览</span>{% endif %}</div>
|
||||
<div class="header-sub" id="school-name">加载中...</div>
|
||||
</div>
|
||||
<div class="header-right">
|
||||
<div class="header-badge">
|
||||
@@ -175,33 +171,31 @@
|
||||
<div class="loading-text">正在加载车辆...</div>
|
||||
</div>
|
||||
|
||||
<button type="button" class="map-tools-toggle" id="map-tools-toggle" aria-expanded="false" aria-controls="discovery-drawer">找车<span id="map-filter-indicator" hidden> · 已筛选</span></button>
|
||||
<section class="discovery-toolbar" id="discovery-drawer" aria-labelledby="discovery-title" hidden><div class="discovery-heading"><h2 id="discovery-title">找车</h2><button type="button" id="discovery-close" aria-label="收起找车工具">×</button></div>
|
||||
<div class="place-search-wrap"><label for="place-search" class="sr-only">搜索校园地点</label><div class="place-search-row"><input id="place-search" type="search" placeholder="搜索教学楼、宿舍或停车点" autocomplete="off" maxlength="40"></div><div id="place-results" class="place-results" hidden></div></div>
|
||||
<div class="discovery-actions"><button type="button" id="nearby-toggle" aria-expanded="false" aria-controls="nearby-panel">附近车辆 <span id="nearby-count">0</span></button><details id="discovery-filters"><summary>筛选条件</summary><div class="discovery-filter-fields">
|
||||
<label class="checkbox-label"><input type="checkbox" id="filter-available">仅看可用车辆</label>
|
||||
<label>最低电量<select id="filter-electric"><option value="0">不限(含未知)</option><option value="20">20%</option><option value="40">40%</option><option value="60">60%</option><option value="80">80%</option></select></label>
|
||||
<label>车型<select id="filter-kind"><option value="all">全部车型</option><option value="small">小车</option><option value="big">大车</option><option value="red">红车</option></select></label>
|
||||
<label>列表范围<select id="filter-radius"><option value="200">200 米</option><option value="500">500 米</option><option value="1000">1 公里</option><option value="0">全部范围</option></select></label>
|
||||
</div></details></div>
|
||||
<button type="button" class="discovery-origin" id="discovery-origin" title="重置到我的位置或地图中心">以地图中心查找</button>
|
||||
<details class="discovery-places"><summary>常用地点</summary><div class="favorite-places" id="favorite-places" aria-label="常用地点"></div><button type="button" id="favorite-save">收藏当前地点</button></details>
|
||||
<section class="nearby-panel" id="nearby-panel" aria-labelledby="nearby-title" hidden><div class="nearby-heading"><h2 id="nearby-title">附近车辆</h2><button type="button" id="nearby-close">返回筛选</button></div><p class="nearby-summary" id="nearby-summary" role="status"></p><label class="nearby-sort">排序<select id="nearby-sort"><option value="distance">距离最近</option><option value="electric">电量最高</option></select></label><div class="nearby-list" id="nearby-list"></div></section>
|
||||
<div id="location-status" class="location-status" role="status" hidden><span id="location-message"></span><div class="location-status-actions"><button type="button" id="location-retry" hidden>定位我的位置</button><button type="button" id="location-center">按地图中心找车</button></div></div>
|
||||
</section>
|
||||
<details class="legend">
|
||||
<summary>状态图例</summary>
|
||||
<div class="stats-card">
|
||||
<button class="stats-analysis-btn" onclick="uiNavigate('/analysis.html')">
|
||||
<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<path d="M3 3v18h18"/>
|
||||
<path d="M18 17V9"/>
|
||||
<path d="M13 17V5"/>
|
||||
<path d="M8 17v-3"/>
|
||||
</svg>
|
||||
数据分析
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="legend">
|
||||
<div class="legend-title">状态图例</div>
|
||||
<div class="legend-item"><div class="legend-ring available"></div><span class="legend-text">可用 <span id="count-available">0</span></span></div>
|
||||
<div class="legend-item"><div class="legend-ring used"></div><span class="legend-text">使用中 <span id="count-used">0</span></span></div>
|
||||
<div class="legend-item"><div class="legend-ring locked"></div><span class="legend-text">欠压 <span id="count-locked">0</span></span></div>
|
||||
<div class="legend-item"><div class="legend-ring reserved"></div><span class="legend-text">损坏 <span id="count-reserved">0</span></span></div>
|
||||
<div class="legend-item"><div class="legend-ring low"></div><span class="legend-text">低电量 <span id="count-low">0</span></span></div>
|
||||
</details>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 底部扫码栏 -->
|
||||
<div class="scan-bar">
|
||||
<label for="scan-input" class="sr-only">输入5位或8位车牌号</label><input class="scan-input" id="scan-input" type="text" inputmode="numeric" pattern="(?:[0-9]{5}|[0-9]{8})" maxlength="8" placeholder="5位或8位车牌号" autocomplete="off" />
|
||||
<input class="scan-input" id="scan-input" type="number" pattern="[0-9]*" maxlength="5" placeholder="输入5位车牌号" />
|
||||
<button class="scan-btn" onclick="scanCode()">查询</button>
|
||||
</div>
|
||||
|
||||
@@ -211,14 +205,14 @@
|
||||
<div class="auth-content">
|
||||
<div class="auth-header">
|
||||
<span>登录</span>
|
||||
<button class="auth-close" aria-label="关闭窗口" onclick="closeLoginModal()">✕</button>
|
||||
<button class="auth-close" onclick="closeLoginModal()">✕</button>
|
||||
</div>
|
||||
<form id="login-form" onsubmit="handleLoginSubmit(event)">
|
||||
<div class="auth-field">
|
||||
<input type="email" aria-label="邮箱" autocomplete="email" id="login-email" placeholder="邮箱" required />
|
||||
<input type="email" id="login-email" placeholder="邮箱" required />
|
||||
</div>
|
||||
<div class="auth-field">
|
||||
<input type="password" aria-label="密码" autocomplete="current-password" id="login-password" placeholder="密码" required />
|
||||
<input type="password" id="login-password" placeholder="密码" required />
|
||||
</div>
|
||||
<div class="auth-tip" id="login-tip"></div>
|
||||
<button type="submit" class="auth-submit">登录</button>
|
||||
@@ -233,7 +227,7 @@
|
||||
<div class="auth-content">
|
||||
<div class="auth-header">
|
||||
<span>注册</span>
|
||||
<button class="auth-close" aria-label="关闭窗口" onclick="closeRegisterModal()">✕</button>
|
||||
<button class="auth-close" onclick="closeRegisterModal()">✕</button>
|
||||
</div>
|
||||
<form id="register-form" onsubmit="handleRegisterSubmit(event)">
|
||||
<div class="auth-field">
|
||||
@@ -310,7 +304,7 @@
|
||||
填写 Token ID 后可查看更多信息;AccessToken 选填(强验证模式下必填)
|
||||
</div>
|
||||
|
||||
<h2 class="settings-section-title">外观</h2><div class="theme-options" aria-label="界面主题"><button type="button" data-theme-choice="light" onclick="UIPreferences.set('light')">浅色</button><button type="button" data-theme-choice="dark" onclick="UIPreferences.set('dark')">深色</button><button type="button" data-theme-choice="system" onclick="UIPreferences.set('system')">跟随系统</button></div><h2 class="settings-section-title">地图显示</h2>
|
||||
<h2 class="settings-section-title">地图显示</h2>
|
||||
<div class="settings-group">
|
||||
<label class="map-setting-row" for="settings-clustering">
|
||||
<span class="map-setting-copy"><strong>车辆聚类</strong><span id="settings-cluster-description">合并附近车辆,让地图更清晰;关闭后始终显示单车。</span></span>
|
||||
@@ -332,7 +326,7 @@
|
||||
<button class="settings-link-row" onclick="openAuthModal()"><span class="map-setting-copy"><strong>微信凭证</strong><span>更新凭证与告警接收邮箱</span></span><span class="settings-chevron" aria-hidden="true">›</span></button>
|
||||
<button class="settings-link-row" onclick="openDevicesModal()"><span class="map-setting-copy"><strong>登录设备</strong><span>查看和管理已登录的设备</span></span><span class="settings-chevron" aria-hidden="true">›</span></button>
|
||||
</div>
|
||||
<button class="settings-link-row" onclick="openVersionModal()"><span class="map-setting-copy"><strong>版本与使用说明</strong><span>查看更新记录与找车帮助</span></span><span aria-hidden="true">›</span></button><button class="settings-link-row" onclick="uiNavigate('/analysis.html')"><span class="map-setting-copy"><strong>数据分析</strong><span>查看车辆分布与历史趋势</span></span><span class="settings-chevron" aria-hidden="true">›</span></button>{% if preview_mode %}<div class="preview-settings"><span class="devices-tip">预览体验</span><div><button type="button" data-preview-demo onclick="previewLogin(this)">演示数据</button><button type="button" onclick="createPreviewSession()">真实接口测试</button></div></div>{% endif %}<button class="settings-logout" onclick="handleLogout()">退出登录</button>
|
||||
<button class="settings-logout" onclick="handleLogout()">退出登录</button>
|
||||
</section>
|
||||
<!-- 账户功能子页面:统一标题、滚动区域与返回路径 -->
|
||||
<section class="settings-view" id="rental-settings-modal" hidden>
|
||||
@@ -367,7 +361,7 @@
|
||||
<section class="settings-view" id="auth-modal" hidden>
|
||||
<div class="settings-view-content">
|
||||
<div class="auth-desc">
|
||||
从微信小程序获取 Token ID 和 AccessToken,保存前会验证凭证。
|
||||
从微信小程序抓包获取 hsf-x-tokenid 和 hsf-x-signature
|
||||
</div>
|
||||
<div class="profile-section">
|
||||
<label class="profile-label">告警接收邮箱(凭据 1 天/1 小时过期、已过期时提醒,留空用账号邮箱)</label>
|
||||
@@ -405,10 +399,10 @@
|
||||
</section>
|
||||
<section class="settings-view" id="orders-modal" hidden>
|
||||
<div class="settings-view-content" style="width:400px;max-width:94%;display:flex;flex-direction:column;">
|
||||
<form class="order-filters" id="orders-filter-form" onsubmit="event.preventDefault(); loadOrderPage(true)"><label>开始日期<input id="orders-from" type="date"></label><label>结束日期<input id="orders-to" type="date"></label><label>车牌号<input id="orders-code" type="text" inputmode="numeric" maxlength="8" placeholder="输入完整或部分车牌"></label><label>订单来源<select id="orders-source"><option value="all">全部订单</option><option value="own">本人用车</option><option value="shared">共享用车</option></select></label><div class="order-filter-actions"><button type="submit" id="orders-search">查询记录</button><button type="button" onclick="resetOrderFilters()">重置</button></div></form><div class="devices-tip" id="orders-summary">最近的真实用车记录(含共享)</div>
|
||||
<div class="devices-tip" id="orders-summary">最近的真实用车记录(含共享)</div>
|
||||
<div class="devices-list" id="orders-list" style="min-height:120px;max-height:60vh;overflow:auto;">
|
||||
<div class="device-loading">加载中...</div>
|
||||
</div><button class="order-load-more" id="orders-more" onclick="loadOrderPage(false)" hidden>加载更多</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<section class="settings-view" id="order-traj-modal" hidden>
|
||||
@@ -425,15 +419,15 @@
|
||||
<div class="devices-tip">定时查看某停车点附近的车辆并发邮件;勾选自动开锁可在命中时直接帮你开锁。每账号最多 5 条规则。</div>
|
||||
<div id="subscribe-list" style="min-height:80px;max-height:34vh;overflow:auto;"></div>
|
||||
<div style="border-top:1px solid var(--bg-tertiary,#e5e5ea);margin-top:10px;padding-top:10px;">
|
||||
<div class="sub-editor-heading"><strong id="sub-editor-title">新增规则</strong><button type="button" id="sub-cancel-edit" onclick="resetSubscribeEditor()" hidden>取消编辑</button></div>
|
||||
<div class="profile-label" style="font-weight:600;margin-bottom:6px;">新增规则</div>
|
||||
<div style="display:flex;gap:8px;flex-wrap:wrap;">
|
||||
<select aria-label="订阅停车点" id="sub-location" style="flex:2;min-width:120px;padding:8px;border:1px solid var(--bg-tertiary,#e5e5ea);border-radius:8px;"></select>
|
||||
<select aria-label="订阅星期" id="sub-weekday" style="flex:1;min-width:80px;padding:8px;border:1px solid var(--bg-tertiary,#e5e5ea);border-radius:8px;">
|
||||
<select id="sub-location" style="flex:2;min-width:120px;padding:8px;border:1px solid var(--bg-tertiary,#e5e5ea);border-radius:8px;"></select>
|
||||
<select id="sub-weekday" style="flex:1;min-width:80px;padding:8px;border:1px solid var(--bg-tertiary,#e5e5ea);border-radius:8px;">
|
||||
<option value="1">周一</option><option value="2">周二</option><option value="3">周三</option>
|
||||
<option value="4">周四</option><option value="5">周五</option><option value="6">周六</option>
|
||||
<option value="7">周日</option><option value="0">每天</option>
|
||||
</select>
|
||||
<input type="time" aria-label="订阅时间" id="sub-time" value="11:55" style="flex:1;min-width:90px;padding:8px;border:1px solid var(--bg-tertiary,#e5e5ea);border-radius:8px;" />
|
||||
<input type="time" id="sub-time" value="11:55" style="flex:1;min-width:90px;padding:8px;border:1px solid var(--bg-tertiary,#e5e5ea);border-radius:8px;" />
|
||||
</div>
|
||||
|
||||
<div style="margin-top:10px;font-size:13px;">
|
||||
@@ -478,7 +472,7 @@
|
||||
<label style="display:flex;align-items:center;gap:5px;"><input type="checkbox" id="sub-auto" /> 帮我自动开锁</label>
|
||||
</div>
|
||||
<div class="devices-tip" style="margin-top:6px;">「帮我自动开锁」:到了你设的时间,系统按上面的条件挑一辆最合适的车直接开锁,结果邮件通知你;如果那辆车刚好被别人骑走,会自动换下一辆再试。</div>
|
||||
<button class="auth-submit" style="margin-top:10px;" id="sub-save" onclick="addSubscribeRule()">添加规则</button>
|
||||
<button class="auth-submit" style="margin-top:10px;" onclick="addSubscribeRule()">添加规则</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
@@ -545,7 +539,7 @@
|
||||
<div class="auth-content download-tip-content">
|
||||
<div class="auth-header">
|
||||
<span>请在浏览器中打开下载</span>
|
||||
<button class="auth-close" aria-label="关闭窗口" onclick="closeExportTipModal()">✕</button>
|
||||
<button class="auth-close" onclick="closeExportTipModal()">✕</button>
|
||||
</div>
|
||||
<div class="download-tip-desc" id="export-tip-desc">
|
||||
当前浏览器无法直接下载文件,请复制下面的链接到系统浏览器打开(1 小时内有效,换浏览器也可用)。
|
||||
@@ -564,7 +558,7 @@
|
||||
<div class="auth-content download-tip-content">
|
||||
<div class="auth-header">
|
||||
<span id="download-tip-title">请在电脑上下载安装</span>
|
||||
<button class="auth-close" aria-label="关闭窗口" onclick="closeDownloadTipModal()">✕</button>
|
||||
<button class="auth-close" onclick="closeDownloadTipModal()">✕</button>
|
||||
</div>
|
||||
<div class="download-tip-desc" id="download-tip-desc">
|
||||
安装包为 Windows 程序,请复制下面的链接到电脑浏览器打开下载。
|
||||
@@ -718,7 +712,7 @@
|
||||
<div class="card-overlay" id="card-overlay" onclick="closeCard()"></div>
|
||||
|
||||
<!-- 车辆详情卡片 -->
|
||||
<div class="bike-card" id="bike-card" role="dialog" aria-label="车辆详情" aria-hidden="true" inert>
|
||||
<div class="bike-card" id="bike-card">
|
||||
<div class="card-handle"></div>
|
||||
<div class="bike-card-header">
|
||||
<div class="bike-card-title">
|
||||
@@ -730,7 +724,7 @@
|
||||
<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><path d="M21 21l-4.35-4.35"/></svg>
|
||||
<span>寻车</span>
|
||||
</button>
|
||||
<button class="bike-card-close" aria-label="关闭车辆详情" onclick="closeCard()">✕</button>
|
||||
<button class="bike-card-close" onclick="closeCard()">✕</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -747,7 +741,7 @@
|
||||
<rect id="battery-fill" x="3" y="5" width="0" height="16" rx="2" fill="#34c759"/>
|
||||
</svg>
|
||||
</div>
|
||||
<span class="battery-label"><span id="card-electric">--</span><span class="battery-unit">%</span></span>
|
||||
<span class="battery-label"><span id="card-electric">--</span>%</span>
|
||||
</div>
|
||||
<!-- 状态 -->
|
||||
<div class="bike-status-wrap">
|
||||
@@ -808,7 +802,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="toast" id="toast" role="status" aria-live="polite" aria-atomic="true"></div>
|
||||
<div class="toast" id="toast"></div>
|
||||
|
||||
<!-- 忘记密码弹窗 -->
|
||||
<div class="auth-modal" id="forgot-modal">
|
||||
@@ -816,7 +810,7 @@
|
||||
<div class="auth-content">
|
||||
<div class="auth-header">
|
||||
<span>重置密码</span>
|
||||
<button class="auth-close" aria-label="关闭窗口" onclick="closeForgotModal()">✕</button>
|
||||
<button class="auth-close" onclick="closeForgotModal()">✕</button>
|
||||
</div>
|
||||
<form id="forgot-form" onsubmit="handleForgotSubmit(event)">
|
||||
<div class="auth-field">
|
||||
@@ -856,24 +850,23 @@
|
||||
<div class="login-gate-title">电动车地图</div>
|
||||
<div class="login-gate-sub">登录后查看校园车辆实时分布</div>
|
||||
<form id="gate-login-form">
|
||||
<div class="auth-field"><input type="email" aria-label="邮箱" autocomplete="email" id="gate-email" placeholder="邮箱" required /></div>
|
||||
<div class="auth-field"><input type="password" aria-label="密码" autocomplete="current-password" id="gate-password" placeholder="密码" required /></div>
|
||||
<div class="auth-field"><input type="email" id="gate-email" placeholder="邮箱" required /></div>
|
||||
<div class="auth-field"><input type="password" id="gate-password" placeholder="密码" required /></div>
|
||||
<div class="auth-tip" id="gate-tip"></div>
|
||||
<button type="submit" class="auth-submit">登录</button>
|
||||
</form>
|
||||
{% if preview_mode %}<div class="preview-entry"><button type="button" data-preview-demo onclick="previewLogin(this)">演示体验</button><span>·</span><button type="button" onclick="createPreviewSession()">真实接口测试</button></div>{% endif %}
|
||||
<div class="login-gate-footer">没有账号?<a href="#" onclick="showRegisterModal(); return false;">注册</a> · <a href="#" onclick="showForgotFromGate(); return false;">忘记密码</a></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 找最近的车:独立悬浮按钮(右下角,手机端仅图标) -->
|
||||
<button class="locate-btn locate-fab" id="locate-btn" aria-label="查找最近的可用车辆" onclick="findNearestBikeManual()">
|
||||
<button class="locate-btn locate-fab" id="locate-btn" onclick="findNearestBikeManual()">
|
||||
<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="3"/><path d="M12 2v4m0 12v4M2 12h4m12 0h4"/></svg>
|
||||
<span class="locate-fab-label">找最近</span>
|
||||
<span class="locate-fab-label">找最近的车</span>
|
||||
</button>
|
||||
|
||||
<!-- 版本号标识 -->
|
||||
|
||||
<div class="version-badge" id="version-badge" onclick="openVersionModal()">v1.6.0</div>
|
||||
|
||||
<!-- 版本更新说明弹窗 -->
|
||||
<div class="auth-modal" id="version-modal">
|
||||
@@ -881,7 +874,7 @@
|
||||
<div class="auth-content">
|
||||
<div class="auth-header">
|
||||
<span>版本更新说明</span>
|
||||
<button class="auth-close" aria-label="关闭窗口" onclick="closeVersionModal()">✕</button>
|
||||
<button class="auth-close" onclick="closeVersionModal()">✕</button>
|
||||
</div>
|
||||
<div class="version-log" id="version-content"></div>
|
||||
</div>
|
||||
@@ -915,7 +908,7 @@
|
||||
<div class="auth-content">
|
||||
<div class="auth-header">
|
||||
<span>选择开锁账号</span>
|
||||
<button class="auth-close" aria-label="关闭窗口" onclick="closeUnlockSrc()">✕</button>
|
||||
<button class="auth-close" onclick="closeUnlockSrc()">✕</button>
|
||||
</div>
|
||||
<div class="share-desc">选择使用谁的账号开锁(使用他人共享需其在线且次数可用,费用由其承担)</div>
|
||||
<div id="unlock-src-list"></div>
|
||||
@@ -929,7 +922,7 @@
|
||||
<div class="auth-content">
|
||||
<div class="auth-header">
|
||||
<span>还车确认</span>
|
||||
<button class="auth-close" aria-label="关闭窗口" onclick="closeShareReturnModal()">✕</button>
|
||||
<button class="auth-close" onclick="closeShareReturnModal()">✕</button>
|
||||
</div>
|
||||
<div class="share-desc" id="share-return-text">确定结束该共享订单吗?</div>
|
||||
<button class="auth-submit" onclick="confirmShareReturn()">确认还车</button>
|
||||
@@ -946,19 +939,7 @@
|
||||
|
||||
<script defer src="/static/js/bike-clusters.js?v={{ map_asset_version }}"></script>
|
||||
<script defer src="/static/js/settings-pages.js?v={{ map_asset_version }}"></script>
|
||||
<script defer src="/static/js/bike-data.js?v={{ map_asset_version }}"></script>
|
||||
<script defer src="/static/js/api-client.js?v={{ map_asset_version }}"></script>
|
||||
<script defer src="/static/js/ui-dialogs.js?v={{ map_asset_version }}"></script>
|
||||
<script defer src="/static/js/map.js?v={{ map_asset_version }}"></script>
|
||||
<script defer src="/static/js/map-account.js?v={{ map_asset_version }}"></script>
|
||||
<script defer src="/static/js/map-orders.js?v={{ map_asset_version }}"></script>
|
||||
<script defer src="/static/js/map-history.js?v={{ map_asset_version }}"></script>
|
||||
<script defer src="/static/js/map-subscriptions.js?v={{ map_asset_version }}"></script>
|
||||
<script defer src="/static/js/map-rental.js?v={{ map_asset_version }}"></script>
|
||||
<script defer src="/static/js/map-utils.js?v={{ map_asset_version }}"></script>
|
||||
<script defer src="/static/js/map-sharing.js?v={{ map_asset_version }}"></script>
|
||||
<script defer src="/static/js/map-discovery.js?v={{ map_asset_version }}"></script>
|
||||
<script defer src="/static/js/map-boot.js?v={{ map_asset_version }}"></script>
|
||||
|
||||
<!-- 还车确认弹窗 -->
|
||||
<div class="return-confirm-modal" id="return-confirm-modal">
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
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');
|
||||
@@ -1,27 +0,0 @@
|
||||
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);
|
||||
});
|
||||
@@ -1,35 +0,0 @@
|
||||
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);
|
||||
});
|
||||
@@ -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", "unknown"}
|
||||
check("stats 桶含6状态", set(r["hourly_distribution"]["08"].keys()) == expected_states)
|
||||
expected_states = {"available", "used", "locked", "reserved", "low"}
|
||||
check("stats 桶含5状态", 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("{{", "{").replace("}}", "}")
|
||||
'''.replace("{root}", str(ROOT).replace("\\", "\\\\"))
|
||||
|
||||
|
||||
def test_history_30d_contract():
|
||||
|
||||
@@ -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 = require('./frontend-source.cjs');
|
||||
const source = fs.readFileSync(path.join(__dirname, '../static/js/map.js'), 'utf8');
|
||||
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,7 +29,6 @@ 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);
|
||||
|
||||
@@ -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 = require('./frontend-source.cjs');
|
||||
const source = fs.readFileSync(path.join(__dirname, '../static/js/map.js'), 'utf8');
|
||||
|
||||
async function environment({ dependencies = true } = {}) {
|
||||
const elements = new Map(), requests = [], notices = [], events = {};
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
"""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
|
||||
@@ -4,8 +4,10 @@ import unittest
|
||||
|
||||
class RingAllFrontendAuthTests(unittest.TestCase):
|
||||
def test_ring_all_request_sends_session_token(self):
|
||||
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]
|
||||
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]
|
||||
|
||||
self.assertIn('"Authorization": `Bearer ${authToken}`', request_block)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user