Compare commits
29
Commits
preview
...
44efe5f4f4
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
44efe5f4f4 | ||
|
|
8ece55983a | ||
|
|
f8db1240b1 | ||
|
|
30592cc07d | ||
|
|
be016621c0 | ||
|
|
5d615bb359 | ||
|
|
d34b5bc375 | ||
|
|
6847482447 | ||
|
|
32d3b8d426 | ||
|
|
33df0b0b11 | ||
|
|
c6531ba8e3 | ||
|
|
c1014ff912 | ||
|
|
246f81137a | ||
|
|
9bdef68650 | ||
|
|
9b1aac9942 | ||
|
|
7181973c1f | ||
|
|
57eae3ac82 | ||
|
|
ff80c31b04 | ||
|
|
e01bd67cd8 | ||
|
|
e51d77d42a | ||
|
|
75f040d90a | ||
|
|
bd147e9f4b | ||
|
|
d4bedb30e0 | ||
|
|
bec9a19b32 | ||
|
|
bd41866a3d | ||
|
|
be3c8f775e | ||
|
|
e3a8df65f1 | ||
|
|
8fa8847384 | ||
|
|
f0537e446b |
@@ -0,0 +1,18 @@
|
|||||||
|
# 统一行尾:仓库内容一律 LF,检出也保持 LF。
|
||||||
|
# 编辑器(Windows)往文件里写 CRLF 时,git 会在提交时归一化,
|
||||||
|
# 不会再出现"改一行、diff 一万行"的情况。
|
||||||
|
* text=auto eol=lf
|
||||||
|
|
||||||
|
# 二进制:不要做任何文本转换
|
||||||
|
*.png binary
|
||||||
|
*.jpg binary
|
||||||
|
*.jpeg binary
|
||||||
|
*.ico binary
|
||||||
|
*.exe binary
|
||||||
|
*.zip binary
|
||||||
|
*.db binary
|
||||||
|
*.db-wal binary
|
||||||
|
*.db-shm binary
|
||||||
|
*.pem binary
|
||||||
|
*.crt binary
|
||||||
|
*.key binary
|
||||||
+21
@@ -12,3 +12,24 @@ server_config.json
|
|||||||
.reasonix/
|
.reasonix/
|
||||||
*.zip
|
*.zip
|
||||||
*.log
|
*.log
|
||||||
|
temp/
|
||||||
|
.pytest_cache/
|
||||||
|
*.db-wal
|
||||||
|
*.db-shm
|
||||||
|
downloads/*.exe
|
||||||
|
token_config.txt.old-bak
|
||||||
|
scripts/.pack_baseline.json
|
||||||
|
update.zip
|
||||||
|
# ===== 敏感文件:证书 / 私钥 / 凭据一律不进库 =====
|
||||||
|
*.pem
|
||||||
|
*.key
|
||||||
|
*.crt
|
||||||
|
*.ca-bundle
|
||||||
|
token_config.txt
|
||||||
|
*.db
|
||||||
|
artifacts/
|
||||||
|
walk_cache.db
|
||||||
|
|
||||||
|
# 前端构建(TS 重写)
|
||||||
|
node_modules/
|
||||||
|
static/dist/*.map
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
- **历史轨迹**:记录每辆车的位置历史,支持按车牌查询轨迹
|
- **历史轨迹**:记录每辆车的位置历史,支持按车牌查询轨迹
|
||||||
- **数据分析**:状态分布、24 小时趋势、活跃车辆 Top10、热力图
|
- **数据分析**:状态分布、24 小时趋势、活跃车辆 Top10、热力图
|
||||||
- **租赁管理**:订单到期倒计时,邮件提醒(10/5/3/2/1/0 分钟多级通知)
|
- **租赁管理**:订单到期倒计时,邮件提醒(10/5/3/2/1/0 分钟多级通知)
|
||||||
- **自动清理**:3 天前历史数据自动归档,定期 VACUUM 释放空间
|
- **自动清理**:30 天前历史数据自动归档,定期 VACUUM 释放空间
|
||||||
|
|
||||||
## 技术栈
|
## 技术栈
|
||||||
|
|
||||||
@@ -19,7 +19,7 @@
|
|||||||
- **数据源**:微信小程序接口(需用户授权 `token_id` + `wx_signature`)
|
- **数据源**:微信小程序接口(需用户授权 `token_id` + `wx_signature`)
|
||||||
- **采集调度**:threading 后台线程 + 自适应间隔
|
- **采集调度**:threading 后台线程 + 自适应间隔
|
||||||
- **通知**:SMTP 邮件 + 内部计时器
|
- **通知**:SMTP 邮件 + 内部计时器
|
||||||
- **前端**:Jinja2 模板 + Leaflet 地图 + ECharts 图表
|
- **前端**:Jinja2 模板 + 百度地图 JS API GL(BMapGL)+ ECharts 图表
|
||||||
|
|
||||||
## 项目结构
|
## 项目结构
|
||||||
|
|
||||||
@@ -42,6 +42,12 @@ xbniu_map/
|
|||||||
│ ├── admin.html # 后台管理页
|
│ ├── admin.html # 后台管理页
|
||||||
│ └── ring_progress.html # 状态环形图组件
|
│ └── ring_progress.html # 状态环形图组件
|
||||||
├── static/ # 地图标记图标(分色)
|
├── static/ # 地图标记图标(分色)
|
||||||
|
│ └── js/
|
||||||
|
│ ├── map.js # 主逻辑(地图/定位/订单/卡片/登录等)
|
||||||
|
│ ├── navigation.js # 跟随式导航 + 步行距离精算
|
||||||
|
│ ├── share.js # 共享电动车
|
||||||
|
│ ├── subscribe.js # 车辆订阅
|
||||||
|
│ └── bike-clusters.js# 车辆聚类
|
||||||
└── requirements.txt
|
└── requirements.txt
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -127,7 +133,7 @@ def get_adaptive_interval():
|
|||||||
|
|
||||||
### 数据清理
|
### 数据清理
|
||||||
|
|
||||||
每 23 小时执行一次:删除 3 天前的 `bike_history` 与过期 `sessions`,并执行 `VACUUM` 压缩 SQLite 文件。
|
每 23 小时执行一次:删除 30 天前的 `bike_history` 与过期 `sessions`,并执行 `VACUUM` 压缩 SQLite 文件。
|
||||||
|
|
||||||
### 订单到期提醒
|
### 订单到期提醒
|
||||||
|
|
||||||
|
|||||||
@@ -59,8 +59,16 @@ def set_alert_emails(emails) -> int:
|
|||||||
return len(cleaned)
|
return len(cleaned)
|
||||||
|
|
||||||
|
|
||||||
# ========== 去重记录 ==========
|
# 老版本 users 表的 token_id 列带 DEFAULT '1291378',注册时没写这一列的用户
|
||||||
# 免打扰策略(用户要求):同一凭据在整个生命周期内【只发一封】邮件——
|
# 就被灌了这个假凭据。它不可能来自真实授权,所有告警检查都要跳过。
|
||||||
|
LEGACY_DEFAULT_TOKEN_ID = "1291378"
|
||||||
|
|
||||||
|
|
||||||
|
def _is_legacy_default_token(token_id) -> bool:
|
||||||
|
return str(token_id or "").strip() == LEGACY_DEFAULT_TOKEN_ID
|
||||||
|
|
||||||
|
|
||||||
|
# ========== 去重记录 ==========# 免打扰策略(用户要求):同一凭据在整个生命周期内【只发一封】邮件——
|
||||||
# 不管命中的是 1天/1小时/已过期 哪一级。credential_alerts.target 含
|
# 不管命中的是 1天/1小时/已过期 哪一级。credential_alerts.target 含
|
||||||
# 凭据标识(用户 id 或 全局+过期时间戳),用户更新凭据后 target 变化
|
# 凭据标识(用户 id 或 全局+过期时间戳),用户更新凭据后 target 变化
|
||||||
# 才会重新武装。查询时【不看 level】,避免 1day→1hour→expired 连发三封。
|
# 才会重新武装。查询时【不看 level】,避免 1day→1hour→expired 连发三封。
|
||||||
@@ -69,8 +77,16 @@ def _now_bj_str():
|
|||||||
|
|
||||||
|
|
||||||
def _sent_already(conn, target, level=None):
|
def _sent_already(conn, target, level=None):
|
||||||
"""该凭据是否已发过提醒邮件(level 仅保留兼容签名,不再参与过滤)。"""
|
"""该凭据是否已发过这一级别的提醒邮件。
|
||||||
|
|
||||||
|
免打扰口径:同一凭据(target 里带凭据指纹/过期时间)在 1天/1小时 之间只发一封,
|
||||||
|
但 **expired 单独放行一封** —— 否则“还剩 1 天”那封被划掉就再也没有第二次机会。
|
||||||
|
"""
|
||||||
try:
|
try:
|
||||||
|
if level == "expired":
|
||||||
|
return conn.execute(
|
||||||
|
"SELECT 1 FROM credential_alerts WHERE target = ? AND level = 'expired' LIMIT 1",
|
||||||
|
(target,)).fetchone() is not None
|
||||||
return conn.execute(
|
return conn.execute(
|
||||||
"SELECT 1 FROM credential_alerts WHERE target = ? LIMIT 1",
|
"SELECT 1 FROM credential_alerts WHERE target = ? LIMIT 1",
|
||||||
(target,)).fetchone() is not None
|
(target,)).fetchone() is not None
|
||||||
@@ -120,24 +136,33 @@ def _send_alert(recipients, level, owner_desc, expiry):
|
|||||||
if level == "expired" and not expiry.get("parseable", True):
|
if level == "expired" and not expiry.get("parseable", True):
|
||||||
# 未填 AccessToken 的凭据:通过上游探测发现已失效,无法给出过期时刻
|
# 未填 AccessToken 的凭据:通过上游探测发现已失效,无法给出过期时刻
|
||||||
lead = ("凭据已失效(探测到上游已拒绝该 Token),该账号的开锁/还车/地图数据"
|
lead = ("凭据已失效(探测到上游已拒绝该 Token),该账号的开锁/还车/地图数据"
|
||||||
"已不可用,请立即在小程序重新登录并更新凭据。"
|
"已不可用,请到个人中心重新获取并保存凭据。")
|
||||||
"提示:打开一次微信小程序就会使网页凭据失效。")
|
|
||||||
elif level == "expired":
|
elif level == "expired":
|
||||||
lead = "凭据已过期,该账号的上游接口(地图/开锁/还车/订单检测)已全部失效,请立即在小程序重新登录并更新凭据。"
|
lead = "凭据已过期,该账号的上游接口(地图/开锁/还车/订单检测)已全部失效,请到个人中心更新凭据。"
|
||||||
elif level == "1hour":
|
elif level == "1hour":
|
||||||
lead = "凭据将在约 1 小时后过期,请尽快在小程序重新登录更新,避免用车高峰失效。"
|
lead = "凭据将在约 1 小时后过期,请尽快更新,避免用车高峰失效。"
|
||||||
else:
|
else:
|
||||||
lead = "凭据将在约 1 天后过期,请安排在小程序重新登录更新。"
|
lead = "凭据将在约 1 天后过期,请安排时间更新。"
|
||||||
details = [("凭据归属", owner_desc), ("当前级别", level_text),
|
details = [("凭据归属", owner_desc), ("当前级别", level_text),
|
||||||
("有效期至", expire_time), ("提醒时间", _now_bj_str())]
|
("有效期至", expire_time), ("提醒时间", _now_bj_str())]
|
||||||
plain = f"{title}\n\n{lead}\n\n" + "\n".join(f"{k}:{v}" for k, v in details)
|
plain = f"{title}\n\n{lead}\n\n" + "\n".join(f"{k}:{v}" for k, v in details)
|
||||||
html_body = _render_alert_html(title, lead, details)
|
html_body = _render_alert_html(title, lead, details)
|
||||||
ok_all = True
|
sent_ok, failed = [], []
|
||||||
for to in sorted(recipients):
|
for to in sorted(recipients):
|
||||||
subject = f"【小白超人·告警】{title}"
|
subject = f"【小白超人·告警】{title}"
|
||||||
if not send_email(to, subject, plain, html_body):
|
try:
|
||||||
ok_all = False
|
if send_email(to, subject, plain, html_body):
|
||||||
return ok_all
|
sent_ok.append(to)
|
||||||
|
else:
|
||||||
|
failed.append(to)
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[凭据告警] 发送给 {to} 异常: {exc}")
|
||||||
|
failed.append(to)
|
||||||
|
if failed:
|
||||||
|
print(f"[凭据告警] {len(failed)} 个收件人发送失败: {failed[:3]}")
|
||||||
|
# 返回成功数:只要有一个人收到就算「已通知」,否则每 15 分钟
|
||||||
|
# 会把所有人重发一遍(原来的 ok_all 聚合就是这个问题)
|
||||||
|
return len(sent_ok)
|
||||||
|
|
||||||
|
|
||||||
# ========== 检查逻辑 ==========
|
# ========== 检查逻辑 ==========
|
||||||
@@ -163,6 +188,8 @@ def check_user_credentials():
|
|||||||
for u in users:
|
for u in users:
|
||||||
if not (u["access_token"] or "").strip():
|
if not (u["access_token"] or "").strip():
|
||||||
continue # 没填 AccessToken 走 check_user_credentials_alive 的失效探测
|
continue # 没填 AccessToken 走 check_user_credentials_alive 的失效探测
|
||||||
|
if _is_legacy_default_token(u["token_id"]):
|
||||||
|
continue # 注册遗留的默认值,不是真凭据
|
||||||
expiry = parse_access_token_expiry(u["access_token"])
|
expiry = parse_access_token_expiry(u["access_token"])
|
||||||
if not expiry.get("parseable") or expiry.get("expire_at") is None:
|
if not expiry.get("parseable") or expiry.get("expire_at") is None:
|
||||||
continue
|
continue
|
||||||
@@ -177,7 +204,7 @@ def check_user_credentials():
|
|||||||
recv = (u["alert_email"] or "").strip() or (u["email"] or "").strip()
|
recv = (u["alert_email"] or "").strip() or (u["email"] or "").strip()
|
||||||
if recv:
|
if recv:
|
||||||
recipients.add(recv)
|
recipients.add(recv)
|
||||||
if _send_alert(recipients, level, f"用户 {u['email']}", expiry):
|
if _send_alert(recipients, level, f"用户 {u['email']}", expiry) > 0:
|
||||||
_mark_sent(conn, target, level)
|
_mark_sent(conn, target, level)
|
||||||
sent += 1
|
sent += 1
|
||||||
finally:
|
finally:
|
||||||
@@ -186,44 +213,35 @@ def check_user_credentials():
|
|||||||
return sent
|
return sent
|
||||||
|
|
||||||
|
|
||||||
# 只填了 token_id 的用户:无法解析有效期(三级预警做不了),
|
# 只填了 token_id 的用户:**不发「凭据失效」邮件**。
|
||||||
# 但可以用一次极轻量的上游探测判断凭据「当前是否还活着」,
|
#
|
||||||
# 死了就发"已失效"邮件。credential_alerts 按 target 去重保证只发一次,
|
# 原因(实测):没有 access_token 时签名只能用假签名(wechat.fake_signature),
|
||||||
# 用户重新配置凭据后 target 变化 → 自动重新武装。
|
# 上游对假签名一律回 102001。这跟「token 过期」是同一个错误码,无法区分。
|
||||||
|
# 以前这里把它当过期发信,结果**所有只填 token_id 的用户都会被判过期**,
|
||||||
|
# 上线后给全站发了一批「凭据已过期」的误报邮件。
|
||||||
|
#
|
||||||
|
# 现在的口径:只探测、只记日志,不发信。真正的到期提醒交给
|
||||||
|
# check_user_credentials()(有 access_token 才能解析 exp),不猜。
|
||||||
def check_user_credentials_alive():
|
def check_user_credentials_alive():
|
||||||
"""探测未填 AccessToken 用户的凭据是否已失效(102001)。返回发送条数。"""
|
"""统计未填 AccessToken 的用户(仅日志,不发邮件、也不探测)。
|
||||||
from wechat import request_with_user_auth
|
|
||||||
sent = 0
|
没有 access_token 时签名只能用假签名,上游一律回 102001,跟「token 过期」
|
||||||
|
是同一个错误码、无法区分;再去探测只会浪费上游配额,所以这里干脆不请求。
|
||||||
|
真要给这批用户做到期提醒,得先让他们补上 access_token。
|
||||||
|
"""
|
||||||
conn = get_db()
|
conn = get_db()
|
||||||
try:
|
try:
|
||||||
users = conn.execute(
|
rows = conn.execute(
|
||||||
"SELECT id, email, token_id, alert_email FROM users "
|
"SELECT id, token_id FROM users "
|
||||||
"WHERE token_id IS NOT NULL AND token_id != '' "
|
"WHERE token_id IS NOT NULL AND token_id != '' "
|
||||||
" AND (access_token IS NULL OR access_token = '')").fetchall()
|
" AND (access_token IS NULL OR access_token = '')").fetchall()
|
||||||
admin_emails = set(get_alert_emails())
|
|
||||||
for u in users:
|
|
||||||
target = f"user-alive:{u['id']}"
|
|
||||||
if _sent_already(conn, target, "expired"):
|
|
||||||
continue
|
|
||||||
try:
|
|
||||||
# /user/info 是最轻的已登录接口;_silent 避免日志刷屏
|
|
||||||
res = request_with_user_auth(u["id"], "GET", "/user/info", _silent=True)
|
|
||||||
except Exception:
|
|
||||||
continue # 网络异常不判死刑,等下一轮
|
|
||||||
if not isinstance(res, dict) or res.get("rtn_code") != 102001:
|
|
||||||
continue # 正常或其他错误(非凭据失效)都不打扰
|
|
||||||
recipients = set(admin_emails)
|
|
||||||
recv = (u["alert_email"] or "").strip() or (u["email"] or "").strip()
|
|
||||||
if recv:
|
|
||||||
recipients.add(recv)
|
|
||||||
if _send_alert(recipients, "expired", f"用户 {u['email']}",
|
|
||||||
{"parseable": False, "expire_time": "未知(未填 AccessToken)"}):
|
|
||||||
_mark_sent(conn, target, "expired")
|
|
||||||
sent += 1
|
|
||||||
finally:
|
finally:
|
||||||
conn.commit()
|
|
||||||
conn.close()
|
conn.close()
|
||||||
return sent
|
unknown = [r for r in rows if not _is_legacy_default_token(r["token_id"])]
|
||||||
|
if unknown:
|
||||||
|
print(f"[凭据告警] {len(unknown)} 个用户只有 token_id、没有 access_token,"
|
||||||
|
f"无法核验有效期(到期提醒需要 access_token)")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
def check_global_credential():
|
def check_global_credential():
|
||||||
@@ -250,7 +268,7 @@ def check_global_credential():
|
|||||||
recipients = set(get_alert_emails())
|
recipients = set(get_alert_emails())
|
||||||
if not recipients:
|
if not recipients:
|
||||||
return 0
|
return 0
|
||||||
if _send_alert(recipients, level, "全局默认凭据", expiry):
|
if _send_alert(recipients, level, "全局默认凭据", expiry) > 0:
|
||||||
_mark_sent(conn, target, level)
|
_mark_sent(conn, target, level)
|
||||||
conn.commit()
|
conn.commit()
|
||||||
return 1
|
return 1
|
||||||
|
|||||||
@@ -170,7 +170,7 @@ def snapshot_bike_positions():
|
|||||||
for bike in bikes:
|
for bike in bikes:
|
||||||
try:
|
try:
|
||||||
cursor.execute("""
|
cursor.execute("""
|
||||||
INSERT INTO bike_history
|
INSERT OR IGNORE INTO bike_history
|
||||||
(bike_code, latitude, longitude, status, state, electric, recorded_at)
|
(bike_code, latitude, longitude, status, state, electric, recorded_at)
|
||||||
VALUES (?, ?, ?, ?, ?, ?, datetime('now', '+8 hours'))
|
VALUES (?, ?, ?, ?, ?, ?, datetime('now', '+8 hours'))
|
||||||
""", (
|
""", (
|
||||||
@@ -654,31 +654,131 @@ def api_history_heatmap():
|
|||||||
|
|
||||||
|
|
||||||
# ========== 启动 ==========
|
# ========== 启动 ==========
|
||||||
|
# 后台线程原来只挂在 `if __name__ == "__main__":` 里,换成 gunicorn/`flask run`
|
||||||
|
# 或任何 WSGI 启动方式时全都不会启动(且静默)——定时采集、订单巡检、
|
||||||
|
# 自动还车、订阅提醒、凭据告警会一起残废。这里收进幂等的 bootstrap(),
|
||||||
|
# WSGI 与 __main__ 都会调用,再由 before_request 兜住「首次请求」。
|
||||||
|
_bootstrap_lock = threading.Lock()
|
||||||
|
_bootstrap_done = False
|
||||||
|
_bootstrap_started = False
|
||||||
|
|
||||||
|
|
||||||
|
LEADER_LEASE = "xbcr-schedulers"
|
||||||
|
LEADER_TTL = 120 # 秒;持有者每 30 秒续期
|
||||||
|
|
||||||
|
|
||||||
|
def _start_leader_renewer():
|
||||||
|
"""leader 每 30 秒续一次租约;续不上就记日志(不自杀,避免抖动时全线停摆)。"""
|
||||||
|
def loop():
|
||||||
|
while True:
|
||||||
|
time.sleep(30)
|
||||||
|
try:
|
||||||
|
from db import acquire_lease, lease_held_by_me
|
||||||
|
if not acquire_lease(LEADER_LEASE, LEADER_TTL):
|
||||||
|
print("[启动] 后台线程租约已被其它进程接管(本进程不再续期)")
|
||||||
|
return
|
||||||
|
if not lease_held_by_me(LEADER_LEASE):
|
||||||
|
print("[启动] 租约校验失败,停止续期")
|
||||||
|
return
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[启动] 租约续期异常: {exc}")
|
||||||
|
threading.Thread(target=loop, daemon=True, name="leader-lease").start()
|
||||||
|
|
||||||
|
|
||||||
|
def bootstrap():
|
||||||
|
"""初始化数据库并启动所有后台线程。幂等:重复调用只会执行一次。"""
|
||||||
|
global _bootstrap_done, _bootstrap_started
|
||||||
|
with _bootstrap_lock:
|
||||||
|
if _bootstrap_done or _bootstrap_started:
|
||||||
|
return False
|
||||||
|
_bootstrap_started = True # 防重入;done 要等工作真正完成再置位
|
||||||
|
|
||||||
|
print("[启动] bootstrap: 初始化数据库 + 启动后台线程")
|
||||||
|
try:
|
||||||
|
init_db()
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[启动] init_db 失败: {exc}")
|
||||||
|
|
||||||
|
# 多 worker 部署时后台线程只能有一份:靠 SQLite 租约选主。
|
||||||
|
# 抢不到就只当 web worker(不跑采集/巡检/定时器),否则会重复发信、
|
||||||
|
# 重复自动还车,月卡还会被扣两次。
|
||||||
|
try:
|
||||||
|
from db import acquire_lease
|
||||||
|
# None = 租约表不可用(老库/单进程):按 leader 处理
|
||||||
|
is_leader = acquire_lease(LEADER_LEASE, LEADER_TTL) is not False
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[启动] 选主失败,按 leader 处理(单进程部署可忽略): {exc}")
|
||||||
|
is_leader = True
|
||||||
|
# 测试/工具场景:只要数据库和路由,不启动任何后台线程(避免采集线程写库
|
||||||
|
# 干扰用例的统计断言)
|
||||||
|
if os.environ.get("XBCR_DISABLE_BACKGROUND") == "1":
|
||||||
|
print("[启动] XBCR_DISABLE_BACKGROUND=1:只初始化数据库,不启动后台线程")
|
||||||
|
with _bootstrap_lock:
|
||||||
|
_bootstrap_done = True
|
||||||
|
return True
|
||||||
|
|
||||||
|
if not is_leader:
|
||||||
|
print("[启动] 本进程不是 leader:跳过采集/巡检/定时器/调度线程")
|
||||||
|
print("[启动] bootstrap 完成(web worker)")
|
||||||
|
return True
|
||||||
|
_start_leader_renewer()
|
||||||
|
|
||||||
|
steps = [
|
||||||
|
("恢复计时器", restore_active_timers),
|
||||||
|
("补还超期订单", _sweep_on_boot),
|
||||||
|
("订单巡检", start_all_order_checkers),
|
||||||
|
("数据采集", start_snapshot_scheduler),
|
||||||
|
]
|
||||||
|
for name, fn in steps:
|
||||||
|
try:
|
||||||
|
fn()
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[启动] {name} 失败: {exc}")
|
||||||
|
|
||||||
|
try:
|
||||||
|
from subscribe import start_subscribe_scheduler
|
||||||
|
start_subscribe_scheduler()
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[启动] 订阅调度失败: {exc}")
|
||||||
|
|
||||||
|
try:
|
||||||
|
from alerts import start_alert_scheduler
|
||||||
|
start_alert_scheduler()
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[启动] 告警调度失败: {exc}")
|
||||||
|
|
||||||
|
with _bootstrap_lock:
|
||||||
|
_bootstrap_done = True
|
||||||
|
print("[启动] bootstrap 完成")
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def _sweep_on_boot():
|
||||||
|
"""启动时把「expired=0 且已过期」的僵尸单捞一遍(带 5 分钟节流)。"""
|
||||||
|
try:
|
||||||
|
from timer import sweep_overdue_rentals
|
||||||
|
n = sweep_overdue_rentals(force=True)
|
||||||
|
if n:
|
||||||
|
print(f"[启动] 补还超期订单 {n} 单")
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[启动] 补还超期订单失败: {exc}")
|
||||||
|
|
||||||
|
|
||||||
|
@app.before_request
|
||||||
|
def _ensure_bootstrap():
|
||||||
|
"""WSGI 部署(gunicorn 等)不会走 __main__,靠首个请求把后台线程拉起来。"""
|
||||||
|
if not _bootstrap_done:
|
||||||
|
bootstrap()
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
from pathlib import Path
|
bootstrap()
|
||||||
|
|
||||||
# 初始化数据库
|
|
||||||
init_db()
|
|
||||||
|
|
||||||
# 恢复未过期的计时器
|
|
||||||
restore_active_timers()
|
|
||||||
|
|
||||||
# 启动用户订单检测
|
|
||||||
start_all_order_checkers()
|
|
||||||
|
|
||||||
# 启动数据采集
|
|
||||||
start_snapshot_scheduler()
|
|
||||||
|
|
||||||
# 启动订阅提醒调度(定时查看教学楼附近车辆 → 邮件)
|
|
||||||
from subscribe import start_subscribe_scheduler
|
|
||||||
start_subscribe_scheduler()
|
|
||||||
|
|
||||||
# 启动凭据到期告警调度(1天/1小时/已过期 三级)
|
|
||||||
from alerts import start_alert_scheduler
|
|
||||||
start_alert_scheduler()
|
|
||||||
|
|
||||||
PORT = 98
|
PORT = 98
|
||||||
# 只监听本机回环:对外统一走 nginx 的 HTTPS(同机回环转发到本端口)。
|
# 只监听本机回环:对外统一走 nginx 的 HTTPS(同机回环转发到本端口)。
|
||||||
# 绑定 0.0.0.0 会让明文 HTTP 绕过 nginx 直接暴露,token/凭据可被局域网窃听。
|
# 绑定 0.0.0.0 会让明文 HTTP 绕过 nginx 直接暴露,token/凭据可被局域网窃听。
|
||||||
print(f"[启动] HTTP 服务: http://127.0.0.1:{PORT} (请由 nginx 反代对外提供 HTTPS)")
|
print(f"[启动] HTTP 服务: http://127.0.0.1:{PORT} (请由 nginx 反代对外提供 HTTPS)")
|
||||||
app.run(host=os.environ.get("XBCR_HOST","0.0.0.0"), port=int(os.environ.get("XBCR_PORT",PORT)), debug=False)
|
# 默认只听回环:对外统一由 nginx 反代 HTTPS。绑定 0.0.0.0 会让明文 HTTP
|
||||||
|
# 绕过 nginx 直接暴露,Bearer token / access_token 可被同网段窃听。
|
||||||
|
# 需要直连(例如容器内自测)时显式设 XBCR_HOST。
|
||||||
|
app.run(host=os.environ.get("XBCR_HOST", "127.0.0.1"),
|
||||||
|
port=int(os.environ.get("XBCR_PORT", PORT)), debug=False)
|
||||||
|
|||||||
@@ -1,35 +0,0 @@
|
|||||||
-----BEGIN CERTIFICATE-----
|
|
||||||
MIIGITCCBAmgAwIBAgIRANCpCCVfjlDl8zltERRwKjcwDQYJKoZIhvcNAQEMBQAw
|
|
||||||
XzELMAkGA1UEBhMCR0IxGDAWBgNVBAoTD1NlY3RpZ28gTGltaXRlZDE2MDQGA1UE
|
|
||||||
AxMtU2VjdGlnbyBQdWJsaWMgU2VydmVyIEF1dGhlbnRpY2F0aW9uIFJvb3QgUjQ2
|
|
||||||
MB4XDTI1MDkyNDAwMDAwMFoXDTM1MDkyMzIzNTk1OVowRjELMAkGA1UEBhMCQVQx
|
|
||||||
FTATBgNVBAoTDFplcm9TU0wgR21iSDEgMB4GA1UEAxMXWmVyb1NTTCBSU0EgRFYg
|
|
||||||
U1NMIENBIDIwggGiMA0GCSqGSIb3DQEBAQUAA4IBjwAwggGKAoIBgQCnXX3Qm/G+
|
|
||||||
ujylvYIkhJ53ZZ7XM03vXY03sCnO9VWjwMsV0qCQMlvhuRiJwrm4M5jgGehxIiCR
|
|
||||||
1qT0AyL2rHTWJR07vjJzuNmp7uoKu3HKwixBk9QuXD5aliO8/EDbzdZDcG/Hm5pC
|
|
||||||
mOeusLtds/UE/Iq24nw5WpcgZE5Ly+F/yCYDuEa7hXLJAPM5SecJIblG1OQ3ukMl
|
|
||||||
HHNBbDxBpGWTyDudd0DTed0NTgCPs1t8RZPhW9Gt/8nDwFX0pQ4eHfPEB8c6eNl2
|
|
||||||
sRr2Afp1YErakR+53yEX2SXc2Kz0fbTlUc+To0ULGcJiWNyZwj//DTZ+M4xxsT2T
|
|
||||||
qjQ4Xfvm2EUTymrXDrh1Pm/wkBouu860c6eeQfNlKlccUyHOSeKCtPIWreMvH3Be
|
|
||||||
Ydeu3DwI8lefn/VUhSB2Bbz7hX3qz3oMmtSTmWhTnobyKlx1L2b/oloaqpy1cBc/
|
|
||||||
QiLRSOptYGPjZtX0pRrTVKQXeP2rPUk0y5q/40WRpugSlHCX6aceWnsCAwEAAaOC
|
|
||||||
AW8wggFrMB8GA1UdIwQYMBaAFFZzWGSV+ZIasBIqBGJ5oUAViCFJMB0GA1UdDgQW
|
|
||||||
BBRLvvp2hCNEBLnOvjFv6fUyBv8MVzAOBgNVHQ8BAf8EBAMCAYYwEgYDVR0TAQH/
|
|
||||||
BAgwBgEB/wIBADATBgNVHSUEDDAKBggrBgEFBQcDATATBgNVHSAEDDAKMAgGBmeB
|
|
||||||
DAECATBUBgNVHR8ETTBLMEmgR6BFhkNodHRwOi8vY3JsLnNlY3RpZ28uY29tL1Nl
|
|
||||||
Y3RpZ29QdWJsaWNTZXJ2ZXJBdXRoZW50aWNhdGlvblJvb3RSNDYuY3JsMIGEBggr
|
|
||||||
BgEFBQcBAQR4MHYwTwYIKwYBBQUHMAKGQ2h0dHA6Ly9jcnQuc2VjdGlnby5jb20v
|
|
||||||
U2VjdGlnb1B1YmxpY1NlcnZlckF1dGhlbnRpY2F0aW9uUm9vdFI0Ni5wN2MwIwYI
|
|
||||||
KwYBBQUHMAGGF2h0dHA6Ly9vY3NwLnNlY3RpZ28uY29tMA0GCSqGSIb3DQEBDAUA
|
|
||||||
A4ICAQCJ/3v2/vdexHsdVyXL9aCTQE01YXl23866TVM/LgRpRW+kneZXXZxP0hy4
|
|
||||||
GnvlqUcxTq97B6qPdQcQxQxpGne7CRn0nWauzqieMcJzYl3fDC2Q/ANyPhyrbwCI
|
|
||||||
zx9EsRrgfjvuJCaUMtlfYpKqBUYiPOCPAN0HdrLD5hU6oV1tvWVsUzTA43skC3uH
|
|
||||||
wQM5YPIk0NDJFw3NhQPOIOwbq09T+SYSEZvsJ3t4sA4H3gh03RETNaAwTcTNS/+u
|
|
||||||
1tAeQUZZmKQyLWYLyoxvbISp/MFr9xqhDqrpAurYVNeiLJ5+4/WZPml20yNZjcxV
|
|
||||||
KKqRYdEurl8rmI2toCnCDWiEcTDvoYGtz60eYIt7VJID4DrCjTxAWTWh2T5ag2pK
|
|
||||||
ryNJGt8BFGLtjeD774SxAFn5MGYBVvEK4LXmCjVX78pb6/0Dceo71dlQUK68yftb
|
|
||||||
+yTeyoqjwgk2L8vNSrkj6UTkvvqXSONFuVU7bvC0O/9bi5MXBv7QUivMNxDsTtaT
|
|
||||||
IZO7PsSCRmLraQM2EPBgbNL9lRSEYi4Hj+NicT/e87pbhv88k0oec9xGcnkcvZpN
|
|
||||||
sJBz78mkZfeFIIjh02e2y9ke/Fqw1FbdhHtU2myaFnX0sRyGLmI/vzXSwyvT+Kxl
|
|
||||||
Wx8FV64z2PBdwd0vXRaAMXomGC0M1vQa5fBDn4dimzewsSiphQ==
|
|
||||||
-----END CERTIFICATE-----
|
|
||||||
@@ -69,6 +69,45 @@ def gcj02_to_bd09(lng, lat):
|
|||||||
return [z * math.cos(theta) + 0.0065, z * math.sin(theta) + 0.006]
|
return [z * math.cos(theta) + 0.0065, z * math.sin(theta) + 0.006]
|
||||||
|
|
||||||
|
|
||||||
|
def wgs84_to_gcj02(lng, lat):
|
||||||
|
"""WGS84(GPS 原始)-> GCJ02。
|
||||||
|
|
||||||
|
用途:浏览器 `navigator.geolocation` 给的是 WGS84,上游车辆/停车区是
|
||||||
|
GCJ02,两者直接比较会差 500 米左右。算法与 static/js/coordtransform.js
|
||||||
|
的 `wgs84togcj02` 完全一致。
|
||||||
|
"""
|
||||||
|
lng, lat = float(lng), float(lat)
|
||||||
|
if _out_of_china(lng, lat):
|
||||||
|
return [lng, lat]
|
||||||
|
dlat = _transform_lat(lng - 105.0, lat - 35.0)
|
||||||
|
dlng = _transform_lng(lng - 105.0, lat - 35.0)
|
||||||
|
radlat = lat / 180.0 * _PI
|
||||||
|
magic = math.sin(radlat)
|
||||||
|
magic = 1 - _EE * magic * magic
|
||||||
|
sqrtmagic = math.sqrt(magic)
|
||||||
|
dlat = (dlat * 180.0) / ((_A * (1 - _EE)) / (magic * sqrtmagic) * _PI)
|
||||||
|
dlng = (dlng * 180.0) / (_A / sqrtmagic * math.cos(radlat) * _PI)
|
||||||
|
return [lng + dlng, lat + dlat]
|
||||||
|
|
||||||
|
|
||||||
|
def gcj02_to_wgs84(lng, lat):
|
||||||
|
"""GCJ02 -> WGS84(把内部算出的点转回浏览器/上游使用的坐标系)。
|
||||||
|
|
||||||
|
用不动点迭代反解(4 轮即收敛到厘米级):先按 GCJ02 猜一个 WGS84,再用
|
||||||
|
正向转换量修正。比 coordtransform 的「对称偏移」反解精度更高 —— 后者在
|
||||||
|
本地实测约 1 米误差,会吃到停车区边界的判断上。
|
||||||
|
"""
|
||||||
|
lng, lat = float(lng), float(lat)
|
||||||
|
if _out_of_china(lng, lat):
|
||||||
|
return [lng, lat]
|
||||||
|
w_lng, w_lat = lng, lat
|
||||||
|
for _ in range(4):
|
||||||
|
g_lng, g_lat = wgs84_to_gcj02(w_lng, w_lat)
|
||||||
|
w_lng -= (g_lng - lng)
|
||||||
|
w_lat -= (g_lat - lat)
|
||||||
|
return [w_lng, w_lat]
|
||||||
|
|
||||||
|
|
||||||
# ========== 几何工具 ==========
|
# ========== 几何工具 ==========
|
||||||
|
|
||||||
def haversine_m(lat1, lng1, lat2, lng2):
|
def haversine_m(lat1, lng1, lat2, lng2):
|
||||||
|
|||||||
@@ -1,19 +0,0 @@
|
|||||||
-----BEGIN CERTIFICATE-----
|
|
||||||
MIIDCTCCAfGgAwIBAgIUcol8xUcjrWOBC1h/XBA3PSL8hr4wDQYJKoZIhvcNAQEL
|
|
||||||
BQAwFDESMBAGA1UEAwwJbG9jYWxob3N0MB4XDTI2MDQyMTEyNTgzM1oXDTI3MDQy
|
|
||||||
MTEyNTgzM1owFDESMBAGA1UEAwwJbG9jYWxob3N0MIIBIjANBgkqhkiG9w0BAQEF
|
|
||||||
AAOCAQ8AMIIBCgKCAQEAugEeAJfOaLGmKkxnHfcbssngyK78LcmC3TvMaGybcTaM
|
|
||||||
LvyVyuKI9vTnb8kfJM8tQZxP104uPVwTBa2bPdlaFju8DEw0tv6SvwPAxXMahBwS
|
|
||||||
lEa+sYEGjgGuwdzDpem9dpkx+3t6MPk/vs5LUN3bJsnqhRHIYFV05IwcUmNQHvu3
|
|
||||||
DkSPyVukBgbkg0kfZmbD0fSd2MOi7W7oPfX7GFs+mow7Ofg9mBvewazTsfm80KkB
|
|
||||||
RLJlG7cEk9r+qME75XnAzPSrxjsr2gUhu44YJ5HPqSgz+jsWiLB47U8D0GgeEZZF
|
|
||||||
DKOxoSzadIhKPcAzH6rmyv+88RORhoftasnml1SMxQIDAQABo1MwUTAdBgNVHQ4E
|
|
||||||
FgQUflZL1SfllduC5LWjr/TTvIunlCIwHwYDVR0jBBgwFoAUflZL1SfllduC5LWj
|
|
||||||
r/TTvIunlCIwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAKQy1
|
|
||||||
YJnUAOXKOGKZJUUDsWjbYZ0i7qG+4YzpyPb0KRfyzTwn0FDnuPbHfSjd5QGZgJxt
|
|
||||||
CoZV0qTUHWctKdid+A8q1fynvu1DERIYHRGWJvKLv9ySY8KmRZLG/gYJvzjxiPkL
|
|
||||||
qDECmVRKJM1wRp5tKynuo97kyCLmQHHEnIlyZ9HM+elItpwZweD/R7yd/qULbKUX
|
|
||||||
lTGzPeReUj7mIcscsuTvKCRKBhslxvUgQDHsN1q4eEwLCNVr94V0wstEp5sdeJvl
|
|
||||||
pL4lqLxXlCqBMxzZ8hm5VK83N+Wj1nokkCsCLmzL96GW6yE7ZffDU+Ibus+YCtj2
|
|
||||||
9zC9vtd3PadkFyHkDQ==
|
|
||||||
-----END CERTIFICATE-----
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
-----BEGIN CERTIFICATE-----
|
|
||||||
MIIFfzCCA+egAwIBAgIQDON/Evu3Aq6w4T67JD84rzANBgkqhkiG9w0BAQsFADBG
|
|
||||||
MQswCQYDVQQGEwJBVDEVMBMGA1UEChMMWmVyb1NTTCBHbWJIMSAwHgYDVQQDExda
|
|
||||||
ZXJvU1NMIFJTQSBEViBTU0wgQ0EgMjAeFw0yNjA0MjEwMDAwMDBaFw0yNjA3MjAy
|
|
||||||
MzU5NTlaMBkxFzAVBgNVBAMTDjQ3LjExMi4xODcuMTcyMIIBIjANBgkqhkiG9w0B
|
|
||||||
AQEFAAOCAQ8AMIIBCgKCAQEA6uK6FJIX3CHtkkWb8s448v5l0UY8yh4hbL/xhvQQ
|
|
||||||
rAGEdeDRm/zwstwsw/OKkkWLe0eE1zC0/zvgZN8gjXNtgUK4A6uev+CjctEPijT6
|
|
||||||
fhcXsWspQQ6ihRGw+giSIm8TIGdh97cwpyKB6e8EgpddLlcaBPBd4Xkyi5aZwGuq
|
|
||||||
DjuvDMeYfd+3Fe0MuZ61RObQ8cplAG14GKBly/HhEkY4ycxrzxKNbMYRJW9wZvUH
|
|
||||||
v+E3ku7ezdCtaLU2AVtVlVYRgPwUT7kB9oSqXSXds18g1H6f3w0Ci1osRgrA/gRQ
|
|
||||||
ZNUIwdJ58FT955xHmvkP98NxRLLPZ8Wqmn9/5jnsVyn12QIDAQABo4ICFDCCAhAw
|
|
||||||
HwYDVR0jBBgwFoAUS776doQjRAS5zr4xb+n1Mgb/DFcwHQYDVR0OBBYEFIyOE+cJ
|
|
||||||
rZ4oLGIPabNopuvEy8ReMA4GA1UdDwEB/wQEAwIFoDAMBgNVHRMBAf8EAjAAMBMG
|
|
||||||
A1UdJQQMMAoGCCsGAQUFBwMBMBMGA1UdIAQMMAowCAYGZ4EMAQIBMG4GCCsGAQUF
|
|
||||||
BwEBBGIwYDA5BggrBgEFBQcwAoYtaHR0cDovL2NydC5zZWN0aWdvLmNvbS9aZXJv
|
|
||||||
U1NMUlNBRFZTU0xDQTIuY3J0MCMGCCsGAQUFBzABhhdodHRwOi8vb2NzcC5zZWN0
|
|
||||||
aWdvLmNvbTCCAQMGCisGAQQB1nkCBAIEgfQEgfEA7wB2ANdtfRDRp/V3wsfpX9cA
|
|
||||||
v/mCyTNaZeHQswFzF8DIxWl3AAABnbBCKukAAAQDAEcwRQIgJjjYYsW+ptzeLGtg
|
|
||||||
MfutQR8kJDZufkJ2IRyuazHm0zYCIQDXWFYyaPX+FDx/4+oahwkrpOpb8ywLfibm
|
|
||||||
oE/KjyEYGwB1AMijxH/Hs625NWsBP2p6Em3jOk5DpcZG+ZetOXWZHc+aAAABnbBC
|
|
||||||
K6IAAAQDAEYwRAIgLP/AOhTK1ZWDFs/wPJ1XnImgiatyMic9yPpjB5+1l0wCIDks
|
|
||||||
CKZq5eKiHo1HlGh/tqg8TVIcEbFH6rd7APD+AtTgMA8GA1UdEQQIMAaHBC9wu6ww
|
|
||||||
DQYJKoZIhvcNAQELBQADggGBADYvxJBts1Z7PqRZrDmR8FYEnHS4ldzq+ANDypZV
|
|
||||||
wY4A0DAq1VkClYC32EW2p7DDLr1+xOX8OIUwGmFh5lZq7m1JiaMe2p3ajFz89pSR
|
|
||||||
QccFgXNsPW1Ux0W70Jb+R6oOW7q9VhwQl8fQRatkeTf8Su1K/LpS/4+72z3AOPJe
|
|
||||||
FqW2Vrp6x1Ecta7GJxlLvuS0Z6276/0h+bWAp2cEsSzJ4cnNfrdCKIhakHcWjN0n
|
|
||||||
zDITy9Sflv7xHDeHyV8p5N7+bTt/9tQE+sr8n0KOmUaxpPLPqfEVjXMdi/2G+YYM
|
|
||||||
YsATqDPgdBpwxClTd4I/bpumVU+Aqf8u0UPOhtCapPjm1cgV3AOfZ4TyQ/0Wd415
|
|
||||||
kjVFfSi/w4vN2D2I+Kp1hG0heqLq4Wm7DV2rt0shaTZxwP6cdEJ7aNqYDIegKGLx
|
|
||||||
xfFKWCWw9VwxuC/L0Fvb7gwFvxZ3fBFYKnexwVgRMvt39JSXWlcAvFW6Pc8+OeZL
|
|
||||||
J29EzuPpiH9B9zwiDeMMO4XzLw==
|
|
||||||
-----END CERTIFICATE-----
|
|
||||||
@@ -20,6 +20,80 @@ MIN_RENTAL_ROUNDS = 1
|
|||||||
MAX_RENTAL_ROUNDS = 20
|
MAX_RENTAL_ROUNDS = 20
|
||||||
|
|
||||||
|
|
||||||
|
# ========== 跨进程租约(多 worker 选主 / 单任务抢占) ==========
|
||||||
|
|
||||||
|
import os as _os
|
||||||
|
import socket as _socket
|
||||||
|
import time as _time
|
||||||
|
import uuid as _uuid
|
||||||
|
|
||||||
|
LEASE_OWNER = f"{_os.getpid()}@{_socket.gethostname()}:{_uuid.uuid4().hex[:6]}"
|
||||||
|
|
||||||
|
|
||||||
|
def acquire_lease(name: str, ttl_seconds: float = 120):
|
||||||
|
"""尝试成为某个租约的持有者;已是自己则续期。
|
||||||
|
|
||||||
|
返回 True=持有 / False=被别的进程持有 / **None=租约表不可用(老库、临时库)**。
|
||||||
|
调用方要把 None 当「按单进程处理」,否则老库上所有后台任务会被误拦。
|
||||||
|
BEGIN IMMEDIATE 保证「读-判断-写」原子:多进程同时抢只有一个成功。
|
||||||
|
"""
|
||||||
|
# 测试里用临时库、但租约走的是真实库:给一个显式开关,避免上一轮进程
|
||||||
|
# 留下的租约(300 秒)把这一轮的单测全拦掉。
|
||||||
|
if _os.environ.get("XBCR_DISABLE_LEASES") == "1":
|
||||||
|
return True
|
||||||
|
|
||||||
|
now = _time.time()
|
||||||
|
conn = get_db()
|
||||||
|
try:
|
||||||
|
conn.execute("BEGIN IMMEDIATE")
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT owner, expires_at FROM leases WHERE name = ?", (name,)).fetchone()
|
||||||
|
if row and float(row["expires_at"] or 0) > now and row["owner"] != LEASE_OWNER:
|
||||||
|
conn.rollback()
|
||||||
|
return False
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO leases (name, owner, expires_at) VALUES (?, ?, ?) "
|
||||||
|
"ON CONFLICT(name) DO UPDATE SET owner = excluded.owner, "
|
||||||
|
"expires_at = excluded.expires_at",
|
||||||
|
(name, LEASE_OWNER, now + ttl_seconds))
|
||||||
|
conn.commit()
|
||||||
|
return True
|
||||||
|
except Exception as exc:
|
||||||
|
try:
|
||||||
|
conn.rollback()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
print(f"[租约] 获取 {name} 失败(按单进程处理): {exc}")
|
||||||
|
return None
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def release_lease(name: str):
|
||||||
|
"""主动释放(进程退出时调用;不释放也会因过期被别人接管)。"""
|
||||||
|
conn = get_db()
|
||||||
|
try:
|
||||||
|
conn.execute("DELETE FROM leases WHERE name = ? AND owner = ?", (name, LEASE_OWNER))
|
||||||
|
conn.commit()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def lease_held_by_me(name: str) -> bool:
|
||||||
|
conn = get_db()
|
||||||
|
try:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT owner, expires_at FROM leases WHERE name = ?", (name,)).fetchone()
|
||||||
|
return bool(row and row["owner"] == LEASE_OWNER
|
||||||
|
and float(row["expires_at"] or 0) > _time.time())
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
def get_db():
|
def get_db():
|
||||||
"""获取数据库连接(WAL + 忙等待,避免多线程写入时 database is locked)"""
|
"""获取数据库连接(WAL + 忙等待,避免多线程写入时 database is locked)"""
|
||||||
conn = sqlite3.connect(str(DB_PATH))
|
conn = sqlite3.connect(str(DB_PATH))
|
||||||
@@ -83,6 +157,32 @@ def init_db():
|
|||||||
except sqlite3.OperationalError:
|
except sqlite3.OperationalError:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
# 老库的 token_id 列带 DEFAULT '1291378'(建表时留下的),注册时没写这一列的用户
|
||||||
|
# 会被灌成这个假凭据 → 巡检拿它去探测、必被上游 102001 拒绝 →
|
||||||
|
# 全站收到「凭据已过期」误报邮件。这里启动时自动清掉:值等于该默认值且没有
|
||||||
|
# access_token 的,一律视为「未配置凭据」。
|
||||||
|
# 新库/新注册都不会再写入默认值(auth 注册显式传 NULL)。
|
||||||
|
try:
|
||||||
|
cursor.execute("""
|
||||||
|
UPDATE users SET token_id = NULL
|
||||||
|
WHERE token_id = '1291378'
|
||||||
|
AND (access_token IS NULL OR access_token = '')
|
||||||
|
""")
|
||||||
|
if cursor.rowcount:
|
||||||
|
print(f"[迁移] 清理 {cursor.rowcount} 个注册遗留的默认 token_id(1291378)")
|
||||||
|
except sqlite3.OperationalError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# 跨进程租约:多 worker 部署时用来选主(只有一个进程跑后台线程/采集/调度),
|
||||||
|
# 也用来做「同一单只能一个进程处理」的原子抢占。
|
||||||
|
cursor.execute("""
|
||||||
|
CREATE TABLE IF NOT EXISTS leases (
|
||||||
|
name TEXT PRIMARY KEY,
|
||||||
|
owner TEXT NOT NULL,
|
||||||
|
expires_at REAL NOT NULL
|
||||||
|
)
|
||||||
|
""")
|
||||||
|
|
||||||
cursor.execute("""
|
cursor.execute("""
|
||||||
CREATE TABLE IF NOT EXISTS sessions (
|
CREATE TABLE IF NOT EXISTS sessions (
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
@@ -181,6 +281,24 @@ def init_db():
|
|||||||
)
|
)
|
||||||
""")
|
""")
|
||||||
|
|
||||||
|
# 多进程/多实例采集会重复写同一秒的位置:先去重再建唯一索引,
|
||||||
|
# 让 INSERT OR IGNORE 把重复写入挡掉,避免行数 ×N 污染 /api/history 统计。
|
||||||
|
try:
|
||||||
|
cursor.execute("""
|
||||||
|
DELETE FROM bike_history
|
||||||
|
WHERE id NOT IN (
|
||||||
|
SELECT MIN(id) FROM bike_history GROUP BY bike_code, recorded_at
|
||||||
|
)
|
||||||
|
""")
|
||||||
|
if cursor.rowcount:
|
||||||
|
print(f"[迁移] bike_history 去重 {cursor.rowcount} 行")
|
||||||
|
cursor.execute("""
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_bike_history_code_time
|
||||||
|
ON bike_history (bike_code, recorded_at)
|
||||||
|
""")
|
||||||
|
except sqlite3.OperationalError as exc:
|
||||||
|
print(f"[迁移] bike_history 唯一索引创建失败(忽略): {exc}")
|
||||||
|
|
||||||
for col_def in [("state", "INTEGER DEFAULT 1"), ("electric", "REAL DEFAULT 100")]:
|
for col_def in [("state", "INTEGER DEFAULT 1"), ("electric", "REAL DEFAULT 100")]:
|
||||||
try:
|
try:
|
||||||
cursor.execute(f"ALTER TABLE bike_history ADD COLUMN {col_def[0]} {col_def[1]}")
|
cursor.execute(f"ALTER TABLE bike_history ADD COLUMN {col_def[0]} {col_def[1]}")
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,172 @@
|
|||||||
|
# 百度地图 JS API GL v1.0 —— 本地速查(BMapGL)
|
||||||
|
|
||||||
|
> 原始文档已下载:`docs/baidu-jsapi-webgl-1.0.html`(664 KB,离线可查)
|
||||||
|
> 来源:https://lbsyun.baidu.com/cms/jsapi/reference/jsapi_webgl_1_0.html
|
||||||
|
>
|
||||||
|
> **约定:改地图相关代码前先查这里 / 查本地 HTML,不要再凭记忆猜方法名和参数顺序。**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 我们实际在用的类
|
||||||
|
|
||||||
|
| 类 | 用途 | 备注 |
|
||||||
|
|---|---|---|
|
||||||
|
| `BMapGL.Map` | 地图实例 | 必须先 `centerAndZoom()` 初始化,否则任何操作无效 |
|
||||||
|
| `BMapGL.Point` | 经纬度点 | **BD09**(百度坐标) |
|
||||||
|
| `BMapGL.Marker` | 标记 | 有 `setRotation()`,可做导航箭头 |
|
||||||
|
| `BMapGL.Icon` | 图标 | `Icon(url, Size, {anchor})` |
|
||||||
|
| `BMapGL.Polyline` | 折线 | 路线、边界 |
|
||||||
|
| `BMapGL.Polygon` | 多边形 | 停车区、骑行边界 |
|
||||||
|
| `BMapGL.ViewAnimation` | 视角动画 | **官方唯一文档化的"旋转/倾斜"入口** |
|
||||||
|
| `BMapGL.ScaleControl` | 比例尺 | |
|
||||||
|
| `BMapGL.Geolocation` | 百度自带定位 | 我们没用,用的是 `navigator.geolocation` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 踩过的坑(按踩的顺序,全部实测)
|
||||||
|
|
||||||
|
### 坑 1:`setHeading()` / `getHeading()` 是**没文档**的私有方法
|
||||||
|
|
||||||
|
在官方文档里 `heading` 只出现在 `ViewAnimationKeyFrames`,`setHeading` 这个词**完全没有**。
|
||||||
|
它们是实例上的隐藏方法(`typeof map.setHeading === 'function'` 为真),能用但不保证稳定。
|
||||||
|
|
||||||
|
**文档化的旋转方式**:
|
||||||
|
|
||||||
|
```js
|
||||||
|
// 关键帧里 heading = 地图旋转角度(度)
|
||||||
|
const anim = new BMapGL.ViewAnimation(
|
||||||
|
[{ heading: 0, percentage: 0 }, { heading: 90, percentage: 1 }],
|
||||||
|
{ duration: 300 }
|
||||||
|
);
|
||||||
|
map.startViewAnimation(anim);
|
||||||
|
// 中止:map.cancelViewAnimation(anim)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 坑 2:`setCenter()` 会把刚设的 heading 抹成 0
|
||||||
|
|
||||||
|
实测(headless + 真机同样的行为):
|
||||||
|
|
||||||
|
| 顺序 | `getHeading()` |
|
||||||
|
|---|---|
|
||||||
|
| `setHeading(90)` → `setCenter(p)` | **0**(被抹掉) |
|
||||||
|
| `setCenter(p)` → `setHeading(90)` | 90 ✅ |
|
||||||
|
| `setCenter(p, {callback})` 里 `setHeading(90)` | 90 ✅ |
|
||||||
|
| `setHeading(45)` → `panBy(0,120)` | 45(平移不抹) |
|
||||||
|
|
||||||
|
所以正确写法是**在 setCenter 的回调里**设 heading:
|
||||||
|
|
||||||
|
```js
|
||||||
|
map.setCenter(point, {
|
||||||
|
noAnimation: true,
|
||||||
|
callback: function () {
|
||||||
|
map.setHeading(deg); // 或 startViewAnimation
|
||||||
|
map.panBy(0, offsetY); // 再把我压到屏幕下方
|
||||||
|
}
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### 坑 2.5:heading 是**逆时针**角度,方位角朝上要取反
|
||||||
|
|
||||||
|
实测(同一段路,路线方位角 145°,用 `map.pointToPixel()` 量目标点在屏幕的位置):
|
||||||
|
|
||||||
|
| 设置 | 目标点相对我的像素偏移 | 结论 |
|
||||||
|
|---|---|---|
|
||||||
|
| `setHeading(145)` | dx=-37, dy=-13(在左上方) | ❌ 不是正上 |
|
||||||
|
| `setHeading(-145)` | dx=**0**, dy=-39(正上方) | ✅ 行进方向朝上 |
|
||||||
|
|
||||||
|
所以 **`map.setHeading(-方位角)`**。方位角是地理学的顺时针(0=北、90=东),
|
||||||
|
BMapGL 的 heading 是逆时针,两者符号相反。
|
||||||
|
|
||||||
|
箭头(`Marker.setRotation`)仍按**顺时针**理解,所以箭头角度 = `罗盘角 - 方位角`。
|
||||||
|
|
||||||
|
### 坑 3:不支持的 WebGL 环境下 `setHeading` 会留下坏相机 → **整张底图变黑**
|
||||||
|
|
||||||
|
表现:调完 `getHeading()` 仍返回 0,但地图黑屏。
|
||||||
|
处理:探测到不支持时立刻 `map.resetHeading()`,再 `map.setCenter(map.getCenter())` 重铺一次。
|
||||||
|
所以我们的代码里 `_headingSupported` 是个三态(null/true/false),只探测一次。
|
||||||
|
|
||||||
|
### 坑 4:`Marker.setRotation(deg)` 才能让箭头转
|
||||||
|
|
||||||
|
`BMapGL.Marker` 文档里就写了 `setRotation(rotation: Number)` / `getRotation()`。
|
||||||
|
配合 `deviceorientation` 的罗盘角度做"箭头指向手机朝向":
|
||||||
|
|
||||||
|
```js
|
||||||
|
// iOS:webkitCompassHeading 已是相对正北的顺时针角度
|
||||||
|
// 安卓:alpha 是逆时针,需要 360 - alpha
|
||||||
|
const h = e.webkitCompassHeading ?? (360 - e.alpha) % 360;
|
||||||
|
marker.setRotation(h);
|
||||||
|
```
|
||||||
|
|
||||||
|
iOS 13+ 要权限,必须在**用户手势**里申请:
|
||||||
|
`DeviceOrientationEvent.requestPermission()`
|
||||||
|
|
||||||
|
### 坑 5:`panBy(x, y)` 的正负
|
||||||
|
|
||||||
|
`panBy(0, +y)` 把地图整体**上移**(视觉上内容往上走)—— 用来把当前位置压到屏幕下方。
|
||||||
|
像素大于可视区时百度会忽略这次调用。
|
||||||
|
|
||||||
|
### 坑 6:`setViewport(points, {margins})`
|
||||||
|
|
||||||
|
`margins: [上, 右, 下, 左]`,做"路线全部可见"时用来避开顶部/底部面板。
|
||||||
|
|
||||||
|
### 坑 7:`getMapScreenshot()` 需要初始化时开 `preserveDrawingBuffer: true`
|
||||||
|
|
||||||
|
否则截出来是黑屏(我们没用它)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 与本项目坐标相关(**不是 JS API,属于 Web 服务 API**)
|
||||||
|
|
||||||
|
`directionlite/v1/walking`:
|
||||||
|
|
||||||
|
| 参数 | 作用 | 坑 |
|
||||||
|
|---|---|---|
|
||||||
|
| `coord_type` | **输入**坐标系 | 只影响入参 |
|
||||||
|
| `ret_coordtype` | **返回**折线坐标系 | **默认 `bd09ll`**!不传就拿到 BD09,前端再按 GCJ02 转会偏 500~900 米 |
|
||||||
|
| `timestamp` + `sn` | 开了 SN 校验必带 | 缺 timestamp → `status=2` |
|
||||||
|
| `steps_info` | 0/1 是否返回分段 | 只要距离时间时传 0,响应更小 |
|
||||||
|
|
||||||
|
我们的坐标约定:**浏览器 `navigator.geolocation` = WGS84 → 统一转 GCJ02 → 再转 BD09 给地图绘制**。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 本项目导航实现用到的 Map 能力清单
|
||||||
|
|
||||||
|
```js
|
||||||
|
map.setCenter(point, {noAnimation, callback}) // 居中 + 回调里设 heading/panBy
|
||||||
|
map.panBy(0, offsetY) // 把"我"压到屏幕下方
|
||||||
|
map.setHeading(deg) / map.getHeading() // 私有,探测后使用
|
||||||
|
map.resetHeading() // 私有,复位
|
||||||
|
map.startViewAnimation(anim) // 文档化的旋转方案
|
||||||
|
map.setViewport(points, {margins}) // 路线全览
|
||||||
|
map.addEventListener('dragstart' | 'dragend' | 'moving', fn) // 拖动进入自由查看
|
||||||
|
map.pointToPixel(point) / map.pixelToPoint(px) // 像素/经纬度互转
|
||||||
|
new BMapGL.ViewAnimation(keyFrames, {duration, delay, iteration})
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. 导航的朝向策略(本项目已定稿)
|
||||||
|
|
||||||
|
| 东西 | 跟谁 | 实现 |
|
||||||
|
|---|---|---|
|
||||||
|
| **地图朝向** | **行进方向**(course-up),不跟手机 | `setHeading(行进方位角)`,在 `setCenter` 的 callback 里设 |
|
||||||
|
| **箭头朝向** | 手机朝向(罗盘) | `Marker.setRotation(罗盘角 - 地图朝向)`;没罗盘就 0(=朝行进方向) |
|
||||||
|
| 我在地图上的位置 | 屏幕下方约 80% | `setCenter` 后 `panBy(0, 屏高×0.20)` |
|
||||||
|
|
||||||
|
方位角公式(0=正北,90=正东):
|
||||||
|
|
||||||
|
```js
|
||||||
|
const y = Math.sin(dLng) * Math.cos(lat2);
|
||||||
|
const x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLng);
|
||||||
|
const bearing = (Math.atan2(y, x) * 180 / Math.PI + 360) % 360;
|
||||||
|
```
|
||||||
|
|
||||||
|
罗盘角度:
|
||||||
|
- iOS `e.webkitCompassHeading` —— 已经是"相对正北的顺时针角度",**直接用**
|
||||||
|
- 安卓 `e.alpha` —— 逆时针,**要 `(360 - alpha) % 360`**
|
||||||
|
- iOS 13+ 必须在用户手势里 `DeviceOrientationEvent.requestPermission()`
|
||||||
|
|
||||||
|
**踩过的坑**:箭头别用绝对罗盘角。地图已经按行进方向转过一次了,
|
||||||
|
再按绝对角转箭头 = 转两次,方向是反的。要减掉地图朝向。
|
||||||
|
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
# 前端重构方案(从单文件走向模块化)
|
||||||
|
|
||||||
|
> 现状数据(2026-11):`static/js/map.js` **213 KB / 4776 行**,模板 `map.html` 里 **136 处内联
|
||||||
|
> `onclick/oninput/onchange`**,全部脚本是 classic script + 全局变量,无构建、无类型、无单测(只有 4 个 node 契约测试)。
|
||||||
|
|
||||||
|
## 1. 为什么现在必须动
|
||||||
|
|
||||||
|
| 现象 | 代价 |
|
||||||
|
|---|---|
|
||||||
|
| 一个文件里塞了地图、标记、卡片、订单、导航、登录、共享、订阅、设置 | 改一处要读 4000 行上下文;合并冲突几乎必冲突 |
|
||||||
|
| 全是全局变量(`map` / `selectedBike` / `_nav` / `authToken`…) | 任何模块都能改任何状态,出现「关掉卡片导航还在跑」这类竞态 |
|
||||||
|
| 内联 `onclick="fn()"` 136 处 | 函数名是隐式 ABI,重命名即线上崩,且 IDE 无法跳转/查引用 |
|
||||||
|
| 无类型、无 lint | `st.electric` vs `st.electric_quantity` 这种字段名错误只能靠人眼(本期已踩过一次) |
|
||||||
|
| 无组件化 | 弹窗/卡片/设置页都是字符串拼接 HTML,XSS 与转义靠自觉 |
|
||||||
|
|
||||||
|
## 2. 约束(决定方案选型)
|
||||||
|
|
||||||
|
1. **部署是 Flask + 静态文件**,没有 Node 运行时;构建产物必须能直接放进 `static/`。
|
||||||
|
2. **136 处内联事件**:短期内不能全部改成 `addEventListener`,否则一次性改动面太大。
|
||||||
|
3. 有 4 个 node 契约测试(`tests/*.cjs`)直接从 `static/js/*.js` 读源码 + `vm` 执行,重构要保证它们仍能跑。
|
||||||
|
4. 地图是 **BMapGL 全局 SDK**(`window.BMapGL`),且用 `callback=onBaiduMapReady` 异步就绪,不能被 tree-shaking / 严格模块作用域搞坏。
|
||||||
|
5. 生产只有单页 + admin 两页,不需要 SSR。
|
||||||
|
|
||||||
|
## 3. 三个候选方案
|
||||||
|
|
||||||
|
### 方案 A:无构建 ES Modules(**第一步就做**)
|
||||||
|
|
||||||
|
```html
|
||||||
|
<script type="module" src="/static/js/main.js?v=..."></script>
|
||||||
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
// main.js
|
||||||
|
import { initMap } from "./map/core.js";
|
||||||
|
import { installGlobals } from "./compat/globals.js"; // 兼容 136 处内联事件
|
||||||
|
installGlobals(); // 把 window.openShareModal = ... 挂回去(一次性、集中)
|
||||||
|
initMap();
|
||||||
|
```
|
||||||
|
|
||||||
|
- 优点:零依赖、零构建、部署方式不变、可以**逐文件替换**,随时能停。
|
||||||
|
- 缺点:没有类型检查、没有打包(模块多会有几十个请求,但都是 `defer` 缓存命中,实际影响小)。
|
||||||
|
- 内联事件兼容:集中一个 `compat/globals.js` 显式导出需要的函数。
|
||||||
|
**实测 `map.html` 里内联事件引用了 95 个标识符**,去掉 `document/event/if/return/this`
|
||||||
|
这类误匹配、以及 `SettingsPages`/`uiNavigate`(本来就在 `window` 上)之后,
|
||||||
|
**真正要挂的约 88 个函数**——分布:`map.js` 约 70、`share.js` 9、`navigation.js` 4、
|
||||||
|
`subscribe.js` 3。这个清单是 Phase 0 的验收依据(`grep` 对照,缺一个线上就有一处按钮失灵)。
|
||||||
|
|
||||||
|
### 方案 B:Vite + TypeScript(**第二步**)
|
||||||
|
|
||||||
|
- Vite build 产出 `static/dist/`,Flask 模板只引 `dist/main.[hash].js`。
|
||||||
|
- 好处:类型(`Bike`/`Order`/`Rental` 接口能直接照 `routes/*.py` 的 JSON 写)、按需打包、真 HMR。
|
||||||
|
- 迁移成本:需要引入 Node(本机/CI 构建),部署多一步 `pnpm build`。
|
||||||
|
|
||||||
|
### 方案 C:Vite + Vue 3(**只在 UI 继续膨胀时才做**)
|
||||||
|
|
||||||
|
- 卡片、订单面板、设置页、订阅弹窗可以做成组件,状态用 `ref/reactive`。
|
||||||
|
- 代价最大:地图容器与 BMapGL 命令式 API 结合需要封装层,团队要熟悉 Vue。
|
||||||
|
- 不建议现在直接跳,除非前端交互还要翻倍。
|
||||||
|
|
||||||
|
## 4. 推荐路径
|
||||||
|
|
||||||
|
```
|
||||||
|
Phase 0(1-2 天,无风险) 方案 A:拆文件 + ESM,收敛全局
|
||||||
|
Phase 1(2-3 天) 方案 B:引入 Vite + TS,只对「数据层 + 新模块」上类型
|
||||||
|
Phase 2(按需) 方案 C:把 3 个最复杂的面板改成 Vue 组件
|
||||||
|
```
|
||||||
|
|
||||||
|
**原则:每一阶段结束都能上线,都不改后端接口。**
|
||||||
|
|
||||||
|
## 4.5 进度(2026-11-16)
|
||||||
|
|
||||||
|
| 步骤 | 状态 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| `src/core/geo.js`(坐标转换 + 距离) | ✅ 已拆 | **经典脚本 + IIFE**,同时把同名函数挂回 `window`,调用点零改动;`map.js` 5017 → 4708 行 |
|
||||||
|
| `src/core/http.js` | ⬜ 待做 | 统一 fetch + Authorization + 错误归一 |
|
||||||
|
| `src/core/state.js` | ⬜ 待做 | 全局状态收敛(`selectedBike` / `activeRental` / `_nav`) |
|
||||||
|
| 其余模块 | ⬜ 待做 | 见第 5 节表格 |
|
||||||
|
|
||||||
|
为什么第一步用经典脚本而不是 `type="module"`:map.html 里还有 136 处内联事件依赖全局函数,
|
||||||
|
一次性切 ESM 会让所有按钮失效。等模块搬得差不多、全局桥(`compat/globals.js`)建好,
|
||||||
|
再整体切 ESM 并加 import。
|
||||||
|
|
||||||
|
## 5. Phase 0 模块边界(把 4776 行拆成这些)
|
||||||
|
| 模块 | 职责 | 现来源 |
|
||||||
|
|---|---|---|
|
||||||
|
| `src/core/http.js` | 统一 `fetch` + `Authorization` + 错误归一 | map.js 里散落的 fetch |
|
||||||
|
| `src/core/state.js` | 只读导出 + setter(`getActiveRental()` 等),替代裸全局 | 全局变量区 |
|
||||||
|
| `src/core/geo.js` | WGS84/GCJ02/BD09 转换、`calcDistance`、`offsetCoord` | map.js 顶部 + coordtransform |
|
||||||
|
| `src/map/map-core.js` | 地图初始化、缩放、视图、地图上的公共图层 | `initMap` 段 |
|
||||||
|
| `src/map/markers.js` | 车辆图标、增量渲染、气泡聚合、高亮 | 图标缓存 + `renderMap` |
|
||||||
|
| `src/card/bike-card.js` | 车辆卡片渲染、距离/电量/状态、按钮可用性 | `showBikeDetail` |
|
||||||
|
| `src/order/order-status.js` | 订单横幅、倒计时、`/api/order/status` 轮询、到期震动 | 订单状态段 |
|
||||||
|
| `src/order/order-actions.js` | 开锁/还车/加轮/月卡/寻车 | 订单动作段 |
|
||||||
|
| `src/nav/navigation.js` | 跟随式导航(已是独立文件,改成 ESM 即可) | navigation.js |
|
||||||
|
| `src/nav/walk-route.js` | 步行/骑行路线请求与缓存 | `refineWalkRoute` |
|
||||||
|
| `src/share/share.js` | 共享关系 | share.js |
|
||||||
|
| `src/subscribe/subscribe.js` | 订阅规则 | subscribe.js |
|
||||||
|
| `src/ui/modals.js` | 通用弹窗、确认框、Toast | `appConfirm` 等 |
|
||||||
|
| `src/ui/settings.js` | 我的/设置页 | settings-pages.js + 相关段 |
|
||||||
|
| `src/compat/globals.js` | **唯一**把函数挂 `window` 的地方(服务内联事件) | 新增 |
|
||||||
|
|
||||||
|
拆完 `map.js` 应降到 **< 300 行**(只剩编排:初始化顺序、事件绑定、模块装配)。
|
||||||
|
|
||||||
|
## 6. 迁移步骤(每步可单独提交、可回滚)
|
||||||
|
|
||||||
|
1. **建 `src/` 骨架 + `main.js`**:先只搬 `geo.js`、`http.js`(纯函数,零依赖),`map.js` 里改成 `import`。
|
||||||
|
2. **搬 `navigation.js`**:它是最近写的、自包含,改 ESM 最安全;用 headless 回归「导航/偏航重算/拖动回正」。
|
||||||
|
3. **搬 markers / card**:这两块与地图耦合最紧,先搬渲染函数,状态仍留在 `state.js`。
|
||||||
|
4. **搬 order / share / subscribe**:这三块有 node 契约测试,改完先跑 `node tests/*.cjs`。
|
||||||
|
5. **收口全局**:`grep -o 'on[a-z]*="[^"]*"' templates/map.html` 逐个对照 `globals.js`,确保 136 处全覆盖。
|
||||||
|
6. **删除旧文件**,`map.html` 只留一个 `<script type="module">`。
|
||||||
|
|
||||||
|
## 7. 风险与对策
|
||||||
|
|
||||||
|
| 风险 | 对策 |
|
||||||
|
|---|---|
|
||||||
|
| ESM 是严格作用域,内联事件全崩 | `globals.js` 集中挂载;上线前用 headless 点一遍 136 个入口里的高频项 |
|
||||||
|
| 模块图循环依赖(map ↔ card ↔ order) | 依赖方向单向:`core → map → card → order`;跨层用事件(`document.dispatchEvent`)而不是互调 |
|
||||||
|
| BMapGL 的 `callback=onBaiduMapReady` 与模块加载顺序冲突 | `map-core.js` 导出 `whenMapReady(): Promise`,其它模块 await 它,去掉隐式顺序依赖 |
|
||||||
|
| 静态资源哈希(`map_asset_version`) | 继续用 `routes/map_api.py` 的 MAP_ASSETS 列表,新增文件加进去即可 |
|
||||||
|
| node 契约测试读源码字符串 | Phase 0 期间保持函数名单不变;测试改为 `import` 后仍能断言 |
|
||||||
|
| 一次搬太多 | 每步一提交,`pytest + node + headless 冒烟` 全绿才继续 |
|
||||||
|
|
||||||
|
## 8. 验收标准
|
||||||
|
|
||||||
|
- `static/js/map.js` < 300 行;单文件最大 < 600 行。
|
||||||
|
- `window.` 上的符号只出现在 `globals.js`(`grep -c "window\." static/js/src | sort`)。
|
||||||
|
- 4 个 node 契约测试 + 161 个 pytest 全绿。
|
||||||
|
- headless 冒烟脚本覆盖:打开卡片 → 导航 → 拖动回正 → 结束导航 → 还车 → 订阅弹窗 → 共享弹窗。
|
||||||
|
- 首屏脚本请求数 ≤ 15,总体积不高于现在(213 KB + 76 KB)。
|
||||||
@@ -53,6 +53,23 @@ def _cleanup_locked(now: float):
|
|||||||
_codes.pop(email, None)
|
_codes.pop(email, None)
|
||||||
|
|
||||||
|
|
||||||
|
def record_cooldown(email: str) -> None:
|
||||||
|
"""只登记「刚发过」,不真正发信。
|
||||||
|
|
||||||
|
用于找回密码的防枚举:未注册邮箱也要占住 60 秒冷却,否则
|
||||||
|
「第二次请求是否 429」就成了判断邮箱有没有注册的预言机。
|
||||||
|
"""
|
||||||
|
email = (email or "").strip().lower()
|
||||||
|
if not email:
|
||||||
|
return
|
||||||
|
now = _now()
|
||||||
|
with _lock:
|
||||||
|
entry = _codes.get(email) or {"hash": "", "expires": now, "attempts": 0}
|
||||||
|
entry["sent_at"] = now
|
||||||
|
entry["purpose"] = "reset"
|
||||||
|
_codes[email] = entry
|
||||||
|
|
||||||
|
|
||||||
def send_code(email: str, purpose: str = "register") -> tuple:
|
def send_code(email: str, purpose: str = "register") -> tuple:
|
||||||
"""发送验证码到邮箱。返回 (ok, message)。受 60s 邮箱冷却与每小时 IP 上限约束。"""
|
"""发送验证码到邮箱。返回 (ok, message)。受 60s 邮箱冷却与每小时 IP 上限约束。"""
|
||||||
email = (email or "").strip().lower()
|
email = (email or "").strip().lower()
|
||||||
|
|||||||
@@ -0,0 +1,65 @@
|
|||||||
|
/* esbuild 构建脚本:把 src-ts/ 打成**一个 IIFE**
|
||||||
|
* (templates/map.html 用 <script defer src>,不是 type="module",所以必须是 IIFE/UMD)。
|
||||||
|
*
|
||||||
|
* node esbuild.config.mjs
|
||||||
|
*
|
||||||
|
* 产物:
|
||||||
|
* static/dist/app.js 入口 bundle(含 sourceMappingURL 注释)
|
||||||
|
* static/dist/app.js.map sourcemap(外部,便于对着原 static/js/*.js 调试)
|
||||||
|
*/
|
||||||
|
import esbuild from "esbuild";
|
||||||
|
import fs from "node:fs";
|
||||||
|
import path from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||||
|
const OUT_FILE = path.join(HERE, "static", "dist", "app.js");
|
||||||
|
|
||||||
|
const result = await esbuild.build({
|
||||||
|
entryPoints: [path.join(HERE, "src-ts", "main.ts")],
|
||||||
|
outfile: OUT_FILE,
|
||||||
|
bundle: true,
|
||||||
|
format: "iife",
|
||||||
|
target: "es2019",
|
||||||
|
platform: "browser",
|
||||||
|
charset: "utf8",
|
||||||
|
sourcemap: "linked", // external map 文件 + 末尾 //# sourceMappingURL(external 模式不会写这行注释)
|
||||||
|
sourcesContent: true,
|
||||||
|
minify: false,
|
||||||
|
legalComments: "none",
|
||||||
|
logLevel: "warning",
|
||||||
|
|
||||||
|
banner: {
|
||||||
|
js: [
|
||||||
|
"/*! 小白超人地图前端 bundle —— 由 src-ts/ 经 esbuild 打包(IIFE)。",
|
||||||
|
" * 源码:src-ts/** (逐块搬自 static/js/{map,navigation,share,subscribe}.js)",
|
||||||
|
" * 构建:node esbuild.config.mjs",
|
||||||
|
" * 回滚:把 templates/map.html 里的 app.js 换回原 static/js/map.js 等脚本即可。",
|
||||||
|
" */",
|
||||||
|
].join("\n"),
|
||||||
|
},
|
||||||
|
metafile: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const warning of result.warnings) console.warn("[esbuild]", warning.text);
|
||||||
|
|
||||||
|
const bytes = fs.statSync(OUT_FILE).size;
|
||||||
|
const mapFile = OUT_FILE + ".map";
|
||||||
|
const mapBytes = fs.existsSync(mapFile) ? fs.statSync(mapFile).size : 0;
|
||||||
|
const kib = (n) => (n / 1024).toFixed(1) + " KiB";
|
||||||
|
|
||||||
|
console.log("构建完成");
|
||||||
|
console.log(` static/dist/app.js ${kib(bytes)} (${bytes} 字节)`);
|
||||||
|
console.log(` static/dist/app.js.map ${kib(mapBytes)} (${mapBytes} 字节)`);
|
||||||
|
|
||||||
|
/* 输入模块体积表:方便对照每个源模块的实际贡献 */
|
||||||
|
const inputs = Object.entries(result.metafile.outputs)
|
||||||
|
.find(([file]) => file.endsWith("app.js"))?.[1]?.inputs;
|
||||||
|
if (inputs) {
|
||||||
|
const rows = Object.entries(inputs)
|
||||||
|
.map(([file, info]) => [file, info.bytesInOutput])
|
||||||
|
.sort((a, b) => b[1] - a[1]);
|
||||||
|
console.log(" 按模块(压缩前进 bundle 的字节数):");
|
||||||
|
for (const [file, n] of rows) console.log(` ${file.padEnd(34)} ${String(n).padStart(7)}`);
|
||||||
|
}
|
||||||
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
-----BEGIN PRIVATE KEY-----
|
|
||||||
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC6AR4Al85osaYq
|
|
||||||
TGcd9xuyyeDIrvwtyYLdO8xobJtxNowu/JXK4oj29OdvyR8kzy1BnE/XTi49XBMF
|
|
||||||
rZs92VoWO7wMTDS2/pK/A8DFcxqEHBKURr6xgQaOAa7B3MOl6b12mTH7e3ow+T++
|
|
||||||
zktQ3dsmyeqFEchgVXTkjBxSY1Ae+7cORI/JW6QGBuSDSR9mZsPR9J3Yw6Ltbug9
|
|
||||||
9fsYWz6ajDs5+D2YG97BrNOx+bzQqQFEsmUbtwST2v6owTvlecDM9KvGOyvaBSG7
|
|
||||||
jhgnkc+pKDP6OxaIsHjtTwPQaB4RlkUMo7GhLNp0iEo9wDMfqubK/7zxE5GGh+1q
|
|
||||||
yeaXVIzFAgMBAAECggEAAz37vjo8gHoAPHfXyvTrXa1ue/EDjO9t7C9GUSz7dKNl
|
|
||||||
GXiQ9S1dAnj4WRbMsoE4omPNccz3ZLMTKHkt3eEeVImMAzwyJbJq77tqrnENgu9T
|
|
||||||
qj6lb5tLzZ6H45yBKIYveulmrqHTWmvYdESiRBw/MqjjAUNzFlgcUSjZYYeWS5lD
|
|
||||||
ViTo/jR0uInj5Ebj3CfNCMZXwMHDZVIcp5EruXbZv/PAozCCEwzUOdxiibs5iX25
|
|
||||||
+ArnVaYRbTTttyWjf1pu0UxmiZaqN7/3Z0nTIL13l8QEakooVGKOBFOG1HLfYBNG
|
|
||||||
hnYcfbWPOzgoowDqfzb3ylovdQJPL4Lrt5Oxd9ajTQKBgQDhSE/i+JhfhZg2+PZW
|
|
||||||
WGKA3FWcFJ8UScCCHdHP5rVxn5fGWIHMWtURnjzzkUm38DONXQihl5M8Mg99wfc9
|
|
||||||
wIGDv7VHqZlSBF/s0aF7w4ndsVXttClh5NFl/7/RGmpVM5EklIwm+9Kox5fAkzOX
|
|
||||||
/UAeHxIoooP6bvWUG5BEksX+KwKBgQDTXcR2VS564poOsFIB93VQ8uwN/qrVz33Z
|
|
||||||
T8PQXV5DkyhQ9mvGknUN0v8jG7xb946ZO4GQmISA6AcOvdkpeQYYNa/HKu3wmZ6G
|
|
||||||
IZmZgA9XNdX4EVnztyuNY7Bnrepm3xHEH4DhafQqeqc2tjplxMmUAqlFTfDhwioq
|
|
||||||
IukFQDgYzwKBgEdcuLGVPe9ESmtfgejoJovbP+MpRRsQIcMV3xiUZHWRsGpMLxGk
|
|
||||||
1Em4bmZZZ5i0ph/pkIpfkWxID1Au2TreeChb2fjRaJfqethxr02dK1bmjem2YEV6
|
|
||||||
TjqZQRHj5DsJErkbtSnEK377er6t4nIK7vybqwzkLhpue6xm7tRKCh3xAoGAA7PU
|
|
||||||
yS3czpJBmJhGF3q6N1zJ/cTEQVKNJc1b5L599DkTr7dhU+0k18UmavsFZacEfHKq
|
|
||||||
ZloFmCx4Uy3ILA3OqYXnOlnqKRjHyhm0kxfHLQPoZ5wGM1q2DJf+cxJ81Kh7qy/S
|
|
||||||
FiDBAi172F2A0F+OGGWjiW9AFPRNwMczxb/GO8kCgYEAuG4Fn/CVrXSY8HyDEjoJ
|
|
||||||
Miamb4fP/xYT0qAQPRZXzdAlsEsWnAO9DlQSevzAWZQbQXEl3V4ZQo9N/GT+3rfw
|
|
||||||
ZiD1fB5SUB+91PAXot5rCgC9G8Yih+78tRifPRnFJVYfn+/o6rw3rNG4LzM/8ssn
|
|
||||||
M+XVUWaErmaUPpUH5dGcOVA=
|
|
||||||
-----END PRIVATE KEY-----
|
|
||||||
+49
-9
@@ -118,7 +118,6 @@ class SharedMapCache:
|
|||||||
success = result.get("rtn_code") == 0
|
success = result.get("rtn_code") == 0
|
||||||
if success:
|
if success:
|
||||||
last_success = started
|
last_success = started
|
||||||
# Store errors for the same window too, preventing an outage retry storm.
|
|
||||||
result = {**result, "map_snapshot": {
|
result = {**result, "map_snapshot": {
|
||||||
"snapshot_id": token,
|
"snapshot_id": token,
|
||||||
"fetched_at": last_success,
|
"fetched_at": last_success,
|
||||||
@@ -129,16 +128,57 @@ class SharedMapCache:
|
|||||||
payload = json.dumps(result, ensure_ascii=False, separators=(",", ":"))
|
payload = json.dumps(result, ensure_ascii=False, separators=(",", ":"))
|
||||||
conn = self._connect()
|
conn = self._connect()
|
||||||
try:
|
try:
|
||||||
cursor = conn.execute("""UPDATE shared_map_snapshots SET
|
if success:
|
||||||
payload=?, fetched_at=?, expires_at=?, last_success_at=?, lease_token=NULL, lease_until=0
|
cursor = conn.execute("""UPDATE shared_map_snapshots SET
|
||||||
WHERE bike_type=? AND lease_token=?""",
|
payload=?, fetched_at=?, expires_at=?, last_success_at=?, lease_token=NULL, lease_until=0
|
||||||
(payload, started, started + self.ttl, last_success, bike_type, token))
|
WHERE bike_type=? AND lease_token=?""",
|
||||||
conn.commit()
|
(payload, started, started + self.ttl, last_success,
|
||||||
published = cursor.rowcount == 1
|
bike_type, token))
|
||||||
|
conn.commit()
|
||||||
|
published = cursor.rowcount == 1
|
||||||
|
else:
|
||||||
|
# 采集失败的这一轮**不要覆盖上一份好数据**:只把租约放掉、
|
||||||
|
# 把过期时间往后推一个窗口(避免重试风暴),payload 保持原样。
|
||||||
|
# 只有「从来没有过好数据」时才写入错误 payload(保证窗口内返回值稳定)。
|
||||||
|
prev = conn.execute(
|
||||||
|
"SELECT payload FROM shared_map_snapshots WHERE bike_type=?",
|
||||||
|
(bike_type,)).fetchone()
|
||||||
|
if prev and prev["payload"]:
|
||||||
|
conn.execute("""UPDATE shared_map_snapshots SET expires_at=?, lease_token=NULL,
|
||||||
|
lease_until=0 WHERE bike_type=? AND lease_token=?""",
|
||||||
|
(started + self.ttl, bike_type, token))
|
||||||
|
published = False
|
||||||
|
else:
|
||||||
|
conn.execute("""UPDATE shared_map_snapshots SET payload=?, fetched_at=?,
|
||||||
|
expires_at=?, last_success_at=?, lease_token=NULL, lease_until=0
|
||||||
|
WHERE bike_type=? AND lease_token=?""",
|
||||||
|
(payload, started, started + self.ttl, last_success,
|
||||||
|
bike_type, token))
|
||||||
|
published = True
|
||||||
|
conn.commit()
|
||||||
|
row = conn.execute("SELECT payload FROM shared_map_snapshots WHERE bike_type=?",
|
||||||
|
(bike_type,)).fetchone()
|
||||||
finally:
|
finally:
|
||||||
conn.close()
|
conn.close()
|
||||||
# An expired lease holder must never publish over a newer worker's snapshot.
|
|
||||||
return json.loads(payload) if published else self.get(bike_type, loader)
|
if success and published:
|
||||||
|
return json.loads(payload)
|
||||||
|
if published:
|
||||||
|
# 失败但已放租约:把当前行(通常是上一份好数据)返回给前端
|
||||||
|
if row and row["payload"]:
|
||||||
|
try:
|
||||||
|
return json.loads(row["payload"])
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return json.loads(payload)
|
||||||
|
# 没抢到发布权(租约被别人接管):直接读当前行,**不再递归调用 self.get**
|
||||||
|
# (原来同名递归 + deadline 每次重置,竞争下会无界重试)
|
||||||
|
if row and row["payload"]:
|
||||||
|
try:
|
||||||
|
return json.loads(row["payload"])
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return json.loads(payload)
|
||||||
|
|
||||||
def freshness(self, bike_type="3"):
|
def freshness(self, bike_type="3"):
|
||||||
conn = self._connect()
|
conn = self._connect()
|
||||||
|
|||||||
Generated
+875
@@ -0,0 +1,875 @@
|
|||||||
|
{
|
||||||
|
"name": "xbniu-map-ts",
|
||||||
|
"version": "0.0.0",
|
||||||
|
"lockfileVersion": 3,
|
||||||
|
"requires": true,
|
||||||
|
"packages": {
|
||||||
|
"": {
|
||||||
|
"name": "xbniu-map-ts",
|
||||||
|
"version": "0.0.0",
|
||||||
|
"devDependencies": {
|
||||||
|
"esbuild": "^0.28.2",
|
||||||
|
"typescript": "^7.0.2"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/aix-ppc64": {
|
||||||
|
"version": "0.28.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz",
|
||||||
|
"integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==",
|
||||||
|
"cpu": [
|
||||||
|
"ppc64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"aix"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/android-arm": {
|
||||||
|
"version": "0.28.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/android-arm/-/android-arm-0.28.2.tgz",
|
||||||
|
"integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==",
|
||||||
|
"cpu": [
|
||||||
|
"arm"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"android"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/android-arm64": {
|
||||||
|
"version": "0.28.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz",
|
||||||
|
"integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"android"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/android-x64": {
|
||||||
|
"version": "0.28.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/android-x64/-/android-x64-0.28.2.tgz",
|
||||||
|
"integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"android"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/darwin-arm64": {
|
||||||
|
"version": "0.28.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz",
|
||||||
|
"integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"darwin"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/darwin-x64": {
|
||||||
|
"version": "0.28.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz",
|
||||||
|
"integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"darwin"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/freebsd-arm64": {
|
||||||
|
"version": "0.28.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz",
|
||||||
|
"integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"freebsd"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/freebsd-x64": {
|
||||||
|
"version": "0.28.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz",
|
||||||
|
"integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"freebsd"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/linux-arm": {
|
||||||
|
"version": "0.28.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz",
|
||||||
|
"integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==",
|
||||||
|
"cpu": [
|
||||||
|
"arm"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/linux-arm64": {
|
||||||
|
"version": "0.28.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz",
|
||||||
|
"integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/linux-ia32": {
|
||||||
|
"version": "0.28.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz",
|
||||||
|
"integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==",
|
||||||
|
"cpu": [
|
||||||
|
"ia32"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/linux-loong64": {
|
||||||
|
"version": "0.28.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz",
|
||||||
|
"integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==",
|
||||||
|
"cpu": [
|
||||||
|
"loong64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/linux-mips64el": {
|
||||||
|
"version": "0.28.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz",
|
||||||
|
"integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==",
|
||||||
|
"cpu": [
|
||||||
|
"mips64el"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/linux-ppc64": {
|
||||||
|
"version": "0.28.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz",
|
||||||
|
"integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==",
|
||||||
|
"cpu": [
|
||||||
|
"ppc64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/linux-riscv64": {
|
||||||
|
"version": "0.28.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz",
|
||||||
|
"integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==",
|
||||||
|
"cpu": [
|
||||||
|
"riscv64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/linux-s390x": {
|
||||||
|
"version": "0.28.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz",
|
||||||
|
"integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==",
|
||||||
|
"cpu": [
|
||||||
|
"s390x"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/linux-x64": {
|
||||||
|
"version": "0.28.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz",
|
||||||
|
"integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/netbsd-arm64": {
|
||||||
|
"version": "0.28.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz",
|
||||||
|
"integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"netbsd"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/netbsd-x64": {
|
||||||
|
"version": "0.28.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz",
|
||||||
|
"integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"netbsd"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/openbsd-arm64": {
|
||||||
|
"version": "0.28.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz",
|
||||||
|
"integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"openbsd"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/openbsd-x64": {
|
||||||
|
"version": "0.28.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz",
|
||||||
|
"integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"openbsd"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/openharmony-arm64": {
|
||||||
|
"version": "0.28.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz",
|
||||||
|
"integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"openharmony"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/sunos-x64": {
|
||||||
|
"version": "0.28.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz",
|
||||||
|
"integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"sunos"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/win32-arm64": {
|
||||||
|
"version": "0.28.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz",
|
||||||
|
"integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"win32"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/win32-ia32": {
|
||||||
|
"version": "0.28.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz",
|
||||||
|
"integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==",
|
||||||
|
"cpu": [
|
||||||
|
"ia32"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"win32"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/win32-x64": {
|
||||||
|
"version": "0.28.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz",
|
||||||
|
"integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"win32"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@typescript/typescript-aix-ppc64": {
|
||||||
|
"version": "7.0.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz",
|
||||||
|
"integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==",
|
||||||
|
"cpu": [
|
||||||
|
"ppc64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"aix"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=16.20.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@typescript/typescript-darwin-arm64": {
|
||||||
|
"version": "7.0.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz",
|
||||||
|
"integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"darwin"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=16.20.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@typescript/typescript-darwin-x64": {
|
||||||
|
"version": "7.0.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz",
|
||||||
|
"integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"darwin"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=16.20.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@typescript/typescript-freebsd-arm64": {
|
||||||
|
"version": "7.0.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz",
|
||||||
|
"integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"freebsd"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=16.20.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@typescript/typescript-freebsd-x64": {
|
||||||
|
"version": "7.0.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz",
|
||||||
|
"integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"freebsd"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=16.20.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@typescript/typescript-linux-arm": {
|
||||||
|
"version": "7.0.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz",
|
||||||
|
"integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==",
|
||||||
|
"cpu": [
|
||||||
|
"arm"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=16.20.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@typescript/typescript-linux-arm64": {
|
||||||
|
"version": "7.0.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz",
|
||||||
|
"integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=16.20.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@typescript/typescript-linux-loong64": {
|
||||||
|
"version": "7.0.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz",
|
||||||
|
"integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==",
|
||||||
|
"cpu": [
|
||||||
|
"loong64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=16.20.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@typescript/typescript-linux-mips64el": {
|
||||||
|
"version": "7.0.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz",
|
||||||
|
"integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==",
|
||||||
|
"cpu": [
|
||||||
|
"mips64el"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=16.20.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@typescript/typescript-linux-ppc64": {
|
||||||
|
"version": "7.0.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz",
|
||||||
|
"integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==",
|
||||||
|
"cpu": [
|
||||||
|
"ppc64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=16.20.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@typescript/typescript-linux-riscv64": {
|
||||||
|
"version": "7.0.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz",
|
||||||
|
"integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==",
|
||||||
|
"cpu": [
|
||||||
|
"riscv64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=16.20.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@typescript/typescript-linux-s390x": {
|
||||||
|
"version": "7.0.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz",
|
||||||
|
"integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==",
|
||||||
|
"cpu": [
|
||||||
|
"s390x"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=16.20.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@typescript/typescript-linux-x64": {
|
||||||
|
"version": "7.0.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz",
|
||||||
|
"integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=16.20.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@typescript/typescript-netbsd-arm64": {
|
||||||
|
"version": "7.0.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz",
|
||||||
|
"integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"netbsd"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=16.20.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@typescript/typescript-netbsd-x64": {
|
||||||
|
"version": "7.0.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz",
|
||||||
|
"integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"netbsd"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=16.20.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@typescript/typescript-openbsd-arm64": {
|
||||||
|
"version": "7.0.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz",
|
||||||
|
"integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"openbsd"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=16.20.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@typescript/typescript-openbsd-x64": {
|
||||||
|
"version": "7.0.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz",
|
||||||
|
"integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"openbsd"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=16.20.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@typescript/typescript-sunos-x64": {
|
||||||
|
"version": "7.0.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz",
|
||||||
|
"integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"sunos"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=16.20.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@typescript/typescript-win32-arm64": {
|
||||||
|
"version": "7.0.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz",
|
||||||
|
"integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"win32"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=16.20.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@typescript/typescript-win32-x64": {
|
||||||
|
"version": "7.0.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz",
|
||||||
|
"integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"win32"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=16.20.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/esbuild": {
|
||||||
|
"version": "0.28.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/esbuild/-/esbuild-0.28.2.tgz",
|
||||||
|
"integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==",
|
||||||
|
"dev": true,
|
||||||
|
"hasInstallScript": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"bin": {
|
||||||
|
"esbuild": "bin/esbuild"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
},
|
||||||
|
"optionalDependencies": {
|
||||||
|
"@esbuild/aix-ppc64": "0.28.2",
|
||||||
|
"@esbuild/android-arm": "0.28.2",
|
||||||
|
"@esbuild/android-arm64": "0.28.2",
|
||||||
|
"@esbuild/android-x64": "0.28.2",
|
||||||
|
"@esbuild/darwin-arm64": "0.28.2",
|
||||||
|
"@esbuild/darwin-x64": "0.28.2",
|
||||||
|
"@esbuild/freebsd-arm64": "0.28.2",
|
||||||
|
"@esbuild/freebsd-x64": "0.28.2",
|
||||||
|
"@esbuild/linux-arm": "0.28.2",
|
||||||
|
"@esbuild/linux-arm64": "0.28.2",
|
||||||
|
"@esbuild/linux-ia32": "0.28.2",
|
||||||
|
"@esbuild/linux-loong64": "0.28.2",
|
||||||
|
"@esbuild/linux-mips64el": "0.28.2",
|
||||||
|
"@esbuild/linux-ppc64": "0.28.2",
|
||||||
|
"@esbuild/linux-riscv64": "0.28.2",
|
||||||
|
"@esbuild/linux-s390x": "0.28.2",
|
||||||
|
"@esbuild/linux-x64": "0.28.2",
|
||||||
|
"@esbuild/netbsd-arm64": "0.28.2",
|
||||||
|
"@esbuild/netbsd-x64": "0.28.2",
|
||||||
|
"@esbuild/openbsd-arm64": "0.28.2",
|
||||||
|
"@esbuild/openbsd-x64": "0.28.2",
|
||||||
|
"@esbuild/openharmony-arm64": "0.28.2",
|
||||||
|
"@esbuild/sunos-x64": "0.28.2",
|
||||||
|
"@esbuild/win32-arm64": "0.28.2",
|
||||||
|
"@esbuild/win32-ia32": "0.28.2",
|
||||||
|
"@esbuild/win32-x64": "0.28.2"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/typescript": {
|
||||||
|
"version": "7.0.2",
|
||||||
|
"resolved": "https://repo.huaweicloud.com/repository/npm/typescript/-/typescript-7.0.2.tgz",
|
||||||
|
"integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"bin": {
|
||||||
|
"tsc": "bin/tsc"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=16.20.0"
|
||||||
|
},
|
||||||
|
"optionalDependencies": {
|
||||||
|
"@typescript/typescript-aix-ppc64": "7.0.2",
|
||||||
|
"@typescript/typescript-darwin-arm64": "7.0.2",
|
||||||
|
"@typescript/typescript-darwin-x64": "7.0.2",
|
||||||
|
"@typescript/typescript-freebsd-arm64": "7.0.2",
|
||||||
|
"@typescript/typescript-freebsd-x64": "7.0.2",
|
||||||
|
"@typescript/typescript-linux-arm": "7.0.2",
|
||||||
|
"@typescript/typescript-linux-arm64": "7.0.2",
|
||||||
|
"@typescript/typescript-linux-loong64": "7.0.2",
|
||||||
|
"@typescript/typescript-linux-mips64el": "7.0.2",
|
||||||
|
"@typescript/typescript-linux-ppc64": "7.0.2",
|
||||||
|
"@typescript/typescript-linux-riscv64": "7.0.2",
|
||||||
|
"@typescript/typescript-linux-s390x": "7.0.2",
|
||||||
|
"@typescript/typescript-linux-x64": "7.0.2",
|
||||||
|
"@typescript/typescript-netbsd-arm64": "7.0.2",
|
||||||
|
"@typescript/typescript-netbsd-x64": "7.0.2",
|
||||||
|
"@typescript/typescript-openbsd-arm64": "7.0.2",
|
||||||
|
"@typescript/typescript-openbsd-x64": "7.0.2",
|
||||||
|
"@typescript/typescript-sunos-x64": "7.0.2",
|
||||||
|
"@typescript/typescript-win32-arm64": "7.0.2",
|
||||||
|
"@typescript/typescript-win32-x64": "7.0.2"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"name": "xbniu-map-ts",
|
||||||
|
"version": "0.0.0",
|
||||||
|
"private": true,
|
||||||
|
"description": "TypeScript + esbuild rebuild of static/js/map.js (plus navigation/share/subscribe) as a single IIFE bundle at static/dist/app.js",
|
||||||
|
"scripts": {
|
||||||
|
"build": "node esbuild.config.mjs",
|
||||||
|
"typecheck": "tsc --noEmit",
|
||||||
|
"verify:globals": "node src-ts/tools/verify-globals.mjs"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"esbuild": "^0.28.2",
|
||||||
|
"typescript": "^7.0.2"
|
||||||
|
}
|
||||||
|
}
|
||||||
+212
@@ -0,0 +1,212 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""上游停车区(parkeArea)多边形:还车点判定 + 失败后吸附到最近合法停车区。
|
||||||
|
|
||||||
|
## 为什么要有这个模块
|
||||||
|
|
||||||
|
上游 `/record/checkLocation` 会判断「这个坐标能不能还车」,不在停车区内返回
|
||||||
|
`parkNoShow`。旧兜底(`routes/rental.py::get_nearest_park_point`)是「找最近的一辆
|
||||||
|
type=1 共享单车,把它的坐标当停车点」—— 拿车当车位,周边没单车就直接失效,
|
||||||
|
而且返回的是 GCJ02、被当成 WGS84 发回上游。本模块改用上游自己返回的
|
||||||
|
`parkeArea` 多边形做判断和吸附。
|
||||||
|
|
||||||
|
## 坐标系(改之前先读完,这里错一次就偏 500 米)
|
||||||
|
|
||||||
|
**本模块只处理 GCJ02,不做任何转换。**
|
||||||
|
|
||||||
|
- `parkeArea.points` / `bicycleStation` / `bike_history` / `campus_locations`
|
||||||
|
全部是 **GCJ02**(上游与本地库同一套);
|
||||||
|
- 唯一不一样的是浏览器 `navigator.geolocation`,它给 **WGS84**;
|
||||||
|
- 所以 WGS84 → GCJ02 的转换只发生在 API 边界(`routes/rental.py::
|
||||||
|
to_upstream_coords`、`routes/share.py` 的共享还车入口),一次转完,
|
||||||
|
之后从判定到发上游全用 GCJ02。
|
||||||
|
|
||||||
|
把 GCJ02 多边形直接和 WGS84 点比较 = 系统性偏移,比不判断更糟;反过来,
|
||||||
|
把 GCJ02 点再转一次也是同一个错误。
|
||||||
|
"""
|
||||||
|
import math
|
||||||
|
|
||||||
|
from campus import point_in_polygon
|
||||||
|
|
||||||
|
#: 吸附距离超过这个值(米)只打日志、仍然吸附:说明坐标本身可能有问题。
|
||||||
|
SNAP_WARN_M = 800.0
|
||||||
|
|
||||||
|
#: 从停车区边界往内部推的试探步长(米),第一个落在多边形内的即采用。
|
||||||
|
_INSIDE_STEPS_M = (0.6, 1.5, 3.0, 6.0, 12.0, 25.0)
|
||||||
|
|
||||||
|
_EARTH_R = 6371000.0
|
||||||
|
|
||||||
|
|
||||||
|
def _num(value):
|
||||||
|
try:
|
||||||
|
return float(value)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
# ========== 解析 ==========
|
||||||
|
|
||||||
|
def parse_park_areas(map_data):
|
||||||
|
"""上游 `/project/map` 的 data -> [{"points": [[lat, lng], ...]}]。
|
||||||
|
|
||||||
|
- **只跳过 `is_disable == 2`(停用)块**;`1` 是启用 —— 这条是实测出来的,
|
||||||
|
别凭字段名猜:拿 23 块的首点逐块问上游 `/record/checkLocation`,
|
||||||
|
21 块 `is_disable=1` 全部返回 `rtn=0 定位已满足还车条件`,唯一的
|
||||||
|
`is_disable=2` 块返回 `204009 请到停车区域进行还车`。
|
||||||
|
(前端 `map.js` 里 `is_disable !== 1` 当启用画绿色,同样判反了。)
|
||||||
|
- points 兼容 `{latitude, longitude}` 与 `[lat, lng]` 两种写法;
|
||||||
|
- 少于 3 个点的(构不成多边形)忽略。
|
||||||
|
|
||||||
|
注意:返回的坐标是上游原样的 **GCJ02**(实测 checkLocation 只认这套),
|
||||||
|
不要在这里转换。
|
||||||
|
"""
|
||||||
|
if not isinstance(map_data, dict):
|
||||||
|
return []
|
||||||
|
raw_areas = map_data.get("parkeArea")
|
||||||
|
if not isinstance(raw_areas, list):
|
||||||
|
return []
|
||||||
|
areas = []
|
||||||
|
for raw in raw_areas:
|
||||||
|
if not isinstance(raw, dict):
|
||||||
|
continue
|
||||||
|
if str(raw.get("is_disable")) == "2": # 2 = 停用;1 = 启用
|
||||||
|
continue
|
||||||
|
points = []
|
||||||
|
for item in raw.get("points") or []:
|
||||||
|
if isinstance(item, dict):
|
||||||
|
lat, lng = _num(item.get("latitude")), _num(item.get("longitude"))
|
||||||
|
elif isinstance(item, (list, tuple)) and len(item) >= 2:
|
||||||
|
lat, lng = _num(item[0]), _num(item[1])
|
||||||
|
else:
|
||||||
|
continue
|
||||||
|
if lat is None or lng is None:
|
||||||
|
continue
|
||||||
|
points.append([lat, lng])
|
||||||
|
if len(points) >= 3:
|
||||||
|
areas.append({"points": points})
|
||||||
|
return areas
|
||||||
|
|
||||||
|
|
||||||
|
# ========== 局部平面投影(百米尺度下足够精确,避免每步开方算球面) ==========
|
||||||
|
|
||||||
|
def _to_xy(lat, lng, origin_lat, origin_lng):
|
||||||
|
x = math.radians(lng - origin_lng) * _EARTH_R * math.cos(math.radians(origin_lat))
|
||||||
|
y = math.radians(lat - origin_lat) * _EARTH_R
|
||||||
|
return x, y
|
||||||
|
|
||||||
|
|
||||||
|
def _to_latlng(x, y, origin_lat, origin_lng):
|
||||||
|
lat = origin_lat + math.degrees(y / _EARTH_R)
|
||||||
|
cos = math.cos(math.radians(origin_lat))
|
||||||
|
lng = origin_lng + math.degrees(x / (_EARTH_R * (cos if abs(cos) > 1e-9 else 1e-9)))
|
||||||
|
return lat, lng
|
||||||
|
|
||||||
|
|
||||||
|
def closest_boundary_point(lat, lng, polygon):
|
||||||
|
"""点到多边形边界最近的点(与边平行的投影)。
|
||||||
|
|
||||||
|
入参与返回均为 GCJ02,返回 `{"latitude", "longitude", "distance"}`(米),
|
||||||
|
多边形非法时返回 None。
|
||||||
|
"""
|
||||||
|
if not polygon or len(polygon) < 3:
|
||||||
|
return None
|
||||||
|
best = None
|
||||||
|
best_d = float("inf")
|
||||||
|
for i in range(len(polygon)):
|
||||||
|
ax, ay = _to_xy(polygon[i][0], polygon[i][1], lat, lng)
|
||||||
|
bx, by = _to_xy(polygon[(i + 1) % len(polygon)][0],
|
||||||
|
polygon[(i + 1) % len(polygon)][1], lat, lng)
|
||||||
|
dx, dy = bx - ax, by - ay
|
||||||
|
seg2 = dx * dx + dy * dy
|
||||||
|
# 查询点就是原点 (0,0)
|
||||||
|
t = 0.0 if seg2 == 0 else max(0.0, min(1.0, -(ax * dx + ay * dy) / seg2))
|
||||||
|
cx, cy = ax + t * dx, ay + t * dy
|
||||||
|
dist = math.hypot(cx, cy)
|
||||||
|
if dist < best_d:
|
||||||
|
best_d = dist
|
||||||
|
best = (cx, cy)
|
||||||
|
if best is None:
|
||||||
|
return None
|
||||||
|
plat, plng = _to_latlng(best[0], best[1], lat, lng)
|
||||||
|
return {"latitude": plat, "longitude": plng, "distance": best_d}
|
||||||
|
|
||||||
|
|
||||||
|
def _centroid(polygon):
|
||||||
|
n = len(polygon)
|
||||||
|
return (sum(p[0] for p in polygon) / n, sum(p[1] for p in polygon) / n)
|
||||||
|
|
||||||
|
|
||||||
|
def _nudge_inside(edge_lat, edge_lng, polygon, target_lat, target_lng):
|
||||||
|
"""从边界点朝 target(一般是质心)方向逐级推,返回第一个落在内部的点。"""
|
||||||
|
dx, dy = _to_xy(target_lat, target_lng, edge_lat, edge_lng)
|
||||||
|
norm = math.hypot(dx, dy)
|
||||||
|
if norm == 0:
|
||||||
|
return None
|
||||||
|
ux, uy = dx / norm, dy / norm
|
||||||
|
for step in _INSIDE_STEPS_M:
|
||||||
|
cand_lat, cand_lng = _to_latlng(ux * step, uy * step, edge_lat, edge_lng)
|
||||||
|
if point_in_polygon(cand_lat, cand_lng, polygon):
|
||||||
|
return {"latitude": cand_lat, "longitude": cand_lng}
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def nearest_parking_point(lat, lng, areas):
|
||||||
|
"""GCJ02 点 -> 最近的可用停车区里的一个 GCJ02 点。
|
||||||
|
|
||||||
|
返回 `{"latitude", "longitude", "distance"}`;没有任何可用区时返回 None。
|
||||||
|
"""
|
||||||
|
if not areas:
|
||||||
|
return None
|
||||||
|
best_area = None
|
||||||
|
best_edge = None
|
||||||
|
best_d = float("inf")
|
||||||
|
for area in areas:
|
||||||
|
edge = closest_boundary_point(lat, lng, area["points"])
|
||||||
|
if edge is None:
|
||||||
|
continue
|
||||||
|
if edge["distance"] < best_d:
|
||||||
|
best_area, best_edge, best_d = area, edge, edge["distance"]
|
||||||
|
if best_area is None or best_edge is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
polygon = best_area["points"]
|
||||||
|
centre_lat, centre_lng = _centroid(polygon)
|
||||||
|
inside = _nudge_inside(best_edge["latitude"], best_edge["longitude"],
|
||||||
|
polygon, centre_lat, centre_lng)
|
||||||
|
if inside is None:
|
||||||
|
# 退化/自交多边形:退到质心,质心也不在多边形内就放弃,不要瞎发坐标。
|
||||||
|
if point_in_polygon(centre_lat, centre_lng, polygon):
|
||||||
|
inside = {"latitude": centre_lat, "longitude": centre_lng}
|
||||||
|
else:
|
||||||
|
return None
|
||||||
|
inside["distance"] = best_d
|
||||||
|
return inside
|
||||||
|
|
||||||
|
|
||||||
|
# ========== 对外主入口 ==========
|
||||||
|
|
||||||
|
def resolve_return_coord(latitude, longitude, areas):
|
||||||
|
"""把一个还车坐标解析成「一定落在停车区内」的坐标(全程 GCJ02)。
|
||||||
|
|
||||||
|
返回:
|
||||||
|
- None:拿不到可用停车区(调用方保留原坐标);
|
||||||
|
- {"inside": True, "moved": False}:本来就在区内,原样返回;
|
||||||
|
- {"inside": False, "moved": True}:已吸附到最近停车区内的点。
|
||||||
|
|
||||||
|
⚠️ 入参必须是 GCJ02。浏览器给的是 WGS84,调用方要先用
|
||||||
|
`campus.wgs84_to_gcj02` / `routes.rental.to_upstream_coords` 转换一次。
|
||||||
|
"""
|
||||||
|
lat, lng = _num(latitude), _num(longitude)
|
||||||
|
if lat is None or lng is None or not areas:
|
||||||
|
return None
|
||||||
|
|
||||||
|
for area in areas:
|
||||||
|
if point_in_polygon(lat, lng, area["points"]):
|
||||||
|
return {"latitude": lat, "longitude": lng,
|
||||||
|
"inside": True, "moved": False, "distance": 0.0}
|
||||||
|
|
||||||
|
snapped = nearest_parking_point(lat, lng, areas)
|
||||||
|
if snapped is None:
|
||||||
|
return None
|
||||||
|
return {"latitude": snapped["latitude"], "longitude": snapped["longitude"],
|
||||||
|
"inside": False, "moved": True, "distance": snapped["distance"]}
|
||||||
-27
@@ -1,27 +0,0 @@
|
|||||||
-----BEGIN RSA PRIVATE KEY-----
|
|
||||||
MIIEpAIBAAKCAQEA6uK6FJIX3CHtkkWb8s448v5l0UY8yh4hbL/xhvQQrAGEdeDR
|
|
||||||
m/zwstwsw/OKkkWLe0eE1zC0/zvgZN8gjXNtgUK4A6uev+CjctEPijT6fhcXsWsp
|
|
||||||
QQ6ihRGw+giSIm8TIGdh97cwpyKB6e8EgpddLlcaBPBd4Xkyi5aZwGuqDjuvDMeY
|
|
||||||
fd+3Fe0MuZ61RObQ8cplAG14GKBly/HhEkY4ycxrzxKNbMYRJW9wZvUHv+E3ku7e
|
|
||||||
zdCtaLU2AVtVlVYRgPwUT7kB9oSqXSXds18g1H6f3w0Ci1osRgrA/gRQZNUIwdJ5
|
|
||||||
8FT955xHmvkP98NxRLLPZ8Wqmn9/5jnsVyn12QIDAQABAoIBAA9Gphf65WLbcQY7
|
|
||||||
kTgiGdmR2oDZCtCRU5atSBHBE0mAgsMg1zkIIwZa4+1tjCRVsgvXO6g8InVcCUy+
|
|
||||||
JzGT4XoP4wRYF8e+Xhr0Rki0h9sF+PRAtirlPwQdAa/NOWXUZ//KQXiZGSixiZXz
|
|
||||||
hc1Rd02xe/94u35TwcoKxh6Z0fJBZwxSi2J72XnEWWQ71ru63RAp70JgxONMrcZ8
|
|
||||||
gHyqit8AN/kmzjT+LGsrw8SKJJTyD7/2Mtcn3QnfAB3+bFrwZPdcDlGIdDn/jmjx
|
|
||||||
sFbtxdug8zHVuI0EbGL6EHVGcgSWhp9FvZ9is2k08dmQdPLotOG8+vSfg9RCMZBT
|
|
||||||
50KrbOUCgYEA9nx8aWsML/0fQisWyN4JTtjqKy6ZizrdfLTktmHCl0OO3gvUQoIH
|
|
||||||
1KHSzlIBIKsC0utQEbM1pszh8aXFBH8bg/x1RrZigT9bTTzTrOfmsIL7Hg+AR/iv
|
|
||||||
GC1LszZdmB2kwaquKgUilfAz6ZCBgkZ5RwpcvmNdoqLfmNlcpQMs95UCgYEA8/Od
|
|
||||||
ro3GRXyq8hZz7LpgOx33XpLtD3Fj4z00TIJqKZAGcsHrlJw/wDHbMQqkdpCSu673
|
|
||||||
TLb67vXLyjyXuOXGCbIsKJpT3Ach5DxwceUnwg3OHWoreuCwyklHjIz9xwGecvpZ
|
|
||||||
qzDN9t/6IoTLlGXEZ28+hoXMDXJQtMq85lpy5DUCgYAu36eNKJVNvvYl0CnqEwd0
|
|
||||||
Hh4SDi+W4Z/jKkdgQ6EMwQU3RsqbxzyT/B4prECYpMzJrYQxiYIHcWj6WkroOv/R
|
|
||||||
jr4Cr4Z2C8ViH9IlTIh7Qr1cjxgXF7y8fUirEQild+WwCrRKO2XDW8WTgi6OxrYj
|
|
||||||
g131utHArvaUi6lpm/v+LQKBgQDVmIqJmWzuzndGvE4ICi/T0ysSTYbvLJMPFjnC
|
|
||||||
e7XEamya8hv45M4U1BJdYDob7f3sAwhYzSXtMJ2cl20o4VaCitSLQIUIc95C3oB9
|
|
||||||
2Oz0xe2gZ6NmVXG1zG+vKovRQSOg/H6im3rbG8UBkFBHwMs03XxbgK7nXx43DgRT
|
|
||||||
lQJfuQKBgQDxLjiwU9nYonBoiwUx8vfB3RGuoPgmVCGh9tEy+nyXxOu0imvx/Mbz
|
|
||||||
DP7PGP9+mG1HxcbAevlGD3tTTLimSTx+UIXIslgX+gY3KRv04PrDv8u44crA8Raf
|
|
||||||
3+sg7ASi8drli7EE6+UdloAR59UjKHOcW23EOS18/v999CnXAuFEqg==
|
|
||||||
-----END RSA PRIVATE KEY-----
|
|
||||||
+152
-24
@@ -1,6 +1,7 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
"""管理后台路由"""
|
"""管理后台路由"""
|
||||||
|
import datetime as dt
|
||||||
import json
|
import json
|
||||||
import random
|
import random
|
||||||
from functools import wraps
|
from functools import wraps
|
||||||
@@ -26,7 +27,7 @@ ADMIN_LOGIN_LOCK_SECONDS = 15 * 60
|
|||||||
|
|
||||||
|
|
||||||
def _load_admin_config() -> dict:
|
def _load_admin_config() -> dict:
|
||||||
cfg = {"admin_username": "", "admin_password": ""}
|
cfg = {"admin_username": "", "admin_password": "", "admin_password_hash": ""}
|
||||||
try:
|
try:
|
||||||
if _ADMIN_CONFIG_PATH.exists():
|
if _ADMIN_CONFIG_PATH.exists():
|
||||||
for line in _ADMIN_CONFIG_PATH.read_text("utf-8").splitlines():
|
for line in _ADMIN_CONFIG_PATH.read_text("utf-8").splitlines():
|
||||||
@@ -41,6 +42,35 @@ def _load_admin_config() -> dict:
|
|||||||
return cfg
|
return cfg
|
||||||
|
|
||||||
|
|
||||||
|
def _verify_admin_password(cfg: dict, password: str) -> bool:
|
||||||
|
"""校验管理员口令:优先比对 pbkdf2 哈希,其次明文(老配置兼容)。
|
||||||
|
|
||||||
|
两边都用恒定时间比较,避免按响应时间猜口令。
|
||||||
|
"""
|
||||||
|
import hmac
|
||||||
|
|
||||||
|
pwd = password or ""
|
||||||
|
hash_value = (cfg.get("admin_password_hash") or "").strip()
|
||||||
|
if hash_value:
|
||||||
|
try:
|
||||||
|
from werkzeug.security import check_password_hash
|
||||||
|
return check_password_hash(hash_value, pwd)
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[admin配置] 口令哈希校验失败: {exc}")
|
||||||
|
return False
|
||||||
|
plain = (cfg.get("admin_password") or "").strip()
|
||||||
|
if not plain:
|
||||||
|
return False
|
||||||
|
return hmac.compare_digest(pwd.encode("utf-8"), plain.encode("utf-8"))
|
||||||
|
|
||||||
|
|
||||||
|
def hash_admin_password(password: str) -> str:
|
||||||
|
"""生成可写进 admin_config.txt 的口令哈希(部署/运维用)。"""
|
||||||
|
from werkzeug.security import generate_password_hash
|
||||||
|
return generate_password_hash(password)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def _nearby_coord(lat, lng, jitter=0.0001):
|
def _nearby_coord(lat, lng, jitter=0.0001):
|
||||||
"""在车辆坐标附近加随机抖动,模拟真实定位(避免每次上报同一精确点被判远程操作)"""
|
"""在车辆坐标附近加随机抖动,模拟真实定位(避免每次上报同一精确点被判远程操作)"""
|
||||||
try:
|
try:
|
||||||
@@ -90,10 +120,13 @@ def admin_login():
|
|||||||
return jsonify({"rtn_code": 429,
|
return jsonify({"rtn_code": 429,
|
||||||
"message": f"失败次数过多,请 {max(wait_seconds // 60, 1)} 分钟后再试"}), 429
|
"message": f"失败次数过多,请 {max(wait_seconds // 60, 1)} 分钟后再试"}), 429
|
||||||
return _login_page(f"失败次数过多,请 {max(wait_seconds // 60, 1)} 分钟后再试"), 429
|
return _login_page(f"失败次数过多,请 {max(wait_seconds // 60, 1)} 分钟后再试"), 429
|
||||||
if (cfg["admin_username"] and cfg["admin_password"]
|
if (cfg["admin_username"]
|
||||||
and username == cfg["admin_username"] and password == cfg["admin_password"]):
|
and (cfg.get("admin_password_hash") or cfg.get("admin_password"))
|
||||||
|
and username == cfg["admin_username"]
|
||||||
|
and _verify_admin_password(cfg, password)):
|
||||||
rate_limit.record_success(rl_key)
|
rate_limit.record_success(rl_key)
|
||||||
session["admin_logged_in"] = True
|
session["admin_logged_in"] = True
|
||||||
|
session.permanent = True # 配合 PERMANENT_SESSION_LIFETIME 过期
|
||||||
if request.is_json:
|
if request.is_json:
|
||||||
return jsonify({"rtn_code": 0, "message": "登录成功"})
|
return jsonify({"rtn_code": 0, "message": "登录成功"})
|
||||||
return redirect("/admin")
|
return redirect("/admin")
|
||||||
@@ -172,6 +205,27 @@ def admin_api_summary():
|
|||||||
}})
|
}})
|
||||||
|
|
||||||
|
|
||||||
|
def _riding_minutes(rental) -> int:
|
||||||
|
"""已骑行分钟:开始时间 → 实际还车时间(未还车就按「现在」算)。"""
|
||||||
|
start = rental.get("start_time")
|
||||||
|
if not start:
|
||||||
|
return 0
|
||||||
|
try:
|
||||||
|
start_at = dt.datetime.strptime(str(start), "%Y-%m-%d %H:%M:%S")
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return 0
|
||||||
|
end_at = None
|
||||||
|
if rental.get("returned_at"):
|
||||||
|
try:
|
||||||
|
end_at = dt.datetime.strptime(str(rental["returned_at"]), "%Y-%m-%d %H:%M:%S")
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
end_at = None
|
||||||
|
if end_at is None:
|
||||||
|
tz = dt.timezone(dt.timedelta(hours=8))
|
||||||
|
end_at = dt.datetime.now(tz).replace(tzinfo=None)
|
||||||
|
return max(0, int((end_at - start_at).total_seconds() // 60))
|
||||||
|
|
||||||
|
|
||||||
@bp.route("/api/admin/rentals")
|
@bp.route("/api/admin/rentals")
|
||||||
@admin_required
|
@admin_required
|
||||||
def admin_api_rentals():
|
def admin_api_rentals():
|
||||||
@@ -185,11 +239,21 @@ def admin_api_rentals():
|
|||||||
"email": r.get("user_email") or r["email"],
|
"email": r.get("user_email") or r["email"],
|
||||||
"rider_email": r.get("rider_email"),
|
"rider_email": r.get("rider_email"),
|
||||||
"user_id": r.get("user_id"),
|
"user_id": r.get("user_id"),
|
||||||
|
"rider_user_id": r.get("rider_user_id"),
|
||||||
"start_time": r["start_time"],
|
"start_time": r["start_time"],
|
||||||
"end_time": r["end_time"],
|
"end_time": r["end_time"],
|
||||||
"expired": r["expired"],
|
"expired": r["expired"],
|
||||||
"source": r.get("source", ""),
|
"source": r.get("source", ""),
|
||||||
"status": get_rental_status_label(r["expired"], r["end_time"]),
|
"status": get_rental_status_label(r["expired"], r["end_time"]),
|
||||||
|
# 骑行起终点(位置标签 + 坐标,GCJ02),供管理端追溯
|
||||||
|
"start_label": r.get("start_label") or "",
|
||||||
|
"end_label": r.get("end_label") or "",
|
||||||
|
"start_latitude": r.get("start_latitude"),
|
||||||
|
"start_longitude": r.get("start_longitude"),
|
||||||
|
"end_latitude": r.get("end_latitude"),
|
||||||
|
"end_longitude": r.get("end_longitude"),
|
||||||
|
"returned_at": r.get("returned_at"),
|
||||||
|
"riding_minutes": _riding_minutes(r),
|
||||||
})
|
})
|
||||||
return jsonify({"rtn_code": 0, "data": result})
|
return jsonify({"rtn_code": 0, "data": result})
|
||||||
|
|
||||||
@@ -222,27 +286,42 @@ def admin_api_return():
|
|||||||
latitude = pos["lat"]
|
latitude = pos["lat"]
|
||||||
longitude = pos["lng"]
|
longitude = pos["lng"]
|
||||||
|
|
||||||
# 先校验当前位置是否为合法还车点;不在还车点则选择最近停车点(与用户端 order_return 一致)
|
# 与用户端还车同一条链路:先发原坐标,失败再按候选点换点重试
|
||||||
check_result = request_with_user_auth(
|
# (自动还车因坐标失败 → 邮件叫管理员代还,代还却用单点老逻辑就永远还不上)
|
||||||
int(user_id), "POST", "/record/checkLocation",
|
from routes.rental import _try_return_candidates, _record_rental_end
|
||||||
data={"longitude": longitude, "latitude": latitude, "bicycleCode": rental["bike_code"]}, _silent=True)
|
upstream_order_id = int(order_id) if str(order_id).isdigit() else order_id
|
||||||
use_nearest = False
|
return_result, used_point, tried = _try_return_candidates(
|
||||||
if check_result.get("rtn_code") != 0 or check_result.get("parkNoShow") is True:
|
int(user_id), upstream_order_id, rental["bike_code"],
|
||||||
from routes.rental import get_nearest_park_point
|
float(latitude), float(longitude)
|
||||||
nearest = get_nearest_park_point(latitude, longitude)
|
)
|
||||||
if nearest:
|
use_nearest = len(tried) > 1
|
||||||
latitude = nearest.get("latitude") or nearest.get("lat")
|
if use_nearest:
|
||||||
longitude = nearest.get("longitude") or nearest.get("lng")
|
latitude, longitude = used_point
|
||||||
use_nearest = True
|
|
||||||
|
|
||||||
return_result = request_with_user_auth(int(user_id), "POST", "/record/return", data={
|
|
||||||
"order_id": int(order_id) if str(order_id).isdigit() else order_id,
|
|
||||||
"longitude": longitude, "latitude": latitude, "code": rental["bike_code"]
|
|
||||||
})
|
|
||||||
|
|
||||||
if return_result.get("rtn_code") == 0:
|
if return_result.get("rtn_code") == 0:
|
||||||
cursor.execute("UPDATE rentals SET expired = 1 WHERE id = ?", (rental_id,))
|
# 写回 expired + 实际还车时间 + 终点坐标,否则「已骑行」会一直往上爬。
|
||||||
conn.commit()
|
# 上游已经还车成功,本地写库失败只记日志 —— 不能把成功报成失败,
|
||||||
|
# 否则管理员会再点一次,第二次拿到「订单信息不存在」更看不懂。
|
||||||
|
sync_warning = ""
|
||||||
|
updated = 0
|
||||||
|
try:
|
||||||
|
updated = _record_rental_end(order_id, int(user_id), latitude, longitude) or 0
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[管理端代还车] 回填终点失败: {exc}")
|
||||||
|
sync_warning = "本地记录稍后同步"
|
||||||
|
if not updated and not sync_warning:
|
||||||
|
# order_id 是脏字符串之类没匹配到行:按 rental_id 兜底,后台立刻正确
|
||||||
|
print(f"[管理端代还车] order_id={order_id} 未匹配到进行中的单,按 rental_id={rental_id} 兜底")
|
||||||
|
try:
|
||||||
|
cursor.execute(
|
||||||
|
"UPDATE rentals SET expired = 1, returned_at = COALESCE(returned_at, ?) "
|
||||||
|
"WHERE id = ?",
|
||||||
|
(dt.datetime.now(dt.timezone(dt.timedelta(hours=8))).strftime("%Y-%m-%d %H:%M:%S"),
|
||||||
|
rental_id))
|
||||||
|
conn.commit()
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[管理端代还车] 兜底回写失败: {exc}")
|
||||||
|
sync_warning = "本地记录稍后同步"
|
||||||
|
|
||||||
# 尝试月卡支付
|
# 尝试月卡支付
|
||||||
from timer import _try_card_pay_auto
|
from timer import _try_card_pay_auto
|
||||||
@@ -252,11 +331,17 @@ def admin_api_return():
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
conn.close()
|
conn.close()
|
||||||
return jsonify({"rtn_code": 0, "message": "还车成功"})
|
msg = "还车成功" if not use_nearest else "还车成功(已换到最近的还车点)"
|
||||||
|
if sync_warning:
|
||||||
|
msg += f"({sync_warning})"
|
||||||
|
return jsonify({"rtn_code": 0, "message": msg, "used_nearest": use_nearest,
|
||||||
|
"local_synced": not sync_warning})
|
||||||
else:
|
else:
|
||||||
conn.close()
|
conn.close()
|
||||||
|
tried_text = "、".join(tried)
|
||||||
return jsonify({"rtn_code": return_result.get("rtn_code", 500),
|
return jsonify({"rtn_code": return_result.get("rtn_code", 500),
|
||||||
"message": return_result.get("message", "还车失败")})
|
"message": (return_result.get("message") or "还车失败")
|
||||||
|
+ f"(已尝试 {len(tried)} 个位置:{tried_text})"})
|
||||||
|
|
||||||
|
|
||||||
@bp.route("/api/admin/unlock", methods=["POST"])
|
@bp.route("/api/admin/unlock", methods=["POST"])
|
||||||
@@ -397,6 +482,49 @@ def admin_api_save_token():
|
|||||||
return jsonify({"rtn_code": 500, "message": "保存失败"})
|
return jsonify({"rtn_code": 500, "message": "保存失败"})
|
||||||
|
|
||||||
|
|
||||||
|
@bp.route("/api/admin/route_key", methods=["GET"])
|
||||||
|
@admin_required
|
||||||
|
def admin_api_route_key():
|
||||||
|
"""步行路线规划用的百度 AK/SK(服务端密钥,SK 只回显尾号)。"""
|
||||||
|
import walk_route
|
||||||
|
return jsonify({"rtn_code": 0, "data": walk_route.masked_credentials()})
|
||||||
|
|
||||||
|
|
||||||
|
@bp.route("/api/admin/route_key", methods=["POST"])
|
||||||
|
@admin_required
|
||||||
|
def admin_api_route_key_save():
|
||||||
|
"""保存 AK/SK。sk 不传=保持原值,传空串=清空。"""
|
||||||
|
import walk_route
|
||||||
|
data = request.get_json() or {}
|
||||||
|
ak = str(data.get("ak") or "").strip()
|
||||||
|
sk = data.get("sk", None)
|
||||||
|
if sk is not None:
|
||||||
|
sk = str(sk).strip()
|
||||||
|
if not ak:
|
||||||
|
return jsonify({"rtn_code": 400, "message": "AK 不能为空(不需要可清空后关闭)"})
|
||||||
|
if not walk_route.save_credentials(ak, sk):
|
||||||
|
return jsonify({"rtn_code": 500, "message": "保存失败"})
|
||||||
|
return jsonify({"rtn_code": 0, "message": "百度步行路线 AK/SK 已保存",
|
||||||
|
"data": walk_route.masked_credentials()})
|
||||||
|
|
||||||
|
|
||||||
|
@bp.route("/api/admin/route_key/test", methods=["POST"])
|
||||||
|
@admin_required
|
||||||
|
def admin_api_route_key_test():
|
||||||
|
"""用当前 AK/SK 真打一次百度,返回距离/耗时或具体错误。"""
|
||||||
|
import walk_route
|
||||||
|
if not walk_route.is_enabled():
|
||||||
|
return jsonify({"rtn_code": 400, "message": "还没配置 AK"})
|
||||||
|
got = walk_route.get_walk_route(36.529440, 116.783740,
|
||||||
|
36.534240, 116.787190, use_cache=False)
|
||||||
|
if got.get("source") == "baidu":
|
||||||
|
return jsonify({"rtn_code": 0,
|
||||||
|
"message": f"连通成功:{got['distance']} 米 / {got['duration']} 秒",
|
||||||
|
"data": got})
|
||||||
|
return jsonify({"rtn_code": 500,
|
||||||
|
"message": f"百度返回失败(已退回估算):{got}"})
|
||||||
|
|
||||||
|
|
||||||
@bp.route("/api/admin/strict_mode", methods=["GET"])
|
@bp.route("/api/admin/strict_mode", methods=["GET"])
|
||||||
@admin_required
|
@admin_required
|
||||||
def admin_api_get_strict_mode():
|
def admin_api_get_strict_mode():
|
||||||
|
|||||||
+60
-2
@@ -37,7 +37,19 @@ def _client_ip() -> str:
|
|||||||
- 其余来源(含内网直连)一律使用 remote_addr,
|
- 其余来源(含内网直连)一律使用 remote_addr,
|
||||||
防止局域网/直连客户端伪造 X-Real-IP 绕过限流与登录锁定。"""
|
防止局域网/直连客户端伪造 X-Real-IP 绕过限流与登录锁定。"""
|
||||||
remote = request.remote_addr or ""
|
remote = request.remote_addr or ""
|
||||||
if remote in ("127.0.0.1", "::1"):
|
# 可信代理:默认回环 + 常见容器网段(Docker/兄弟 nginx 下 remote_addr 是 172.x)。
|
||||||
|
# 可用环境变量 TRUSTED_PROXIES 覆盖(逗号分隔的前缀,如 "127.,172.,10.")。
|
||||||
|
# 不这样做的话,容器部署里所有客户端会塌成同一个限流 key:
|
||||||
|
# 45 次/分钟变成全站共享额度,一两个人就能把所有人打成 429。
|
||||||
|
import os as _os
|
||||||
|
trusted = tuple(
|
||||||
|
part.strip() for part in
|
||||||
|
_os.environ.get("TRUSTED_PROXIES", "127.,::1,172.,10.,192.168.").split(",")
|
||||||
|
if part.strip()
|
||||||
|
)
|
||||||
|
is_trusted = remote in ("127.0.0.1", "::1") or any(
|
||||||
|
remote.startswith(pref) for pref in trusted if pref not in ("127.", "::1"))
|
||||||
|
if remote in ("127.0.0.1", "::1") or is_trusted:
|
||||||
real = request.headers.get("X-Real-IP", "").strip()
|
real = request.headers.get("X-Real-IP", "").strip()
|
||||||
if real:
|
if real:
|
||||||
return real
|
return real
|
||||||
@@ -99,9 +111,39 @@ def _register_rate_ok(ip: str):
|
|||||||
|
|
||||||
|
|
||||||
def hash_password(password: str) -> str:
|
def hash_password(password: str) -> str:
|
||||||
|
"""口令哈希:pbkdf2(加盐、可调迭代)。
|
||||||
|
|
||||||
|
老库里存的是无盐 sha256,拖库即可反查;verify_password 兼容旧格式,
|
||||||
|
并在登录成功时透明升级成新哈希。
|
||||||
|
"""
|
||||||
|
from werkzeug.security import generate_password_hash
|
||||||
|
return generate_password_hash(password, method="pbkdf2:sha256:260000")
|
||||||
|
|
||||||
|
|
||||||
|
def _legacy_sha256(password: str) -> str:
|
||||||
return hashlib.sha256(password.encode()).hexdigest()
|
return hashlib.sha256(password.encode()).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def verify_password(stored: str, password: str) -> bool:
|
||||||
|
"""校验口令:新格式走 werkzeug,旧格式(64 位 hex)兼容且恒定时间比较。"""
|
||||||
|
import hmac
|
||||||
|
|
||||||
|
stored = (stored or "").strip()
|
||||||
|
if not stored:
|
||||||
|
return False
|
||||||
|
if stored.startswith(("pbkdf2:", "scrypt:", "argon2")):
|
||||||
|
try:
|
||||||
|
from werkzeug.security import check_password_hash
|
||||||
|
return check_password_hash(stored, password or "")
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
return hmac.compare_digest(stored, _legacy_sha256(password or ""))
|
||||||
|
|
||||||
|
|
||||||
|
def password_needs_upgrade(stored: str) -> bool:
|
||||||
|
return not (stored or "").strip().startswith(("pbkdf2:", "scrypt:", "argon2"))
|
||||||
|
|
||||||
|
|
||||||
def generate_token() -> str:
|
def generate_token() -> str:
|
||||||
return secrets.token_urlsafe(32)
|
return secrets.token_urlsafe(32)
|
||||||
|
|
||||||
@@ -236,6 +278,9 @@ def auth_send_code():
|
|||||||
row = conn.execute("SELECT id FROM users WHERE email = ?", (email,)).fetchone()
|
row = conn.execute("SELECT id FROM users WHERE email = ?", (email,)).fetchone()
|
||||||
conn.close()
|
conn.close()
|
||||||
if not row:
|
if not row:
|
||||||
|
# 未注册邮箱:同样占住 60 秒冷却(不发信),
|
||||||
|
# 否则「第二次请求是否 429」会泄漏这个邮箱是否已注册。
|
||||||
|
email_verify.record_cooldown(email)
|
||||||
return jsonify({"rtn_code": 0, "message": "验证码已发送,请查收邮箱(注意垃圾箱)"})
|
return jsonify({"rtn_code": 0, "message": "验证码已发送,请查收邮箱(注意垃圾箱)"})
|
||||||
ok, message = email_verify.send_code(email, purpose=purpose)
|
ok, message = email_verify.send_code(email, purpose=purpose)
|
||||||
if not ok:
|
if not ok:
|
||||||
@@ -389,11 +434,20 @@ def login():
|
|||||||
conn.close()
|
conn.close()
|
||||||
return jsonify({"rtn_code": 429,
|
return jsonify({"rtn_code": 429,
|
||||||
"message": f"失败次数过多,请 {max(wait_seconds // 60, 1)} 分钟后再试"})
|
"message": f"失败次数过多,请 {max(wait_seconds // 60, 1)} 分钟后再试"})
|
||||||
if not user or user["password_hash"] != hash_password(password):
|
if not user or not verify_password(user["password_hash"], password):
|
||||||
conn.close()
|
conn.close()
|
||||||
_login_record_fail(ip, email)
|
_login_record_fail(ip, email)
|
||||||
return jsonify({"rtn_code": 400, "message": "邮箱或密码错误"})
|
return jsonify({"rtn_code": 400, "message": "邮箱或密码错误"})
|
||||||
_login_record_success(ip, email)
|
_login_record_success(ip, email)
|
||||||
|
# 旧的无盐 sha256 哈希:登录成功后顺手升级(用户无感)
|
||||||
|
if password_needs_upgrade(user["password_hash"]):
|
||||||
|
try:
|
||||||
|
conn.execute("UPDATE users SET password_hash = ? WHERE id = ?",
|
||||||
|
(hash_password(password), user["id"]))
|
||||||
|
conn.commit()
|
||||||
|
print(f"[登录] 已升级 {email} 的口令哈希")
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[登录] 口令哈希升级失败: {exc}")
|
||||||
|
|
||||||
# 支持多设备同时登录:不再清空该用户的旧会话,仅为本设备新增一条会话
|
# 支持多设备同时登录:不再清空该用户的旧会话,仅为本设备新增一条会话
|
||||||
session_token = generate_token()
|
session_token = generate_token()
|
||||||
@@ -552,6 +606,10 @@ def save_xbniu_token():
|
|||||||
def _verify_upstream_token(token_id: str, access_token: str) -> tuple:
|
def _verify_upstream_token(token_id: str, access_token: str) -> tuple:
|
||||||
"""向上游校验微信凭据有效性。返回 (valid, message)。
|
"""向上游校验微信凭据有效性。返回 (valid, message)。
|
||||||
供 verify_token 接口(已登录,防枚举)与注册流程(注册时尚无登录态)共用。"""
|
供 verify_token 接口(已登录,防枚举)与注册流程(注册时尚无登录态)共用。"""
|
||||||
|
# 没有 access_token 时只能用假签名,上游一律回 102001 —— 那不代表 token 失效,
|
||||||
|
# 不能因此拦掉合法用户(注册/校验都会误判),这里直接放行并标记未校验。
|
||||||
|
if not (access_token or "").strip():
|
||||||
|
return True, "未填 AccessToken,无法校验有效期(已放行)"
|
||||||
import requests as req
|
import requests as req
|
||||||
from wechat import BASE_URL, make_signature
|
from wechat import BASE_URL, make_signature
|
||||||
timestamp = str(int(time.time()))
|
timestamp = str(int(time.time()))
|
||||||
|
|||||||
+2
-2
@@ -2,7 +2,7 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
"""抓包工具安装包下载
|
"""抓包工具安装包下载
|
||||||
|
|
||||||
安装包体积较大(约 160MB),放在项目根的 downloads/ 目录而不是 static/,
|
安装包体积较大(约 25MB),放在项目根的 downloads/ 目录而不是 static/,
|
||||||
避免被 Flask 静态路由以外的缓存策略干扰,也便于单独替换升级。
|
避免被 Flask 静态路由以外的缓存策略干扰,也便于单独替换升级。
|
||||||
|
|
||||||
公开访问:用户注册前就需要拿到工具,若加登录校验会形成「没工具拿不到凭据、
|
公开访问:用户注册前就需要拿到工具,若加登录校验会形成「没工具拿不到凭据、
|
||||||
@@ -18,7 +18,7 @@ bp = Blueprint("download", __name__)
|
|||||||
# 容易出编码问题。对外的下载文件名由 download_name 还原。
|
# 容易出编码问题。对外的下载文件名由 download_name 还原。
|
||||||
DOWNLOADS_DIR = Path(__file__).parent.parent / "downloads"
|
DOWNLOADS_DIR = Path(__file__).parent.parent / "downloads"
|
||||||
CAPTURE_TOOL_FILE = "xbniu-capture-tool.exe"
|
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"])
|
@bp.route("/download/capture-tool.exe", methods=["GET", "HEAD"])
|
||||||
|
|||||||
+1
-1
@@ -6,7 +6,7 @@
|
|||||||
返回 /export/csv/<token> 直链(免登录,1 小时有效,一次性换浏览器可继续下载)。
|
返回 /export/csv/<token> 直链(免登录,1 小时有效,一次性换浏览器可继续下载)。
|
||||||
前端用 detectInAppBrowser 复用「复制链接到外部浏览器」提示(微信/原生壳内无法下载)。
|
前端用 detectInAppBrowser 复用「复制链接到外部浏览器」提示(微信/原生壳内无法下载)。
|
||||||
|
|
||||||
CSV 内容:最近 3 天全部车辆点位(与库内保留策略一致)。
|
CSV 内容:最近 30 天全部车辆点位(与库内保留策略一致)。
|
||||||
"""
|
"""
|
||||||
import csv
|
import csv
|
||||||
import datetime as dt
|
import datetime as dt
|
||||||
|
|||||||
+82
-1
@@ -143,13 +143,22 @@ def api_ring_cancel(task_id):
|
|||||||
def api_ring_progress(task_id):
|
def api_ring_progress(task_id):
|
||||||
from flask import Response as FlaskResponse
|
from flask import Response as FlaskResponse
|
||||||
global ring_tasks
|
global ring_tasks
|
||||||
|
RING_SSE_MAX_SECONDS = 180 # 单个进度 SSE 最长占用时间
|
||||||
|
|
||||||
def _sse(obj):
|
def _sse(obj):
|
||||||
return f"data: {json.dumps(obj, ensure_ascii=False)}\n\n"
|
return f"data: {json.dumps(obj, ensure_ascii=False)}\n\n"
|
||||||
|
|
||||||
def generate():
|
def generate():
|
||||||
last_done = -1
|
last_done = -1
|
||||||
last_status = None
|
last_status = None
|
||||||
tick = 0
|
tick = 0
|
||||||
|
# 硬超时:SSE 是同步长连接,一个连接占死一个 worker。任务卡住时
|
||||||
|
# 不设上限的话(-w 4 只要 4 个进度页)整站会被打满。
|
||||||
|
deadline = time.time() + RING_SSE_MAX_SECONDS
|
||||||
while True:
|
while True:
|
||||||
|
if time.time() > deadline:
|
||||||
|
yield _sse({"type": "error", "message": "进度推送超时,请刷新页面查看结果"})
|
||||||
|
return
|
||||||
with _ring_lock:
|
with _ring_lock:
|
||||||
task = ring_tasks.get(task_id)
|
task = ring_tasks.get(task_id)
|
||||||
if not task:
|
if not task:
|
||||||
@@ -266,6 +275,78 @@ def api_config():
|
|||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
|
@bp.route("/api/nav_route")
|
||||||
|
def api_nav_route():
|
||||||
|
"""导航路线:距离/耗时/分段指引/整条折线(前端直接画到地图上)。
|
||||||
|
|
||||||
|
参数:origin_lat/origin_lng/dest_lat/dest_lng(GCJ02),mode=walking|riding
|
||||||
|
返回:{rtn_code:0, data:{distance, duration, points:[[lng,lat],...], steps:[...]}}
|
||||||
|
"""
|
||||||
|
user = get_current_user()
|
||||||
|
if not user:
|
||||||
|
return jsonify({"rtn_code": 401, "message": "请先登录后使用"}), 401
|
||||||
|
|
||||||
|
from routes.auth import _client_ip
|
||||||
|
from rate_limit import hit as rl_hit
|
||||||
|
# 导航比查卡片更重,按 IP 每分钟 20 次
|
||||||
|
if not rl_hit(("nav_route", _client_ip()), 20, 60):
|
||||||
|
return jsonify({"rtn_code": 429, "message": "导航请求过于频繁,请稍后再试"}), 429
|
||||||
|
|
||||||
|
try:
|
||||||
|
o_lat = float(request.args.get("origin_lat"))
|
||||||
|
o_lng = float(request.args.get("origin_lng"))
|
||||||
|
d_lat = float(request.args.get("dest_lat"))
|
||||||
|
d_lng = float(request.args.get("dest_lng"))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return jsonify({"rtn_code": 400, "message": "缺少或非法的坐标参数"})
|
||||||
|
|
||||||
|
mode = (request.args.get("mode") or "walking").strip().lower()
|
||||||
|
if mode not in ("walking", "riding"):
|
||||||
|
mode = "walking"
|
||||||
|
|
||||||
|
import walk_route
|
||||||
|
data = walk_route.get_nav_route(o_lat, o_lng, d_lat, d_lng, api=mode)
|
||||||
|
if data.get("error"):
|
||||||
|
return jsonify({"rtn_code": 500, "message": data["error"]}), 200
|
||||||
|
response = jsonify({"rtn_code": 0, "data": data})
|
||||||
|
response.headers["Cache-Control"] = "private, max-age=30"
|
||||||
|
return response
|
||||||
|
|
||||||
|
|
||||||
|
@bp.route("/api/walk_route")
|
||||||
|
def api_walk_route():
|
||||||
|
"""步行路线:真实道路距离 + 步行耗时(百度轻量级路线规划)。
|
||||||
|
|
||||||
|
参数:origin_lat/origin_lng/dest_lat/dest_lng,**全部 GCJ02**
|
||||||
|
(前端要把 BD09 的我方位置先转 GCJ02 再传)。
|
||||||
|
返回:{rtn_code:0, data:{distance, duration, source}}
|
||||||
|
source = baidu(实时)/ cache(命中缓存)/ estimate(百度不可用时的本地估算)
|
||||||
|
"""
|
||||||
|
user = get_current_user()
|
||||||
|
if not user:
|
||||||
|
return jsonify({"rtn_code": 401, "message": "请先登录后使用"}), 401
|
||||||
|
|
||||||
|
from routes.auth import _client_ip
|
||||||
|
from rate_limit import hit as rl_hit
|
||||||
|
# 保护百度配额:同一 IP 每分钟 60 次(正常点卡片远低于此)
|
||||||
|
if not rl_hit(("walk_route", _client_ip()), 60, 60):
|
||||||
|
return jsonify({"rtn_code": 429, "message": "请求过于频繁,请稍后再试"}), 429
|
||||||
|
|
||||||
|
try:
|
||||||
|
o_lat = float(request.args.get("origin_lat"))
|
||||||
|
o_lng = float(request.args.get("origin_lng"))
|
||||||
|
d_lat = float(request.args.get("dest_lat"))
|
||||||
|
d_lng = float(request.args.get("dest_lng"))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return jsonify({"rtn_code": 400, "message": "缺少或非法的坐标参数"})
|
||||||
|
|
||||||
|
import walk_route
|
||||||
|
data = walk_route.get_walk_route(o_lat, o_lng, d_lat, d_lng)
|
||||||
|
response = jsonify({"rtn_code": 0, "data": data})
|
||||||
|
response.headers["Cache-Control"] = "private, max-age=60"
|
||||||
|
return response
|
||||||
|
|
||||||
|
|
||||||
# ========== 校园地点(订阅下拉 / 地点解析标签) ==========
|
# ========== 校园地点(订阅下拉 / 地点解析标签) ==========
|
||||||
@bp.route("/api/map/freshness")
|
@bp.route("/api/map/freshness")
|
||||||
def api_map_freshness():
|
def api_map_freshness():
|
||||||
@@ -379,7 +460,7 @@ def api_user_info():
|
|||||||
MAP_ASSETS = (
|
MAP_ASSETS = (
|
||||||
"css/map.css", "css/bike-clusters.css", "css/map-settings.css", "css/ui-system.css",
|
"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/ui-motion.js", "js/qrcode.min.js", "js/coordtransform.js", "js/bike-clusters.js",
|
||||||
"js/settings-pages.js", "js/map.js",
|
"js/settings-pages.js", "js/src/core/geo.js", "dist/app.js",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+373
-47
@@ -4,6 +4,7 @@
|
|||||||
import json
|
import json
|
||||||
import math
|
import math
|
||||||
import random
|
import random
|
||||||
|
import sqlite3
|
||||||
import datetime as dt
|
import datetime as dt
|
||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
@@ -13,6 +14,7 @@ from flask import Blueprint, jsonify, request, render_template, make_response
|
|||||||
from db import get_db, get_user_auth, get_user_display_name, get_user_rental_settings
|
from db import get_db, get_user_auth, get_user_display_name, get_user_rental_settings
|
||||||
from routes.auth import get_current_user
|
from routes.auth import get_current_user
|
||||||
from wechat import request_api, request_with_user_auth
|
from wechat import request_api, request_with_user_auth
|
||||||
|
import park_area
|
||||||
from timer import (start_rental_timer, _cancel_rental_timers, _get_remaining_seconds,
|
from timer import (start_rental_timer, _cancel_rental_timers, _get_remaining_seconds,
|
||||||
_check_user_order, auto_return_bike)
|
_check_user_order, auto_return_bike)
|
||||||
from rental_mail import get_rental_mail_context, resolve_return_token
|
from rental_mail import get_rental_mail_context, resolve_return_token
|
||||||
@@ -43,17 +45,25 @@ def _serialize_order_return(func):
|
|||||||
return wrapped
|
return wrapped
|
||||||
|
|
||||||
|
|
||||||
def _upstream_order_finished(user_id: int, order_id) -> bool:
|
def _upstream_order_finished(user_id: int, order_id, bike_code=None) -> bool:
|
||||||
"""还车响应不明确时,确认指定订单是否已经不再骑行。"""
|
"""还车响应不明确时,确认指定订单是否已经不再骑行。
|
||||||
|
|
||||||
|
注意:上游 `nonDealOrder` 只保留**当前那一张**进行中的订单。如果它挂着的是
|
||||||
|
另一张单,不能直接判本单结束 —— 多轮续租/共享场景下订单号会轮换,
|
||||||
|
拿错 id(例如把本地自增 id 当 order_id 传上来)时会把"仍在计费的车"判成已还。
|
||||||
|
所以再按车牌兜一层:上游挂着同车牌的订单,就当本单还没结束。
|
||||||
|
"""
|
||||||
result = request_with_user_auth(user_id, "GET", "/user/info", _silent=True)
|
result = request_with_user_auth(user_id, "GET", "/user/info", _silent=True)
|
||||||
if result.get("rtn_code") != 0:
|
if result.get("rtn_code") != 0:
|
||||||
return False
|
return False
|
||||||
non_deal = (result.get("data") or {}).get("nonDealOrder")
|
non_deal = (result.get("data") or {}).get("nonDealOrder")
|
||||||
if not non_deal or not non_deal.get("order_id"):
|
if not non_deal or not non_deal.get("order_id"):
|
||||||
return True
|
return True
|
||||||
if str(non_deal.get("order_id")) != str(order_id):
|
if str(non_deal.get("order_id")) == str(order_id):
|
||||||
return True
|
return str(non_deal.get("status")) != "2"
|
||||||
return str(non_deal.get("status")) != "2"
|
if bike_code and str(non_deal.get("code") or "") == str(bike_code):
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
def _return_page(**context):
|
def _return_page(**context):
|
||||||
@@ -123,12 +133,200 @@ def _try_card_pay_auto(user_id: int, order_id: str, code: str) -> dict:
|
|||||||
return {"success": False, "message": pay_result.get("message", "支付失败")}
|
return {"success": False, "message": pay_result.get("message", "支付失败")}
|
||||||
|
|
||||||
|
|
||||||
def get_nearest_park_point(lat: float, lng: float) -> dict:
|
def to_upstream_coords(latitude, longitude):
|
||||||
"""获取最近的停车点坐标(从 app.py.bak 原样复制)"""
|
"""浏览器上报坐标 -> 上游/本地库坐标(WGS84 -> GCJ02)。
|
||||||
result = request_api("GET", "/project/map", params={"type": "1"})
|
|
||||||
if result.get("rtn_code") != 0 or not result.get("data"):
|
结论来自数据本身,不是猜的:
|
||||||
|
- 上游车辆坐标、`parkeArea` 停车区,以及本项目 `bike_history`、
|
||||||
|
`rentals.start_*`、`campus_locations` 全部是 **GCJ02**;
|
||||||
|
- 前端把车辆坐标按 `gcj02tobd09` 画到百度地图上位置正确,反证上游是 GCJ02;
|
||||||
|
- 只有浏览器 `navigator.geolocation` 给 **WGS84**。
|
||||||
|
|
||||||
|
所以入口(`/api/order/*`、共享还车)收到的经纬度先转成 GCJ02,之后从停车区
|
||||||
|
判定到发上游、写本地库一律用 GCJ02。原来把 WGS84 直接发上游,在中国境内
|
||||||
|
等于偏 500 米 —— 能还上只是因为停车区够大,还不上就频繁触发 used_nearest。
|
||||||
|
|
||||||
|
坐标非法/转换异常时原样返回,不阻断还车。
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
lat, lng = float(latitude), float(longitude)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return latitude, longitude
|
||||||
|
from campus import wgs84_to_gcj02
|
||||||
|
try:
|
||||||
|
g_lng, g_lat = wgs84_to_gcj02(lng, lat)
|
||||||
|
except Exception as exc: # 不该发生,兜底别阻断业务
|
||||||
|
print(f"[坐标] WGS84->GCJ02 转换失败,按原值继续: {exc}")
|
||||||
|
return lat, lng
|
||||||
|
return g_lat, g_lng
|
||||||
|
|
||||||
|
|
||||||
|
def _upstream_map_data(user_id=None) -> dict:
|
||||||
|
"""上游 `/project/map` 的 data。
|
||||||
|
|
||||||
|
**优先用用户自己的凭据**:全局凭据一旦失效(`token_config.txt` 过期,或强验证
|
||||||
|
模式下必填 accessToken),走 `request_api` 会静默失败,停车区吸附就整体失效
|
||||||
|
—— 实测过:只有全局凭据坏掉时,区外还车会一直退回原始坐标。用户凭据拿不到
|
||||||
|
再退全局共享快照(60 秒缓存,不额外压上游)。
|
||||||
|
"""
|
||||||
|
if user_id:
|
||||||
|
try:
|
||||||
|
res = request_with_user_auth(
|
||||||
|
user_id, "GET", "/project/map", params={"type": "1"}, _silent=True)
|
||||||
|
if isinstance(res, dict) and res.get("rtn_code") in (None, 0):
|
||||||
|
data = res.get("data") or {}
|
||||||
|
if data.get("parkeArea"):
|
||||||
|
return data
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[停车区] 用户凭据读取地图失败: {exc}")
|
||||||
|
try:
|
||||||
|
res = request_api("GET", "/project/map", params={"type": "1"})
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[停车区] 读取上游地图失败: {exc}")
|
||||||
|
return {}
|
||||||
|
if not isinstance(res, dict) or res.get("rtn_code") not in (None, 0):
|
||||||
|
return {}
|
||||||
|
return res.get("data") or {}
|
||||||
|
|
||||||
|
|
||||||
|
def _park_areas(user_id=None) -> list:
|
||||||
|
"""上游停车区多边形(parkeArea,GCJ02)。拿不到就返回空列表。"""
|
||||||
|
return park_area.parse_park_areas(_upstream_map_data(user_id))
|
||||||
|
|
||||||
|
|
||||||
|
def _snap_to_park_area(lat: float, lng: float, user_id=None):
|
||||||
|
"""还车点(GCJ02)-> 最近可用停车区内的点(GCJ02)。
|
||||||
|
|
||||||
|
返回 `{"latitude", "longitude", "inside", "moved", "distance"}` 或 None。
|
||||||
|
"""
|
||||||
|
resolved = park_area.resolve_return_coord(lat, lng, _park_areas(user_id))
|
||||||
|
if not resolved:
|
||||||
return None
|
return None
|
||||||
bike_stations = result["data"].get("bicycleStation", [])
|
if resolved.get("moved") and resolved.get("distance", 0) > park_area.SNAP_WARN_M:
|
||||||
|
print(f"[停车区] 吸附距离 {resolved['distance']:.0f}m 偏大,坐标可能异常: "
|
||||||
|
f"({lat:.6f}, {lng:.6f})")
|
||||||
|
return resolved
|
||||||
|
|
||||||
|
|
||||||
|
def _approx_m(lat1, lng1, lat2, lng2) -> float:
|
||||||
|
"""两点近似距离(米),只用来做候选点去重,不需要高精度。"""
|
||||||
|
dx = (lng1 - lng2) * 111320.0 * math.cos(math.radians(lat1))
|
||||||
|
dy = (lat1 - lat2) * 110540.0
|
||||||
|
return math.hypot(dx, dy)
|
||||||
|
|
||||||
|
|
||||||
|
def _campus_parking_points(lat, lng, limit=2):
|
||||||
|
"""校园停车点表(`campus_locations.kind='parking'`)—— 不依赖上游的保底候选。
|
||||||
|
|
||||||
|
上游 parkeArea 与全局快照同时失效时(全站地图空白那种状态),
|
||||||
|
这份自己在地图上点出来的坐标仍然可用。
|
||||||
|
"""
|
||||||
|
conn = None
|
||||||
|
try:
|
||||||
|
conn = get_db()
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT name, latitude, longitude FROM campus_locations WHERE kind = 'parking'"
|
||||||
|
).fetchall()
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[还车位置] 读取校园停车点失败: {exc}")
|
||||||
|
return []
|
||||||
|
finally:
|
||||||
|
if conn is not None:
|
||||||
|
conn.close()
|
||||||
|
scored = []
|
||||||
|
for row in rows:
|
||||||
|
try:
|
||||||
|
plat, plng = float(row["latitude"]), float(row["longitude"])
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
continue
|
||||||
|
scored.append((_approx_m(lat, lng, plat, plng), plat, plng, row["name"]))
|
||||||
|
scored.sort(key=lambda x: x[0])
|
||||||
|
return [(p[1], p[2], p[3] or "校园停车点") for p in scored[:limit]]
|
||||||
|
|
||||||
|
|
||||||
|
def _return_candidates(lat: float, lng: float, user_id=None, area_limit=2):
|
||||||
|
"""还车候选坐标(GCJ02),按「先原坐标、再近处合法点」的顺序。
|
||||||
|
|
||||||
|
设计口径:**位置只是修坐标的手段,不是还车的前置条件**。
|
||||||
|
上游 parkeArea → 全局快照 → 校园停车点表,三级逐级兜底。
|
||||||
|
"""
|
||||||
|
candidates = [(lat, lng, "你上报的位置")]
|
||||||
|
|
||||||
|
areas = _park_areas(user_id)
|
||||||
|
scored = []
|
||||||
|
for area in areas:
|
||||||
|
boundary = park_area.closest_boundary_point(lat, lng, area.get("points") or [])
|
||||||
|
if boundary:
|
||||||
|
scored.append((boundary["distance"], area))
|
||||||
|
scored.sort(key=lambda x: x[0])
|
||||||
|
for _, area in scored[:area_limit]:
|
||||||
|
resolved = park_area.resolve_return_coord(lat, lng, [area])
|
||||||
|
if resolved:
|
||||||
|
candidates.append((resolved["latitude"], resolved["longitude"],
|
||||||
|
"附近停车区"))
|
||||||
|
|
||||||
|
for plat, plng, name in _campus_parking_points(lat, lng):
|
||||||
|
candidates.append((plat, plng, name))
|
||||||
|
|
||||||
|
return _distinct_points(candidates)
|
||||||
|
|
||||||
|
|
||||||
|
def _distinct_points(points, min_gap_m=12.0):
|
||||||
|
"""去掉彼此太近的候选点,避免对着同一个位置重复试。"""
|
||||||
|
out = []
|
||||||
|
for p in points:
|
||||||
|
if all(_approx_m(p[0], p[1], q[0], q[1]) >= min_gap_m for q in out):
|
||||||
|
out.append(p)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _try_return_candidates(user_id, order_id, code, lat, lng):
|
||||||
|
"""按「先原坐标,失败再算候选点」的顺序调 `/record/return`。
|
||||||
|
|
||||||
|
返回 (结果, 用到的点, 试过的点描述列表)。候选点要等真的失败才算,
|
||||||
|
否则每次还车都白白多打一次 `/project/map`。
|
||||||
|
"""
|
||||||
|
tried = ["你上报的位置"]
|
||||||
|
result = request_with_user_auth(
|
||||||
|
user_id, "POST", "/record/return",
|
||||||
|
data={"order_id": order_id, "longitude": lng, "latitude": lat, "code": code}
|
||||||
|
)
|
||||||
|
if result.get("rtn_code") == 0:
|
||||||
|
return result, (lat, lng), tried
|
||||||
|
# 「订单信息不存在」换坐标也没用,直接收工
|
||||||
|
if (result.get("rtn_code") == 204010
|
||||||
|
or "订单信息不存在" in str(result.get("message") or "")):
|
||||||
|
return result, (lat, lng), tried
|
||||||
|
|
||||||
|
last_result = result
|
||||||
|
for plat, plng, label in _return_candidates(lat, lng, user_id)[1:]:
|
||||||
|
tried.append(label)
|
||||||
|
result = request_with_user_auth(
|
||||||
|
user_id, "POST", "/record/return",
|
||||||
|
data={"order_id": order_id, "longitude": plng, "latitude": plat, "code": code}
|
||||||
|
)
|
||||||
|
last_result = result
|
||||||
|
if result.get("rtn_code") == 0:
|
||||||
|
print(f"[还车位置] 第 {len(tried)} 个候选点成功({label})")
|
||||||
|
return result, (plat, plng), tried
|
||||||
|
if (result.get("rtn_code") == 204010
|
||||||
|
or "订单信息不存在" in str(result.get("message") or "")):
|
||||||
|
return result, (plat, plng), tried
|
||||||
|
print(f"[还车位置] 候选点 {label} 失败: {result.get('message')}")
|
||||||
|
return last_result, (lat, lng), tried
|
||||||
|
|
||||||
|
|
||||||
|
def _legacy_nearest_bike_point(lat: float, lng: float, user_id=None) -> dict:
|
||||||
|
"""旧兜底:拿最近的一辆 type=1 共享单车当停车点。只在没有 parkeArea 时用。
|
||||||
|
|
||||||
|
入参与返回都是 GCJ02(上游车辆坐标就是这个),**不要再转换**。
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
data = _upstream_map_data(user_id)
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[停车区] legacy 兜底读取失败: {exc}")
|
||||||
|
return None
|
||||||
|
bike_stations = (data or {}).get("bicycleStation") or []
|
||||||
if not bike_stations:
|
if not bike_stations:
|
||||||
return None
|
return None
|
||||||
nearest = None
|
nearest = None
|
||||||
@@ -145,6 +343,25 @@ def get_nearest_park_point(lat: float, lng: float) -> dict:
|
|||||||
return nearest
|
return nearest
|
||||||
|
|
||||||
|
|
||||||
|
def get_nearest_park_point(lat: float, lng: float, user_id=None) -> dict:
|
||||||
|
"""最近的合法还车点(入参/返回都是 GCJ02)。
|
||||||
|
|
||||||
|
优先用上游 parkeArea 多边形算「最近停车区内的一个点」;上游没给多边形时,
|
||||||
|
退回历史逻辑(最近单车点)。`admin.py` / `routes/share.py` 传入的是上游车辆
|
||||||
|
坐标,本身就是 GCJ02,所以这里不做任何坐标转换。
|
||||||
|
|
||||||
|
`user_id` 传了就用该用户凭据读地图(比全局凭据可靠),见 `_upstream_map_data`。
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
lat, lng = float(lat), float(lng)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return None
|
||||||
|
resolved = _snap_to_park_area(lat, lng, user_id)
|
||||||
|
if resolved:
|
||||||
|
return {"latitude": resolved["latitude"], "longitude": resolved["longitude"]}
|
||||||
|
return _legacy_nearest_bike_point(lat, lng, user_id)
|
||||||
|
|
||||||
|
|
||||||
def _near_coord(lat, lng, jitter=0.0001):
|
def _near_coord(lat, lng, jitter=0.0001):
|
||||||
"""车辆坐标附近加随机抖动,模拟真实定位。返回 (lat, lng)"""
|
"""车辆坐标附近加随机抖动,模拟真实定位。返回 (lat, lng)"""
|
||||||
try:
|
try:
|
||||||
@@ -184,22 +401,46 @@ def _resolve_order_location(user_id: int, code: str, latitude, longitude):
|
|||||||
"""按还车的同一套规则校验并解析订单操作位置。
|
"""按还车的同一套规则校验并解析订单操作位置。
|
||||||
|
|
||||||
临时锁车也需要把当前位置同步给车辆服务,因此不能复用一键开锁时
|
临时锁车也需要把当前位置同步给车辆服务,因此不能复用一键开锁时
|
||||||
的车辆坐标或随机坐标。停车点校验失败时,沿用还车逻辑切到最近停车点。
|
的车辆坐标或随机坐标。
|
||||||
|
|
||||||
|
坐标系:**入口先 WGS84 -> GCJ02 转一次**(见 `to_upstream_coords`),之后
|
||||||
|
停车区判定、发上游、回写本地订单终点坐标/楼栋标签全部用 GCJ02。
|
||||||
|
|
||||||
|
判定顺序:
|
||||||
|
1. 上游 `/record/checkLocation` 为权威判定(`parkNoShow` = 不在停车区);
|
||||||
|
2. 上游判定不通过时,用本地 parkeArea 多边形算一个最近的合法还车点
|
||||||
|
(旧的「拿最近一辆共享单车当停车点」只在没有 parkeArea 时兜底)。
|
||||||
"""
|
"""
|
||||||
|
latitude, longitude = to_upstream_coords(latitude, longitude)
|
||||||
|
|
||||||
check_result = request_with_user_auth(
|
check_result = request_with_user_auth(
|
||||||
user_id, "POST", "/record/checkLocation",
|
user_id, "POST", "/record/checkLocation",
|
||||||
data={"longitude": longitude, "latitude": latitude, "bicycleCode": code}
|
data={"longitude": longitude, "latitude": latitude, "bicycleCode": code}
|
||||||
)
|
)
|
||||||
|
|
||||||
use_nearest = False
|
check_passed = (check_result.get("rtn_code") == 0
|
||||||
if check_result.get("rtn_code") != 0 or check_result.get("parkNoShow") is True:
|
and check_result.get("parkNoShow") is not True)
|
||||||
nearest = get_nearest_park_point(latitude, longitude)
|
if check_passed:
|
||||||
if nearest:
|
return latitude, longitude, False
|
||||||
latitude = nearest.get("latitude") or nearest.get("lat")
|
|
||||||
longitude = nearest.get("longitude") or nearest.get("lng")
|
|
||||||
use_nearest = True
|
|
||||||
|
|
||||||
return latitude, longitude, use_nearest
|
resolved = _snap_to_park_area(latitude, longitude, user_id)
|
||||||
|
if resolved:
|
||||||
|
if not resolved.get("moved"):
|
||||||
|
# 本地多边形判定本来就在停车区内:上游与本地边界有偏差,保持原坐标。
|
||||||
|
return latitude, longitude, False
|
||||||
|
print(f"[还车位置] 上游判 parkNoShow,吸附到最近停车区: "
|
||||||
|
f"({latitude:.6f}, {longitude:.6f}) -> "
|
||||||
|
f"({resolved['latitude']:.6f}, {resolved['longitude']:.6f}) "
|
||||||
|
f"[{resolved.get('distance', 0):.0f}m]")
|
||||||
|
return resolved["latitude"], resolved["longitude"], True
|
||||||
|
|
||||||
|
nearest = _legacy_nearest_bike_point(latitude, longitude, user_id)
|
||||||
|
if nearest:
|
||||||
|
print(f"[还车位置] 无 parkeArea 数据,退回最近单车点兜底: "
|
||||||
|
f"({nearest['latitude']:.6f}, {nearest['longitude']:.6f})")
|
||||||
|
return nearest["latitude"], nearest["longitude"], True
|
||||||
|
|
||||||
|
return latitude, longitude, False
|
||||||
|
|
||||||
|
|
||||||
def _location_label(latitude, longitude):
|
def _location_label(latitude, longitude):
|
||||||
@@ -272,7 +513,7 @@ def _set_rental_finished(conn, where_sql, where_params, latitude, longitude):
|
|||||||
"""
|
"""
|
||||||
params = (now_str, end_lat, end_lng, label, *where_params)
|
params = (now_str, end_lat, end_lng, label, *where_params)
|
||||||
try:
|
try:
|
||||||
conn.execute(sql, params)
|
cursor = conn.execute(sql, params)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
if "no such column" not in str(e).lower():
|
if "no such column" not in str(e).lower():
|
||||||
raise
|
raise
|
||||||
@@ -283,16 +524,57 @@ def _set_rental_finished(conn, where_sql, where_params, latitude, longitude):
|
|||||||
conn.execute(f"ALTER TABLE rentals ADD COLUMN {col_def[0]} {col_def[1]}")
|
conn.execute(f"ALTER TABLE rentals ADD COLUMN {col_def[0]} {col_def[1]}")
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
conn.execute(sql, params)
|
cursor = conn.execute(sql, params)
|
||||||
|
# 返回命中行数:调用方(管理端代还车)需要知道「没匹配到任何一行」,
|
||||||
|
# 比如库里 order_id 是脏字符串时,否则后台会继续显示「进行中」
|
||||||
|
return cursor.rowcount
|
||||||
|
|
||||||
|
|
||||||
|
def _record_raw_coords(order_id: str, user_id: int, latitude, longitude):
|
||||||
|
"""单独留存用户「当时真实上报」的坐标(吸附/换点之后的点会失真)。
|
||||||
|
|
||||||
|
以后要做「车到底停在哪」的分析时,end_latitude/end_longitude 是判定用点,
|
||||||
|
raw_latitude/raw_longitude 才是现场位置。缺列时自动补。
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
lat, lng = float(latitude), float(longitude)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return
|
||||||
|
sql = """
|
||||||
|
UPDATE rentals SET raw_latitude = ?, raw_longitude = ?
|
||||||
|
WHERE order_id = ? AND user_id = ?
|
||||||
|
"""
|
||||||
|
params = (lat, lng, str(order_id), user_id)
|
||||||
|
conn = get_db()
|
||||||
|
try:
|
||||||
|
try:
|
||||||
|
conn.execute(sql, params)
|
||||||
|
except Exception as e:
|
||||||
|
if "no such column" not in str(e).lower():
|
||||||
|
raise
|
||||||
|
for col, decl in (("raw_latitude", "REAL"), ("raw_longitude", "REAL")):
|
||||||
|
try:
|
||||||
|
conn.execute(f"ALTER TABLE rentals ADD COLUMN {col} {decl}")
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
conn.execute(sql, params)
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
def _record_rental_end(order_id: str, user_id: int, latitude, longitude):
|
def _record_rental_end(order_id: str, user_id: int, latitude, longitude):
|
||||||
"""标记订单结束:实际还车时间 + 终点坐标与位置标签。"""
|
"""标记订单结束:实际还车时间 + 终点坐标与位置标签。
|
||||||
|
|
||||||
|
返回命中的行数(0 表示这条 order_id 在库里没匹配到进行中的单)。
|
||||||
|
"""
|
||||||
conn = get_db()
|
conn = get_db()
|
||||||
try:
|
try:
|
||||||
_set_rental_finished(conn, "WHERE order_id = ? AND user_id = ? AND expired = 0",
|
updated = _set_rental_finished(
|
||||||
(str(order_id), user_id), latitude, longitude)
|
conn, "WHERE order_id = ? AND user_id = ? AND expired = 0",
|
||||||
|
(str(order_id), user_id), latitude, longitude)
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
return updated
|
||||||
finally:
|
finally:
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
@@ -389,23 +671,37 @@ def order_unlock():
|
|||||||
end_time = now_beijing + dt.timedelta(minutes=duration)
|
end_time = now_beijing + dt.timedelta(minutes=duration)
|
||||||
conn = get_db()
|
conn = get_db()
|
||||||
cursor = conn.cursor()
|
cursor = conn.cursor()
|
||||||
cursor.execute("""
|
try:
|
||||||
INSERT INTO rentals (id, order_id, bike_code, email, user_id, start_time, end_time,
|
cursor.execute("""
|
||||||
duration, expired, source)
|
INSERT INTO rentals (id, order_id, bike_code, email, user_id, start_time, end_time,
|
||||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, 'unlock')
|
duration, expired, source)
|
||||||
""", (int(order_id), order_id, code, user["email"], user["id"],
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, 'unlock')
|
||||||
now_beijing.strftime("%Y-%m-%d %H:%M:%S"),
|
""", (int(order_id), order_id, code, user["email"], user["id"],
|
||||||
end_time.strftime("%Y-%m-%d %H:%M:%S"), duration))
|
now_beijing.strftime("%Y-%m-%d %H:%M:%S"),
|
||||||
|
end_time.strftime("%Y-%m-%d %H:%M:%S"), duration))
|
||||||
|
rental_row_id = int(order_id)
|
||||||
|
except sqlite3.IntegrityError:
|
||||||
|
# rentals.id 可能被 reminder/sync 的自增行占用(序列漂移):改用自增 id,
|
||||||
|
# order_id 仍记录真实上游单号。用 lastrowid 当 rental_id,别把计时器挂到别人单上。
|
||||||
|
print(f"[开锁] rentals.id={order_id} 已被占用,改用自增 id")
|
||||||
|
cur2 = conn.execute("""
|
||||||
|
INSERT INTO rentals (order_id, bike_code, email, user_id, start_time, end_time,
|
||||||
|
duration, expired, source)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, 0, 'unlock')
|
||||||
|
""", (order_id, code, user["email"], user["id"],
|
||||||
|
now_beijing.strftime("%Y-%m-%d %H:%M:%S"),
|
||||||
|
end_time.strftime("%Y-%m-%d %H:%M:%S"), duration))
|
||||||
|
rental_row_id = cur2.lastrowid
|
||||||
conn.commit()
|
conn.commit()
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
start_rental_timer(rental_id=int(order_id), email=user["email"],
|
start_rental_timer(rental_id=int(rental_row_id), email=user["email"],
|
||||||
bike_code=code, duration_minutes=duration, user_id=user["id"])
|
bike_code=code, duration_minutes=duration, user_id=user["id"])
|
||||||
_record_rental_start(int(order_id), latitude, longitude)
|
_record_rental_start(int(rental_row_id), latitude, longitude)
|
||||||
# 带上轮次预估:前端租车条要显示「共N轮 · 预计HH:MM还车」
|
# 带上轮次预估:前端租车条要显示「共N轮 · 预计HH:MM还车」
|
||||||
row = get_db().execute(
|
row = get_db().execute(
|
||||||
"SELECT renewal_round, rounds_override, end_time FROM rentals WHERE id = ?",
|
"SELECT renewal_round, rounds_override, end_time FROM rentals WHERE id = ?",
|
||||||
(int(order_id),)).fetchone()
|
(int(rental_row_id),)).fetchone()
|
||||||
summary = _rounds_summary(
|
summary = _rounds_summary(
|
||||||
dict(row) if row else {"order_id": str(order_id),
|
dict(row) if row else {"order_id": str(order_id),
|
||||||
"end_time": end_time.strftime("%Y-%m-%d %H:%M:%S")},
|
"end_time": end_time.strftime("%Y-%m-%d %H:%M:%S")},
|
||||||
@@ -415,10 +711,19 @@ def order_unlock():
|
|||||||
else:
|
else:
|
||||||
from wechat import friendly_upstream_message
|
from wechat import friendly_upstream_message
|
||||||
raw_open_msg = open_result.get("message", "")
|
raw_open_msg = open_result.get("message", "")
|
||||||
|
# 上车失败必须把刚下的单撤掉,否则上游留一张没人骑的「未支付」订单;
|
||||||
|
# 下次开锁命中「未支付」分支时会用月卡把它付掉 —— 白扣一次卡次。
|
||||||
|
try:
|
||||||
|
from subscribe import _discard_pending_order
|
||||||
|
cleaned = _discard_pending_order(user["id"], order_id, code, latitude, longitude)
|
||||||
|
except Exception as exc:
|
||||||
|
cleaned = False
|
||||||
|
print(f"[开锁] 撤销半成品订单异常: {exc}")
|
||||||
if open_result.get("rtn_code") == 102001 or "token" in raw_open_msg.lower():
|
if open_result.get("rtn_code") == 102001 or "token" in raw_open_msg.lower():
|
||||||
return jsonify({"rtn_code": 102001, "message": "Token失效,微信凭据已过期,请在个人中心重新配置"})
|
return jsonify({"rtn_code": 102001, "message": "Token失效,微信凭据已过期,请在个人中心重新配置"})
|
||||||
return jsonify({"rtn_code": open_result.get("rtn_code", 500),
|
return jsonify({"rtn_code": open_result.get("rtn_code", 500),
|
||||||
"message": friendly_upstream_message(raw_open_msg, fallback="开锁失败,请稍后重试"),
|
"message": friendly_upstream_message(raw_open_msg, fallback="开锁失败,请稍后重试")
|
||||||
|
+ ("(已撤销本次下单)" if cleaned else ""),
|
||||||
"order_id": order_id})
|
"order_id": order_id})
|
||||||
|
|
||||||
|
|
||||||
@@ -541,21 +846,26 @@ def order_return():
|
|||||||
user_name = get_user_display_name(user["id"])
|
user_name = get_user_display_name(user["id"])
|
||||||
print(f"[操作日志] 手动还车: order_id={order_id}, code={data.get('code','')}, lat={latitude}, lng={longitude}, user={user_name}")
|
print(f"[操作日志] 手动还车: order_id={order_id}, code={data.get('code','')}, lat={latitude}, lng={longitude}, user={user_name}")
|
||||||
|
|
||||||
latitude, longitude, use_nearest = _resolve_order_location(
|
# 位置只用来「修坐标」,不再当还车的前置条件:
|
||||||
user["id"], data.get("code", ""), latitude, longitude
|
# 先拿你上报的坐标直接发,失败了再换最近的合法点,最多试几个候选点。
|
||||||
)
|
raw_lat, raw_lng = to_upstream_coords(latitude, longitude)
|
||||||
|
return_result, used_point, tried_labels = _try_return_candidates(
|
||||||
return_result = request_with_user_auth(
|
user["id"], order_id, data.get("code", ""), raw_lat, raw_lng
|
||||||
user["id"], "POST", "/record/return",
|
|
||||||
data={"order_id": order_id, "longitude": longitude, "latitude": latitude}
|
|
||||||
)
|
)
|
||||||
|
latitude, longitude = used_point
|
||||||
|
use_nearest = len(tried_labels) > 1
|
||||||
|
|
||||||
confirmed_by_status = False
|
confirmed_by_status = False
|
||||||
if return_result.get("rtn_code") != 0:
|
# 「订单信息不存在」(实测 204010) 不能当成功:本来就没有这张单,
|
||||||
|
# 若还走"状态确认"会拿上游另一张进行中订单当本单已结束,前端显示"还车成功"
|
||||||
|
# 而实际车还在计费。这类硬错误直接原样回给前端。
|
||||||
|
hard_reject = (return_result.get("rtn_code") == 204010
|
||||||
|
or "订单信息不存在" in str(return_result.get("message") or ""))
|
||||||
|
if return_result.get("rtn_code") != 0 and not hard_reject:
|
||||||
for attempt in range(4):
|
for attempt in range(4):
|
||||||
if attempt:
|
if attempt:
|
||||||
time.sleep(1)
|
time.sleep(1)
|
||||||
if _upstream_order_finished(user["id"], order_id):
|
if _upstream_order_finished(user["id"], order_id, data.get("code", "")):
|
||||||
confirmed_by_status = True
|
confirmed_by_status = True
|
||||||
break
|
break
|
||||||
|
|
||||||
@@ -570,8 +880,21 @@ def order_return():
|
|||||||
""", (str(order_id), user["id"]))
|
""", (str(order_id), user["id"]))
|
||||||
rental_ids = [row["id"] for row in cursor.fetchall()]
|
rental_ids = [row["id"] for row in cursor.fetchall()]
|
||||||
conn.close()
|
conn.close()
|
||||||
# 统一回填:expired=1 + 实际还车时间 + 终点坐标/位置标签
|
# 统一回填:expired=1 + 实际还车时间 + 终点坐标/位置标签。
|
||||||
_record_rental_end(order_id, user["id"], latitude, longitude)
|
# 上游已经还车成功,这两行写库失败也只记日志 —— 不能因为本地写不进去
|
||||||
|
# 就把「还车成功」报成失败(用户会再点一次,撞上 204010 更看不懂)。
|
||||||
|
local_sync_warning = ""
|
||||||
|
try:
|
||||||
|
_record_rental_end(order_id, user["id"], latitude, longitude)
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[order_return] 本地回填终点失败(不影响还车结果): {exc}")
|
||||||
|
local_sync_warning = "本地记录稍后同步"
|
||||||
|
try:
|
||||||
|
# 你当时真实上报的位置单独留一份(吸附后的点会失真,做分析要用原始值)
|
||||||
|
_record_raw_coords(order_id, user["id"], raw_lat, raw_lng)
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[order_return] 本地记录原始坐标失败(不影响还车结果): {exc}")
|
||||||
|
local_sync_warning = "本地记录稍后同步"
|
||||||
for rental_id in rental_ids:
|
for rental_id in rental_ids:
|
||||||
_cancel_rental_timers(rental_id)
|
_cancel_rental_timers(rental_id)
|
||||||
_user_info_cache.pop(user["id"], None)
|
_user_info_cache.pop(user["id"], None)
|
||||||
@@ -589,9 +912,12 @@ def order_return():
|
|||||||
success_message = "还车成功"
|
success_message = "还车成功"
|
||||||
if confirmed_by_status:
|
if confirmed_by_status:
|
||||||
success_message += "(已通过订单状态确认)"
|
success_message += "(已通过订单状态确认)"
|
||||||
|
if local_sync_warning:
|
||||||
|
success_message += f"({local_sync_warning})"
|
||||||
return jsonify({"rtn_code": 0,
|
return jsonify({"rtn_code": 0,
|
||||||
"message": success_message + (f",{pay_msg}" if pay_success else ""),
|
"message": success_message + (f",{pay_msg}" if pay_success else ""),
|
||||||
"used_nearest": use_nearest, "card_pay": pay_result})
|
"used_nearest": use_nearest, "card_pay": pay_result,
|
||||||
|
"local_synced": not local_sync_warning})
|
||||||
else:
|
else:
|
||||||
return jsonify({"rtn_code": return_result.get("rtn_code", 500),
|
return jsonify({"rtn_code": return_result.get("rtn_code", 500),
|
||||||
"message": return_result.get("message", "还车失败")})
|
"message": return_result.get("message", "还车失败")})
|
||||||
|
|||||||
+29
-9
@@ -49,17 +49,25 @@ def _today_str():
|
|||||||
return _beijing_now().strftime("%Y-%m-%d")
|
return _beijing_now().strftime("%Y-%m-%d")
|
||||||
|
|
||||||
|
|
||||||
def _upstream_order_finished(user_id: int, order_id) -> bool:
|
def _upstream_order_finished(user_id: int, order_id, bike_code=None) -> bool:
|
||||||
"""在还车调用响应不明确时,以用户真实订单状态做二次确认。"""
|
"""还车响应不明确时,确认指定订单是否已经不再骑行。
|
||||||
|
|
||||||
|
与 routes/rental.py 的同名函数保持一致:上游 `nonDealOrder` 只保留
|
||||||
|
**当前那一张**进行中的订单,如果挂着的是另一张单(多轮续租/共享轮换),
|
||||||
|
不能直接判本单结束 —— 否则会把「仍在计费的车」当成功还掉。
|
||||||
|
所以再按车牌兜一层:上游挂着同车牌的订单,就当本单还没结束。
|
||||||
|
"""
|
||||||
result = request_with_user_auth(user_id, "GET", "/user/info", _silent=True)
|
result = request_with_user_auth(user_id, "GET", "/user/info", _silent=True)
|
||||||
if result.get("rtn_code") != 0:
|
if result.get("rtn_code") != 0:
|
||||||
return False
|
return False
|
||||||
non_deal = (result.get("data") or {}).get("nonDealOrder")
|
non_deal = (result.get("data") or {}).get("nonDealOrder")
|
||||||
if not non_deal or not non_deal.get("order_id"):
|
if not non_deal or not non_deal.get("order_id"):
|
||||||
return True
|
return True
|
||||||
if str(non_deal.get("order_id")) != str(order_id):
|
if str(non_deal.get("order_id")) == str(order_id):
|
||||||
return True
|
return str(non_deal.get("status")) != "2"
|
||||||
return str(non_deal.get("status")) != "2"
|
if bike_code and str(non_deal.get("code") or "") == str(bike_code):
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
def _user_email(user_id: int):
|
def _user_email(user_id: int):
|
||||||
@@ -844,16 +852,20 @@ def share_return():
|
|||||||
latitude, longitude = 36.67, 116.98
|
latitude, longitude = 36.67, 116.98
|
||||||
|
|
||||||
# 真实还车(owner 凭据):checkLocation → 非还车点则就近停车点
|
# 真实还车(owner 凭据):checkLocation → 非还车点则就近停车点
|
||||||
from routes.rental import _try_card_pay_auto, get_nearest_park_point
|
from routes.rental import (_try_card_pay_auto, get_nearest_park_point,
|
||||||
|
to_upstream_coords)
|
||||||
from timer import _cancel_rental_timers
|
from timer import _cancel_rental_timers
|
||||||
|
|
||||||
|
# 浏览器上报的是 WGS84,上游/停车区是 GCJ02,入口先统一转一次
|
||||||
|
latitude, longitude = to_upstream_coords(latitude, longitude)
|
||||||
|
|
||||||
check_result = request_with_user_auth(
|
check_result = request_with_user_auth(
|
||||||
owner_user_id, "POST", "/record/checkLocation",
|
owner_user_id, "POST", "/record/checkLocation",
|
||||||
data={"longitude": longitude, "latitude": latitude, "bicycleCode": bike_code},
|
data={"longitude": longitude, "latitude": latitude, "bicycleCode": bike_code},
|
||||||
_silent=True)
|
_silent=True)
|
||||||
use_nearest = False
|
use_nearest = False
|
||||||
if check_result.get("rtn_code") != 0 or check_result.get("parkNoShow") is True:
|
if check_result.get("rtn_code") != 0 or check_result.get("parkNoShow") is True:
|
||||||
nearest = get_nearest_park_point(latitude, longitude)
|
nearest = get_nearest_park_point(latitude, longitude, owner_user_id)
|
||||||
if nearest:
|
if nearest:
|
||||||
latitude = nearest.get("latitude") or nearest.get("lat")
|
latitude = nearest.get("latitude") or nearest.get("lat")
|
||||||
longitude = nearest.get("longitude") or nearest.get("lng")
|
longitude = nearest.get("longitude") or nearest.get("lng")
|
||||||
@@ -866,18 +878,26 @@ def share_return():
|
|||||||
"longitude": longitude, "latitude": latitude}, _silent=True)
|
"longitude": longitude, "latitude": latitude}, _silent=True)
|
||||||
|
|
||||||
confirmed_by_status = False
|
confirmed_by_status = False
|
||||||
if return_result.get("rtn_code") != 0:
|
# 「订单信息不存在」(204010) 是硬错误:本来就没有这张单,别去状态确认,
|
||||||
|
# 否则会把上游另一张进行中的订单当成本单已结束,用户看到「还车成功」而车还在计费。
|
||||||
|
hard_reject = (return_result.get("rtn_code") == 204010
|
||||||
|
or "订单信息不存在" in str(return_result.get("message") or ""))
|
||||||
|
if return_result.get("rtn_code") != 0 and not hard_reject:
|
||||||
# 锁车指令可能已经被车辆执行,但 HTTP 响应超时/异常。短暂复查真实订单
|
# 锁车指令可能已经被车辆执行,但 HTTP 响应超时/异常。短暂复查真实订单
|
||||||
# 状态;只在上游明确显示不再骑行时按成功处理,避免误报也避免误清理。
|
# 状态;只在上游明确显示不再骑行时按成功处理,避免误报也避免误清理。
|
||||||
for attempt in range(4):
|
for attempt in range(4):
|
||||||
if attempt:
|
if attempt:
|
||||||
time.sleep(1)
|
time.sleep(1)
|
||||||
if _upstream_order_finished(owner_user_id, upstream_order_id):
|
if _upstream_order_finished(
|
||||||
|
owner_user_id, upstream_order_id,
|
||||||
|
(rental["bike_code"] if rental is not None else None)):
|
||||||
confirmed_by_status = True
|
confirmed_by_status = True
|
||||||
break
|
break
|
||||||
if not confirmed_by_status:
|
if not confirmed_by_status:
|
||||||
return jsonify({"rtn_code": return_result.get("rtn_code", 500),
|
return jsonify({"rtn_code": return_result.get("rtn_code", 500),
|
||||||
"message": return_result.get("message", "还车失败")})
|
"message": return_result.get("message", "还车失败")})
|
||||||
|
elif hard_reject:
|
||||||
|
return jsonify({"rtn_code": 204010, "message": "订单信息不存在,请刷新后重试"})
|
||||||
|
|
||||||
conn = get_db()
|
conn = get_db()
|
||||||
cur = conn.cursor()
|
cur = conn.cursor()
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""百度「步行路线规划(轻量)」连通性探针。
|
||||||
|
|
||||||
|
用法(把你的 AK/SK 填进来):
|
||||||
|
PowerShell:
|
||||||
|
$env:BAIDU_ROUTE_AK="你的AK"; $env:BAIDU_ROUTE_SK="你的SK"
|
||||||
|
python scripts/probe_baidu_route.py
|
||||||
|
bash:
|
||||||
|
BAIDU_ROUTE_AK=... BAIDU_ROUTE_SK=... python scripts/probe_baidu_route.py
|
||||||
|
|
||||||
|
会依次尝试两种 SN 算法(官方样例 / 社区写法),打印谁通了、返回多少米多少秒。
|
||||||
|
通了就把 AK/SK 写进 server_config.json:
|
||||||
|
{ "baidu_route_ak": "...", "baidu_route_sk": "..." }
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
|
||||||
|
import walk_route
|
||||||
|
|
||||||
|
# 校内两点(GCJ02):学生公寓附近 -> 教学楼附近
|
||||||
|
ORIGIN = (36.529440, 116.783740)
|
||||||
|
DEST = (36.534240, 116.787190)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
ak = walk_route.get_ak()
|
||||||
|
sk = walk_route.get_sk()
|
||||||
|
print(f"AK: {ak[:8] + '…' if ak else '(未配置)'} SK: {'已配置(' + str(len(sk)) + '位)' if sk else '(未配置)'}")
|
||||||
|
if not ak:
|
||||||
|
print("先设置 BAIDU_ROUTE_AK / BAIDU_ROUTE_SK 再跑")
|
||||||
|
return 2
|
||||||
|
|
||||||
|
ok = False
|
||||||
|
for mode in ("official", "simple"):
|
||||||
|
try:
|
||||||
|
got = walk_route._call_baidu(ak, sk, *ORIGIN, *DEST, mode)
|
||||||
|
print(f"[{mode:8}] ✔ 通过 distance={got['distance']} 米 "
|
||||||
|
f"duration={got['duration']} 秒 ({got['duration'] / 60:.1f} 分钟)")
|
||||||
|
ok = True
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[{mode:8}] ✘ {exc}")
|
||||||
|
|
||||||
|
print("\n结论:", "SN 算法可用,把 AK/SK 写进 server_config.json 即可。" if ok else
|
||||||
|
"两种算法都没通,检查 AK 是否开启了「步行路线规划(轻量)」、SK 是否正确、配额是否用尽。")
|
||||||
|
return 0 if ok else 1
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,218 @@
|
|||||||
|
/* 由 static/js/{navigation,share,subscribe,map}.js 逐块搬运而来;正文与原实现一致。 */
|
||||||
|
|
||||||
|
import { S } from "../core/state";
|
||||||
|
import { calcDistance, offsetCoord } from "../core/geo";
|
||||||
|
import { getBikeKind, getBikeState } from "../map/icons";
|
||||||
|
import { clearHighlight, setHighlight } from "../map/markers";
|
||||||
|
import { _nav, _navBtnText, stopNavigation } from "../nav/navigation";
|
||||||
|
import { MAX_WALK_DISTANCE_M, refineWalkRoute } from "../nav/walk-route";
|
||||||
|
import { disableLostMode, scanCode } from "../order/actions";
|
||||||
|
import { closeOrderActionsModal } from "../order/status";
|
||||||
|
import { showToast } from "../ui/modals";
|
||||||
|
// static/js/map.js:159-170
|
||||||
|
export function updateRingProgress(percent, color) {
|
||||||
|
const fill = document.getElementById("battery-fill");
|
||||||
|
if (fill) {
|
||||||
|
// 电量填充区域最大宽度 39px(外框内宽 = 43-4 left offset-2border=39)
|
||||||
|
const maxW = 39;
|
||||||
|
const w = Math.round((percent / 100) * maxW);
|
||||||
|
fill.setAttribute("width", String(w));
|
||||||
|
fill.setAttribute("fill", color);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== Canvas 电量圆环图标 ==========
|
||||||
|
|
||||||
|
// static/js/map.js:1938-1941
|
||||||
|
export function viewBikeDetailFromOrderModal() {
|
||||||
|
closeOrderActionsModal();
|
||||||
|
viewBikeDetailFromOrder();
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:2005-2011
|
||||||
|
export function viewBikeDetailFromOrder() {
|
||||||
|
if (!S.currentOrder) { showToast("当前没有进行中的订单"); return; }
|
||||||
|
const code = (S.currentOrder.code || "").toString().trim();
|
||||||
|
if (!code) { showToast("该订单没有车牌信息"); return; }
|
||||||
|
document.getElementById("scan-input").value = code;
|
||||||
|
scanCode();
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:3265-3275
|
||||||
|
export function _fitCardActions() {
|
||||||
|
const card = document.getElementById("bike-card");
|
||||||
|
const codeEl = document.getElementById("card-code");
|
||||||
|
const title = card && card.querySelector(".bike-card-title");
|
||||||
|
if (!card || !codeEl) return;
|
||||||
|
card.classList.remove("compact-actions");
|
||||||
|
// 读一次布局,看车牌是否被 ellipsis 截断
|
||||||
|
const truncated = (title && title.scrollWidth > title.clientWidth + 1)
|
||||||
|
|| (codeEl.scrollWidth > codeEl.clientWidth + 1);
|
||||||
|
if (truncated) card.classList.add("compact-actions");
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:3285-3428
|
||||||
|
export function showBikeDetail(id) {
|
||||||
|
let bike = S.markersData[id];
|
||||||
|
// 多格式尝试查找
|
||||||
|
if (!bike) bike = S.markersData[String(id)];
|
||||||
|
if (!bike) bike = S.markersData[Number(id)];
|
||||||
|
// 按 code 遍历查找
|
||||||
|
if (!bike) {
|
||||||
|
for (const key in S.markersData) {
|
||||||
|
if (S.markersData[key] && String(S.markersData[key].code) === String(id)) {
|
||||||
|
bike = S.markersData[key];
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!bike) {
|
||||||
|
console.error("[showBikeDetail] 找不到车辆数据, id=", id, "markersData keys样本=", Object.keys(S.markersData).slice(0, 5));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// 换了另一辆车:先把上一辆的导航停掉,避免路线残留在图上
|
||||||
|
if (typeof _nav !== "undefined" && _nav && String(_nav.destCode) !== String(bike.code)) {
|
||||||
|
try { stopNavigation(); } catch (e) {}
|
||||||
|
}
|
||||||
|
S.selectedBike = bike;
|
||||||
|
|
||||||
|
// 设置高亮
|
||||||
|
setHighlight(id);
|
||||||
|
|
||||||
|
document.getElementById("card-code").textContent = `#${bike.code || id}`;
|
||||||
|
|
||||||
|
// 正在导航的就是这辆车 -> 按钮显示「结束」
|
||||||
|
_navBtnText((_nav && String(_nav.destCode) === String(bike.code)) ? "结束" : "导航");
|
||||||
|
|
||||||
|
// 距离/步行时间:取自动定位留下的标记点(BD09),没开定位就整格隐藏。
|
||||||
|
// 注意别引用 watchPosition 回调里的局部 myPoint —— 那是函数内变量。
|
||||||
|
const metaLeft = document.getElementById("card-meta-left");
|
||||||
|
const distEl = document.getElementById("card-distance");
|
||||||
|
const walkEl = document.getElementById("card-walk");
|
||||||
|
let distMeters = null; // 直线距离(BD09 平面对比),用于决定是否显示导航按钮
|
||||||
|
if (metaLeft && distEl && walkEl) {
|
||||||
|
let distText = "";
|
||||||
|
let walkText = "";
|
||||||
|
try {
|
||||||
|
const me = (typeof S.autoLocationMarker !== "undefined" && S.autoLocationMarker)
|
||||||
|
? S.autoLocationMarker.getPosition() : null;
|
||||||
|
if (me && bike.latitude && bike.longitude) {
|
||||||
|
const c = offsetCoord(bike.latitude, bike.longitude); // GCJ02 -> BD09
|
||||||
|
const meters = calcDistance(me.lat, me.lng, c.lat, c.lng);
|
||||||
|
distMeters = meters;
|
||||||
|
if (Number.isFinite(meters) && meters < MAX_WALK_DISTANCE_M) {
|
||||||
|
distText = meters < 1000
|
||||||
|
? `距你 ${Math.round(meters)} 米`
|
||||||
|
: `距你 ${(meters / 1000).toFixed(1)} 公里`;
|
||||||
|
walkText = `步行 ${Math.max(1, Math.round(meters / 80))} 分钟`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
distText = "";
|
||||||
|
walkText = "";
|
||||||
|
}
|
||||||
|
distEl.textContent = distText;
|
||||||
|
walkEl.textContent = walkText;
|
||||||
|
metaLeft.hidden = !distText;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 太远就不给「导航」按钮(百度步行路线超过 200km 会直接报错,
|
||||||
|
// 而且现实中也没人会走 20 公里去取车)。正在导航这辆车时始终保留「结束」。
|
||||||
|
const navBtnEl2 = document.getElementById("bike-nav-btn");
|
||||||
|
if (navBtnEl2) {
|
||||||
|
const navigatingThis = _nav && String(_nav.destCode) === String(bike.code);
|
||||||
|
const tooFar = !navigatingThis && Number.isFinite(distMeters)
|
||||||
|
&& distMeters >= MAX_WALK_DISTANCE_M;
|
||||||
|
navBtnEl2.style.display = tooFar ? "none" : "";
|
||||||
|
}
|
||||||
|
// 车牌长短 + 屏宽一起决定按钮是否收成纯图标
|
||||||
|
_fitCardActions();
|
||||||
|
|
||||||
|
// 异步换成「真实道路距离 + 步行耗时」:先问后端(百度轻量级路线规划),
|
||||||
|
// 后端没配 AK 就退到浏览器端 JS API,两者都失败则保留上面的直线估算。
|
||||||
|
refineWalkRoute(bike);
|
||||||
|
|
||||||
|
// 车辆类型角标(红车 / 大车 / 小车)
|
||||||
|
const kind = getBikeKind(bike);
|
||||||
|
const kindEl = document.getElementById("card-kind");
|
||||||
|
if (kindEl) {
|
||||||
|
kindEl.textContent = kind.label;
|
||||||
|
kindEl.classList.remove("kind-red", "kind-big", "kind-small");
|
||||||
|
kindEl.classList.add("kind-" + kind.key);
|
||||||
|
}
|
||||||
|
|
||||||
|
const electric = parseFloat(bike.electric_quantity || bike.electricQuantity || 0);
|
||||||
|
document.getElementById("card-electric").textContent = String(Math.round(electric));
|
||||||
|
|
||||||
|
let ringColor = "#34c759";
|
||||||
|
const bikeState = getBikeState(bike);
|
||||||
|
if (bikeState === 'inuse') {
|
||||||
|
ringColor = "#ff2d55";
|
||||||
|
} else if (bikeState === 'locked') {
|
||||||
|
ringColor = "#ff9f0a";
|
||||||
|
} else if (bikeState === 'reserved') {
|
||||||
|
ringColor = "#5856D6";
|
||||||
|
} else if (bikeState === 'lowbattery' || electric < 20) {
|
||||||
|
ringColor = "#8e8e93";
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
updateRingProgress(electric, ringColor);
|
||||||
|
} catch (e) {
|
||||||
|
console.error("[showBikeDetail] updateRingProgress 错误:", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 状态文本:结合 state 和 status 判断
|
||||||
|
let stateText = "--";
|
||||||
|
if (bike.state === 1 && bike.status === 1) {
|
||||||
|
stateText = "使用中";
|
||||||
|
} else if (bike.state === 1) {
|
||||||
|
stateText = "空闲";
|
||||||
|
} else if (bike.state === 10) {
|
||||||
|
stateText = "低电量";
|
||||||
|
} else if (bike.state === 4) {
|
||||||
|
stateText = "欠压车辆";
|
||||||
|
} else if (bike.state === 2) {
|
||||||
|
stateText = "损坏车辆";
|
||||||
|
} else {
|
||||||
|
stateText = "未知";
|
||||||
|
}
|
||||||
|
document.getElementById("card-state").textContent = stateText;
|
||||||
|
document.getElementById("card-state").className = "bike-status-value" +
|
||||||
|
(stateText === "使用中" ? " warning" : stateText === "空闲" ? " highlight" : "");
|
||||||
|
|
||||||
|
document.getElementById("bike-card").classList.add("show");
|
||||||
|
const overlay = document.getElementById("card-overlay");
|
||||||
|
if (overlay) overlay.classList.add("show");
|
||||||
|
|
||||||
|
if (bike.latitude && bike.longitude) {
|
||||||
|
const c = offsetCoord(bike.latitude, bike.longitude);
|
||||||
|
const bikePoint = new BMapGL.Point(c.lng, c.lat);
|
||||||
|
S.map.panTo(bikePoint);
|
||||||
|
// 单实例定时器 + 放大上限:以前每开一次卡片就排一个不跟踪的 setTimeout,
|
||||||
|
// 连点几辆车会把地图永久放大到最大级别。
|
||||||
|
clearTimeout(_cardZoomTimer);
|
||||||
|
_cardZoomTimer = setTimeout(() => {
|
||||||
|
if (S.map.getZoom() < 19) S.map.setZoom(S.map.getZoom() + 1);
|
||||||
|
}, 300);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:3429-3429
|
||||||
|
let _cardZoomTimer: any = null;
|
||||||
|
|
||||||
|
// static/js/map.js:3431-3445
|
||||||
|
export function closeCard() {
|
||||||
|
// 关卡片**不**结束导航(导航条上有单独的「结束导航」按钮)
|
||||||
|
const card = document.getElementById("bike-card");
|
||||||
|
const overlay = document.getElementById("card-overlay");
|
||||||
|
card.classList.remove("show");
|
||||||
|
card.style.transform = "";
|
||||||
|
if (overlay) overlay.classList.remove("show");
|
||||||
|
S.selectedBike = null;
|
||||||
|
// 关闭卡片时清除高亮,让车辆图标还原为普通大小(不再保持放大带车牌)
|
||||||
|
clearHighlight();
|
||||||
|
// 关闭卡片时同步停止丢失模式
|
||||||
|
if (typeof disableLostMode === "function") disableLostMode();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 下滑关闭手势 ==========
|
||||||
@@ -0,0 +1,324 @@
|
|||||||
|
/* **唯一**把函数挂到 window 的地方。
|
||||||
|
*
|
||||||
|
* templates/map.html 里还有大量内联 onclick="foo()",它们要求 foo 是全局函数。
|
||||||
|
* 原实现是经典脚本(顶层 function 声明天然成为全局),bundle 之后必须显式挂回去。
|
||||||
|
* 函数清单由 tools/gen.mjs 从源文件里抓,正常情况下与 map.js 的全局面 1:1 对应。
|
||||||
|
*/
|
||||||
|
import { Geo, offsetCoord, calcDistance } from "../core/geo";
|
||||||
|
import { S } from "../core/state";
|
||||||
|
import { _fitCardActions, closeCard, showBikeDetail, updateRingProgress, viewBikeDetailFromOrder, viewBikeDetailFromOrderModal } from "../card/bike-card";
|
||||||
|
import { describeTokenExpiry, escHtml, fmtClock, fmtDuration, fmtLocalTime, fmtOrderTime, fmtRemainShort, fmtTime, friendlyError, remainingTimeText, rideProgressText } from "../core/format";
|
||||||
|
import { shareApi } from "../core/http";
|
||||||
|
import { createAutoLocationIcon, findNearestBike, findNearestBikeManual, initMap, initMapCore, loadMapData, locateMe, mapSnapshotNow, refreshMap, scheduleMapRefresh, showFreshnessDetail, showMyLocation, startAutoLocation, stopAutoLocation, updateAutoLocation, updateMapFreshnessBadge, updateMapStyle, updateTime } from "../map/core";
|
||||||
|
import { createFullIcon, getBikeIcon, getBikeKind, getBikeState, makeIconDataURI, preloadBaseIcons } from "../map/icons";
|
||||||
|
import { bindMarkerDomTouch, bindMarkerTap, bringMarkerToTop, clearHighlight, findMarkerById, rebuildMarkersForZoom, renderMap, setHighlight, setupClusterListener } from "../map/markers";
|
||||||
|
import { _applyHeading, _applyRoute, _bearing, _bindCompass, _centerOnUser, _clearNavArrow, _clearNavLayers, _destIcon, _ensureCompassPermission, _gpsToGcj, _haversineM, _markProgrammaticMove, _navArrowIcon, _navBanner, _navBtnText, _navGuidance, _navPill, _navTick, _onMapDragEnd, _onMapDragStart, _onMapDragging, _placeNavArrow, _projectOnRoute, _recomputeRoute, _redrawRoute, _requestNavRoute, _rotateByAnimation, _rotateNavArrow, _scheduleResume, _setTurnIcon, _turnKind, _turnSvg, bindNavMapEvents, resumeNavigation, startNavigation, stopNavigation, toggleNavigation } from "../nav/navigation";
|
||||||
|
import { parseWalkDistance, parseWalkDuration, refineWalkRoute } from "../nav/walk-route";
|
||||||
|
import { _doFindBikeRequest, _onPageUnload, _onVisibilityChange, addRoundForCurrent, addRoundFromBanner, checkRentalStatus, chooseUnlockSrc, clearRentalState, closeAddRoundModal, closeBellModal, closeLostModal, closeOrderTrajModal, closeOrdersModal, closeRentalSettingsModal, closeReturnConfirm, closeReturnModal, closeUnlockConfirm, closeUnlockSrc, confirmAddRound, confirmReturn, disableLostMode, doReturnBike, doUnlockBike, enableLostMode, findBike, getFilteredBikes, getOrderOperationLocation, handleQuickUnlock, isNativeShell, loadUnlockPreview, loadUnlockSrcShowAll, nativeUnlockBike, openOrderTrajectory, openOrdersModal, openRentalSettingsModal, openUnlockAccountChooser, proceedToUnlockConfirm, quickUnlock, renderOrderTrajectory, renderUnlockPreview, renderUnlockSrcList, saveRentalSettings, scanCode, selectRadius, showAddRoundConfirm, showBellPasswordModal, showLostModal, showRentalBar, showReturnConfirm, showReturnModal, startRental, startRentalFromServer, submitBellPassword, switchBellTab, syncWechatOrder, tempLockCurrentOrder, tempUnlockCurrentOrder, toggleStatusFilter, tryCardPayOrRedirect, unlockBike, updateFilterInfo, updateRangeCircle, updateRentalCountdown, updateRentalFinalTime, updateStatusCounts, useCenterLocation, useCurrentLocation } from "../order/actions";
|
||||||
|
import { _alertOrderExpiring, checkOrderStatus, closeOrderActionsModal, fetchOrderCountdown, findCurrentOrderBike, handleOrderBannerClick, handleOrderBannerSurfaceClick, hideOrderBanner, hideOrderCountdown, isOrderActionEligible, orderCardHtml, payCurrentOrderFromModal, returnCurrentOrderFromModal, showOrderActionsModal, showOrderBanner, showOrderCountdown, startOrderCountdown, updateOrderCountdownText } from "../order/status";
|
||||||
|
import { acceptCurrentShareAsk, acceptShareRequest, checkPendingShareRequests, closeShareConfig, closeShareModal, closeShareRemark, closeShareReturnModal, confirmShareReturn, loadShareData, nextShareAskIfQueue, openShareConfig, openShareModal, openShareRemark, openShareReturnByIdx, partnerLabel, refreshShareBanners, rejectCurrentShareAsk, rejectShareRequest, saveShareConfig, saveShareRemark, sendShareRequest, sharePendingHtml, switchShareTab, unbindShare, updateShareCountdowns } from "../share/share";
|
||||||
|
import { addSubscribeRule, closeSubscribeModal, deleteSubscribeRule, loadSubscribeLocations, loadSubscribeRules, openSubscribeModal, subRuleRowHtml, toggleSubAdvanced, toggleSubscribeRule } from "../subscribe/subscribe";
|
||||||
|
import { appConfirm, appConfirmClose, captureToolUrl, closeDownloadTipModal, closeExportTipModal, closeQrModal, closeTokenExpiredModal, copyDownloadLink, copyExportLink, createQrImage, detectHarmony, detectInAppBrowser, detectMobile, exportHistoryCsv, loadExpiredTokenFields, notifyCredentialInvalid, onDownloadCaptureTool, saveExpiredToken, setupQrLongPress, shareAfterLogin, showDownloadTipModal, showQrModal, showToast, showTokenExpiredModal } from "../ui/modals";
|
||||||
|
import { backToLoginFromForgot, canUseBatchRing, checkAuthStatus, checkStrictGuide, closeAllModals, closeAuthModal, closeDevicesModal, closeForgotModal, closeLoginModal, closePackagesModal, closeProfileModal, closeRegisterModal, closeSettingsPage, closeVersionModal, doLogin, getDeviceId, getDeviceName, handleAuthBtnClick, handleForgotSubmit, handleLoginSubmit, handleLogout, handleRegisterSubmit, hideLoginGate, kickDevice, loadDevicesList, loadPackagesList, loadProfileData, loadUserInfo, logoutAllOtherDevices, maybeAutoShowVersion, maybeStrictGuide, openAuthModal, openDevicesModal, openPackagesModal, openSettingsPage, openVersionModal, parseJwtExpiry, refreshAuthExpiry, renderAuthExpiryBanner, renderTokenExpiry, saveMapClusteringSetting, saveProfileToken, sendForgotCode, sendRegisterCode, setForgotCodeBtn, setRegisterCodeBtn, showForgotFromGate, showForgotModal, showLoginGate, showLoginModal, showProfileModal, showRegisterModal, updateAuthButton, updateBellBtnVisibility, updateTokenExpiryDisplays } from "../ui/settings";
|
||||||
|
|
||||||
|
/* 直接写 window.X = X,便于正则核对与调试(Window 已加索引签名,见 types/api.d.ts) */
|
||||||
|
|
||||||
|
window._alertOrderExpiring = _alertOrderExpiring;
|
||||||
|
window._applyHeading = _applyHeading;
|
||||||
|
window._applyRoute = _applyRoute;
|
||||||
|
window._bearing = _bearing;
|
||||||
|
window._bindCompass = _bindCompass;
|
||||||
|
window._centerOnUser = _centerOnUser;
|
||||||
|
window._clearNavArrow = _clearNavArrow;
|
||||||
|
window._clearNavLayers = _clearNavLayers;
|
||||||
|
window._destIcon = _destIcon;
|
||||||
|
window._doFindBikeRequest = _doFindBikeRequest;
|
||||||
|
window._ensureCompassPermission = _ensureCompassPermission;
|
||||||
|
window._fitCardActions = _fitCardActions;
|
||||||
|
window._gpsToGcj = _gpsToGcj;
|
||||||
|
window._haversineM = _haversineM;
|
||||||
|
window._markProgrammaticMove = _markProgrammaticMove;
|
||||||
|
window._navArrowIcon = _navArrowIcon;
|
||||||
|
window._navBanner = _navBanner;
|
||||||
|
window._navBtnText = _navBtnText;
|
||||||
|
window._navGuidance = _navGuidance;
|
||||||
|
window._navPill = _navPill;
|
||||||
|
window._navTick = _navTick;
|
||||||
|
window._onMapDragEnd = _onMapDragEnd;
|
||||||
|
window._onMapDragStart = _onMapDragStart;
|
||||||
|
window._onMapDragging = _onMapDragging;
|
||||||
|
window._onPageUnload = _onPageUnload;
|
||||||
|
window._onVisibilityChange = _onVisibilityChange;
|
||||||
|
window._placeNavArrow = _placeNavArrow;
|
||||||
|
window._projectOnRoute = _projectOnRoute;
|
||||||
|
window._recomputeRoute = _recomputeRoute;
|
||||||
|
window._redrawRoute = _redrawRoute;
|
||||||
|
window._requestNavRoute = _requestNavRoute;
|
||||||
|
window._rotateByAnimation = _rotateByAnimation;
|
||||||
|
window._rotateNavArrow = _rotateNavArrow;
|
||||||
|
window._scheduleResume = _scheduleResume;
|
||||||
|
window._setTurnIcon = _setTurnIcon;
|
||||||
|
window._turnKind = _turnKind;
|
||||||
|
window._turnSvg = _turnSvg;
|
||||||
|
window.acceptCurrentShareAsk = acceptCurrentShareAsk;
|
||||||
|
window.acceptShareRequest = acceptShareRequest;
|
||||||
|
window.addRoundForCurrent = addRoundForCurrent;
|
||||||
|
window.addRoundFromBanner = addRoundFromBanner;
|
||||||
|
window.addSubscribeRule = addSubscribeRule;
|
||||||
|
window.appConfirm = appConfirm;
|
||||||
|
window.appConfirmClose = appConfirmClose;
|
||||||
|
window.backToLoginFromForgot = backToLoginFromForgot;
|
||||||
|
window.bindMarkerDomTouch = bindMarkerDomTouch;
|
||||||
|
window.bindMarkerTap = bindMarkerTap;
|
||||||
|
window.bindNavMapEvents = bindNavMapEvents;
|
||||||
|
window.bringMarkerToTop = bringMarkerToTop;
|
||||||
|
window.canUseBatchRing = canUseBatchRing;
|
||||||
|
window.captureToolUrl = captureToolUrl;
|
||||||
|
window.checkAuthStatus = checkAuthStatus;
|
||||||
|
window.checkOrderStatus = checkOrderStatus;
|
||||||
|
window.checkPendingShareRequests = checkPendingShareRequests;
|
||||||
|
window.checkRentalStatus = checkRentalStatus;
|
||||||
|
window.checkStrictGuide = checkStrictGuide;
|
||||||
|
window.chooseUnlockSrc = chooseUnlockSrc;
|
||||||
|
window.clearHighlight = clearHighlight;
|
||||||
|
window.clearRentalState = clearRentalState;
|
||||||
|
window.closeAddRoundModal = closeAddRoundModal;
|
||||||
|
window.closeAllModals = closeAllModals;
|
||||||
|
window.closeAuthModal = closeAuthModal;
|
||||||
|
window.closeBellModal = closeBellModal;
|
||||||
|
window.closeCard = closeCard;
|
||||||
|
window.closeDevicesModal = closeDevicesModal;
|
||||||
|
window.closeDownloadTipModal = closeDownloadTipModal;
|
||||||
|
window.closeExportTipModal = closeExportTipModal;
|
||||||
|
window.closeForgotModal = closeForgotModal;
|
||||||
|
window.closeLoginModal = closeLoginModal;
|
||||||
|
window.closeLostModal = closeLostModal;
|
||||||
|
window.closeOrderActionsModal = closeOrderActionsModal;
|
||||||
|
window.closeOrderTrajModal = closeOrderTrajModal;
|
||||||
|
window.closeOrdersModal = closeOrdersModal;
|
||||||
|
window.closePackagesModal = closePackagesModal;
|
||||||
|
window.closeProfileModal = closeProfileModal;
|
||||||
|
window.closeQrModal = closeQrModal;
|
||||||
|
window.closeRegisterModal = closeRegisterModal;
|
||||||
|
window.closeRentalSettingsModal = closeRentalSettingsModal;
|
||||||
|
window.closeReturnConfirm = closeReturnConfirm;
|
||||||
|
window.closeReturnModal = closeReturnModal;
|
||||||
|
window.closeSettingsPage = closeSettingsPage;
|
||||||
|
window.closeShareConfig = closeShareConfig;
|
||||||
|
window.closeShareModal = closeShareModal;
|
||||||
|
window.closeShareRemark = closeShareRemark;
|
||||||
|
window.closeShareReturnModal = closeShareReturnModal;
|
||||||
|
window.closeSubscribeModal = closeSubscribeModal;
|
||||||
|
window.closeTokenExpiredModal = closeTokenExpiredModal;
|
||||||
|
window.closeUnlockConfirm = closeUnlockConfirm;
|
||||||
|
window.closeUnlockSrc = closeUnlockSrc;
|
||||||
|
window.closeVersionModal = closeVersionModal;
|
||||||
|
window.confirmAddRound = confirmAddRound;
|
||||||
|
window.confirmReturn = confirmReturn;
|
||||||
|
window.confirmShareReturn = confirmShareReturn;
|
||||||
|
window.copyDownloadLink = copyDownloadLink;
|
||||||
|
window.copyExportLink = copyExportLink;
|
||||||
|
window.createAutoLocationIcon = createAutoLocationIcon;
|
||||||
|
window.createFullIcon = createFullIcon;
|
||||||
|
window.createQrImage = createQrImage;
|
||||||
|
window.deleteSubscribeRule = deleteSubscribeRule;
|
||||||
|
window.describeTokenExpiry = describeTokenExpiry;
|
||||||
|
window.detectHarmony = detectHarmony;
|
||||||
|
window.detectInAppBrowser = detectInAppBrowser;
|
||||||
|
window.detectMobile = detectMobile;
|
||||||
|
window.disableLostMode = disableLostMode;
|
||||||
|
window.doLogin = doLogin;
|
||||||
|
window.doReturnBike = doReturnBike;
|
||||||
|
window.doUnlockBike = doUnlockBike;
|
||||||
|
window.enableLostMode = enableLostMode;
|
||||||
|
window.escHtml = escHtml;
|
||||||
|
window.exportHistoryCsv = exportHistoryCsv;
|
||||||
|
window.fetchOrderCountdown = fetchOrderCountdown;
|
||||||
|
window.findBike = findBike;
|
||||||
|
window.findCurrentOrderBike = findCurrentOrderBike;
|
||||||
|
window.findMarkerById = findMarkerById;
|
||||||
|
window.findNearestBike = findNearestBike;
|
||||||
|
window.findNearestBikeManual = findNearestBikeManual;
|
||||||
|
window.fmtClock = fmtClock;
|
||||||
|
window.fmtDuration = fmtDuration;
|
||||||
|
window.fmtLocalTime = fmtLocalTime;
|
||||||
|
window.fmtOrderTime = fmtOrderTime;
|
||||||
|
window.fmtRemainShort = fmtRemainShort;
|
||||||
|
window.fmtTime = fmtTime;
|
||||||
|
window.friendlyError = friendlyError;
|
||||||
|
window.getBikeIcon = getBikeIcon;
|
||||||
|
window.getBikeKind = getBikeKind;
|
||||||
|
window.getBikeState = getBikeState;
|
||||||
|
window.getDeviceId = getDeviceId;
|
||||||
|
window.getDeviceName = getDeviceName;
|
||||||
|
window.getFilteredBikes = getFilteredBikes;
|
||||||
|
window.getOrderOperationLocation = getOrderOperationLocation;
|
||||||
|
window.handleAuthBtnClick = handleAuthBtnClick;
|
||||||
|
window.handleForgotSubmit = handleForgotSubmit;
|
||||||
|
window.handleLoginSubmit = handleLoginSubmit;
|
||||||
|
window.handleLogout = handleLogout;
|
||||||
|
window.handleOrderBannerClick = handleOrderBannerClick;
|
||||||
|
window.handleOrderBannerSurfaceClick = handleOrderBannerSurfaceClick;
|
||||||
|
window.handleQuickUnlock = handleQuickUnlock;
|
||||||
|
window.handleRegisterSubmit = handleRegisterSubmit;
|
||||||
|
window.hideLoginGate = hideLoginGate;
|
||||||
|
window.hideOrderBanner = hideOrderBanner;
|
||||||
|
window.hideOrderCountdown = hideOrderCountdown;
|
||||||
|
window.initMap = initMap;
|
||||||
|
window.initMapCore = initMapCore;
|
||||||
|
window.isNativeShell = isNativeShell;
|
||||||
|
window.isOrderActionEligible = isOrderActionEligible;
|
||||||
|
window.kickDevice = kickDevice;
|
||||||
|
window.loadDevicesList = loadDevicesList;
|
||||||
|
window.loadExpiredTokenFields = loadExpiredTokenFields;
|
||||||
|
window.loadMapData = loadMapData;
|
||||||
|
window.loadPackagesList = loadPackagesList;
|
||||||
|
window.loadProfileData = loadProfileData;
|
||||||
|
window.loadShareData = loadShareData;
|
||||||
|
window.loadSubscribeLocations = loadSubscribeLocations;
|
||||||
|
window.loadSubscribeRules = loadSubscribeRules;
|
||||||
|
window.loadUnlockPreview = loadUnlockPreview;
|
||||||
|
window.loadUnlockSrcShowAll = loadUnlockSrcShowAll;
|
||||||
|
window.loadUserInfo = loadUserInfo;
|
||||||
|
window.locateMe = locateMe;
|
||||||
|
window.logoutAllOtherDevices = logoutAllOtherDevices;
|
||||||
|
window.makeIconDataURI = makeIconDataURI;
|
||||||
|
window.mapSnapshotNow = mapSnapshotNow;
|
||||||
|
window.maybeAutoShowVersion = maybeAutoShowVersion;
|
||||||
|
window.maybeStrictGuide = maybeStrictGuide;
|
||||||
|
window.nativeUnlockBike = nativeUnlockBike;
|
||||||
|
window.nextShareAskIfQueue = nextShareAskIfQueue;
|
||||||
|
window.notifyCredentialInvalid = notifyCredentialInvalid;
|
||||||
|
window.onDownloadCaptureTool = onDownloadCaptureTool;
|
||||||
|
window.openAuthModal = openAuthModal;
|
||||||
|
window.openDevicesModal = openDevicesModal;
|
||||||
|
window.openOrderTrajectory = openOrderTrajectory;
|
||||||
|
window.openOrdersModal = openOrdersModal;
|
||||||
|
window.openPackagesModal = openPackagesModal;
|
||||||
|
window.openRentalSettingsModal = openRentalSettingsModal;
|
||||||
|
window.openSettingsPage = openSettingsPage;
|
||||||
|
window.openShareConfig = openShareConfig;
|
||||||
|
window.openShareModal = openShareModal;
|
||||||
|
window.openShareRemark = openShareRemark;
|
||||||
|
window.openShareReturnByIdx = openShareReturnByIdx;
|
||||||
|
window.openSubscribeModal = openSubscribeModal;
|
||||||
|
window.openUnlockAccountChooser = openUnlockAccountChooser;
|
||||||
|
window.openVersionModal = openVersionModal;
|
||||||
|
window.orderCardHtml = orderCardHtml;
|
||||||
|
window.parseJwtExpiry = parseJwtExpiry;
|
||||||
|
window.parseWalkDistance = parseWalkDistance;
|
||||||
|
window.parseWalkDuration = parseWalkDuration;
|
||||||
|
window.partnerLabel = partnerLabel;
|
||||||
|
window.payCurrentOrderFromModal = payCurrentOrderFromModal;
|
||||||
|
window.preloadBaseIcons = preloadBaseIcons;
|
||||||
|
window.proceedToUnlockConfirm = proceedToUnlockConfirm;
|
||||||
|
window.quickUnlock = quickUnlock;
|
||||||
|
window.rebuildMarkersForZoom = rebuildMarkersForZoom;
|
||||||
|
window.refineWalkRoute = refineWalkRoute;
|
||||||
|
window.refreshAuthExpiry = refreshAuthExpiry;
|
||||||
|
window.refreshMap = refreshMap;
|
||||||
|
window.refreshShareBanners = refreshShareBanners;
|
||||||
|
window.rejectCurrentShareAsk = rejectCurrentShareAsk;
|
||||||
|
window.rejectShareRequest = rejectShareRequest;
|
||||||
|
window.remainingTimeText = remainingTimeText;
|
||||||
|
window.renderAuthExpiryBanner = renderAuthExpiryBanner;
|
||||||
|
window.renderMap = renderMap;
|
||||||
|
window.renderOrderTrajectory = renderOrderTrajectory;
|
||||||
|
window.renderTokenExpiry = renderTokenExpiry;
|
||||||
|
window.renderUnlockPreview = renderUnlockPreview;
|
||||||
|
window.renderUnlockSrcList = renderUnlockSrcList;
|
||||||
|
window.resumeNavigation = resumeNavigation;
|
||||||
|
window.returnCurrentOrderFromModal = returnCurrentOrderFromModal;
|
||||||
|
window.rideProgressText = rideProgressText;
|
||||||
|
window.saveExpiredToken = saveExpiredToken;
|
||||||
|
window.saveMapClusteringSetting = saveMapClusteringSetting;
|
||||||
|
window.saveProfileToken = saveProfileToken;
|
||||||
|
window.saveRentalSettings = saveRentalSettings;
|
||||||
|
window.saveShareConfig = saveShareConfig;
|
||||||
|
window.saveShareRemark = saveShareRemark;
|
||||||
|
window.scanCode = scanCode;
|
||||||
|
window.scheduleMapRefresh = scheduleMapRefresh;
|
||||||
|
window.selectRadius = selectRadius;
|
||||||
|
window.sendForgotCode = sendForgotCode;
|
||||||
|
window.sendRegisterCode = sendRegisterCode;
|
||||||
|
window.sendShareRequest = sendShareRequest;
|
||||||
|
window.setForgotCodeBtn = setForgotCodeBtn;
|
||||||
|
window.setHighlight = setHighlight;
|
||||||
|
window.setRegisterCodeBtn = setRegisterCodeBtn;
|
||||||
|
window.setupClusterListener = setupClusterListener;
|
||||||
|
window.setupQrLongPress = setupQrLongPress;
|
||||||
|
window.shareAfterLogin = shareAfterLogin;
|
||||||
|
window.shareApi = shareApi;
|
||||||
|
window.sharePendingHtml = sharePendingHtml;
|
||||||
|
window.showAddRoundConfirm = showAddRoundConfirm;
|
||||||
|
window.showBellPasswordModal = showBellPasswordModal;
|
||||||
|
window.showBikeDetail = showBikeDetail;
|
||||||
|
window.showDownloadTipModal = showDownloadTipModal;
|
||||||
|
window.showForgotFromGate = showForgotFromGate;
|
||||||
|
window.showForgotModal = showForgotModal;
|
||||||
|
window.showFreshnessDetail = showFreshnessDetail;
|
||||||
|
window.showLoginGate = showLoginGate;
|
||||||
|
window.showLoginModal = showLoginModal;
|
||||||
|
window.showLostModal = showLostModal;
|
||||||
|
window.showMyLocation = showMyLocation;
|
||||||
|
window.showOrderActionsModal = showOrderActionsModal;
|
||||||
|
window.showOrderBanner = showOrderBanner;
|
||||||
|
window.showOrderCountdown = showOrderCountdown;
|
||||||
|
window.showProfileModal = showProfileModal;
|
||||||
|
window.showQrModal = showQrModal;
|
||||||
|
window.showRegisterModal = showRegisterModal;
|
||||||
|
window.showRentalBar = showRentalBar;
|
||||||
|
window.showReturnConfirm = showReturnConfirm;
|
||||||
|
window.showReturnModal = showReturnModal;
|
||||||
|
window.showToast = showToast;
|
||||||
|
window.showTokenExpiredModal = showTokenExpiredModal;
|
||||||
|
window.startAutoLocation = startAutoLocation;
|
||||||
|
window.startNavigation = startNavigation;
|
||||||
|
window.startOrderCountdown = startOrderCountdown;
|
||||||
|
window.startRental = startRental;
|
||||||
|
window.startRentalFromServer = startRentalFromServer;
|
||||||
|
window.stopAutoLocation = stopAutoLocation;
|
||||||
|
window.stopNavigation = stopNavigation;
|
||||||
|
window.subRuleRowHtml = subRuleRowHtml;
|
||||||
|
window.submitBellPassword = submitBellPassword;
|
||||||
|
window.switchBellTab = switchBellTab;
|
||||||
|
window.switchShareTab = switchShareTab;
|
||||||
|
window.syncWechatOrder = syncWechatOrder;
|
||||||
|
window.tempLockCurrentOrder = tempLockCurrentOrder;
|
||||||
|
window.tempUnlockCurrentOrder = tempUnlockCurrentOrder;
|
||||||
|
window.toggleNavigation = toggleNavigation;
|
||||||
|
window.toggleStatusFilter = toggleStatusFilter;
|
||||||
|
window.toggleSubAdvanced = toggleSubAdvanced;
|
||||||
|
window.toggleSubscribeRule = toggleSubscribeRule;
|
||||||
|
window.tryCardPayOrRedirect = tryCardPayOrRedirect;
|
||||||
|
window.unbindShare = unbindShare;
|
||||||
|
window.unlockBike = unlockBike;
|
||||||
|
window.updateAuthButton = updateAuthButton;
|
||||||
|
window.updateAutoLocation = updateAutoLocation;
|
||||||
|
window.updateBellBtnVisibility = updateBellBtnVisibility;
|
||||||
|
window.updateFilterInfo = updateFilterInfo;
|
||||||
|
window.updateMapFreshnessBadge = updateMapFreshnessBadge;
|
||||||
|
window.updateMapStyle = updateMapStyle;
|
||||||
|
window.updateOrderCountdownText = updateOrderCountdownText;
|
||||||
|
window.updateRangeCircle = updateRangeCircle;
|
||||||
|
window.updateRentalCountdown = updateRentalCountdown;
|
||||||
|
window.updateRentalFinalTime = updateRentalFinalTime;
|
||||||
|
window.updateRingProgress = updateRingProgress;
|
||||||
|
window.updateShareCountdowns = updateShareCountdowns;
|
||||||
|
window.updateStatusCounts = updateStatusCounts;
|
||||||
|
window.updateTime = updateTime;
|
||||||
|
window.updateTokenExpiryDisplays = updateTokenExpiryDisplays;
|
||||||
|
window.useCenterLocation = useCenterLocation;
|
||||||
|
window.useCurrentLocation = useCurrentLocation;
|
||||||
|
window.viewBikeDetailFromOrder = viewBikeDetailFromOrder;
|
||||||
|
window.viewBikeDetailFromOrderModal = viewBikeDetailFromOrderModal;
|
||||||
|
|
||||||
|
/* 原 static/js/src/core/geo.js 也把这三个挂在 window 上,这里挂同一份实现。 */
|
||||||
|
window.Geo = Geo;
|
||||||
|
window.offsetCoord = offsetCoord;
|
||||||
|
window.calcDistance = calcDistance;
|
||||||
|
|
||||||
|
/* 排障用:原版 91 个顶层 let/var 都是全局词法绑定,控制台可直接读写;
|
||||||
|
bundle 里它们收在 state 对象内(ESM 不能给 import 绑定赋值),
|
||||||
|
这里把 state 本身挂出去,保持同样的可观测性。 */
|
||||||
|
(window as any).S = S;
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
/* 由 static/js/{navigation,share,subscribe,map}.js 逐块搬运而来;正文与原实现一致。 */
|
||||||
|
// static/js/map.js:674-678
|
||||||
|
export function fmtLocalTime(ts) {
|
||||||
|
const d = new Date(ts * 1000);
|
||||||
|
const p = n => String(n).padStart(2, "0");
|
||||||
|
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:679-685
|
||||||
|
export function describeTokenExpiry(expiry) {
|
||||||
|
const remain = expiry.expireAt - Math.floor(Date.now() / 1000);
|
||||||
|
const when = fmtLocalTime(expiry.expireAt);
|
||||||
|
const left = remain <= 0 ? "已过期" : `约剩 ${fmtRemainShort(remain)}`;
|
||||||
|
const note = expiry.source === "iat+30d" ? "(按签发时间 +30 天推算)" : "";
|
||||||
|
return { text: `该凭据(登录态)有效期至 ${when}${note},${left}`, remain };
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:686-692
|
||||||
|
export function fmtRemainShort(remain) {
|
||||||
|
const dd = Math.floor(remain / 86400), hh = Math.floor((remain % 86400) / 3600),
|
||||||
|
mm = Math.floor((remain % 3600) / 60);
|
||||||
|
if (dd >= 1) return `${dd} 天${hh ? " " + hh + " 小时" : ""}`;
|
||||||
|
if (hh >= 1) return `${hh} 小时${mm ? " " + mm + " 分" : ""}`;
|
||||||
|
return `${Math.max(1, mm)} 分钟`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:865-868
|
||||||
|
export function escHtml(s) {
|
||||||
|
return String(s == null ? "" : s).replace(/[&<>"']/g,
|
||||||
|
c => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]));
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:869-872
|
||||||
|
export function fmtTime(t) {
|
||||||
|
if (!t) return "";
|
||||||
|
return escHtml(String(t).replace("T", " ").slice(0, 16));
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:1748-1754
|
||||||
|
export 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]} 结束` : "");
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:1756-1759
|
||||||
|
export function remainingTimeText(seconds) {
|
||||||
|
const remaining = Math.max(0, Math.ceil(Number(seconds) || 0));
|
||||||
|
return `${Math.floor(remaining / 60)}:${String(remaining % 60).padStart(2, "0")}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:2668-2673
|
||||||
|
export 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} 分钟`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:2674-2677
|
||||||
|
export function fmtOrderTime(s) {
|
||||||
|
if (!s) return "--";
|
||||||
|
return String(s).replace("T", " ").slice(5, 16); // MM-DD HH:MM
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:2678-2681
|
||||||
|
export function fmtClock(s) {
|
||||||
|
if (!s) return "--";
|
||||||
|
return String(s).slice(11, 16); // HH:MM
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:4532-4541
|
||||||
|
export function friendlyError(e) {
|
||||||
|
const msg = (e && e.message) || "";
|
||||||
|
if (/Unexpected token|is not valid JSON|JSON\.parse/i.test(msg)) {
|
||||||
|
return "服务响应异常,请稍后重试";
|
||||||
|
}
|
||||||
|
return msg || "网络错误,请重试";
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== Token失效弹窗 ==========
|
||||||
|
// 仅在真正检测到微信凭据失效时调用;带冷却时间,避免轮询/刷新反复打扰
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
/* 坐标转换 + 距离计算。
|
||||||
|
*
|
||||||
|
* 来源:static/js/src/core/geo.js(经典脚本 IIFE,把 offsetCoord / calcDistance / Geo
|
||||||
|
* 挂到 window),以及 coordtransform.js 的用法。这里把**同一份逻辑**搬成 ES 模块,
|
||||||
|
* 逐字对应,不做"重新设计":
|
||||||
|
* - offsetCoord:GCJ02 → BD09,优先 coordtransform.gcj02tobd09,失败退回常量偏移;
|
||||||
|
* - calcDistance:Haversine,单位米。
|
||||||
|
*
|
||||||
|
* coordtransform.js 仍然作为外部脚本加载(不进 bundle),这里只是类型化的访问入口。
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** coordtransform 不可用时的降级偏移(约 610 米纬度 / 600 米经度)。 */
|
||||||
|
export const COORD_OFFSET = {
|
||||||
|
lat: 0.00603, // 约 610 米(纬度)
|
||||||
|
lng: 0.00650, // 约 600 米 - 20 米(经度,往西 20 米)
|
||||||
|
};
|
||||||
|
|
||||||
|
/** GCJ02 → BD09 的坐标对。 */
|
||||||
|
export interface LatLng {
|
||||||
|
lat: number;
|
||||||
|
lng: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GCJ02 -> BD09。
|
||||||
|
* 优先用 coordtransform(与百度官方算法一致),失败则退回常量偏移,
|
||||||
|
* 避免整张图的点位整体偏移几百米。
|
||||||
|
*/
|
||||||
|
export function offsetCoord(lat: any, lng: any): LatLng {
|
||||||
|
lat = parseFloat(lat);
|
||||||
|
lng = parseFloat(lng);
|
||||||
|
if (typeof coordtransform !== "undefined" && coordtransform.gcj02tobd09) {
|
||||||
|
try {
|
||||||
|
const bd = coordtransform.gcj02tobd09(lng, lat); // [lng, lat]
|
||||||
|
return { lat: bd[1], lng: bd[0] };
|
||||||
|
} catch (e) {
|
||||||
|
console.warn("[坐标转换] gcj02tobd09 失败,回退手动偏移:", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
lat: lat + COORD_OFFSET.lat,
|
||||||
|
lng: lng + COORD_OFFSET.lng,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 两点球面距离(米),Haversine。 */
|
||||||
|
export function calcDistance(lat1: number, lng1: number, lat2: number, lng2: number): number {
|
||||||
|
const R = 6371000; // 地球半径(米)
|
||||||
|
const dLat = (lat2 - lat1) * Math.PI / 180;
|
||||||
|
const dLng = (lng2 - lng1) * Math.PI / 180;
|
||||||
|
const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
|
||||||
|
Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
|
||||||
|
Math.sin(dLng / 2) * Math.sin(dLng / 2);
|
||||||
|
return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 与 geo.js 里的全局同名对象(某些调试/外部页面会读 window.Geo)。 */
|
||||||
|
export const Geo = { COORD_OFFSET, offsetCoord, calcDistance };
|
||||||
|
|
||||||
|
/* ---- coordtransform 的类型化薄封装:外部库在页面上就是真身,这里不重复实现 ---- */
|
||||||
|
|
||||||
|
/** 外部坐标库是否可用。 */
|
||||||
|
export function coordTransformAvailable(): boolean {
|
||||||
|
return typeof coordtransform !== "undefined" && !!coordtransform.gcj02tobd09;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** GCJ02 → BD09([lng, lat]),库未加载时返回 null。 */
|
||||||
|
export function gcj02tobd09(lng: number, lat: number): [number, number] | null {
|
||||||
|
if (!coordTransformAvailable()) return null;
|
||||||
|
return coordtransform!.gcj02tobd09(lng, lat);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** BD09 → GCJ02([lng, lat]),库未加载时返回 null。 */
|
||||||
|
export function bd09togcj02(lng: number, lat: number): [number, number] | null {
|
||||||
|
if (!coordTransformAvailable()) return null;
|
||||||
|
return coordtransform!.bd09togcj02(lng, lat);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** WGS84 → GCJ02([lng, lat]),库未加载时返回 null。 */
|
||||||
|
export function wgs84togcj02(lng: number, lat: number): [number, number] | null {
|
||||||
|
if (!coordTransformAvailable()) return null;
|
||||||
|
return coordtransform!.wgs84togcj02(lng, lat);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** WGS84 → BD09([lng, lat]),库未加载时返回 null。 */
|
||||||
|
export function wgs84tobd09(lng: number, lat: number): [number, number] | null {
|
||||||
|
if (!coordTransformAvailable()) return null;
|
||||||
|
return coordtransform!.wgs84tobd09(lng, lat);
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
/* 由 static/js/{navigation,share,subscribe,map}.js 逐块搬运而来;正文与原实现一致。 */
|
||||||
|
|
||||||
|
import { S } from "./state";
|
||||||
|
// static/js/share.js:6-17
|
||||||
|
export function shareApi(url: string, method?: string, body?: any) {
|
||||||
|
const opts: any = { method: method || "GET", headers: {} };
|
||||||
|
if (S.authToken) opts.headers["Authorization"] = `Bearer ${S.authToken}`;
|
||||||
|
if (body !== undefined) {
|
||||||
|
opts.headers["Content-Type"] = "application/json";
|
||||||
|
opts.body = JSON.stringify(body);
|
||||||
|
}
|
||||||
|
return fetch(url, opts).then(r => r.json());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 私密备注(昵称) 工具 =====
|
||||||
|
// 显示对方时:优先用“我给他起的备注(昵称)”,其次显示名,最后退回邮箱
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
/* 全局可变状态集中处。
|
||||||
|
*
|
||||||
|
* 原实现里 map.js 顶部那一堆 `let xxx = ...` 是**经典脚本的全局词法绑定**,
|
||||||
|
* 被 navigation/share/subscribe/map 四个脚本一起读写。改成 ES 模块后,import 进来的
|
||||||
|
* 绑定不可赋值,所以这里统一收进 S 对象;正文里的裸标识符写成 S.xxx(由 tools/gen.mjs 改写)。
|
||||||
|
* 语义不变:同一个对象、同一份可变状态、初始化顺序仍在模块求值阶段。
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** 状态容器类型:字段按需增删,读取处一律 any。 */
|
||||||
|
export type AppState = Record<string, any>;
|
||||||
|
|
||||||
|
export const S: AppState = {
|
||||||
|
// static/js/share.js:208
|
||||||
|
shareAskQueue: [],
|
||||||
|
// static/js/share.js:209
|
||||||
|
shareAskActive: false,
|
||||||
|
// static/js/map.js:2
|
||||||
|
map: null,
|
||||||
|
// static/js/map.js:3
|
||||||
|
currentType: "3",
|
||||||
|
// static/js/map.js:4
|
||||||
|
currentUser: null,
|
||||||
|
// static/js/map.js:5
|
||||||
|
authKickToastShown: false,
|
||||||
|
// static/js/map.js:6
|
||||||
|
authMode: "login",
|
||||||
|
// static/js/map.js:7
|
||||||
|
authToken: localStorage.getItem("auth_token") || null,
|
||||||
|
// static/js/map.js:8
|
||||||
|
currentMarkers: [],
|
||||||
|
// static/js/map.js:9
|
||||||
|
currentPolygons: [],
|
||||||
|
// static/js/map.js:10
|
||||||
|
selectedBike: null,
|
||||||
|
// static/js/map.js:11
|
||||||
|
markersData: {},
|
||||||
|
// static/js/map.js:12
|
||||||
|
currentMarkersById: {},
|
||||||
|
// static/js/map.js:13
|
||||||
|
scannedMarkers: {},
|
||||||
|
// static/js/map.js:14
|
||||||
|
myLocationMarker: null,
|
||||||
|
// static/js/map.js:15
|
||||||
|
autoLocationMarker: null,
|
||||||
|
// static/js/map.js:16
|
||||||
|
autoLocationWatchId: null,
|
||||||
|
// static/js/map.js:17
|
||||||
|
hasLocationPermission: false,
|
||||||
|
// static/js/map.js:18
|
||||||
|
initialLocationCentered: false,
|
||||||
|
// static/js/map.js:19
|
||||||
|
nearestBikeId: null,
|
||||||
|
// static/js/map.js:20
|
||||||
|
isFirstLoad: true,
|
||||||
|
// static/js/map.js:21
|
||||||
|
highlightedBikeId: null,
|
||||||
|
// static/js/map.js:23
|
||||||
|
bikeClusteringEnabled: typeof BikeClusters !== "undefined"
|
||||||
|
? BikeClusters.readClusteringPreference(localStorage) : true,
|
||||||
|
// static/js/map.js:122
|
||||||
|
activeRental: null,
|
||||||
|
// static/js/map.js:123
|
||||||
|
rentalCountdownTimer: null,
|
||||||
|
// static/js/map.js:1658
|
||||||
|
currentOrder: null,
|
||||||
|
// static/js/map.js:3276
|
||||||
|
_fitCardTimer: null,
|
||||||
|
// static/js/map.js:3582
|
||||||
|
_findClickCount: 0,
|
||||||
|
// static/js/map.js:3584
|
||||||
|
_findLongPressTimer: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
// static/js/map.js:124
|
||||||
|
export const RENTAL_KEY = "xbniu_rental_key";
|
||||||
|
|
||||||
+253
@@ -0,0 +1,253 @@
|
|||||||
|
/* 入口:装配顺序 + 原先分散在各脚本顶层的「注册/定时器/首屏初始化」语句。
|
||||||
|
*
|
||||||
|
* 这些语句在原实现里按 [navigation → share → subscribe → map] 的脚本顺序,
|
||||||
|
* 在各文件中「按行号」执行;这里 1:1 按同一顺序搬进 bootstrap(),末尾立即调用。
|
||||||
|
*/
|
||||||
|
import "./compat/globals";
|
||||||
|
import { S } from "./core/state";
|
||||||
|
import { _fitCardActions, closeCard } from "./card/bike-card";
|
||||||
|
import { initMap, loadMapData, updateMapFreshnessBadge, updateMapStyle } from "./map/core";
|
||||||
|
import { bikeBubbleLayer } from "./map/markers";
|
||||||
|
import { bindNavMapEvents } from "./nav/navigation";
|
||||||
|
import { LOST_TRIGGER_LONG, _findClickTimer, _lostModeActive, checkRentalStatus, closeAddRoundModal, scanCode, showLostModal, syncWechatOrder } from "./order/actions";
|
||||||
|
import { checkOrderStatus, closeOrderActionsModal, fetchOrderCountdown } from "./order/status";
|
||||||
|
import { checkPendingShareRequests, refreshShareBanners, updateShareCountdowns } from "./share/share";
|
||||||
|
import { appConfirmClose, closeQrModal, setupQrLongPress, shareAfterLogin } from "./ui/modals";
|
||||||
|
import { VERSION_TAG, checkAuthStatus, checkStrictGuide, doLogin, refreshAuthExpiry, showLoginGate, updateTokenExpiryDisplays } from "./ui/settings";
|
||||||
|
|
||||||
|
/** 原脚本顶层副作用:注册监听 / 起定时器 / 首屏 auth 与弹窗判定。 */
|
||||||
|
export function bootstrap(): void {
|
||||||
|
// static/js/navigation.js:778-780
|
||||||
|
window.bindNavMapEvents = bindNavMapEvents;
|
||||||
|
|
||||||
|
// 兜底:万一 map.js 忘了调,这里再轮询几次(最多约 10 秒)
|
||||||
|
// static/js/navigation.js:781-788
|
||||||
|
(function _retryBindNavMapEvents(tries = 0) {
|
||||||
|
if (bindNavMapEvents()) return;
|
||||||
|
if (tries >= 20) {
|
||||||
|
console.warn("[导航] 地图拖动事件未能绑定(map 一直未就绪)");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setTimeout(() => _retryBindNavMapEvents(tries + 1), 500);
|
||||||
|
})();
|
||||||
|
// static/js/share.js:305-306
|
||||||
|
setInterval(updateShareCountdowns, 1000);
|
||||||
|
// HTML 的 ✕ / 取消 / 遮罩都调用它(此前漏了定义 → 点击直接 ReferenceError,弹窗关不掉)
|
||||||
|
// static/js/map.js:549-555
|
||||||
|
window.addEventListener("storage", event => {
|
||||||
|
if (typeof BikeClusters === "undefined") return;
|
||||||
|
if (event.key !== BikeClusters.PREFERENCE_KEY && event.key !== null) return;
|
||||||
|
S.bikeClusteringEnabled = BikeClusters.readClusteringPreference(localStorage);
|
||||||
|
if (bikeBubbleLayer) bikeBubbleLayer.setClusteringEnabled(S.bikeClusteringEnabled);
|
||||||
|
document.getElementById("settings-clustering").checked = S.bikeClusteringEnabled;
|
||||||
|
});
|
||||||
|
// static/js/map.js:777-779
|
||||||
|
setInterval(updateTokenExpiryDisplays, 30000); // 实时倒计时:每 30 秒刷新
|
||||||
|
|
||||||
|
// 打开凭证填写弹窗
|
||||||
|
// static/js/map.js:1450-1458
|
||||||
|
document.getElementById("gate-login-form").addEventListener("submit", function (e) {
|
||||||
|
e.preventDefault();
|
||||||
|
doLogin(
|
||||||
|
document.getElementById("gate-email").value.trim().toLowerCase(),
|
||||||
|
document.getElementById("gate-password").value,
|
||||||
|
document.getElementById("gate-tip"),
|
||||||
|
this.querySelector("button[type='submit']")
|
||||||
|
);
|
||||||
|
});
|
||||||
|
// static/js/map.js:2013-2024
|
||||||
|
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; }
|
||||||
|
});
|
||||||
|
|
||||||
|
// ========== 月卡/周卡自动支付 ==========
|
||||||
|
// static/js/map.js:2955-2963
|
||||||
|
document.addEventListener("DOMContentLoaded", async () => {
|
||||||
|
if (S.authToken) {
|
||||||
|
await syncWechatOrder(); // 先同步微信订单状态
|
||||||
|
checkOrderStatus();
|
||||||
|
checkRentalStatus(); // 再恢复租车横幅
|
||||||
|
checkStrictGuide(); // 强签名验证:缺 AccessToken 进页面立即引导
|
||||||
|
refreshAuthExpiry(); // 登录态有效期:不足 2 天在主页面挂提醒横幅
|
||||||
|
}
|
||||||
|
});
|
||||||
|
// static/js/map.js:3022-3026
|
||||||
|
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
|
||||||
|
updateMapStyle();
|
||||||
|
});
|
||||||
|
|
||||||
|
// ========== 加载地图数据 ==========
|
||||||
|
// static/js/map.js:3277-3283
|
||||||
|
window.addEventListener("resize", () => {
|
||||||
|
clearTimeout(S._fitCardTimer);
|
||||||
|
S._fitCardTimer = setTimeout(() => {
|
||||||
|
if (document.getElementById("bike-card"))
|
||||||
|
_fitCardActions();
|
||||||
|
}, 120);
|
||||||
|
});
|
||||||
|
// static/js/map.js:3446-3481
|
||||||
|
(function initSwipeClose() {
|
||||||
|
const card = document.getElementById("bike-card");
|
||||||
|
let startY = 0, startTime = 0, dragging = false;
|
||||||
|
|
||||||
|
card.addEventListener("touchstart", (e) => {
|
||||||
|
// 只响应从 card-handle 或卡片顶部区域发起的手势
|
||||||
|
startY = e.touches[0].clientY;
|
||||||
|
startTime = Date.now();
|
||||||
|
dragging = true;
|
||||||
|
card.style.transition = "none";
|
||||||
|
}, { passive: true });
|
||||||
|
|
||||||
|
card.addEventListener("touchmove", (e) => {
|
||||||
|
if (!dragging) return;
|
||||||
|
const dy = e.touches[0].clientY - startY;
|
||||||
|
if (dy > 0) {
|
||||||
|
card.style.transform = `translateY(${dy}px)`;
|
||||||
|
}
|
||||||
|
}, { passive: true });
|
||||||
|
|
||||||
|
card.addEventListener("touchend", (e) => {
|
||||||
|
if (!dragging) return;
|
||||||
|
dragging = false;
|
||||||
|
card.style.transition = "";
|
||||||
|
const dy = e.changedTouches[0].clientY - startY;
|
||||||
|
const dt = Date.now() - startTime;
|
||||||
|
// 快速下划(速度 > 0.5px/ms)或位移超过120px则关闭
|
||||||
|
if (dy > 120 || (dy > 40 && dt < 250)) {
|
||||||
|
closeCard();
|
||||||
|
} else {
|
||||||
|
card.style.transform = "";
|
||||||
|
}
|
||||||
|
}, { passive: true });
|
||||||
|
})();
|
||||||
|
|
||||||
|
// ========== 扫码查询 ==========
|
||||||
|
// static/js/map.js:3727-3755
|
||||||
|
(function initFindBtnLongPress() {
|
||||||
|
const btn = document.getElementById("bike-find-btn-header");
|
||||||
|
if (!btn) return;
|
||||||
|
|
||||||
|
function startLongPress(e) {
|
||||||
|
// 丢失模式下不需要长按(单击退出即可)
|
||||||
|
if (_lostModeActive) return;
|
||||||
|
clearTimeout(S._findLongPressTimer);
|
||||||
|
S._findLongPressTimer = setTimeout(() => {
|
||||||
|
// 长按成功,阻止后续 click 事件触发普通寻车
|
||||||
|
S._findClickCount = 0;
|
||||||
|
clearTimeout(_findClickTimer);
|
||||||
|
showLostModal();
|
||||||
|
}, LOST_TRIGGER_LONG);
|
||||||
|
}
|
||||||
|
|
||||||
|
function cancelLongPress() {
|
||||||
|
clearTimeout(S._findLongPressTimer);
|
||||||
|
}
|
||||||
|
|
||||||
|
btn.addEventListener("mousedown", startLongPress);
|
||||||
|
btn.addEventListener("touchstart", startLongPress, { passive: true });
|
||||||
|
btn.addEventListener("mouseup", cancelLongPress);
|
||||||
|
btn.addEventListener("mouseleave", cancelLongPress);
|
||||||
|
btn.addEventListener("touchend", cancelLongPress);
|
||||||
|
btn.addEventListener("touchcancel", cancelLongPress);
|
||||||
|
})();
|
||||||
|
|
||||||
|
// ========== 用车计时相关 ==========
|
||||||
|
// static/js/map.js:4248-4250
|
||||||
|
setupQrLongPress();
|
||||||
|
|
||||||
|
// 点击遮罩关闭
|
||||||
|
// static/js/map.js:4251-4258
|
||||||
|
document.getElementById("qr-modal").addEventListener("click", function(e) {
|
||||||
|
if (e.target === this) closeQrModal();
|
||||||
|
});
|
||||||
|
|
||||||
|
// ========== 通用确认弹窗(替换 window.confirm) ==========
|
||||||
|
// 为什么不用 confirm:原生壳是 Android WebView,WebView 默认不弹 JS 原生对话框
|
||||||
|
// (Chromium 需要宿主实现 onJsConfirm,未实现时 confirm 直接返回 false,用户点不到"确认")。
|
||||||
|
// 这里用页面内弹窗,行为一致但任何环境都能用。
|
||||||
|
// static/js/map.js:4852-4858
|
||||||
|
checkAuthStatus().then(() => {
|
||||||
|
if (S.authToken && typeof SettingsPages !== "undefined") SettingsPages.restore();
|
||||||
|
checkRentalStatus();
|
||||||
|
if (S.authToken) shareAfterLogin();
|
||||||
|
});
|
||||||
|
|
||||||
|
// 未登录:全屏登录门覆盖地图(后端 /api/map 同样有登录门禁)
|
||||||
|
// static/js/map.js:4859-4859
|
||||||
|
if (!S.authToken) showLoginGate();
|
||||||
|
// static/js/map.js:4861-4861
|
||||||
|
document.addEventListener("DOMContentLoaded", initMap);
|
||||||
|
// static/js/map.js:4862-4862
|
||||||
|
window.addEventListener("xbniu-map-ready", initMap);
|
||||||
|
// static/js/map.js:4863-4866
|
||||||
|
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.
|
||||||
|
// static/js/map.js:4867-4869
|
||||||
|
setInterval(updateMapFreshnessBadge, 1000);
|
||||||
|
|
||||||
|
// 进行中订单:每 2 分钟主动刷新一次(与上游对账 + 重算剩余时长/预计还车)
|
||||||
|
// static/js/map.js:4870-4884
|
||||||
|
setInterval(async () => {
|
||||||
|
if (!S.authToken || document.visibilityState !== "visible") return;
|
||||||
|
if (!S.currentOrder || Number(S.currentOrder.status) !== 2) return;
|
||||||
|
try {
|
||||||
|
await syncWechatOrder(); // 上游可能已被还车/换单
|
||||||
|
checkOrderStatus(); // 刷新横幅状态
|
||||||
|
if (S.currentOrder && S.currentOrder.order_id) {
|
||||||
|
fetchOrderCountdown(S.currentOrder.order_id); // 重算剩余 + 预计还车
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error("[订单2分钟刷新] 失败:", e);
|
||||||
|
}
|
||||||
|
}, 120000);
|
||||||
|
|
||||||
|
// 页面重新可见时检查租车状态
|
||||||
|
// static/js/map.js:4885-4905
|
||||||
|
document.addEventListener("visibilitychange", () => {
|
||||||
|
if (document.visibilityState === "visible") {
|
||||||
|
if (S.authToken && S.map) loadMapData(S.currentType, false, true);
|
||||||
|
checkAuthStatus().then(async () => {
|
||||||
|
// 从微信或其他端回到页面时,先主动对账,再刷新本地横幅。
|
||||||
|
if (S.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") && S.currentOrder && S.currentOrder.status === 2) {
|
||||||
|
console.log("[visibilitychange] order-banner 进行中,同步倒计时");
|
||||||
|
fetchOrderCountdown(S.currentOrder.order_id);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// ================= 版本号 & 更新说明 =================
|
||||||
|
// static/js/map.js:4935-4938
|
||||||
|
(function () {
|
||||||
|
var b = document.getElementById("version-badge");
|
||||||
|
if (b) b.textContent = VERSION_TAG;
|
||||||
|
})();
|
||||||
|
// static/js/map.js:4992-5000
|
||||||
|
document.addEventListener("DOMContentLoaded", () => {
|
||||||
|
if (S.authToken) shareAfterLogin();
|
||||||
|
setInterval(() => { if (S.authToken) { checkAuthStatus(); checkOrderStatus(); refreshShareBanners(); } }, 20000);
|
||||||
|
setInterval(() => { if (S.authToken) checkPendingShareRequests(); }, 30000);
|
||||||
|
// 版本更新说明不再自动弹(右下角版本徽标也已去掉);
|
||||||
|
// 需要看历史更新时可以从控制台 openVersionModal() 调出来
|
||||||
|
});
|
||||||
|
|
||||||
|
// 共享电动车已拆到 static/js/share.js
|
||||||
|
}
|
||||||
|
|
||||||
|
bootstrap();
|
||||||
@@ -0,0 +1,501 @@
|
|||||||
|
/* 由 static/js/{navigation,share,subscribe,map}.js 逐块搬运而来;正文与原实现一致。 */
|
||||||
|
|
||||||
|
import { S } from "../core/state";
|
||||||
|
import { showBikeDetail } from "../card/bike-card";
|
||||||
|
import { friendlyError } from "../core/format";
|
||||||
|
import { calcDistance, offsetCoord } from "../core/geo";
|
||||||
|
import { getBikeState, preloadBaseIcons } from "./icons";
|
||||||
|
import { renderMap, setupClusterListener } from "./markers";
|
||||||
|
import { bindNavMapEvents } from "../nav/navigation";
|
||||||
|
import { showToast } from "../ui/modals";
|
||||||
|
import { showLoginGate } from "../ui/settings";
|
||||||
|
// static/js/map.js:26-29
|
||||||
|
const BAIDU_AK = "GzzqszczKmI7RNTclpLtOXZDTT4mq8a6";
|
||||||
|
|
||||||
|
// ========== 图标缓存(性能优化)==========
|
||||||
|
// 缓存: key = "电量|颜色|是否高亮" → BMapGL.Icon
|
||||||
|
|
||||||
|
// static/js/map.js:129-129
|
||||||
|
const INIT_OFFSET_EXTRA = 0.00027; // 约30米(向北)
|
||||||
|
|
||||||
|
// static/js/map.js:130-140
|
||||||
|
const INIT_OFFSET_EAST = 0.003; // 约300米(向东)
|
||||||
|
|
||||||
|
// 坐标转换:车辆/地图数据为 GCJ02,逐点精确转百度 BD09(coordtransform,无在线转换上限)。
|
||||||
|
// coordtransform.gcj02tobd09(lng, lat) -> [bd09_lng, bd09_lat]
|
||||||
|
|
||||||
|
// 状态判断函数 - 基于 state + status 组合判断
|
||||||
|
// state=1 + status=0: 空闲可用
|
||||||
|
// state=1 + status=1: 使用中(被占用)
|
||||||
|
// state=10: 低电量车辆
|
||||||
|
// state=4: 欠压车辆
|
||||||
|
// state=2: 损坏车辆
|
||||||
|
|
||||||
|
// static/js/map.js:473-473
|
||||||
|
let mapInitializationStarted: any = false;
|
||||||
|
|
||||||
|
// static/js/map.js:474-492
|
||||||
|
export function initMap() {
|
||||||
|
// 等待 BMapGL 对象加载完成
|
||||||
|
function waitForBMap(retries = 30) {
|
||||||
|
if (mapInitializationStarted) return;
|
||||||
|
if (typeof BMapGL !== 'undefined' && typeof BMapGL.Map === 'function') {
|
||||||
|
mapInitializationStarted = true;
|
||||||
|
initMapCore();
|
||||||
|
} else if (retries > 0) {
|
||||||
|
console.log(`等待百度地图GL API加载... (${retries})`);
|
||||||
|
setTimeout(() => waitForBMap(retries - 1), 500);
|
||||||
|
} else {
|
||||||
|
console.error("百度地图GL API加载失败");
|
||||||
|
showToast("地图API加载失败,请检查网络后刷新");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
waitForBMap();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 登录认证 ==========
|
||||||
|
|
||||||
|
// static/js/map.js:2965-3003
|
||||||
|
export function initMapCore() {
|
||||||
|
// 预加载基础图标(在请求地图数据之前就开始)
|
||||||
|
preloadBaseIcons();
|
||||||
|
|
||||||
|
fetch("/api/config")
|
||||||
|
.then(r => r.json())
|
||||||
|
.then(cfg => {
|
||||||
|
document.getElementById("school-name").textContent = cfg.school_name || "山东管理学院";
|
||||||
|
// 初始位置:整体偏移 + 额外上移30米 + 东移200米
|
||||||
|
const c = offsetCoord(cfg.center_lat, cfg.center_lng);
|
||||||
|
c.lat += INIT_OFFSET_EXTRA;
|
||||||
|
c.lng += INIT_OFFSET_EAST;
|
||||||
|
|
||||||
|
// 初始化百度地图 GL
|
||||||
|
S.map = new BMapGL.Map("baidu_map");
|
||||||
|
// 地图实例刚建好:立刻把导航模块的拖动监听绑上(浏览器里唯一可靠的时机,
|
||||||
|
// 之前 navigation.js 只靠 setTimeout(0),那时 map 还是 null,监听从未生效)
|
||||||
|
try { if (typeof bindNavMapEvents === "function") bindNavMapEvents(); } catch (e) {}
|
||||||
|
S.map.centerAndZoom(new BMapGL.Point(c.lng, c.lat), cfg.scale || 17);
|
||||||
|
S.map.enableScrollWheelZoom(true);
|
||||||
|
S.map.enableDragging(true);
|
||||||
|
S.map.enableInertialDragging(true);
|
||||||
|
// 不加 NavigationControl:它带出的左上角方向键/缩放滑杆(以及其中的“定位失败”钮)
|
||||||
|
// 业务里用不到,双指缩放与拖拽手势不依赖该控件。
|
||||||
|
S.map.addControl(new BMapGL.ScaleControl());
|
||||||
|
|
||||||
|
updateMapStyle();
|
||||||
|
loadMapData(S.currentType);
|
||||||
|
|
||||||
|
// 启动自动持续定位(地图加载后立即开始)
|
||||||
|
startAutoLocation();
|
||||||
|
})
|
||||||
|
.catch(err => {
|
||||||
|
console.error("初始化失败:", err);
|
||||||
|
showToast("地图初始化失败,请刷新重试");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 深色模式适配 ==========
|
||||||
|
|
||||||
|
// static/js/map.js:3004-3021
|
||||||
|
export function updateMapStyle() {
|
||||||
|
const isDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
|
||||||
|
if (isDark) {
|
||||||
|
// Only filter the basemap canvas; native DOM overlays retain their colours.
|
||||||
|
const mapEl = document.getElementById("baidu_map");
|
||||||
|
mapEl.style.filter = "";
|
||||||
|
mapEl.style.setProperty("--basemap-filter", "invert(90%) hue-rotate(180deg) brightness(95%) contrast(90%)");
|
||||||
|
mapEl.style.background = "#1c1c1e";
|
||||||
|
} else {
|
||||||
|
// 浅色模式 - 移除滤镜
|
||||||
|
const mapEl = document.getElementById("baidu_map");
|
||||||
|
mapEl.style.filter = "";
|
||||||
|
mapEl.style.setProperty("--basemap-filter", "none");
|
||||||
|
mapEl.style.background = "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 监听系统颜色变化
|
||||||
|
|
||||||
|
// static/js/map.js:3027-3027
|
||||||
|
let mapRequest: any = null;
|
||||||
|
|
||||||
|
// static/js/map.js:3028-3028
|
||||||
|
export let mapRefreshTimer: any = null;
|
||||||
|
|
||||||
|
// static/js/map.js:3029-3029
|
||||||
|
let renderedMapSnapshot: any = null;
|
||||||
|
|
||||||
|
// static/js/map.js:3030-3030
|
||||||
|
let mapRefreshFailed: any = false;
|
||||||
|
|
||||||
|
// static/js/map.js:3032-3043
|
||||||
|
export function scheduleMapRefresh(snapshot, serverTime, retrySeconds = 5) {
|
||||||
|
clearTimeout(mapRefreshTimer);
|
||||||
|
const expires = Number(snapshot?.expires_at);
|
||||||
|
const delay = Number.isFinite(expires) && Number.isFinite(serverTime)
|
||||||
|
? Math.max(500, (expires - serverTime) * 1000 + 150)
|
||||||
|
: Math.max(1000, retrySeconds * 1000);
|
||||||
|
mapRefreshTimer = setTimeout(() => {
|
||||||
|
if (S.authToken && S.map && document.visibilityState === "visible") {
|
||||||
|
loadMapData(S.currentType, false, true);
|
||||||
|
}
|
||||||
|
}, Math.min(delay, 60000));
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:3045-3096
|
||||||
|
export function loadMapData(type, showLoading = true, quiet = false) {
|
||||||
|
if (!S.authToken) { showLoginGate(); return Promise.resolve(); }
|
||||||
|
if (!S.map) return Promise.resolve();
|
||||||
|
if (mapRequest && mapRequest.type === String(type)) return mapRequest.promise;
|
||||||
|
const requestToken = S.authToken;
|
||||||
|
const loading = document.getElementById("loading");
|
||||||
|
if (S.isFirstLoad && showLoading) loading.classList.remove("hidden");
|
||||||
|
const pending = { type: String(type), promise: null };
|
||||||
|
mapRequest = pending;
|
||||||
|
pending.promise = fetch(`/api/map?type=${encodeURIComponent(type)}`, {
|
||||||
|
headers: { "Authorization": `Bearer ${requestToken}` },
|
||||||
|
cache: "no-store"
|
||||||
|
})
|
||||||
|
.then(async response => {
|
||||||
|
const result = await response.json();
|
||||||
|
const stamp = response.headers.get("X-Map-Server-Time");
|
||||||
|
const serverTime = stamp !== null ? Number(stamp) : Date.now() / 1000;
|
||||||
|
return { result, serverTime };
|
||||||
|
})
|
||||||
|
.then(({ result, serverTime }) => {
|
||||||
|
if (S.authToken !== requestToken || String(type) !== String(S.currentType)) return;
|
||||||
|
loading.classList.add("hidden");
|
||||||
|
if (result.rtn_code === 401) { showLoginGate(); return; }
|
||||||
|
scheduleMapRefresh(result.map_snapshot, serverTime, result.retry_after || 5);
|
||||||
|
if (result.rtn_code !== 0) {
|
||||||
|
mapRefreshFailed = true;
|
||||||
|
updateMapFreshnessBadge();
|
||||||
|
if (!quiet) showToast(result.message || "车辆数据更新失败,正在自动重试");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
renderMap([result], !S.isFirstLoad);
|
||||||
|
S.isFirstLoad = false;
|
||||||
|
mapRefreshFailed = false;
|
||||||
|
if (result.map_snapshot) {
|
||||||
|
renderedMapSnapshot = { ...result.map_snapshot, serverTime, receivedAt: performance.now() };
|
||||||
|
updateMapFreshnessBadge();
|
||||||
|
} else updateTime();
|
||||||
|
if (S.map) setupClusterListener();
|
||||||
|
})
|
||||||
|
.catch(err => {
|
||||||
|
if (S.authToken !== requestToken || String(type) !== String(S.currentType)) return;
|
||||||
|
loading.classList.add("hidden");
|
||||||
|
mapRefreshFailed = true;
|
||||||
|
updateMapFreshnessBadge();
|
||||||
|
scheduleMapRefresh(null, null);
|
||||||
|
if (!quiet) showToast("加载失败: " + friendlyError(err));
|
||||||
|
})
|
||||||
|
.finally(() => { if (mapRequest === pending) mapRequest = null; });
|
||||||
|
return pending.promise;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 手动刷新 ==========
|
||||||
|
|
||||||
|
// static/js/map.js:3097-3104
|
||||||
|
export function refreshMap() {
|
||||||
|
const btn = document.getElementById("refresh-btn");
|
||||||
|
btn.classList.add("spinning");
|
||||||
|
loadMapData(S.currentType, false);
|
||||||
|
setTimeout(() => btn.classList.remove("spinning"), 1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 渲染地图(坐标归一化 + 增量气泡图层)==========
|
||||||
|
|
||||||
|
// static/js/map.js:4305-4309
|
||||||
|
export function mapSnapshotNow() {
|
||||||
|
return renderedMapSnapshot
|
||||||
|
? renderedMapSnapshot.serverTime + (performance.now() - renderedMapSnapshot.receivedAt) / 1000
|
||||||
|
: Date.now() / 1000;
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:4311-4327
|
||||||
|
export 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";
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:4329-4344
|
||||||
|
export function updateTime() {
|
||||||
|
if (renderedMapSnapshot) { updateMapFreshnessBadge(); return; }
|
||||||
|
// Compatibility for a server without snapshot metadata; never show client time.
|
||||||
|
fetch(`/api/map/freshness?type=${encodeURIComponent(S.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(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:4346-4355
|
||||||
|
export 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 ? "地图数据暂时不可用,正在自动重试" : "正在获取最新车辆数据");
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:4630-4640
|
||||||
|
export function locateMe() {
|
||||||
|
if (!navigator.geolocation) {
|
||||||
|
showToast("您的浏览器不支持定位");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 启动自动持续定位(页面启动时调用一次即可)
|
||||||
|
startAutoLocation();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 手动找最近的车(基于当前自动定位的位置)
|
||||||
|
|
||||||
|
// static/js/map.js:4641-4651
|
||||||
|
export function findNearestBikeManual() {
|
||||||
|
if (!S.autoLocationMarker) {
|
||||||
|
showToast("请先开启定位");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const point = S.autoLocationMarker.getPosition();
|
||||||
|
findNearestBike(point);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 显示我的位置(手动定位模式,带 panTo)
|
||||||
|
|
||||||
|
// static/js/map.js:4652-4677
|
||||||
|
export function showMyLocation(point) {
|
||||||
|
if (S.myLocationMarker) {
|
||||||
|
S.map.removeOverlay(S.myLocationMarker);
|
||||||
|
}
|
||||||
|
// 蓝色脉冲点
|
||||||
|
const size = 24;
|
||||||
|
const canvas = document.createElement("canvas");
|
||||||
|
canvas.width = size;
|
||||||
|
canvas.height = size;
|
||||||
|
const ctx = canvas.getContext("2d");
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.arc(size/2, size/2, size/2 - 2, 0, Math.PI * 2);
|
||||||
|
ctx.fillStyle = "#007AFF";
|
||||||
|
ctx.fill();
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.arc(size/2, size/2, 6, 0, Math.PI * 2);
|
||||||
|
ctx.fillStyle = "white";
|
||||||
|
ctx.fill();
|
||||||
|
|
||||||
|
const icon = new BMapGL.Icon(canvas.toDataURL(), new BMapGL.Size(size, size), new BMapGL.Size(size/2, size/2));
|
||||||
|
S.myLocationMarker = new BMapGL.Marker(point, { icon });
|
||||||
|
S.map.addOverlay(S.myLocationMarker);
|
||||||
|
S.map.panTo(point);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 绘制自动定位标记(带外圈脉冲效果,灰色调)
|
||||||
|
|
||||||
|
// static/js/map.js:4678-4708
|
||||||
|
export function createAutoLocationIcon() {
|
||||||
|
const size = 28;
|
||||||
|
const canvas = document.createElement("canvas");
|
||||||
|
canvas.width = size;
|
||||||
|
canvas.height = size;
|
||||||
|
const ctx = canvas.getContext("2d");
|
||||||
|
|
||||||
|
// 外圈(浅蓝色,脉冲感)
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.arc(size/2, size/2, size/2 - 2, 0, Math.PI * 2);
|
||||||
|
ctx.strokeStyle = "rgba(0, 122, 255, 0.3)";
|
||||||
|
ctx.lineWidth = 3;
|
||||||
|
ctx.stroke();
|
||||||
|
|
||||||
|
// 中圈
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.arc(size/2, size/2, 8, 0, Math.PI * 2);
|
||||||
|
ctx.strokeStyle = "rgba(0, 122, 255, 0.6)";
|
||||||
|
ctx.lineWidth = 2;
|
||||||
|
ctx.stroke();
|
||||||
|
|
||||||
|
// 中心点
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.arc(size/2, size/2, 4, 0, Math.PI * 2);
|
||||||
|
ctx.fillStyle = "#007AFF";
|
||||||
|
ctx.fill();
|
||||||
|
|
||||||
|
return canvas.toDataURL("image/png");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新自动定位标记位置(不 panTo)
|
||||||
|
|
||||||
|
// static/js/map.js:4709-4722
|
||||||
|
export function updateAutoLocation(point) {
|
||||||
|
if (!S.autoLocationMarker) {
|
||||||
|
// 首次创建
|
||||||
|
const iconUrl = createAutoLocationIcon();
|
||||||
|
const icon = new BMapGL.Icon(iconUrl, new BMapGL.Size(28, 28), new BMapGL.Size(14, 14));
|
||||||
|
S.autoLocationMarker = new BMapGL.Marker(point, { icon });
|
||||||
|
S.map.addOverlay(S.autoLocationMarker);
|
||||||
|
} else {
|
||||||
|
// 更新位置
|
||||||
|
S.autoLocationMarker.setPosition(point);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 启动自动持续定位
|
||||||
|
|
||||||
|
// static/js/map.js:4723-4776
|
||||||
|
export function startAutoLocation() {
|
||||||
|
if (!navigator.geolocation) {
|
||||||
|
console.log("[自动定位] 浏览器不支持定位");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果已经在监听,先停止
|
||||||
|
if (S.autoLocationWatchId !== null) {
|
||||||
|
navigator.geolocation.clearWatch(S.autoLocationWatchId);
|
||||||
|
}
|
||||||
|
|
||||||
|
showToast("正在获取您的位置...");
|
||||||
|
S.autoLocationWatchId = navigator.geolocation.watchPosition(
|
||||||
|
(pos) => {
|
||||||
|
const gpsLat = pos.coords.latitude;
|
||||||
|
const gpsLng = pos.coords.longitude;
|
||||||
|
|
||||||
|
// GPS(WGS84) -> 百度 BD09,本地用 coordtransform 同步转换,
|
||||||
|
// 替代原 BMapGL.Convertor 在线接口(无网络/异步依赖)。
|
||||||
|
// coordtransform.wgs84tobd09(lng, lat) 返回 [bd09_lng, bd09_lat]
|
||||||
|
let myPoint = null;
|
||||||
|
if (typeof coordtransform !== "undefined" && coordtransform.wgs84tobd09) {
|
||||||
|
try {
|
||||||
|
const bd09 = coordtransform.wgs84tobd09(gpsLng, gpsLat);
|
||||||
|
myPoint = new BMapGL.Point(bd09[0], bd09[1]);
|
||||||
|
} catch (e) {
|
||||||
|
console.warn("[自动定位] 坐标转换失败,使用原始坐标:", e);
|
||||||
|
myPoint = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 库未加载或转换失败时,直接使用原始坐标兜底
|
||||||
|
if (!myPoint) {
|
||||||
|
myPoint = new BMapGL.Point(gpsLng, gpsLat);
|
||||||
|
}
|
||||||
|
updateAutoLocation(myPoint);
|
||||||
|
S.hasLocationPermission = true;
|
||||||
|
|
||||||
|
// 用户授权定位时:本页首次拿到位置后,把地图居中到用户位置(仅一次)
|
||||||
|
if (!S.initialLocationCentered) {
|
||||||
|
S.initialLocationCentered = true;
|
||||||
|
if (S.map) {
|
||||||
|
S.map.setCenter(myPoint);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
(err) => {
|
||||||
|
console.log("[自动定位] 定位失败:", err.message);
|
||||||
|
S.hasLocationPermission = false;
|
||||||
|
},
|
||||||
|
{ enableHighAccuracy: false, maximumAge: 5000, timeout: 10000 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 停止自动定位
|
||||||
|
|
||||||
|
// static/js/map.js:4777-4788
|
||||||
|
export function stopAutoLocation() {
|
||||||
|
if (S.autoLocationWatchId !== null) {
|
||||||
|
navigator.geolocation.clearWatch(S.autoLocationWatchId);
|
||||||
|
S.autoLocationWatchId = null;
|
||||||
|
}
|
||||||
|
if (S.autoLocationMarker) {
|
||||||
|
S.map.removeOverlay(S.autoLocationMarker);
|
||||||
|
S.autoLocationMarker = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 计算距离并找最近可用车辆(智能电量匹配)
|
||||||
|
|
||||||
|
// static/js/map.js:4789-4851
|
||||||
|
export function findNearestBike(myPoint) {
|
||||||
|
// Haversine公式计算两点距离(米)
|
||||||
|
|
||||||
|
const myLat = myPoint.lat;
|
||||||
|
const myLng = myPoint.lng;
|
||||||
|
const NEARBY_THRESHOLD = 200; // 附近范围(米)
|
||||||
|
const LOW_BATTERY = 20; // 低电量阈值
|
||||||
|
|
||||||
|
// 收集所有可用车(电量>20%,非使用中)
|
||||||
|
const available = [];
|
||||||
|
for (const id in S.markersData) {
|
||||||
|
const bike = S.markersData[id];
|
||||||
|
if (!bike.latitude || !bike.longitude) continue;
|
||||||
|
// 只把「空闲可用」的车推荐给用户:分类规则与 getBikeState / 后端一致
|
||||||
|
// (使用中 state=1&status=1 / 低电量 state=10 或 电量<20 / 欠压 4 / 损坏 2)
|
||||||
|
const bs = getBikeState(bike);
|
||||||
|
if (bs !== 'available') continue;
|
||||||
|
const electric = parseFloat(bike.electric_quantity || bike.electricQuantity || 0);
|
||||||
|
if (electric <= LOW_BATTERY) continue; // 过滤低电量
|
||||||
|
|
||||||
|
const c = offsetCoord(bike.latitude, bike.longitude);
|
||||||
|
const dist = calcDistance(myLat, myLng, c.lat, c.lng);
|
||||||
|
available.push({ id, bike, dist, electric });
|
||||||
|
}
|
||||||
|
|
||||||
|
// 过滤:只选电量 > 40% 的车
|
||||||
|
const enoughElec = available.filter(v => v.electric > 40);
|
||||||
|
|
||||||
|
if (enoughElec.length === 0) {
|
||||||
|
showToast("附近没有电量足够的车辆(需要>40%)");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 直接选距离最近的
|
||||||
|
enoughElec.sort((a, b) => a.dist - b.dist);
|
||||||
|
const selected = enoughElec[0];
|
||||||
|
const matchType = "最近可用";
|
||||||
|
|
||||||
|
|
||||||
|
S.nearestBikeId = selected.id;
|
||||||
|
const bike = selected.bike;
|
||||||
|
const c = offsetCoord(bike.latitude, bike.longitude);
|
||||||
|
const bikePoint = new BMapGL.Point(c.lng, c.lat);
|
||||||
|
|
||||||
|
// 飞到这个车并放大一级
|
||||||
|
S.map.panTo(bikePoint);
|
||||||
|
setTimeout(() => {
|
||||||
|
S.map.setZoom(S.map.getZoom() + 1);
|
||||||
|
}, 300);
|
||||||
|
|
||||||
|
// 文案与 getBikeState 的分类一一对应(推荐出来的车一定是 available,正常走「空闲」)
|
||||||
|
const stateLabel = {
|
||||||
|
inuse: "使用中", available: "空闲", lowbattery: "低电量",
|
||||||
|
locked: "欠压车辆", reserved: "损坏车辆", unknown: "未知",
|
||||||
|
}[getBikeState(bike)] || "未知";
|
||||||
|
const distText = selected.dist < 1000 ? `${Math.round(selected.dist)}米` : `${(selected.dist/1000).toFixed(1)}公里`;
|
||||||
|
showToast(`${matchType}:#${bike.code}(${stateLabel} ${selected.electric}%),${distText}`);
|
||||||
|
|
||||||
|
setTimeout(() => showBikeDetail(selected.id), 500);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 启动 ==========
|
||||||
|
// 启动时检查登录状态,然后检查租车
|
||||||
@@ -0,0 +1,280 @@
|
|||||||
|
/* 由 static/js/{navigation,share,subscribe,map}.js 逐块搬运而来;正文与原实现一致。 */
|
||||||
|
// static/js/map.js:30-30
|
||||||
|
const iconCache = new Map();
|
||||||
|
|
||||||
|
// static/js/map.js:31-34
|
||||||
|
const ICON_CACHE_MAX = 500; // 最多缓存500个不同图标
|
||||||
|
|
||||||
|
// ========== 预创建完整图标(首次加载优化)==========
|
||||||
|
// 预创建各电量和颜色的完整图标(避免首次加载时大量 Canvas 绘制)
|
||||||
|
|
||||||
|
// static/js/map.js:35-43
|
||||||
|
const BASE_ICON_COLORS = {
|
||||||
|
available: "#34C759", // 绿色-可用
|
||||||
|
inuse: "#FF2D55", // 红色-使用中
|
||||||
|
locked: "#FF9F0A", // 橙色-欠压
|
||||||
|
reserved: "#5856D6", // 紫色-损坏
|
||||||
|
lowbattery: "#8E8E93" // 灰色-低电量
|
||||||
|
};
|
||||||
|
|
||||||
|
// 预创建非高亮状态的完整图标(电量档位 0, 20, 40, 60, 80, 100)
|
||||||
|
|
||||||
|
// static/js/map.js:44-44
|
||||||
|
const prebuiltIcons = new Map(); // key: "电量档位|颜色", value: BMapGL.Icon
|
||||||
|
|
||||||
|
// static/js/map.js:46-101
|
||||||
|
export function createFullIcon(size, color, electric, isHighlighted, bikeCode) {
|
||||||
|
const canvas = document.createElement("canvas");
|
||||||
|
canvas.width = size;
|
||||||
|
canvas.height = size;
|
||||||
|
const ctx = canvas.getContext("2d");
|
||||||
|
const r = size / 2 - (isHighlighted ? 12 : 8);
|
||||||
|
const lineWidth = isHighlighted ? 16 : 12;
|
||||||
|
const centerX = size / 2;
|
||||||
|
const centerY = size / 2;
|
||||||
|
|
||||||
|
// 高亮时加阴影
|
||||||
|
if (isHighlighted) {
|
||||||
|
ctx.shadowColor = color;
|
||||||
|
ctx.shadowBlur = 48;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 白色背景
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.arc(centerX, centerY, r, 0, Math.PI * 2);
|
||||||
|
ctx.fillStyle = "white";
|
||||||
|
ctx.fill();
|
||||||
|
|
||||||
|
// 边框
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.arc(centerX, centerY, r, 0, Math.PI * 2);
|
||||||
|
ctx.strokeStyle = isHighlighted ? color : "rgba(200,200,200,0.5)";
|
||||||
|
ctx.lineWidth = isHighlighted ? 16 : lineWidth;
|
||||||
|
ctx.stroke();
|
||||||
|
ctx.shadowBlur = 0;
|
||||||
|
|
||||||
|
// 使用中:实心圆环
|
||||||
|
if (isHighlighted) {
|
||||||
|
// 高亮时只显示车牌号,没有进度环
|
||||||
|
} else {
|
||||||
|
// 非高亮:绘制电量进度环
|
||||||
|
const startAngle = -Math.PI / 2;
|
||||||
|
const endAngle = startAngle + (Math.PI * 2 * electric / 100);
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.arc(centerX, centerY, r, startAngle, endAngle);
|
||||||
|
ctx.strokeStyle = color;
|
||||||
|
ctx.lineWidth = lineWidth;
|
||||||
|
ctx.lineCap = "round";
|
||||||
|
ctx.stroke();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 绘制数字
|
||||||
|
ctx.fillStyle = "#333";
|
||||||
|
ctx.font = isHighlighted ? "bold 60px Arial" : "bold 44px Arial";
|
||||||
|
ctx.textAlign = "center";
|
||||||
|
ctx.textBaseline = "middle";
|
||||||
|
ctx.fillText(isHighlighted ? (bikeCode + "") : (Math.round(electric) + ""), centerX, centerY);
|
||||||
|
|
||||||
|
return canvas.toDataURL("image/png");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 预初始化完整图标(在地图加载前调用)
|
||||||
|
|
||||||
|
// static/js/map.js:102-121
|
||||||
|
export function preloadBaseIcons() {
|
||||||
|
const displaySize = 36;
|
||||||
|
const imageSize = displaySize * 4; // 高清4倍
|
||||||
|
const electricLevels = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]; // 21个电量档位(5%分度)
|
||||||
|
|
||||||
|
Object.values<any>(BASE_ICON_COLORS).forEach(color => {
|
||||||
|
// 非高亮状态:每个电量档位创建一个
|
||||||
|
electricLevels.forEach(electric => {
|
||||||
|
const key = `${electric}|${color}`;
|
||||||
|
if (!prebuiltIcons.has(key)) {
|
||||||
|
// 存储 data URL 而不是 Icon 对象
|
||||||
|
const dataUrl = createFullIcon(imageSize, color, electric, false, null);
|
||||||
|
prebuiltIcons.set(key, dataUrl);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
console.log("[预创建] 已预创建 " + prebuiltIcons.size + " 个图标");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 用车计时 ==========
|
||||||
|
|
||||||
|
// static/js/map.js:141-158
|
||||||
|
export function getBikeState(bike) {
|
||||||
|
const state = bike.state;
|
||||||
|
const status = bike.status;
|
||||||
|
const electric = Number(bike.electric_quantity ?? bike.electricQuantity ?? 100);
|
||||||
|
// 使用中:被占用
|
||||||
|
if (state === 1 && status === 1) return 'inuse';
|
||||||
|
// 低电量:state=10 或电量<20(与后端 _classify_bike_state 同序)
|
||||||
|
if (state === 10 || electric < 20) return 'lowbattery';
|
||||||
|
// 空闲可用
|
||||||
|
if (state === 1) return 'available';
|
||||||
|
// 欠压车辆
|
||||||
|
if (state === 4) return 'locked';
|
||||||
|
// 损坏车辆
|
||||||
|
if (state === 2) return 'reserved';
|
||||||
|
return 'unknown';
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 电池绘制 ==========
|
||||||
|
|
||||||
|
// static/js/map.js:171-222
|
||||||
|
export function makeIconDataURI(color, percent, isInUse, size = 36) {
|
||||||
|
const canvas = document.createElement("canvas");
|
||||||
|
canvas.width = size;
|
||||||
|
canvas.height = size;
|
||||||
|
const ctx = canvas.getContext("2d");
|
||||||
|
const r = size / 2 - 2;
|
||||||
|
const lineWidth = 3;
|
||||||
|
const centerX = size / 2;
|
||||||
|
const centerY = size / 2;
|
||||||
|
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.arc(centerX, centerY, r - lineWidth, 0, Math.PI * 2);
|
||||||
|
ctx.fillStyle = "rgba(255,255,255,0.9)";
|
||||||
|
ctx.fill();
|
||||||
|
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.arc(centerX, centerY, r, 0, Math.PI * 2);
|
||||||
|
ctx.strokeStyle = "rgba(200,200,200,0.5)";
|
||||||
|
ctx.lineWidth = lineWidth;
|
||||||
|
ctx.stroke();
|
||||||
|
|
||||||
|
if (isInUse) {
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.arc(centerX, centerY, r, 0, Math.PI * 2);
|
||||||
|
ctx.strokeStyle = color;
|
||||||
|
ctx.lineWidth = lineWidth;
|
||||||
|
ctx.stroke();
|
||||||
|
} else {
|
||||||
|
const startAngle = -Math.PI / 2;
|
||||||
|
const endAngle = startAngle + (Math.PI * 2 * percent / 100);
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.arc(centerX, centerY, r, startAngle, endAngle);
|
||||||
|
ctx.strokeStyle = color;
|
||||||
|
ctx.lineWidth = lineWidth;
|
||||||
|
ctx.lineCap = "round";
|
||||||
|
ctx.stroke();
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx.fillStyle = "#333";
|
||||||
|
ctx.font = `bold ${size < 36 ? 10 : 11}px Arial`;
|
||||||
|
ctx.textAlign = "center";
|
||||||
|
ctx.textBaseline = "middle";
|
||||||
|
ctx.fillText(Math.round(percent) + "", centerX, centerY);
|
||||||
|
|
||||||
|
return canvas.toDataURL("image/png");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 车辆类型(编号规则,按实车号段)==========
|
||||||
|
// - 编号超过 5 位(如 30000193 / 30000033,共 8 位):新引进红色外观车 → 红车
|
||||||
|
// - 5 位编号取「前三位号段」:511 及以上=大车,510 及以下=小车
|
||||||
|
// (实测号段:503/504/505/510=小车,511/512/513=大车)
|
||||||
|
// 红车电量球统一用柔和砖红(不用"使用中"那种血红 #FF2D55,避免视觉惊扰)
|
||||||
|
|
||||||
|
// static/js/map.js:223-223
|
||||||
|
const RED_BIKE_COLOR = "#B4615A"; // 柔和砖红
|
||||||
|
|
||||||
|
// static/js/map.js:225-239
|
||||||
|
export function getBikeKind(bike) {
|
||||||
|
const digits = String((bike && bike.code) || "").replace(/\D/g, "");
|
||||||
|
if (digits.length > 5) {
|
||||||
|
return { key: "red", label: "红车", color: RED_BIKE_COLOR };
|
||||||
|
}
|
||||||
|
const num = parseInt(digits, 10);
|
||||||
|
if (!isFinite(num)) {
|
||||||
|
return { key: "small", label: "小车", color: null };
|
||||||
|
}
|
||||||
|
// 5 位取前三位号段;不足 5 位直接用编号本身比较
|
||||||
|
const series = digits.length >= 5 ? Math.floor(num / Math.pow(10, digits.length - 3)) : num;
|
||||||
|
return series >= 511
|
||||||
|
? { key: "big", label: "大车", color: null }
|
||||||
|
: { key: "small", label: "小车", color: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:241-321
|
||||||
|
export function getBikeIcon(bike, isHighlighted = false) {
|
||||||
|
const electric = Number(bike.electric_quantity ?? bike.electricQuantity ?? 100);
|
||||||
|
const bikeState = getBikeState(bike);
|
||||||
|
// 车辆类型只影响弹起卡片上的标注,地图电量球保持原有「按状态配色」
|
||||||
|
|
||||||
|
let color = "#34C759"; // 默认绿色-可用
|
||||||
|
if (bikeState === 'inuse') {
|
||||||
|
color = "#FF2D55"; // 红色-使用中
|
||||||
|
} else if (bikeState === 'locked') {
|
||||||
|
color = "#FF9F0A"; // 橙色-欠压车辆
|
||||||
|
} else if (bikeState === 'reserved') {
|
||||||
|
color = "#5856D6"; // 紫色-损坏车辆
|
||||||
|
} else if (bikeState === 'lowbattery' || electric < 20) {
|
||||||
|
color = "#8E8E93"; // 灰色-低电量
|
||||||
|
}
|
||||||
|
|
||||||
|
// 生成缓存 key
|
||||||
|
const electricLevel = Math.floor(electric / 5) * 5;
|
||||||
|
const cacheKey = isHighlighted
|
||||||
|
? `${electricLevel}|${color}|1|${bike.code}`
|
||||||
|
: `${electricLevel}|${color}|0`;
|
||||||
|
|
||||||
|
// 检查缓存
|
||||||
|
if (iconCache.has(cacheKey)) {
|
||||||
|
return iconCache.get(cacheKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
const renderSize = isHighlighted ? 192 : 144; // 内部渲染尺寸
|
||||||
|
const displaySize = isHighlighted ? 48 : 36; // 显示尺寸不变
|
||||||
|
|
||||||
|
// 非高亮模式:尝试使用预创建的图标
|
||||||
|
if (!isHighlighted && prebuiltIcons.size > 0) {
|
||||||
|
// 找到最接近的电量档位
|
||||||
|
const levels = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100];
|
||||||
|
let closestLevel = levels[0];
|
||||||
|
let minDiff = Math.abs(electric - closestLevel);
|
||||||
|
for (const lvl of levels) {
|
||||||
|
const diff = Math.abs(electric - lvl);
|
||||||
|
if (diff < minDiff) {
|
||||||
|
minDiff = diff;
|
||||||
|
closestLevel = lvl;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const prebuiltKey = `${closestLevel}|${color}`;
|
||||||
|
if (prebuiltIcons.has(prebuiltKey)) {
|
||||||
|
// 找到预创建的 data URL,直接创建 Icon
|
||||||
|
const dataUrl = prebuiltIcons.get(prebuiltKey);
|
||||||
|
const icon = new BMapGL.Icon(
|
||||||
|
dataUrl,
|
||||||
|
new BMapGL.Size(displaySize, displaySize),
|
||||||
|
new BMapGL.Size(displaySize / 2, displaySize / 2)
|
||||||
|
);
|
||||||
|
icon.__xbniuAppearance = { url: dataUrl, size: displaySize };
|
||||||
|
iconCache.set(cacheKey, icon);
|
||||||
|
return icon;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果没有预创建的图标,或者需要高亮状态:直接创建完整图标
|
||||||
|
// imageSize 用于渲染高清内容,displaySize 控制显示大小
|
||||||
|
const imageSize = renderSize * 4; // 高清4倍
|
||||||
|
const dataUrl = createFullIcon(imageSize, color, electric, isHighlighted, bike.code);
|
||||||
|
const icon = new BMapGL.Icon(
|
||||||
|
dataUrl,
|
||||||
|
new BMapGL.Size(displaySize, displaySize),
|
||||||
|
new BMapGL.Size(displaySize / 2, displaySize / 2)
|
||||||
|
);
|
||||||
|
icon.__xbniuAppearance = { url: dataUrl, size: displaySize };
|
||||||
|
|
||||||
|
// 缓存图标
|
||||||
|
if (iconCache.size >= ICON_CACHE_MAX) {
|
||||||
|
const keysToDelete = Array.from(iconCache.keys()).slice(0, Math.floor(ICON_CACHE_MAX * 0.2));
|
||||||
|
keysToDelete.forEach(k => iconCache.delete(k));
|
||||||
|
}
|
||||||
|
iconCache.set(cacheKey, icon);
|
||||||
|
|
||||||
|
return icon;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 高亮相关 ==========
|
||||||
|
// 稳健查找 marker:优先用索引,索引 miss(如批量渲染未完成/刷新过程中)时按 __animId 或标题扫描 currentMarkers 兜底
|
||||||
@@ -0,0 +1,333 @@
|
|||||||
|
/* 由 static/js/{navigation,share,subscribe,map}.js 逐块搬运而来;正文与原实现一致。 */
|
||||||
|
|
||||||
|
import { S } from "../core/state";
|
||||||
|
import { showBikeDetail } from "../card/bike-card";
|
||||||
|
import { offsetCoord } from "../core/geo";
|
||||||
|
import { createAutoLocationIcon } from "./core";
|
||||||
|
import { getBikeIcon, getBikeState } from "./icons";
|
||||||
|
// static/js/map.js:322-341
|
||||||
|
export function findMarkerById(id) {
|
||||||
|
const key = String(id);
|
||||||
|
if (S.currentMarkersById && S.currentMarkersById[id]) return S.currentMarkersById[id];
|
||||||
|
if (Array.isArray(S.currentMarkers)) {
|
||||||
|
for (let i = S.currentMarkers.length - 1; i >= 0; i--) {
|
||||||
|
const m = S.currentMarkers[i];
|
||||||
|
if (m && m.__animId !== undefined && String(m.__animId) === key) return m;
|
||||||
|
}
|
||||||
|
for (let i = S.currentMarkers.length - 1; i >= 0; i--) {
|
||||||
|
const m = S.currentMarkers[i];
|
||||||
|
if (m && m.getTitle) {
|
||||||
|
const t = String(m.getTitle()).replace(/^#/, "");
|
||||||
|
if (t === key) return m;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 让指定 marker 显示在最上层(放大高亮图标避免被其它普通 marker 遮住)
|
||||||
|
|
||||||
|
// static/js/map.js:342-353
|
||||||
|
export function bringMarkerToTop(marker) {
|
||||||
|
if (marker && marker.bringToTop) { marker.bringToTop(); return; }
|
||||||
|
if (marker && typeof S.map !== 'undefined' && S.map && typeof S.map.removeOverlay === 'function' && typeof S.map.addOverlay === 'function') {
|
||||||
|
try {
|
||||||
|
const markerId = marker.__animId;
|
||||||
|
S.map.removeOverlay(marker);
|
||||||
|
S.map.addOverlay(marker);
|
||||||
|
// removeOverlay/addOverlay 可能重建 marker 的 DOM,重绑一次原生 touch 兜底,避免点按失效
|
||||||
|
if (markerId !== undefined) bindMarkerDomTouch(marker);
|
||||||
|
} catch (e) { /* 忽略:个别情况下不允许重排 */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:355-379
|
||||||
|
export function setHighlight(id) {
|
||||||
|
// 清除之前的高亮
|
||||||
|
if (S.highlightedBikeId !== null) {
|
||||||
|
const prevMarker = findMarkerById(S.highlightedBikeId);
|
||||||
|
const prevBike = S.markersData[S.highlightedBikeId];
|
||||||
|
if (prevMarker && prevBike) {
|
||||||
|
try { prevMarker.setIcon(getBikeIcon(prevBike, false)); } catch (e) { console.warn("[setHighlight] 还原图标失败", e); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 设置新高亮
|
||||||
|
S.highlightedBikeId = id;
|
||||||
|
if (bikeBubbleLayer) bikeBubbleLayer.setSelected(id);
|
||||||
|
if (id === null || id === undefined) return;
|
||||||
|
const marker = findMarkerById(id);
|
||||||
|
const bike = S.markersData[id] || S.markersData[String(id)] || S.markersData[Number(id)];
|
||||||
|
if (marker && bike) {
|
||||||
|
try {
|
||||||
|
marker.setIcon(getBikeIcon(bike, true));
|
||||||
|
bringMarkerToTop(marker);
|
||||||
|
} catch (e) { console.warn("[setHighlight] 放大高亮失败", e); }
|
||||||
|
} else {
|
||||||
|
console.warn("[setHighlight] 未找到 marker 或 bike, id=", id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:381-399
|
||||||
|
export function clearHighlight() {
|
||||||
|
if (S.highlightedBikeId !== null) {
|
||||||
|
const prevMarker = findMarkerById(S.highlightedBikeId);
|
||||||
|
const prevBike = S.markersData[S.highlightedBikeId];
|
||||||
|
if (prevMarker && prevBike) {
|
||||||
|
try { prevMarker.setIcon(getBikeIcon(prevBike, false)); } catch (e) { console.warn("[clearHighlight] 还原图标失败", e); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
S.highlightedBikeId = null;
|
||||||
|
if (bikeBubbleLayer) bikeBubbleLayer.setSelected(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== Marker 点按绑定(统一入口)==========
|
||||||
|
// 背景:BMapGL 在拖动地图后会把紧接的一次对 marker 的 click 吞掉(当作拖拽延续),
|
||||||
|
// 导致“点了点但模态框弹不出”。因此这里不用单一 click,而是额外用
|
||||||
|
// mousedown/mouseup 与原生 touch 的“按下→抬起无位移”判定作为自控点击路径。
|
||||||
|
|
||||||
|
// 把原生 touch 兜底绑到 marker 的当前 DOM 元素上(幂等,可被重复调用,
|
||||||
|
// 用于 domElement 延迟就绪或 removeOverlay/addOverlay 重建 DOM 之后补绑)。
|
||||||
|
|
||||||
|
// static/js/map.js:400-422
|
||||||
|
export function bindMarkerDomTouch(marker) {
|
||||||
|
const tap = marker && marker.__xbniuTap;
|
||||||
|
if (!tap) return;
|
||||||
|
const el = marker.domElement;
|
||||||
|
if (!el) return;
|
||||||
|
if (el.__xbniuTapBound) return;
|
||||||
|
el.__xbniuTapBound = true;
|
||||||
|
try {
|
||||||
|
el.addEventListener('touchstart', (e) => {
|
||||||
|
const t = e.touches && e.touches[0];
|
||||||
|
if (t) tap._down(t.clientX, t.clientY);
|
||||||
|
}, { passive: true });
|
||||||
|
el.addEventListener('touchend', (e) => {
|
||||||
|
const t = e.changedTouches && e.changedTouches[0];
|
||||||
|
if (t) {
|
||||||
|
try { e.preventDefault(); } catch (err) {}
|
||||||
|
tap._up(t.clientX, t.clientY);
|
||||||
|
}
|
||||||
|
}, { passive: false });
|
||||||
|
} catch (e) { /* 忽略绑定失败 */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
// 给单个 marker 绑定点按处理。marker 需已 __animId = id。
|
||||||
|
|
||||||
|
// static/js/map.js:423-472
|
||||||
|
export function bindMarkerTap(marker, id) {
|
||||||
|
const tap = {
|
||||||
|
lastFire: 0, // 防重入:同一 marker 短时间内只触发一次
|
||||||
|
downX: null, downY: null, downT: 0,
|
||||||
|
_fire() {
|
||||||
|
// 同一 marker 的 click / mouseup / touchend 都可能触发本路径,300ms 内只放行一次
|
||||||
|
const now = Date.now();
|
||||||
|
if (now - this.lastFire < 300) return;
|
||||||
|
this.lastFire = now;
|
||||||
|
clearHighlight();
|
||||||
|
showBikeDetail(id);
|
||||||
|
},
|
||||||
|
_down(x, y) { this.downX = x; this.downY = y; this.downT = Date.now(); },
|
||||||
|
_up(x, y) {
|
||||||
|
if (this.downX === null) return;
|
||||||
|
const dx = x - this.downX, dy = y - this.downY;
|
||||||
|
const moved = Math.sqrt(dx * dx + dy * dy);
|
||||||
|
const dt = Date.now() - this.downT;
|
||||||
|
this.downX = this.downY = null;
|
||||||
|
// 无位移(<10px)且按压短暂(<600ms) 判定为点按 → 即使 BMapGL 吞了 click 也能打开
|
||||||
|
if (moved < 10 && dt < 600) this._fire();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
marker.__xbniuTap = tap;
|
||||||
|
|
||||||
|
// 1) BMapGL 对象级事件:click 为主路径,mousedown/mouseup 补偿“拖动后被吞的 click”
|
||||||
|
try {
|
||||||
|
marker.addEventListener('click', () => tap._fire());
|
||||||
|
marker.addEventListener('mousedown', (e) => tap._down(e.clientX, e.clientY));
|
||||||
|
marker.addEventListener('mouseup', (e) => tap._up(e.clientX, e.clientY));
|
||||||
|
} catch (e) { /* 个别事件类型不支持时忽略 */ }
|
||||||
|
|
||||||
|
// 2) 原生 touch 兜底(移动端最可靠)。domElement 可能延迟生成,故稍后补绑。
|
||||||
|
bindMarkerDomTouch(marker);
|
||||||
|
if (!marker.domElement) {
|
||||||
|
// domElement 尚未就绪:极轻量轮询补绑(最多约 1s),避免移动端兜底落空
|
||||||
|
let tries = 0;
|
||||||
|
const timer = setInterval(() => {
|
||||||
|
tries++;
|
||||||
|
if (marker.domElement) {
|
||||||
|
bindMarkerDomTouch(marker);
|
||||||
|
clearInterval(timer);
|
||||||
|
} else if (tries > 10) {
|
||||||
|
clearInterval(timer);
|
||||||
|
}
|
||||||
|
}, 100);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 初始化地图 ==========
|
||||||
|
|
||||||
|
// static/js/map.js:3106-3237
|
||||||
|
export function renderMap(results, isRefresh = false) {
|
||||||
|
if (typeof BikeClusters === "undefined") {
|
||||||
|
throw new Error("地图组件未加载,请刷新页面;订单还车功能仍可使用");
|
||||||
|
}
|
||||||
|
// 扫码补的临时点每次渲染都回收:它们不在快照数据里,
|
||||||
|
// 不清理的话车早被骑走了地图上还留着一个能点开的旧点。
|
||||||
|
Object.keys(S.scannedMarkers).forEach((key) => {
|
||||||
|
try { S.map.removeOverlay(S.scannedMarkers[key]); } catch (e) {}
|
||||||
|
delete S.scannedMarkers[key];
|
||||||
|
delete S.currentMarkersById[key];
|
||||||
|
});
|
||||||
|
|
||||||
|
// 刷新时不清除边界和停车区(首次加载才绘制)
|
||||||
|
if (!isRefresh) {
|
||||||
|
// 保存自动定位标记的位置
|
||||||
|
const autoPoint = S.autoLocationMarker ? S.autoLocationMarker.getPosition() : null;
|
||||||
|
|
||||||
|
// 清除所有覆盖物
|
||||||
|
S.map.clearOverlays();
|
||||||
|
if (bikeBubbleLayer) {
|
||||||
|
bikeBubbleLayer.destroy();
|
||||||
|
bikeBubbleLayer = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 清理旧的标记变量引用
|
||||||
|
S.autoLocationMarker = null;
|
||||||
|
S.myLocationMarker = null;
|
||||||
|
S.currentMarkers = [];
|
||||||
|
|
||||||
|
// 重新添加自动定位标记
|
||||||
|
if (autoPoint) {
|
||||||
|
const iconUrl = createAutoLocationIcon();
|
||||||
|
const icon = new BMapGL.Icon(iconUrl, new BMapGL.Size(28, 28), new BMapGL.Size(14, 14));
|
||||||
|
S.autoLocationMarker = new BMapGL.Marker(autoPoint, { icon });
|
||||||
|
S.map.addOverlay(S.autoLocationMarker);
|
||||||
|
}
|
||||||
|
|
||||||
|
S.currentPolygons = [];
|
||||||
|
S.currentMarkersById = {};
|
||||||
|
S.markersData = {};
|
||||||
|
S.nearestBikeId = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const nextBikes = [];
|
||||||
|
let availableCount = 0;
|
||||||
|
let usedCount = 0;
|
||||||
|
let lockedCount = 0;
|
||||||
|
let reservedCount = 0;
|
||||||
|
let lowCount = 0;
|
||||||
|
|
||||||
|
results.forEach(result => {
|
||||||
|
if (result.rtn_code !== 0 || !result.data) return;
|
||||||
|
const data = result.data;
|
||||||
|
|
||||||
|
// 首次加载:绘制骑行区域边界
|
||||||
|
if (!isRefresh && data.driverArea && data.driverArea.length > 0) {
|
||||||
|
const boundaryPoints = data.driverArea.map(p => {
|
||||||
|
const c = offsetCoord(p.latitude, p.longitude);
|
||||||
|
return new BMapGL.Point(c.lng, c.lat);
|
||||||
|
});
|
||||||
|
const boundaryPolygon = new BMapGL.Polygon(boundaryPoints, {
|
||||||
|
strokeColor: "#007AFF",
|
||||||
|
strokeWeight: 2,
|
||||||
|
strokeOpacity: 0.8,
|
||||||
|
fillColor: "#007AFF",
|
||||||
|
fillOpacity: 0.05,
|
||||||
|
});
|
||||||
|
S.map.addOverlay(boundaryPolygon);
|
||||||
|
S.currentPolygons.push(boundaryPolygon);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 首次加载:绘制停车区(只画启用的:is_disable=2 是停用区,
|
||||||
|
// 上游 /record/checkLocation 会直接拒绝,画出来只会误导人)
|
||||||
|
if (!isRefresh && data.parkeArea && data.parkeArea.length > 0) {
|
||||||
|
data.parkeArea.forEach(area => {
|
||||||
|
if (!area.points || area.points.length < 3) return;
|
||||||
|
if (String(area.is_disable) === "2") return;
|
||||||
|
|
||||||
|
const parkingPoints = area.points.map(p => {
|
||||||
|
const c = offsetCoord(p.latitude, p.longitude);
|
||||||
|
return new BMapGL.Point(c.lng, c.lat);
|
||||||
|
});
|
||||||
|
const parkingPolygon = new BMapGL.Polygon(parkingPoints, {
|
||||||
|
strokeColor: "#34C759",
|
||||||
|
strokeWeight: 2,
|
||||||
|
strokeOpacity: 0.8,
|
||||||
|
fillColor: "#34C759",
|
||||||
|
fillOpacity: 0.1,
|
||||||
|
});
|
||||||
|
S.map.addOverlay(parkingPolygon);
|
||||||
|
S.currentPolygons.push(parkingPolygon);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 收集所有车辆数据用于批量处理
|
||||||
|
const allBikes = BikeClusters.normalizeBikes(data.bicycleStation);
|
||||||
|
|
||||||
|
// 统计数量(所有车辆)
|
||||||
|
// 分类顺序必须与后端 app.py::_classify_bike_state 一致:
|
||||||
|
// state=10 或 电量<20 优先判低电量,其次欠压/损坏,最后 state=1 分使用中/可用。
|
||||||
|
// 注意电量字段是 electric_quantity(上游字段名),不存在 bike.electric。
|
||||||
|
allBikes.forEach(bike => {
|
||||||
|
const electric = Number(bike.electric_quantity ?? bike.electricQuantity ?? 100);
|
||||||
|
if (bike.state === 10 || electric < 20) {
|
||||||
|
lowCount++;
|
||||||
|
} else if (bike.state === 1 && bike.status === 1) {
|
||||||
|
usedCount++;
|
||||||
|
} else if (bike.state === 1) {
|
||||||
|
availableCount++;
|
||||||
|
} else if (bike.state === 4) {
|
||||||
|
lockedCount++;
|
||||||
|
} else if (bike.state === 2) {
|
||||||
|
reservedCount++;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
nextBikes.push(...allBikes);
|
||||||
|
});
|
||||||
|
|
||||||
|
// A response is a complete snapshot: remove vanished cars and honour empty results.
|
||||||
|
S.markersData = {};
|
||||||
|
nextBikes.forEach(bike => { S.markersData[BikeClusters.bikeId(bike)] = bike; });
|
||||||
|
document.getElementById("count-available").textContent = String(availableCount);
|
||||||
|
document.getElementById("count-used").textContent = String(usedCount);
|
||||||
|
document.getElementById("count-locked").textContent = String(lockedCount);
|
||||||
|
document.getElementById("count-reserved").textContent = String(reservedCount);
|
||||||
|
document.getElementById("count-low").textContent = String(lowCount);
|
||||||
|
rebuildMarkersForZoom(nextBikes);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Native overlay coordinates keep markers aligned during reverse zooming.
|
||||||
|
// Recomposition cross-fades at the real coordinates instead of moving centroids.
|
||||||
|
|
||||||
|
// static/js/map.js:3238-3238
|
||||||
|
export let bikeBubbleLayer: any = null;
|
||||||
|
|
||||||
|
// static/js/map.js:3239-3255
|
||||||
|
export function setupClusterListener() {
|
||||||
|
if (!S.map || bikeBubbleLayer || typeof BikeClusters === "undefined") return;
|
||||||
|
bikeBubbleLayer = BikeClusters.createLayer({
|
||||||
|
map: S.map,
|
||||||
|
enabled: S.bikeClusteringEnabled,
|
||||||
|
getPoint: bike => offsetCoord(bike.latitude, bike.longitude),
|
||||||
|
getState: getBikeState,
|
||||||
|
getIcon: getBikeIcon,
|
||||||
|
onBikeClick: id => { clearHighlight(); showBikeDetail(id); },
|
||||||
|
onMarkersChanged: markers => {
|
||||||
|
S.currentMarkers = markers;
|
||||||
|
S.currentMarkersById = {};
|
||||||
|
markers.forEach(marker => { S.currentMarkersById[marker.__animId] = marker; });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
bikeBubbleLayer.setSelected(S.highlightedBikeId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:3257-3264
|
||||||
|
export function rebuildMarkersForZoom(bikes) {
|
||||||
|
setupClusterListener();
|
||||||
|
if (bikeBubbleLayer) bikeBubbleLayer.setData(bikes ?? Object.values<any>(S.markersData));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 车辆详情 ==========
|
||||||
|
// 卡片顶部按钮是否收成纯图标:不按屏宽猜,直接量车牌有没有被截断。
|
||||||
|
// 车牌越长越早收;收起后再量一次,仍截断就保持(空间真不够了)。
|
||||||
@@ -0,0 +1,750 @@
|
|||||||
|
/* 由 static/js/{navigation,share,subscribe,map}.js 逐块搬运而来;正文与原实现一致。 */
|
||||||
|
|
||||||
|
import { S } from "../core/state";
|
||||||
|
import { _fitCardActions, closeCard } from "../card/bike-card";
|
||||||
|
import { calcDistance, offsetCoord } from "../core/geo";
|
||||||
|
import { MAX_WALK_DISTANCE_M } from "./walk-route";
|
||||||
|
import { showToast } from "../ui/modals";
|
||||||
|
// static/js/navigation.js:111-111
|
||||||
|
export let _nav: any = null;
|
||||||
|
|
||||||
|
// static/js/navigation.js:112-113
|
||||||
|
let _navLoading: any = false;
|
||||||
|
// 每次 start/stop 都自增;await 回来发现变了就说明中途被关掉了,别再自动开起来
|
||||||
|
|
||||||
|
// static/js/navigation.js:114-117
|
||||||
|
let _navEpoch: any = 0;
|
||||||
|
|
||||||
|
// 偏航阈值:百度会把起点吸附到最近道路,和真实 GPS 天然差 20~50 米,
|
||||||
|
// 所以阈值不能太小,且重算要有冷却,否则会陷入"重算->又偏->再重算"。
|
||||||
|
|
||||||
|
// static/js/navigation.js:118-118
|
||||||
|
const NAV_DEVIATE_M = 60;
|
||||||
|
|
||||||
|
// static/js/navigation.js:119-120
|
||||||
|
const NAV_RECOMPUTE_COOLDOWN_MS = 12000;
|
||||||
|
// 偏差在这个范围内就把箭头吸附到路线上(10 米内才贴线,超过了就老实显示真实位置)
|
||||||
|
|
||||||
|
// static/js/navigation.js:121-121
|
||||||
|
const NAV_SNAP_M = 10;
|
||||||
|
|
||||||
|
// static/js/navigation.js:122-122
|
||||||
|
const NAV_BOTTOM_RATIO = 0.20; // 当前位置压在屏幕下方约 80% 高度处
|
||||||
|
|
||||||
|
// static/js/navigation.js:123-123
|
||||||
|
const NAV_FREE_TIMEOUT = 8000; // 拖动后多久自动回正
|
||||||
|
|
||||||
|
// static/js/navigation.js:125-135
|
||||||
|
export function _haversineM(lat1, lng1, lat2, lng2) {
|
||||||
|
const R = 6371000;
|
||||||
|
const dLat = (lat2 - lat1) * Math.PI / 180;
|
||||||
|
const dLng = (lng2 - lng1) * Math.PI / 180;
|
||||||
|
const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
|
||||||
|
Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
|
||||||
|
Math.sin(dLng / 2) * Math.sin(dLng / 2);
|
||||||
|
return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 浏览器定位给的是 WGS84,转成 GCJ02 才能和百度/上游坐标对齐
|
||||||
|
|
||||||
|
// static/js/navigation.js:136-147
|
||||||
|
export function _gpsToGcj(coords) {
|
||||||
|
const lat = coords.latitude, lng = coords.longitude;
|
||||||
|
if (typeof coordtransform !== "undefined" && coordtransform.wgs84togcj02) {
|
||||||
|
try {
|
||||||
|
const g = coordtransform.wgs84togcj02(lng, lat); // -> [lng, lat]
|
||||||
|
return { lat: g[1], lng: g[0] };
|
||||||
|
} catch (e) { /* 落到下面原值兜底 */ }
|
||||||
|
}
|
||||||
|
return { lat: lat, lng: lng };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 航向角:0=正北,90=正东
|
||||||
|
|
||||||
|
// static/js/navigation.js:148-157
|
||||||
|
export function _bearing(from, to) {
|
||||||
|
const p1 = from.lat * Math.PI / 180, p2 = to.lat * Math.PI / 180;
|
||||||
|
const dl = (to.lng - from.lng) * Math.PI / 180;
|
||||||
|
const y = Math.sin(dl) * Math.cos(p2);
|
||||||
|
const x = Math.cos(p1) * Math.sin(p2) - Math.sin(p1) * Math.cos(p2) * Math.cos(dl);
|
||||||
|
return (Math.atan2(y, x) * 180 / Math.PI + 360) % 360;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 当前位置在折线上的最近点(投影到线段上,不是只找最近顶点)
|
||||||
|
// 返回 {index, meters, point};point 为线段上的插值点
|
||||||
|
|
||||||
|
// static/js/navigation.js:158-184
|
||||||
|
export function _projectOnRoute(ptsBD, point) {
|
||||||
|
if (!ptsBD || ptsBD.length === 0) return { index: 0, meters: Infinity, point: point };
|
||||||
|
if (ptsBD.length === 1) {
|
||||||
|
return { index: 0, meters: _haversineM(point.lat, point.lng, ptsBD[0].lat, ptsBD[0].lng),
|
||||||
|
point: ptsBD[0] };
|
||||||
|
}
|
||||||
|
const cosLat = Math.cos(point.lat * Math.PI / 180);
|
||||||
|
const toXY = (p) => [
|
||||||
|
(p.lng - point.lng) * 111320 * cosLat,
|
||||||
|
(p.lat - point.lat) * 110540
|
||||||
|
];
|
||||||
|
let bestI = 0, bestM = Infinity, bestT = 0;
|
||||||
|
for (let i = 0; i < ptsBD.length - 1; i++) {
|
||||||
|
const a = toXY(ptsBD[i]), b = toXY(ptsBD[i + 1]);
|
||||||
|
const dx = b[0] - a[0], dy = b[1] - a[1];
|
||||||
|
const seg2 = dx * dx + dy * dy;
|
||||||
|
// 查询点是原点 (0,0),投影参数 t 落在 [0,1]
|
||||||
|
const t = seg2 === 0 ? 0 : Math.max(0, Math.min(1, -(a[0] * dx + a[1] * dy) / seg2));
|
||||||
|
const cx = a[0] + t * dx, cy = a[1] + t * dy;
|
||||||
|
const d = Math.hypot(cx, cy);
|
||||||
|
if (d < bestM) { bestM = d; bestI = i; bestT = t; }
|
||||||
|
}
|
||||||
|
const a = ptsBD[bestI], b = ptsBD[bestI + 1];
|
||||||
|
const p = new BMapGL.Point(a.lng + bestT * (b.lng - a.lng),
|
||||||
|
a.lat + bestT * (b.lat - a.lat));
|
||||||
|
return { index: bestI, meters: bestM, point: p };
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/navigation.js:186-189
|
||||||
|
export function _navBanner(show) {
|
||||||
|
const el = document.getElementById("nav-banner");
|
||||||
|
if (el) el.hidden = !show;
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/navigation.js:191-194
|
||||||
|
export function _navPill(show) {
|
||||||
|
const el = document.getElementById("nav-resume");
|
||||||
|
if (el) el.hidden = !show;
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/navigation.js:196-201
|
||||||
|
export function _navBtnText(text) {
|
||||||
|
const el = document.getElementById("bike-nav-btn-text");
|
||||||
|
if (el) el.textContent = text;
|
||||||
|
// 「导航」和「结束」宽度不同,换字后重新量一次是否还放得下
|
||||||
|
if (typeof _fitCardActions === "function") _fitCardActions();
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/navigation.js:203-211
|
||||||
|
export function _clearNavLayers() {
|
||||||
|
if (!_nav) return;
|
||||||
|
(_nav.walking || []).forEach(ov => { try { S.map.removeOverlay(ov); } catch (e) {} });
|
||||||
|
(_nav.remaining || []).forEach(ov => { try { S.map.removeOverlay(ov); } catch (e) {} });
|
||||||
|
if (_nav.endMarker) { try { S.map.removeOverlay(_nav.endMarker); } catch (e) {} }
|
||||||
|
_nav.walking = []; _nav.remaining = []; _nav.endMarker = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 按进度把折线切成「已走(灰)」与「剩余(蓝)」
|
||||||
|
|
||||||
|
// static/js/navigation.js:212-247
|
||||||
|
export function _redrawRoute(fromIndex) {
|
||||||
|
if (!_nav || !_nav.ptsBD || !_nav.ptsBD.length) return;
|
||||||
|
_clearNavLayers();
|
||||||
|
const pts = _nav.ptsBD;
|
||||||
|
const cut = Math.max(0, Math.min(fromIndex, pts.length - 1));
|
||||||
|
|
||||||
|
if (cut > 0) {
|
||||||
|
const walked = new BMapGL.Polyline(pts.slice(0, cut + 1), {
|
||||||
|
strokeColor: "#9E9E9E", strokeWeight: 6, strokeOpacity: 0.85,
|
||||||
|
strokeStyle: "solid"
|
||||||
|
});
|
||||||
|
S.map.addOverlay(walked);
|
||||||
|
_nav.walking.push(walked);
|
||||||
|
}
|
||||||
|
if (cut < pts.length - 1) {
|
||||||
|
const rest = pts.slice(cut);
|
||||||
|
const casing = new BMapGL.Polyline(rest, {
|
||||||
|
strokeColor: "#FFFFFF", strokeWeight: 11, strokeOpacity: 0.95,
|
||||||
|
strokeStyle: "solid"
|
||||||
|
});
|
||||||
|
const line = new BMapGL.Polyline(rest, {
|
||||||
|
strokeColor: "#0A84FF", strokeWeight: 6, strokeOpacity: 1,
|
||||||
|
strokeStyle: "solid"
|
||||||
|
});
|
||||||
|
S.map.addOverlay(casing);
|
||||||
|
S.map.addOverlay(line);
|
||||||
|
_nav.remaining.push(casing, line);
|
||||||
|
}
|
||||||
|
if (!_nav.endMarker) {
|
||||||
|
_nav.endMarker = new BMapGL.Marker(pts[pts.length - 1], { icon: _destIcon() });
|
||||||
|
S.map.addOverlay(_nav.endMarker);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 跟随:把当前位置压到屏幕下方,并让行进方向朝上
|
||||||
|
// 部分环境(例如 WebGL 软件渲染)setHeading 不生效,探测一次后退化为「正北朝上」
|
||||||
|
|
||||||
|
// static/js/navigation.js:248-248
|
||||||
|
let _headingSupported: any = null;
|
||||||
|
|
||||||
|
// static/js/navigation.js:249-252
|
||||||
|
let _headingAnim: any = null;
|
||||||
|
|
||||||
|
// 文档化的旋转方式:ViewAnimation 关键帧里的 heading
|
||||||
|
// (setHeading 是没写进文档的私有方法,见 docs/baidu-map-gl-cheatsheet.md 坑 1)
|
||||||
|
|
||||||
|
// static/js/navigation.js:253-269
|
||||||
|
export function _rotateByAnimation(deg) {
|
||||||
|
try {
|
||||||
|
if (typeof BMapGL.ViewAnimation !== "function") return false;
|
||||||
|
const from = (typeof S.map.getHeading === "function" ? S.map.getHeading() : 0) || 0;
|
||||||
|
if (_headingAnim && S.map.cancelViewAnimation) {
|
||||||
|
try { S.map.cancelViewAnimation(_headingAnim); } catch (e) {}
|
||||||
|
}
|
||||||
|
_headingAnim = new BMapGL.ViewAnimation([
|
||||||
|
{ heading: from, percentage: 0 },
|
||||||
|
{ heading: deg, percentage: 1 }
|
||||||
|
], { duration: 260 });
|
||||||
|
S.map.startViewAnimation(_headingAnim);
|
||||||
|
return true;
|
||||||
|
} catch (e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/navigation.js:271-302
|
||||||
|
export function _applyHeading(deg) {
|
||||||
|
if (_headingSupported === false) return;
|
||||||
|
try {
|
||||||
|
if (typeof S.map.setHeading !== "function") { _headingSupported = false; return; }
|
||||||
|
S.map.setHeading(deg);
|
||||||
|
if (_headingSupported === null) {
|
||||||
|
const got = typeof S.map.getHeading === "function" ? S.map.getHeading() : undefined;
|
||||||
|
// 调了 45 度结果还是 0,说明这个环境不支持地图旋转
|
||||||
|
_headingSupported = (typeof got === "number" && Math.abs(got) > 0.5);
|
||||||
|
if (!_headingSupported) {
|
||||||
|
console.info("[导航] 当前环境不支持 setHeading,尝试 ViewAnimation 旋转");
|
||||||
|
// 关键:有些 WebGL 环境调完 setHeading 会留下坏的相机状态,
|
||||||
|
// 表现为整张底图变黑。这里复位并把视野重新设一次,把瓦片拉回来。
|
||||||
|
try { if (S.map.resetHeading) S.map.resetHeading(); } catch (e) {}
|
||||||
|
try {
|
||||||
|
const c = S.map.getCenter ? S.map.getCenter() : null;
|
||||||
|
if (c) S.map.setCenter(c);
|
||||||
|
} catch (e) {}
|
||||||
|
// 文档化兜底:ViewAnimation 关键帧旋转
|
||||||
|
if (_rotateByAnimation(deg)) {
|
||||||
|
_headingSupported = true;
|
||||||
|
console.info("[导航] ViewAnimation 旋转可用");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) { _headingSupported = false; }
|
||||||
|
}
|
||||||
|
|
||||||
|
// 迁就百度的一个坑:setCenter 会把刚设置的 heading 抹回 0,
|
||||||
|
// 必须在它的回调里再 setHeading(官方 setCenter 支持 callback,动画结束后触发)。
|
||||||
|
// 另一个坑:BMapGL 的 heading 是**逆时针**角度,要让行进方向朝上必须传 -方位角。
|
||||||
|
//(实测方位角 145° 时:setHeading(145) 前方在左上;setHeading(-145) 前方正上方)
|
||||||
|
|
||||||
|
// static/js/navigation.js:303-330
|
||||||
|
export function _centerOnUser(point, headingDeg) {
|
||||||
|
const h = window.innerHeight || 800;
|
||||||
|
const offsetY = Math.round(h * NAV_BOTTOM_RATIO);
|
||||||
|
const mapHeading = (typeof headingDeg === "number") ? -headingDeg : null;
|
||||||
|
_markProgrammaticMove();
|
||||||
|
try {
|
||||||
|
S.map.setCenter(point, {
|
||||||
|
noAnimation: true,
|
||||||
|
callback: function () {
|
||||||
|
if (mapHeading !== null) _applyHeading(mapHeading);
|
||||||
|
try {
|
||||||
|
// 把「我」推到屏幕下方:地图整体上移
|
||||||
|
if (S.map.panBy) S.map.panBy(0, offsetY);
|
||||||
|
} catch (e) {}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
// 老版本 setCenter 不支持 options,退回手动顺序
|
||||||
|
try {
|
||||||
|
S.map.setCenter(point);
|
||||||
|
if (mapHeading !== null) _applyHeading(mapHeading);
|
||||||
|
if (S.map.panBy) S.map.panBy(0, offsetY);
|
||||||
|
} catch (e2) { /* 忽略 */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 罗盘 + 导航箭头 ==========
|
||||||
|
// 手机朝向(罗盘):iOS 用 webkitCompassHeading,安卓用 360 - alpha
|
||||||
|
|
||||||
|
// static/js/navigation.js:331-331
|
||||||
|
let _compassHeading: any = null;
|
||||||
|
|
||||||
|
// static/js/navigation.js:332-332
|
||||||
|
let _compassBound: any = false;
|
||||||
|
|
||||||
|
// static/js/navigation.js:334-350
|
||||||
|
export function _bindCompass() {
|
||||||
|
if (_compassBound) return;
|
||||||
|
_compassBound = true;
|
||||||
|
const onOrient = (e) => {
|
||||||
|
let h = null;
|
||||||
|
if (typeof e.webkitCompassHeading === "number") {
|
||||||
|
h = e.webkitCompassHeading; // iOS:已经是「相对正北的顺时针角度」
|
||||||
|
} else if (typeof e.alpha === "number") {
|
||||||
|
h = (360 - e.alpha) % 360; // 安卓:alpha 是逆时针
|
||||||
|
}
|
||||||
|
if (h !== null && Number.isFinite(h)) _compassHeading = h;
|
||||||
|
};
|
||||||
|
window.addEventListener("deviceorientationabsolute", onOrient, true);
|
||||||
|
window.addEventListener("deviceorientation", onOrient, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
// iOS 13+ 必须由用户手势触发权限申请;导航按钮的点击正好是手势
|
||||||
|
|
||||||
|
// static/js/navigation.js:351-364
|
||||||
|
export async function _ensureCompassPermission() {
|
||||||
|
const D: any = (window as any).DeviceOrientationEvent;
|
||||||
|
try {
|
||||||
|
if (D && typeof D.requestPermission === "function") {
|
||||||
|
const res = await D.requestPermission();
|
||||||
|
if (res !== "granted") {
|
||||||
|
console.info("[导航] 未获得方向传感器权限,箭头改用行进方向");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) { /* 用户拒绝或非 iOS */ }
|
||||||
|
_bindCompass();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 导航箭头图标(向上指,旋转由 Marker.setRotation 控制)
|
||||||
|
|
||||||
|
// static/js/navigation.js:365-375
|
||||||
|
export function _navArrowIcon() {
|
||||||
|
const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="72" height="72" viewBox="0 0 72 72">'
|
||||||
|
+ '<circle cx="36" cy="36" r="30" fill="#0A84FF" fill-opacity="0.16"/>'
|
||||||
|
+ '<path d="M36 10 L52 52 L36 43 L20 52 Z" fill="#0A84FF" stroke="#FFFFFF"'
|
||||||
|
+ ' stroke-width="3" stroke-linejoin="round"/></svg>';
|
||||||
|
const url = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(svg);
|
||||||
|
return new BMapGL.Icon(url, new BMapGL.Size(36, 36),
|
||||||
|
{ anchor: new BMapGL.Size(18, 18) });
|
||||||
|
}
|
||||||
|
|
||||||
|
// 转弯/掉头/直行的图标(画在导航条文字左边,不再画到地图上)
|
||||||
|
|
||||||
|
// static/js/navigation.js:376-382
|
||||||
|
export function _turnKind(turnType) {
|
||||||
|
const t = String(turnType || "");
|
||||||
|
if (t.indexOf("掉头") >= 0) return "uturn";
|
||||||
|
if (t.indexOf("左") >= 0) return "left";
|
||||||
|
if (t.indexOf("右") >= 0) return "right";
|
||||||
|
return "straight";
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/navigation.js:384-394
|
||||||
|
export function _turnSvg(kind) {
|
||||||
|
const paths = {
|
||||||
|
straight: '<path d="M24 42 L24 12" /><path d="M14 22 L24 10 L34 22" />',
|
||||||
|
left: '<path d="M34 42 L34 22 L16 22" /><path d="M24 12 L12 22 L24 32" />',
|
||||||
|
right: '<path d="M14 42 L14 22 L32 22" /><path d="M30 12 L42 22 L30 32" />',
|
||||||
|
uturn: '<path d="M18 42 L18 18 A8 8 0 0 1 34 18 L34 26" /><path d="M26 20 L34 10 L42 20" />'
|
||||||
|
};
|
||||||
|
const body = paths[kind] || paths.straight;
|
||||||
|
return '<svg viewBox="0 0 48 48" fill="none" stroke="currentColor" stroke-width="4.5"'
|
||||||
|
+ ' stroke-linecap="round" stroke-linejoin="round">' + body + '</svg>';
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/navigation.js:396-404
|
||||||
|
export function _setTurnIcon(kind) {
|
||||||
|
const el = document.getElementById("nav-banner-turn");
|
||||||
|
if (!el) return;
|
||||||
|
if (el.__kind === kind) return; // 同一个图标不重复写 DOM
|
||||||
|
el.__kind = kind;
|
||||||
|
el.innerHTML = _turnSvg(kind);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 目的地图标(SVG 定位针,底端对准坐标点)
|
||||||
|
|
||||||
|
// static/js/navigation.js:405-412
|
||||||
|
export function _destIcon() {
|
||||||
|
const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="64" height="76" viewBox="0 0 32 38">'
|
||||||
|
+ '<path d="M16 36C16 36 30 22.5 30 14A14 14 0 1 0 2 14C2 22.5 16 36 16 36Z"'
|
||||||
|
+ ' fill="#FF3B30" stroke="#FFFFFF" stroke-width="2.4"/>'
|
||||||
|
+ '<circle cx="16" cy="14" r="5" fill="#FFFFFF"/></svg>';
|
||||||
|
const url = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(svg);
|
||||||
|
return new BMapGL.Icon(url, new BMapGL.Size(30, 36), { anchor: new BMapGL.Size(15, 36) });
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/navigation.js:414-424
|
||||||
|
export function _placeNavArrow(point) {
|
||||||
|
if (!_nav) return;
|
||||||
|
if (!_nav.arrow) {
|
||||||
|
_nav.arrow = new BMapGL.Marker(point, { icon: _navArrowIcon() });
|
||||||
|
S.map.addOverlay(_nav.arrow);
|
||||||
|
// 导航时用箭头代替原来的蓝点
|
||||||
|
try { if (typeof S.autoLocationMarker !== "undefined" && S.autoLocationMarker) S.autoLocationMarker.hide(); } catch (e) {}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try { _nav.arrow.setPosition(point); } catch (e) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/navigation.js:426-429
|
||||||
|
export function _rotateNavArrow(deg) {
|
||||||
|
if (!_nav || !_nav.arrow) return;
|
||||||
|
try { if (typeof _nav.arrow.setRotation === "function") _nav.arrow.setRotation(deg); } catch (e) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/navigation.js:431-437
|
||||||
|
export function _clearNavArrow() {
|
||||||
|
if (_nav && _nav.arrow) {
|
||||||
|
try { S.map.removeOverlay(_nav.arrow); } catch (e) {}
|
||||||
|
_nav.arrow = null;
|
||||||
|
}
|
||||||
|
try { if (typeof S.autoLocationMarker !== "undefined" && S.autoLocationMarker) S.autoLocationMarker.show(); } catch (e) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/navigation.js:439-505
|
||||||
|
export function _navTick(position) {
|
||||||
|
if (!_nav || _nav.follow === false) return; // 拖动查看时不抢镜头
|
||||||
|
const gcj = _gpsToGcj(position); // WGS84 -> GCJ02
|
||||||
|
const c = offsetCoord(gcj.lat, gcj.lng); // GCJ02 -> BD09
|
||||||
|
const me = new BMapGL.Point(c.lng, c.lat);
|
||||||
|
|
||||||
|
const proj = _projectOnRoute(_nav.ptsBD, me);
|
||||||
|
const now = Date.now();
|
||||||
|
if (proj.meters > NAV_DEVIATE_M && !_nav.recomputing
|
||||||
|
&& now - (_nav.lastRecomputeAt || 0) > NAV_RECOMPUTE_COOLDOWN_MS) {
|
||||||
|
_nav.recomputing = true;
|
||||||
|
_nav.lastRecomputeAt = now;
|
||||||
|
_recomputeRoute(gcj).finally(() => { if (_nav) _nav.recomputing = false; });
|
||||||
|
return; // 本帧不更新进度,等新路线
|
||||||
|
}
|
||||||
|
if (proj.index !== _nav.idx) {
|
||||||
|
_nav.idx = proj.index;
|
||||||
|
_redrawRoute(_nav.idx);
|
||||||
|
}
|
||||||
|
// 箭头位置:偏差在吸附范围内就贴到路线上,否则用真实位置
|
||||||
|
const anchor = (proj.meters <= NAV_SNAP_M && proj.point) ? proj.point : me;
|
||||||
|
// 朝向:沿路线往后看几个点算切线,比"我→下一个点"稳得多(GPS 抖动不会乱转)
|
||||||
|
const aheadIdx = Math.min(proj.index + 3, _nav.ptsBD.length - 1);
|
||||||
|
const travelHeading = _bearing(_nav.ptsBD[proj.index], _nav.ptsBD[aheadIdx]);
|
||||||
|
_placeNavArrow(anchor);
|
||||||
|
// 地图始终按「行进方向」朝上(不跟手机朝向)
|
||||||
|
const mapDeg = (_headingSupported === false) ? 0 : travelHeading;
|
||||||
|
// 箭头指手机朝向;没有罗盘权限就让它跟着行进方向(朝前)
|
||||||
|
const arrowDeg = (typeof _compassHeading === "number")
|
||||||
|
? (_compassHeading - mapDeg)
|
||||||
|
: 0;
|
||||||
|
_rotateNavArrow(arrowDeg);
|
||||||
|
_centerOnUser(anchor, travelHeading);
|
||||||
|
|
||||||
|
// 剩余距离/时间(按进度线性折算,仅用于展示)
|
||||||
|
const total = _nav.ptsBD.length - 1;
|
||||||
|
const ratio = total > 0 ? Math.max(0, 1 - _nav.idx / total) : 0;
|
||||||
|
const leftM = Math.round((_nav.distance || 0) * ratio);
|
||||||
|
const leftS = Math.round((_nav.duration || 0) * ratio);
|
||||||
|
const travelled = (_nav.distance || 0) * (total > 0 ? _nav.idx / total : 0);
|
||||||
|
|
||||||
|
// 第一行:当前指引「前方 120 米 右前方转弯」
|
||||||
|
const actEl = document.getElementById("nav-banner-action");
|
||||||
|
if (actEl) {
|
||||||
|
const guide = _navGuidance(travelled);
|
||||||
|
if (guide.text) actEl.textContent = guide.text;
|
||||||
|
_setTurnIcon(guide.kind);
|
||||||
|
}
|
||||||
|
// 第二行:剩余距离与时间
|
||||||
|
const bannerText = document.getElementById("nav-banner-text");
|
||||||
|
if (bannerText) {
|
||||||
|
bannerText.textContent = leftM < 1000
|
||||||
|
? "剩余 " + leftM + " 米 · 约 " + Math.max(1, Math.round(leftS / 60)) + " 分钟"
|
||||||
|
: "剩余 " + (leftM / 1000).toFixed(1) + " 公里 · 约 " +
|
||||||
|
Math.max(1, Math.round(leftS / 60)) + " 分钟";
|
||||||
|
}
|
||||||
|
// 到达判定用「到终点的真实距离」,避免 GPS 抖动跳点就结束导航
|
||||||
|
const dest = _nav.ptsBD[_nav.ptsBD.length - 1];
|
||||||
|
const toDest = _haversineM(me.lat, me.lng, dest.lat, dest.lng);
|
||||||
|
if (toDest < 25) {
|
||||||
|
showToast("已到达车辆附近");
|
||||||
|
stopNavigation();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 当前该播报哪一段:按「已走里程」在分段累计距离里定位
|
||||||
|
// 返回 { text: 文案, kind: straight|left|right|uturn },kind 用来画导航条左边的图标
|
||||||
|
|
||||||
|
// static/js/navigation.js:506-531
|
||||||
|
export function _navGuidance(travelled) {
|
||||||
|
if (!_nav || !_nav.stepEnds || !_nav.stepEnds.length) {
|
||||||
|
return { text: "", kind: "straight" };
|
||||||
|
}
|
||||||
|
const ends = _nav.stepEnds;
|
||||||
|
const steps = _nav.steps || [];
|
||||||
|
let i = ends.findIndex(e => e > travelled);
|
||||||
|
const isLast = (i === -1) || (i >= ends.length - 1);
|
||||||
|
if (i === -1) i = ends.length - 1;
|
||||||
|
const left = Math.max(0, Math.round(ends[i] - travelled));
|
||||||
|
if (isLast) {
|
||||||
|
return {
|
||||||
|
text: left > 5 ? "前方 " + left + " 米 到达目的地" : "即将到达目的地",
|
||||||
|
kind: "straight"
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const step = steps[i] || {};
|
||||||
|
// 优先用转向名(右前方转弯/左转…),没有就用指引文本的最后一小段
|
||||||
|
let action = step.turn || "";
|
||||||
|
if (!action && step.text) {
|
||||||
|
const parts = step.text.split(/[,,]/);
|
||||||
|
action = parts[parts.length - 1] || step.text;
|
||||||
|
}
|
||||||
|
if (!action) action = "继续前行";
|
||||||
|
return { text: "前方 " + left + " 米 " + action, kind: _turnKind(step.turn) };
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/navigation.js:533-549
|
||||||
|
export async function _recomputeRoute(gcj) { // gcj = {lat, lng}(GCJ02)
|
||||||
|
if (!_nav || !_nav.destLat) return;
|
||||||
|
// 快照:重算期间用户可能点了「结束导航」或改导航到另一辆车,
|
||||||
|
// 回包若不再属于这次导航就必须丢弃,否则旧路线会盖掉新导航。
|
||||||
|
const myNav = _nav;
|
||||||
|
const epoch = _navEpoch;
|
||||||
|
try {
|
||||||
|
const data = await _requestNavRoute(gcj.lat, gcj.lng,
|
||||||
|
_nav.destLat, _nav.destLng);
|
||||||
|
if (!data) return;
|
||||||
|
if (_nav !== myNav || epoch !== _navEpoch || !_nav) return;
|
||||||
|
_applyRoute(data);
|
||||||
|
showToast("已重新规划路线");
|
||||||
|
} catch (e) {
|
||||||
|
console.warn("[导航] 重算失败", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/navigation.js:551-570
|
||||||
|
export async function _requestNavRoute(originLat, originLng, destLat, destLng) {
|
||||||
|
const url = "/api/nav_route?mode=walking"
|
||||||
|
+ "&origin_lat=" + originLat + "&origin_lng=" + originLng
|
||||||
|
+ "&dest_lat=" + destLat + "&dest_lng=" + destLng;
|
||||||
|
const resp = await fetch(url, { headers: { "Authorization": "Bearer " + S.authToken } });
|
||||||
|
const json = await resp.json();
|
||||||
|
const d = json && json.data;
|
||||||
|
if (json.rtn_code !== 0 || !d || !d.points || !d.points.length) {
|
||||||
|
const msg = (json && json.message) || "没有拿到路线";
|
||||||
|
const err: any = new Error(msg);
|
||||||
|
// 后端已挡掉超远距离;这里再认一次文案,前端可静默处理
|
||||||
|
if (json && (json.error_kind === "too_far" || /太远|200Km/i.test(msg))) {
|
||||||
|
err.tooFar = true;
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
return d;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 用接口结果重建导航状态(首次与重算共用)
|
||||||
|
|
||||||
|
// static/js/navigation.js:571-590
|
||||||
|
export function _applyRoute(d) {
|
||||||
|
_nav.ptsGcj = d.points;
|
||||||
|
_nav.ptsBD = d.points.map(pt => {
|
||||||
|
const c = offsetCoord(pt[1], pt[0]);
|
||||||
|
return new BMapGL.Point(c.lng, c.lat);
|
||||||
|
});
|
||||||
|
_nav.distance = d.distance;
|
||||||
|
_nav.duration = d.duration;
|
||||||
|
_nav.idx = 0;
|
||||||
|
_nav.recomputing = false;
|
||||||
|
// 分段指引:把 steps 的累计距离算出来,tick 里按「已走里程」定位当前段
|
||||||
|
_nav.steps = (d.steps || []).map(s => ({
|
||||||
|
distance: s.distance || 0,
|
||||||
|
turn: s.turn_type || "",
|
||||||
|
text: String(s.instruction || "").replace(/<[^>]+>/g, "")
|
||||||
|
}));
|
||||||
|
let acc = 0;
|
||||||
|
_nav.stepEnds = _nav.steps.map(s => (acc += s.distance));
|
||||||
|
_redrawRoute(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/navigation.js:592-606
|
||||||
|
export function stopNavigation() {
|
||||||
|
_navEpoch++; // 让还在 await 的 startNavigation 作废
|
||||||
|
if (_nav && _nav.watchId !== null && navigator.geolocation) {
|
||||||
|
navigator.geolocation.clearWatch(_nav.watchId);
|
||||||
|
}
|
||||||
|
if (_nav && _nav.timer) clearTimeout(_nav.timer);
|
||||||
|
_clearNavLayers();
|
||||||
|
_clearNavArrow();
|
||||||
|
_nav = null;
|
||||||
|
_navBanner(false);
|
||||||
|
_navPill(false);
|
||||||
|
_navBtnText("导航");
|
||||||
|
try { if (S.map.resetHeading) S.map.resetHeading(); } catch (e) {}
|
||||||
|
_headingSupported = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/navigation.js:608-620
|
||||||
|
export function toggleNavigation() {
|
||||||
|
const bike = S.selectedBike;
|
||||||
|
if (!bike) return;
|
||||||
|
if (_nav && String(_nav.destCode) === String(bike.code)) {
|
||||||
|
stopNavigation();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
startNavigation(bike);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 拖动地图后:显示「返回导航」,超时自动回正。
|
||||||
|
// 注意:移动端 dragend 经常不触发,所以计时器从 dragstart 就开始,
|
||||||
|
// 并且在 dragging/moving 里不断续期——手指一离开就重新倒计时。
|
||||||
|
|
||||||
|
// static/js/navigation.js:621-621
|
||||||
|
let _navSelfMoveUntil: any = 0; // 我们自己调 setCenter/panBy 的时间窗,避免误判成用户拖动
|
||||||
|
|
||||||
|
// static/js/navigation.js:622-622
|
||||||
|
export function _markProgrammaticMove() { _navSelfMoveUntil = Date.now() + 250; }
|
||||||
|
|
||||||
|
// static/js/navigation.js:624-630
|
||||||
|
export function _scheduleResume() {
|
||||||
|
if (!_nav) return;
|
||||||
|
if (_nav.timer) clearTimeout(_nav.timer);
|
||||||
|
_nav.timer = setTimeout(() => {
|
||||||
|
if (_nav && _nav.follow === false) resumeNavigation();
|
||||||
|
}, NAV_FREE_TIMEOUT);
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/navigation.js:632-638
|
||||||
|
export function _onMapDragStart() {
|
||||||
|
if (!_nav) return;
|
||||||
|
if (Date.now() < _navSelfMoveUntil) return; // 我们自己挪的,不算用户操作
|
||||||
|
_nav.follow = false;
|
||||||
|
_navPill(true);
|
||||||
|
_scheduleResume();
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/navigation.js:640-643
|
||||||
|
export function _onMapDragging() {
|
||||||
|
if (!_nav || _nav.follow !== false) return;
|
||||||
|
_scheduleResume(); // 还在拖,续期
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/navigation.js:645-648
|
||||||
|
export function _onMapDragEnd() {
|
||||||
|
if (!_nav || _nav.follow !== false) return;
|
||||||
|
_scheduleResume();
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/navigation.js:650-664
|
||||||
|
export function resumeNavigation() {
|
||||||
|
if (!_nav) return;
|
||||||
|
_nav.follow = true;
|
||||||
|
_navPill(false);
|
||||||
|
if (_nav.timer) { clearTimeout(_nav.timer); _nav.timer = null; }
|
||||||
|
// 回到行进方向并重新居中(用路线切线,别用"我→下一点")
|
||||||
|
const i = Math.min(_nav.idx, _nav.ptsBD.length - 1);
|
||||||
|
const j = Math.min(i + 3, _nav.ptsBD.length - 1);
|
||||||
|
const heading = _bearing(_nav.ptsBD[i], _nav.ptsBD[j]);
|
||||||
|
const me = (typeof S.autoLocationMarker !== "undefined" && S.autoLocationMarker)
|
||||||
|
? S.autoLocationMarker.getPosition() : null;
|
||||||
|
const anchor = me || _nav.ptsBD[i];
|
||||||
|
_placeNavArrow(anchor);
|
||||||
|
_centerOnUser(anchor, heading);
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/navigation.js:666-760
|
||||||
|
export async function startNavigation(bike) {
|
||||||
|
if (_navLoading) return;
|
||||||
|
const me = (typeof S.autoLocationMarker !== "undefined" && S.autoLocationMarker)
|
||||||
|
? S.autoLocationMarker.getPosition() : null;
|
||||||
|
if (!me) { showToast("请先开启定位,才能规划路线"); return; }
|
||||||
|
if (!bike || !bike.latitude || !bike.longitude) {
|
||||||
|
showToast("这辆车没有坐标,无法导航"); return;
|
||||||
|
}
|
||||||
|
// 兜底:太远就不导航(卡片上「导航」按钮本身已隐藏,正常点不到这里)。
|
||||||
|
// 百度步行路线有 200km 上限,超了会返回 status=2 的英文报错,不要把它抛给用户。
|
||||||
|
try {
|
||||||
|
const dest = offsetCoord(bike.latitude, bike.longitude); // GCJ02 -> BD09
|
||||||
|
const straight = calcDistance(me.lat, me.lng, dest.lat, dest.lng);
|
||||||
|
if (Number.isFinite(straight) && straight >= MAX_WALK_DISTANCE_M) return;
|
||||||
|
} catch (e) { /* 距离算不出来就照常尝试 */ }
|
||||||
|
|
||||||
|
if (_nav) stopNavigation();
|
||||||
|
const epoch = ++_navEpoch;
|
||||||
|
_navLoading = true;
|
||||||
|
_navBanner(true);
|
||||||
|
const bannerText = document.getElementById("nav-banner-text");
|
||||||
|
if (bannerText) bannerText.textContent = "正在规划路线…";
|
||||||
|
|
||||||
|
try {
|
||||||
|
let gcj = null;
|
||||||
|
if (typeof coordtransform !== "undefined" && coordtransform.bd09togcj02) {
|
||||||
|
gcj = coordtransform.bd09togcj02(me.lng, me.lat);
|
||||||
|
}
|
||||||
|
if (!gcj) throw new Error("坐标转换不可用");
|
||||||
|
|
||||||
|
const d = await _requestNavRoute(gcj[1], gcj[0], bike.latitude, bike.longitude);
|
||||||
|
|
||||||
|
// 路线回来时卡片已经被关掉了:直接放弃,不要把导航又"It's on"起来
|
||||||
|
if (epoch !== _navEpoch) {
|
||||||
|
_navBanner(false);
|
||||||
|
_navBtnText("导航");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_nav = {
|
||||||
|
destCode: bike.code, destLat: bike.latitude, destLng: bike.longitude,
|
||||||
|
follow: true, timer: null, watchId: null,
|
||||||
|
walking: [], remaining: [], endMarker: null, idx: 0, recomputing: false
|
||||||
|
};
|
||||||
|
_applyRoute(d);
|
||||||
|
_navBtnText("结束");
|
||||||
|
|
||||||
|
// 首次定位:压到屏幕下方 + 朝行进方向
|
||||||
|
const start = _nav.ptsBD[0];
|
||||||
|
const next = _nav.ptsBD[Math.min(1, _nav.ptsBD.length - 1)];
|
||||||
|
_placeNavArrow(start);
|
||||||
|
_rotateNavArrow(_bearing(start, next));
|
||||||
|
_centerOnUser(start, _bearing(start, next));
|
||||||
|
// 罗盘权限要在用户手势里申请(导航按钮的点击就是手势)
|
||||||
|
_ensureCompassPermission();
|
||||||
|
const actEl0 = document.getElementById("nav-banner-action");
|
||||||
|
const g0 = _navGuidance(0);
|
||||||
|
if (actEl0) actEl0.textContent = g0.text || "沿路线前行";
|
||||||
|
_setTurnIcon(g0.kind);
|
||||||
|
if (bannerText) {
|
||||||
|
bannerText.textContent = d.distance < 1000
|
||||||
|
? "剩余 " + Math.round(d.distance) + " 米 · 约 " +
|
||||||
|
Math.max(1, Math.round(d.duration / 60)) + " 分钟"
|
||||||
|
: "剩余 " + (d.distance / 1000).toFixed(1) + " 公里 · 约 " +
|
||||||
|
Math.max(1, Math.round(d.duration / 60)) + " 分钟";
|
||||||
|
}
|
||||||
|
|
||||||
|
// 收起卡片:导航要占满屏幕(关卡片不会停止导航)
|
||||||
|
try { closeCard(); } catch (e) {}
|
||||||
|
|
||||||
|
// 持续跟随
|
||||||
|
if (navigator.geolocation) {
|
||||||
|
_nav.watchId = navigator.geolocation.watchPosition(
|
||||||
|
pos => _navTick(pos.coords),
|
||||||
|
err => console.warn("[导航] 定位失败", err.message),
|
||||||
|
{ enableHighAccuracy: true, maximumAge: 3000, timeout: 10000 });
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error("[导航] 失败", err);
|
||||||
|
_navBanner(false);
|
||||||
|
if (err && err.tooFar) {
|
||||||
|
// 距离太远:静默退出,不弹报错(卡片上的「导航」按钮本来也已隐藏)
|
||||||
|
_navBtnText("导航");
|
||||||
|
_nav = null;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
showToast("导航失败:" + (err && err.message ? err.message : "请稍后再试"));
|
||||||
|
if (_nav && !_nav.ptsBD) _nav = null;
|
||||||
|
} finally {
|
||||||
|
_navLoading = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 地图拖动事件(只注册一次)。map 由 map.js 在 /api/config 回来后才创建,
|
||||||
|
// 所以这里只负责「准备好就绑」;map.js 建好地图后会显式调一次 bindNavMapEvents()。
|
||||||
|
|
||||||
|
// static/js/navigation.js:761-777
|
||||||
|
export function bindNavMapEvents() {
|
||||||
|
// navigation.js 在 map.js 之前执行,此时 `let map` 还在 TDZ,
|
||||||
|
// 连 typeof 都会抛 ReferenceError,所以整段包在 try 里。
|
||||||
|
try {
|
||||||
|
if (typeof S.map === "undefined" || !S.map || !S.map.addEventListener) return false;
|
||||||
|
if (S.map.__navBound) return true;
|
||||||
|
S.map.__navBound = true;
|
||||||
|
S.map.addEventListener("dragstart", _onMapDragStart);
|
||||||
|
S.map.addEventListener("dragging", _onMapDragging);
|
||||||
|
S.map.addEventListener("dragend", _onMapDragEnd);
|
||||||
|
} catch (e) {
|
||||||
|
return false; // map 还没声明(或地图未就绪)
|
||||||
|
}
|
||||||
|
try { console.info("[导航] 已绑定地图拖动事件"); } catch (e) {}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
// 给 map.js 用(它创建完地图主动调一次)
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
/* 由 static/js/{navigation,share,subscribe,map}.js 逐块搬运而来;正文与原实现一致。 */
|
||||||
|
|
||||||
|
import { S } from "../core/state";
|
||||||
|
import { calcDistance, offsetCoord } from "../core/geo";
|
||||||
|
// static/js/navigation.js:6-8
|
||||||
|
const _walkRouteCache = new Map(); // `${code}|${我的坐标}` -> {d, t}
|
||||||
|
// 超过这个直线距离就不显示「距离/步行」——太远的车走过去没有意义,
|
||||||
|
// 而且会让百度步行规划白白消耗配额。直线估算与精算共用同一个阈值。
|
||||||
|
|
||||||
|
// static/js/navigation.js:9-9
|
||||||
|
export const MAX_WALK_DISTANCE_M = 20000;
|
||||||
|
|
||||||
|
// static/js/navigation.js:11-17
|
||||||
|
export function parseWalkDistance(text) {
|
||||||
|
const s = String(text || "");
|
||||||
|
const km = s.match(/([\d.]+)\s*公里/);
|
||||||
|
if (km) return Math.round(parseFloat(km[1]) * 1000);
|
||||||
|
const m = s.match(/([\d.]+)\s*米/);
|
||||||
|
return m ? Math.round(parseFloat(m[1])) : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/navigation.js:19-27
|
||||||
|
export function parseWalkDuration(text) {
|
||||||
|
const s = String(text || "");
|
||||||
|
let sec = 0;
|
||||||
|
const h = s.match(/([\d.]+)\s*小时/);
|
||||||
|
const min = s.match(/([\d.]+)\s*分钟/);
|
||||||
|
if (h) sec += Math.round(parseFloat(h[1]) * 3600);
|
||||||
|
if (min) sec += Math.round(parseFloat(min[1]) * 60);
|
||||||
|
return sec;
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/navigation.js:29-110
|
||||||
|
export async function refineWalkRoute(bike) {
|
||||||
|
const bikeCode = String((bike && bike.code) || "");
|
||||||
|
if (!bikeCode) return;
|
||||||
|
const me = (typeof S.autoLocationMarker !== "undefined" && S.autoLocationMarker)
|
||||||
|
? S.autoLocationMarker.getPosition() : null;
|
||||||
|
if (!me || !bike.latitude || !bike.longitude) return;
|
||||||
|
|
||||||
|
// 太远就整块不显示(与直线估算口径一致,别让精算把隐藏的行又显示回来)
|
||||||
|
const c0 = offsetCoord(bike.latitude, bike.longitude);
|
||||||
|
if (calcDistance(me.lat, me.lng, c0.lat, c0.lng) > MAX_WALK_DISTANCE_M) return;
|
||||||
|
|
||||||
|
const key = bikeCode + "|" + me.lat.toFixed(4) + "," + me.lng.toFixed(4);
|
||||||
|
|
||||||
|
const apply = (distanceM, seconds) => {
|
||||||
|
if (!S.selectedBike || String(S.selectedBike.code) !== bikeCode) return; // 已换车
|
||||||
|
const distEl = document.getElementById("card-distance");
|
||||||
|
const walkEl = document.getElementById("card-walk");
|
||||||
|
const metaLeft = document.getElementById("card-meta-left");
|
||||||
|
if (!distEl || !walkEl || !metaLeft) return;
|
||||||
|
distEl.textContent = distanceM < 1000
|
||||||
|
? `步行 ${Math.round(distanceM)} 米`
|
||||||
|
: `步行 ${(distanceM / 1000).toFixed(1)} 公里`;
|
||||||
|
walkEl.textContent = `约 ${Math.max(1, Math.round(seconds / 60))} 分钟`;
|
||||||
|
metaLeft.hidden = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
const cached = _walkRouteCache.get(key);
|
||||||
|
if (cached) { apply(cached.d, cached.t); return; }
|
||||||
|
|
||||||
|
// ① 后端(百度 Web 服务 API,需服务端 AK + SK,结果服务端缓存 7 天)
|
||||||
|
try {
|
||||||
|
const gcj = (typeof coordtransform !== "undefined" && coordtransform.bd09togcj02)
|
||||||
|
? coordtransform.bd09togcj02(me.lng, me.lat) : null;
|
||||||
|
if (gcj) {
|
||||||
|
const url = "/api/walk_route?origin_lat=" + gcj[1] + "&origin_lng=" + gcj[0]
|
||||||
|
+ "&dest_lat=" + bike.latitude + "&dest_lng=" + bike.longitude;
|
||||||
|
const resp = await fetch(url, {
|
||||||
|
headers: { "Authorization": "Bearer " + S.authToken }
|
||||||
|
});
|
||||||
|
const data = await resp.json();
|
||||||
|
const d = data && data.data;
|
||||||
|
if (data.rtn_code === 0 && d && d.distance > 0 && d.duration > 0
|
||||||
|
&& (d.source === "baidu" || d.source === "cache")) {
|
||||||
|
_walkRouteCache.set(key, { d: d.distance, t: d.duration });
|
||||||
|
apply(d.distance, d.duration);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) { /* 忽略,走 SDK */ }
|
||||||
|
|
||||||
|
// ② 浏览器端 JS API 步行规划(现成浏览器 AK,返回 "1.6公里"/"23分钟" 字符串)
|
||||||
|
try {
|
||||||
|
if (typeof BMapGL !== "undefined" && BMapGL.WalkingRoute && S.map) {
|
||||||
|
const plan = await new Promise<any>(resolve => {
|
||||||
|
let done = false;
|
||||||
|
const finish = v => { if (!done) { done = true; resolve(v); } };
|
||||||
|
const walk = new BMapGL.WalkingRoute(S.map, {
|
||||||
|
renderOptions: { map: null, panel: null },
|
||||||
|
onSearchComplete: res => {
|
||||||
|
// 退化路线(起点≈终点)时 res 可能是空壳、没有 getStatus,
|
||||||
|
// 直接调用会抛未捕获 TypeError(与原 JS 版同步修复)
|
||||||
|
let status = -1;
|
||||||
|
try {
|
||||||
|
status = (res && typeof (res as any).getStatus === "function")
|
||||||
|
? (res as any).getStatus() : -1;
|
||||||
|
} catch (e) { status = -1; }
|
||||||
|
if (status !== 0) return finish(null);
|
||||||
|
try {
|
||||||
|
const p = res.getPlan(0);
|
||||||
|
const d = parseWalkDistance(p.getDistance());
|
||||||
|
const t = parseWalkDuration(p.getDuration());
|
||||||
|
finish(d > 0 && t > 0 ? { d: d, t: t } : null);
|
||||||
|
} catch (err) { finish(null); }
|
||||||
|
}
|
||||||
|
});
|
||||||
|
walk.search(me, new BMapGL.Point(bike.longitude, bike.latitude));
|
||||||
|
setTimeout(() => finish(null), 8000);
|
||||||
|
});
|
||||||
|
if (plan) {
|
||||||
|
_walkRouteCache.set(key, plan);
|
||||||
|
apply(plan.d, plan.t);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) { /* 保留直线估算 */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 跟随式导航 ==========
|
||||||
|
// 状态:null = 未导航;对象存在 = 导航中
|
||||||
|
// { ptsGcj, ptsBD, idx, walking, follow, timer, watchId, destCode, distance, duration }
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,396 @@
|
|||||||
|
/* 由 static/js/{navigation,share,subscribe,map}.js 逐块搬运而来;正文与原实现一致。 */
|
||||||
|
|
||||||
|
import { S } from "../core/state";
|
||||||
|
import { escHtml, fmtClock, fmtDuration, fmtOrderTime, rideProgressText } from "../core/format";
|
||||||
|
import { _doFindBikeRequest, showReturnConfirm, tryCardPayOrRedirect } from "./actions";
|
||||||
|
import { partnerLabel } from "../share/share";
|
||||||
|
import { notifyCredentialInvalid, showToast } from "../ui/modals";
|
||||||
|
// static/js/map.js:1660-1699
|
||||||
|
export async function checkOrderStatus() {
|
||||||
|
if (!S.authToken) {
|
||||||
|
hideOrderBanner();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const resp = await fetch("/api/order/status", {
|
||||||
|
headers: { "Authorization": `Bearer ${S.authToken}` }
|
||||||
|
});
|
||||||
|
const data = await resp.json();
|
||||||
|
|
||||||
|
if (data.rtn_code === 0) {
|
||||||
|
if (!data.has_credentials) {
|
||||||
|
// 用户没有配置凭据
|
||||||
|
hideOrderBanner();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.has_order && data.order) {
|
||||||
|
S.currentOrder = data.order;
|
||||||
|
// 仅当“当前微信订单本身就是我共享出去的这笔订单”时隐藏普通横幅。
|
||||||
|
// 骑行者自己账号另有待支付/进行中订单时,必须与借用中的共享横幅同时保留。
|
||||||
|
if (data.order.shared) {
|
||||||
|
hideOrderBanner();
|
||||||
|
} else {
|
||||||
|
showOrderBanner(data.order);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
S.currentOrder = null;
|
||||||
|
hideOrderBanner();
|
||||||
|
}
|
||||||
|
} else if (data.rtn_code === 102001 || data.token_invalid) {
|
||||||
|
// token_id 已失效(小程序重新登录会踢掉旧会话):弹窗引导重新配置(带冷却,避免每20秒轮询骚扰)
|
||||||
|
notifyCredentialInvalid(data.message);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error("检查订单状态失败:", err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:1701-1741
|
||||||
|
export 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");
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:1743-1743
|
||||||
|
let orderCountdownTimer: any = null;
|
||||||
|
|
||||||
|
// static/js/map.js:1744-1744
|
||||||
|
export let orderCountdownSeconds: any = 0;
|
||||||
|
|
||||||
|
// static/js/map.js:1745-1745
|
||||||
|
let orderCountdownDeadline: any = null;
|
||||||
|
|
||||||
|
// static/js/map.js:1746-1746
|
||||||
|
let orderCountdownOrderId: any = null;
|
||||||
|
|
||||||
|
// static/js/map.js:1761-1796
|
||||||
|
export function fetchOrderCountdown(orderId) {
|
||||||
|
if (!S.authToken || !orderId) return;
|
||||||
|
|
||||||
|
fetch(`/api/rental/status?order_id=${encodeURIComponent(orderId)}`, {
|
||||||
|
headers: { "Authorization": `Bearer ${S.authToken}` }
|
||||||
|
})
|
||||||
|
.then(r => r.json())
|
||||||
|
.then(data => {
|
||||||
|
if (!S.currentOrder || String(S.currentOrder.order_id) !== String(orderId) || Number(S.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));
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:1798-1802
|
||||||
|
export function showOrderCountdown() {
|
||||||
|
const el = document.getElementById("order-countdown");
|
||||||
|
el.style.display = "inline";
|
||||||
|
updateOrderCountdownText();
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:1804-1818
|
||||||
|
export 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 到期提醒:手机在兜里时页面横幅看不见,这里补一次震动 + 明确文案。
|
||||||
|
// 只在跨过阈值的瞬间触发,不会每秒抖。
|
||||||
|
|
||||||
|
// static/js/map.js:1819-1819
|
||||||
|
let _orderLastAlertAt: any = 0;
|
||||||
|
|
||||||
|
// static/js/map.js:1820-1834
|
||||||
|
export function _alertOrderExpiring(remaining) {
|
||||||
|
const banner = document.getElementById("order-banner");
|
||||||
|
if (banner) banner.classList.add("expiring");
|
||||||
|
const el = document.getElementById("order-countdown");
|
||||||
|
if (el) el.textContent = `再骑 ${Math.max(0, remaining)} 秒就到期 · 超时要加钱`;
|
||||||
|
const now = Date.now();
|
||||||
|
if (now - _orderLastAlertAt < 25000) return; // 25 秒内只提醒一次
|
||||||
|
_orderLastAlertAt = now;
|
||||||
|
try {
|
||||||
|
if (navigator.vibrate) navigator.vibrate([200, 100, 200]);
|
||||||
|
} catch (e) { /* 不支持就算了 */ }
|
||||||
|
if (document.visibilityState === "visible") {
|
||||||
|
showToast("还有不到 1 分钟到期,就近停车还车");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:1835-1861
|
||||||
|
export function updateOrderCountdownText() {
|
||||||
|
const el = document.getElementById("order-countdown");
|
||||||
|
const remaining = Math.max(0, orderCountdownSeconds);
|
||||||
|
const mins = Math.floor(remaining / 60);
|
||||||
|
const secs = remaining % 60;
|
||||||
|
|
||||||
|
if (remaining > 0 && remaining <= 60) {
|
||||||
|
_alertOrderExpiring(remaining); // 内部会写文案/变色/震动
|
||||||
|
} else {
|
||||||
|
el.textContent = remaining > 0
|
||||||
|
? `本轮剩余 ${mins}:${secs.toString().padStart(2, "0")}`
|
||||||
|
: "本轮到期 · 同步状态中";
|
||||||
|
}
|
||||||
|
|
||||||
|
// 变色提示
|
||||||
|
const banner = document.getElementById("order-banner");
|
||||||
|
if (remaining <= 60) {
|
||||||
|
el.style.color = "#ff3b30";
|
||||||
|
if (banner) banner.classList.add("expiring");
|
||||||
|
} else if (remaining <= 300) {
|
||||||
|
el.style.color = "#ffcc00";
|
||||||
|
if (banner) banner.classList.remove("expiring");
|
||||||
|
} else {
|
||||||
|
el.style.color = "white";
|
||||||
|
if (banner) banner.classList.remove("expiring");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:1863-1874
|
||||||
|
export 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:1876-1880
|
||||||
|
export function hideOrderBanner() {
|
||||||
|
document.getElementById("order-banner").classList.remove("show");
|
||||||
|
hideOrderCountdown();
|
||||||
|
closeOrderActionsModal();
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:1882-1887
|
||||||
|
export function isOrderActionEligible(order) {
|
||||||
|
if (!order) return false;
|
||||||
|
const type = String(order.type || "").toLowerCase();
|
||||||
|
const source = String(order.source || "").toLowerCase();
|
||||||
|
return type !== "reminder" && source !== "reminder";
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:1889-1894
|
||||||
|
export function handleOrderBannerSurfaceClick(event) {
|
||||||
|
// 横幅右侧已有的两个按钮继续走原有行为,不触发全屏面板。
|
||||||
|
if (event && event.target && event.target.closest && event.target.closest("button")) return;
|
||||||
|
if (!isOrderActionEligible(S.currentOrder)) return;
|
||||||
|
showOrderActionsModal();
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:1896-1928
|
||||||
|
export function showOrderActionsModal() {
|
||||||
|
if (!isOrderActionEligible(S.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 = S.currentOrder.code || S.currentOrder.order_id || "未知";
|
||||||
|
const pending = Number(S.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);
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:1930-1936
|
||||||
|
export 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");
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:1943-1973
|
||||||
|
export async function findCurrentOrderBike() {
|
||||||
|
if (!isOrderActionEligible(S.currentOrder)) return;
|
||||||
|
const code = (S.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 = "寻车";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:1975-1978
|
||||||
|
export function payCurrentOrderFromModal() {
|
||||||
|
closeOrderActionsModal();
|
||||||
|
tryCardPayOrRedirect();
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:1980-1983
|
||||||
|
export function returnCurrentOrderFromModal() {
|
||||||
|
closeOrderActionsModal();
|
||||||
|
showReturnConfirm();
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:1985-2004
|
||||||
|
export function handleOrderBannerClick() {
|
||||||
|
if (!S.currentOrder) {
|
||||||
|
showToast("订单状态已变化,正在刷新,请稍后重试");
|
||||||
|
checkOrderStatus();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Number(S.currentOrder.status) === 1) {
|
||||||
|
// 待支付 - 先检查是否有月卡/周卡
|
||||||
|
tryCardPayOrRedirect();
|
||||||
|
} else if (Number(S.currentOrder.status) === 2) {
|
||||||
|
// 进行中 - 显示还车确认弹窗
|
||||||
|
showReturnConfirm();
|
||||||
|
} else {
|
||||||
|
showToast("订单状态已变化,正在刷新,请稍后重试");
|
||||||
|
checkOrderStatus();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 查看详情:等同在搜索框输入当前订单车牌并点击查询,直接弹出车辆详情
|
||||||
|
|
||||||
|
// static/js/map.js:2682-2713
|
||||||
|
export function orderCardHtml(o) {
|
||||||
|
const badge = o.returned
|
||||||
|
? '<span class="badge muted" style="padding:2px 8px;border-radius:8px;font-size:11px;background:#ececf1;color:#6e6e73;">已完成</span>'
|
||||||
|
: '<span class="badge" style="padding:2px 8px;border-radius:8px;font-size:11px;background:#e8f5e9;color:#2e7d32;">进行中</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:#005bbf;">共 ${o.rounds} 轮 · 总用时 ${fmtDuration(o.duration_seconds)}</div>` : "";
|
||||||
|
const timeRow = `${fmtOrderTime(o.start_time)} ${fmtClock(o.start_time)} → ${fmtOrderTime(o.end_time)} ${fmtClock(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:#005bbf;"
|
||||||
|
onclick="openOrderTrajectory(${o.id})">查看轨迹</button>
|
||||||
|
</div>
|
||||||
|
</div>`;
|
||||||
|
}
|
||||||
|
// ========== 订单骑行轨迹 ==========
|
||||||
@@ -0,0 +1,391 @@
|
|||||||
|
/* 由 static/js/{navigation,share,subscribe,map}.js 逐块搬运而来;正文与原实现一致。 */
|
||||||
|
|
||||||
|
import { S } from "../core/state";
|
||||||
|
import { escHtml, remainingTimeText, rideProgressText } from "../core/format";
|
||||||
|
import { shareApi } from "../core/http";
|
||||||
|
import { refreshMap } from "../map/core";
|
||||||
|
import { checkOrderStatus } from "../order/status";
|
||||||
|
import { appConfirm, showToast } from "../ui/modals";
|
||||||
|
// static/js/share.js:18-21
|
||||||
|
export function partnerLabel(name, email, remark) {
|
||||||
|
return (remark && String(remark).trim()) || name || email || "";
|
||||||
|
}
|
||||||
|
// share_id -> {email,name,remark},备注编辑用(不把用户文本嵌进 HTML 属性/JS 字面量)
|
||||||
|
|
||||||
|
// static/js/share.js:22-24
|
||||||
|
let shareRec: any = {};
|
||||||
|
|
||||||
|
// ---------- 管理弹窗 ----------
|
||||||
|
|
||||||
|
// static/js/share.js:25-25
|
||||||
|
let shareTabNow: any = "usable";
|
||||||
|
|
||||||
|
// static/js/share.js:26-30
|
||||||
|
export function openShareModal() {
|
||||||
|
if (!S.authToken || !S.currentUser) { showToast("请先登录"); return; }
|
||||||
|
SettingsPages.open("share-modal");
|
||||||
|
switchShareTab(shareTabNow); // 内部已调 loadShareData()
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/share.js:31-33
|
||||||
|
export function closeShareModal() {
|
||||||
|
SettingsPages.back();
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/share.js:34-41
|
||||||
|
export 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();
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/share.js:42-53
|
||||||
|
export 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";
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/share.js:54-94
|
||||||
|
export async function loadShareData() {
|
||||||
|
if (!S.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); }
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/share.js:95-108
|
||||||
|
export async function sendShareRequest() {
|
||||||
|
if (!S.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; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/share.js:110-126
|
||||||
|
export async function acceptShareRequest(reqId, fromEmail) {
|
||||||
|
const askM = document.getElementById("share-ask-modal");
|
||||||
|
if (askM) askM.classList.remove("show");
|
||||||
|
S.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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/share.js:127-140
|
||||||
|
export async function rejectShareRequest(reqId) {
|
||||||
|
const askM = document.getElementById("share-ask-modal");
|
||||||
|
if (askM) askM.classList.remove("show");
|
||||||
|
S.shareAskActive = false;
|
||||||
|
try {
|
||||||
|
const data = await shareApi("/api/share/respond", "POST", { request_id: reqId, accept: false });
|
||||||
|
showToast(data.message || "已拒绝");
|
||||||
|
} finally {
|
||||||
|
loadShareData();
|
||||||
|
checkPendingShareRequests();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 权限设置 ----------
|
||||||
|
|
||||||
|
// static/js/share.js:141-141
|
||||||
|
let shareCfg: any = { share_id: null };
|
||||||
|
|
||||||
|
// static/js/share.js:142-149
|
||||||
|
export 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");
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/share.js:150-153
|
||||||
|
export function closeShareConfig() {
|
||||||
|
SettingsPages.back();
|
||||||
|
setTimeout(() => checkPendingShareRequests(), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/share.js:154-166
|
||||||
|
export 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();
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/share.js:168-176
|
||||||
|
export 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();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 给对方的私密备注(昵称) ----------
|
||||||
|
|
||||||
|
// static/js/share.js:177-177
|
||||||
|
let shareRemarkCfg: any = { share_id: null };
|
||||||
|
|
||||||
|
// static/js/share.js:178-187
|
||||||
|
export 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");
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/share.js:188-191
|
||||||
|
export function closeShareRemark() {
|
||||||
|
SettingsPages.back();
|
||||||
|
shareRemarkCfg.share_id = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/share.js:192-207
|
||||||
|
export 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; }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 全屏接收申请 ----------
|
||||||
|
|
||||||
|
// static/js/share.js:210-210
|
||||||
|
let shareAskCur: any = null;
|
||||||
|
|
||||||
|
// static/js/share.js:211-220
|
||||||
|
export async function checkPendingShareRequests() {
|
||||||
|
if (!S.authToken || S.shareAskActive) return;
|
||||||
|
try {
|
||||||
|
const data = await shareApi("/api/share/pending");
|
||||||
|
if (data.rtn_code === 0 && data.data && data.data.length) {
|
||||||
|
S.shareAskQueue = data.data.slice();
|
||||||
|
nextShareAskIfQueue();
|
||||||
|
}
|
||||||
|
} catch (e) { /* 忽略 */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/share.js:221-231
|
||||||
|
export function nextShareAskIfQueue() {
|
||||||
|
if (S.shareAskQueue.length > 0) {
|
||||||
|
shareAskCur = S.shareAskQueue.shift();
|
||||||
|
S.shareAskActive = true;
|
||||||
|
document.getElementById("share-ask-from").textContent = shareAskCur.from_email || "";
|
||||||
|
document.getElementById("share-ask-modal").classList.add("show");
|
||||||
|
} else if (S.shareAskActive) {
|
||||||
|
S.shareAskActive = false;
|
||||||
|
document.getElementById("share-ask-modal").classList.remove("show");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/share.js:232-236
|
||||||
|
export async function acceptCurrentShareAsk() {
|
||||||
|
if (!shareAskCur) return;
|
||||||
|
await acceptShareRequest(shareAskCur.id, shareAskCur.from_email);
|
||||||
|
// 接受后弹权限设置由 acceptShareRequest 处理;队列推进
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/share.js:237-242
|
||||||
|
export async function rejectCurrentShareAsk() {
|
||||||
|
if (!shareAskCur) return;
|
||||||
|
await rejectShareRequest(shareAskCur.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 共享横幅(车主:共享中 / 骑行者:使用中) ----------
|
||||||
|
|
||||||
|
// static/js/share.js:243-243
|
||||||
|
let shareActiveList: any = [];
|
||||||
|
|
||||||
|
// static/js/share.js:244-244
|
||||||
|
let pendingShareReturn: any = null;
|
||||||
|
|
||||||
|
// static/js/share.js:245-281
|
||||||
|
export async function refreshShareBanners() {
|
||||||
|
const cont = document.getElementById("share-banners");
|
||||||
|
if (!cont) return;
|
||||||
|
if (!S.authToken || !S.currentUser) { cont.innerHTML = ""; return; }
|
||||||
|
try {
|
||||||
|
const data = await shareApi("/api/share/active");
|
||||||
|
if (data.rtn_code !== 0) return;
|
||||||
|
// 接口异常时 data.data 可能是对象/字符串,不是数组 → forEach 会抛错并每秒刷屏
|
||||||
|
shareActiveList = Array.isArray(data.data) ? 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>';
|
||||||
|
});
|
||||||
|
// 内容没变就不动 DOM:否则手指按在「还车」上时按钮被替换,
|
||||||
|
// touch-up 落空(点了没反应),入场动画也会每 20 秒重播一次。
|
||||||
|
if (cont.__lastHtml !== html) {
|
||||||
|
cont.innerHTML = html;
|
||||||
|
cont.__lastHtml = html;
|
||||||
|
}
|
||||||
|
} catch (e) { console.error("[share] banners失败", e); }
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/share.js:282-295
|
||||||
|
export 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");
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/share.js:296-304
|
||||||
|
export function updateShareCountdowns() {
|
||||||
|
if (!Array.isArray(shareActiveList)) return; // 接口异常时不刷屏
|
||||||
|
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) : '本轮到期 · 同步状态中';
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/share.js:307-311
|
||||||
|
export function closeShareReturnModal() {
|
||||||
|
const modal = document.getElementById("share-return-modal");
|
||||||
|
if (modal) modal.classList.remove("show");
|
||||||
|
pendingShareReturn = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/share.js:312-343
|
||||||
|
export 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<any>(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 = "确认还车"; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,177 @@
|
|||||||
|
/* 由 static/js/{navigation,share,subscribe,map}.js 逐块搬运而来;正文与原实现一致。 */
|
||||||
|
|
||||||
|
import { S } from "../core/state";
|
||||||
|
import { escHtml } from "../core/format";
|
||||||
|
import { appConfirm, showToast } from "../ui/modals";
|
||||||
|
import { closeAllModals } from "../ui/settings";
|
||||||
|
// static/js/subscribe.js:6-6
|
||||||
|
let subscribeLocations: any = [];
|
||||||
|
|
||||||
|
// static/js/subscribe.js:7-7
|
||||||
|
const SUB_WEEKDAYS = { 0: "每天", 1: "周一", 2: "周二", 3: "周三", 4: "周四", 5: "周五", 6: "周六", 7: "周日" };
|
||||||
|
|
||||||
|
// static/js/subscribe.js:8-13
|
||||||
|
export async function openSubscribeModal() {
|
||||||
|
closeAllModals();
|
||||||
|
SettingsPages.open("subscribe-modal");
|
||||||
|
await loadSubscribeLocations();
|
||||||
|
loadSubscribeRules();
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/subscribe.js:14-16
|
||||||
|
export function closeSubscribeModal() {
|
||||||
|
SettingsPages.back();
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/subscribe.js:17-32
|
||||||
|
export async function loadSubscribeLocations() {
|
||||||
|
const sel = document.getElementById("sub-location");
|
||||||
|
sel.innerHTML = '<option value="">加载中...</option>';
|
||||||
|
try {
|
||||||
|
const resp = await fetch("/api/campus/locations");
|
||||||
|
const data = await resp.json();
|
||||||
|
// 订阅只针对「停车点」(楼/兴趣点只用于起终点归属)
|
||||||
|
subscribeLocations = ((data.rtn_code === 0 ? data.data : []) || [])
|
||||||
|
.filter(l => l.kind === "parking");
|
||||||
|
} catch (err) {
|
||||||
|
subscribeLocations = [];
|
||||||
|
}
|
||||||
|
sel.innerHTML = subscribeLocations.length
|
||||||
|
? subscribeLocations.map(l => `<option value="${l.id}">${escHtml(l.name)}</option>`).join("")
|
||||||
|
: '<option value="">(管理员尚未配置停车点)</option>';
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/subscribe.js:33-63
|
||||||
|
export function subRuleRowHtml(r) {
|
||||||
|
const loc = subscribeLocations.find(l => l.id === r.location_id);
|
||||||
|
const locName = loc ? loc.name : (r.location_name || "停车点已删除");
|
||||||
|
const hh = String(Math.floor(r.minute_of_day / 60)).padStart(2, "0");
|
||||||
|
const mm = String(r.minute_of_day % 60).padStart(2, "0");
|
||||||
|
const kindText = (r.kind_labels && r.kind_labels.length)
|
||||||
|
? r.kind_labels.join("/") : "全部车型";
|
||||||
|
const eMin = r.min_electric != null ? r.min_electric : 0;
|
||||||
|
const eMax = r.max_electric != null ? r.max_electric : 100;
|
||||||
|
const sortLabel = r.sort_by_label || r.sort_by || "";
|
||||||
|
const tags = [];
|
||||||
|
if (r.auto_unlock) {
|
||||||
|
tags.push(`自动开锁 · ${kindText} · 电量${eMin}-${eMax}% · ${sortLabel} · 重试${r.retry_times || 3}次`);
|
||||||
|
}
|
||||||
|
return `
|
||||||
|
<div class="device-item" style="display:block;padding:9px 12px;border-bottom:1px solid var(--bg-tertiary,#ececf1);">
|
||||||
|
<div style="display:flex;justify-content:space-between;align-items:flex-start;gap:8px;">
|
||||||
|
<div style="font-size:13px;line-height:1.6;min-width:0;">
|
||||||
|
<b>${escHtml(locName)}</b>
|
||||||
|
<span style="color:var(--text-secondary);"> · ${SUB_WEEKDAYS[r.weekday] || "每周"} ${hh}:${mm}</span>
|
||||||
|
<div style="font-size:11.5px;color:var(--text-secondary);">${r.enabled ? "已启用" : "已停用"}${r.notify_enabled ? " · 邮件提醒" : ""}</div>
|
||||||
|
${tags.length ? `<div style="font-size:11.5px;color:#005bbf;">${escHtml(tags[0])}</div>` : ""}
|
||||||
|
</div>
|
||||||
|
<div style="display:flex;gap:6px;flex:0 0 auto;">
|
||||||
|
<button class="btn" style="padding:4px 9px;border:none;border-radius:8px;font-size:12px;background:#ececf1;" onclick="toggleSubscribeRule(${r.id}, ${r.enabled ? 0 : 1})">${r.enabled ? "停用" : "启用"}</button>
|
||||||
|
<button class="btn" style="padding:4px 9px;border:none;border-radius:8px;font-size:12px;background:#fce4ec;color:#c62828;" onclick="deleteSubscribeRule(${r.id})">删除</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>`;
|
||||||
|
}
|
||||||
|
// 订阅表单「更多筛选」折叠开关(高级调优项默认收起)
|
||||||
|
|
||||||
|
// static/js/subscribe.js:64-69
|
||||||
|
export function toggleSubAdvanced() {
|
||||||
|
const box = document.getElementById("sub-advanced");
|
||||||
|
if (!box) return;
|
||||||
|
const show = box.style.display === "none";
|
||||||
|
box.style.display = show ? "block" : "none";
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/subscribe.js:70-89
|
||||||
|
export async function loadSubscribeRules() {
|
||||||
|
const box = document.getElementById("subscribe-list");
|
||||||
|
box.innerHTML = '<div class="device-loading">加载中...</div>';
|
||||||
|
try {
|
||||||
|
const resp = await fetch("/api/subscribe/rules", {
|
||||||
|
headers: { "Authorization": `Bearer ${S.authToken}` }
|
||||||
|
});
|
||||||
|
const data = await resp.json();
|
||||||
|
if (data.rtn_code !== 0) {
|
||||||
|
box.innerHTML = `<div class="device-loading">${escHtml(data.message || "加载失败")}</div>`;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const rules = data.data || [];
|
||||||
|
box.innerHTML = rules.length
|
||||||
|
? rules.map(subRuleRowHtml).join("")
|
||||||
|
: '<div class="device-loading">暂无规则,在下方添加</div>';
|
||||||
|
} catch (err) {
|
||||||
|
box.innerHTML = '<div class="device-loading">网络错误,请重试</div>';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/subscribe.js:90-132
|
||||||
|
export async function addSubscribeRule() {
|
||||||
|
const locationId = Number(document.getElementById("sub-location").value || 0);
|
||||||
|
const weekday = Number(document.getElementById("sub-weekday").value);
|
||||||
|
const time = document.getElementById("sub-time").value;
|
||||||
|
const notify = document.getElementById("sub-notify").checked;
|
||||||
|
const auto = document.getElementById("sub-auto").checked;
|
||||||
|
const kinds = [...document.querySelectorAll(".sub-kind:checked")].map(el => el.value);
|
||||||
|
const minE = Number(document.getElementById("sub-min-e").value || 0);
|
||||||
|
const maxE = Number(document.getElementById("sub-max-e").value || 100);
|
||||||
|
const sortBy = document.getElementById("sub-sort").value;
|
||||||
|
const retry = Number(document.getElementById("sub-retry").value || 3);
|
||||||
|
|
||||||
|
if (!locationId) { showToast("请先选择停车点(需要管理员先配置停车点)"); return; }
|
||||||
|
if (!/^\d{2}:\d{2}$/.test(time)) { showToast("请选择时间"); return; }
|
||||||
|
if (!kinds.length) { showToast("至少选择一个车型"); return; }
|
||||||
|
if (!(minE >= 0 && maxE <= 100 && minE <= maxE)) { showToast("电量区间需在 0-100 且下限≤上限"); return; }
|
||||||
|
if (auto) {
|
||||||
|
const ok = await appConfirm(
|
||||||
|
"开启自动开锁后,命中规则时系统会用你的账号直接开锁车辆。\n\n" +
|
||||||
|
`筛选:${kinds.map(k => ({small:"小车",big:"大车",red:"红车"}[k])).join("/")},` +
|
||||||
|
`电量 ${minE}%-${maxE}%,${document.getElementById("sub-sort").selectedOptions[0].textContent};` +
|
||||||
|
`被他人抢先时最多重试 ${retry} 次。`,
|
||||||
|
{ title: "开启自动开锁", okText: "确认添加" });
|
||||||
|
if (!ok) return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const resp = await fetch("/api/subscribe/rules", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Authorization": `Bearer ${S.authToken}`, "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({
|
||||||
|
location_id: locationId, weekday, time,
|
||||||
|
notify_enabled: notify, auto_unlock: auto,
|
||||||
|
kinds, min_electric: minE, max_electric: maxE,
|
||||||
|
sort_by: sortBy, retry_times: retry
|
||||||
|
})
|
||||||
|
});
|
||||||
|
const data = await resp.json();
|
||||||
|
showToast(data.message || (data.rtn_code === 0 ? "已添加" : "添加失败"));
|
||||||
|
if (data.rtn_code === 0) loadSubscribeRules();
|
||||||
|
} catch (err) {
|
||||||
|
showToast("网络错误,请重试");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/subscribe.js:133-144
|
||||||
|
export async function toggleSubscribeRule(ruleId, enable) {
|
||||||
|
try {
|
||||||
|
const resp = await fetch(`/api/subscribe/rules/${ruleId}`, {
|
||||||
|
method: "PUT",
|
||||||
|
headers: { "Authorization": `Bearer ${S.authToken}`, "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ enabled: !!enable })
|
||||||
|
});
|
||||||
|
const data = await resp.json();
|
||||||
|
if (data.rtn_code === 0) loadSubscribeRules();
|
||||||
|
else showToast(data.message || "操作失败");
|
||||||
|
} catch (err) { showToast("网络错误"); }
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/subscribe.js:145-155
|
||||||
|
export async function deleteSubscribeRule(ruleId) {
|
||||||
|
try {
|
||||||
|
const resp = await fetch(`/api/subscribe/rules/${ruleId}`, {
|
||||||
|
method: "DELETE",
|
||||||
|
headers: { "Authorization": `Bearer ${S.authToken}` }
|
||||||
|
});
|
||||||
|
const data = await resp.json();
|
||||||
|
if (data.rtn_code === 0) loadSubscribeRules();
|
||||||
|
else showToast(data.message || "删除失败");
|
||||||
|
} catch (err) { showToast("网络错误"); }
|
||||||
|
}
|
||||||
@@ -0,0 +1,848 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
/* 迁移工具(**不是**构建的一部分,只用来生成 src-ts/ 的初稿)
|
||||||
|
*
|
||||||
|
* 作用:把 static/js/{navigation,share,subscribe,map}.js 这些**经典脚本**里的
|
||||||
|
* 顶层「函数声明 / 变量声明 / 顶层语句」逐块切出来,按 MODULES 表分派到 src-ts/
|
||||||
|
* 各模块,代码正文逐字搬运(只去掉 4 空格缩进),并自动生成 import 头。
|
||||||
|
*
|
||||||
|
* 唯一会改写正文的地方:原先靠「全局词法绑定」跨模块共享的可变状态(map /
|
||||||
|
* selectedBike / currentOrder / authToken …),在 bundle 里集中到 core/state.ts
|
||||||
|
* 的 S 对象上,正文里的裸标识符改写为 S.xxx(ES 模块不允许改 import 进来的绑定)。
|
||||||
|
*
|
||||||
|
* 用法:
|
||||||
|
* node src-ts/tools/gen.mjs --analyze # 只打印分析结果
|
||||||
|
* node src-ts/tools/gen.mjs # 生成 / 覆盖 src-ts/**\/*.ts
|
||||||
|
*/
|
||||||
|
import fs from "node:fs";
|
||||||
|
import path from "node:path";
|
||||||
|
import vm from "node:vm";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||||
|
const ROOT = path.resolve(HERE, "..", "..");
|
||||||
|
const SRC_TS = path.resolve(HERE, "..");
|
||||||
|
const ANALYZE_ONLY = process.argv.includes("--analyze");
|
||||||
|
|
||||||
|
const SOURCES = [
|
||||||
|
{ id: "navigation", file: "static/js/navigation.js" },
|
||||||
|
{ id: "share", file: "static/js/share.js" },
|
||||||
|
{ id: "subscribe", file: "static/js/subscribe.js" },
|
||||||
|
{ id: "map", file: "static/js/map.js" },
|
||||||
|
];
|
||||||
|
|
||||||
|
/* ---------------- 1. 遮罩(注释 / 字符串字面量 / 模板字面量的**文本部分** / 正则 → 空格)
|
||||||
|
* 注意:模板里的 `${ ... }` 是**代码**,必须保持原样,否则 ${authToken} 这类
|
||||||
|
* 表达式里的标识符会被当成字符串内容漏掉。这里用状态栈递归处理。 */
|
||||||
|
function mask(text) {
|
||||||
|
const out = text.split("");
|
||||||
|
const n = text.length;
|
||||||
|
const blank = (a, b) => { for (let k = a; k < b; k++) if (out[k] !== "\n") out[k] = " "; };
|
||||||
|
const stack = [{ type: "code", depth: 0 }];
|
||||||
|
let prev = "";
|
||||||
|
let i = 0;
|
||||||
|
const top = () => stack[stack.length - 1];
|
||||||
|
const wordBefore = (at) => {
|
||||||
|
let j = at - 1;
|
||||||
|
while (j >= 0 && /\s/.test(text[j])) j--;
|
||||||
|
const end = j + 1;
|
||||||
|
while (j >= 0 && /[\w$]/.test(text[j])) j--;
|
||||||
|
return text.slice(j + 1, end);
|
||||||
|
};
|
||||||
|
while (i < n) {
|
||||||
|
const cur = top();
|
||||||
|
const c = text[i], c2 = text[i + 1];
|
||||||
|
if (cur.type === "tpl") {
|
||||||
|
if (c === "\\") { blank(i, i + 2); i += 2; continue; }
|
||||||
|
if (c === "`") { blank(i, i + 1); stack.pop(); i++; prev = "str"; continue; }
|
||||||
|
if (c === "$" && c2 === "{") { stack.push({ type: "code", depth: 0 }); i += 2; prev = "{"; continue; }
|
||||||
|
blank(i, i + 1); i++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
/* code 帧 */
|
||||||
|
if (c === "}" && stack.length > 1 && cur.depth === 0) { stack.pop(); i++; prev = "}"; continue; }
|
||||||
|
if (c === "/" && c2 === "/") { let j = text.indexOf("\n", i); if (j < 0) j = n; blank(i, j); i = j; continue; }
|
||||||
|
if (c === "/" && c2 === "*") { let j = text.indexOf("*/", i + 2); j = j < 0 ? n : j + 2; blank(i, j); i = j; continue; }
|
||||||
|
if (c === '"' || c === "'") {
|
||||||
|
let j = i + 1;
|
||||||
|
while (j < n) {
|
||||||
|
if (text[j] === "\\") { j += 2; continue; }
|
||||||
|
if (text[j] === c) { j++; break; }
|
||||||
|
if (text[j] === "\n") break;
|
||||||
|
j++;
|
||||||
|
}
|
||||||
|
blank(i + 1, Math.max(i + 1, j - 1));
|
||||||
|
i = j; prev = "str";
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (c === "`") { stack.push({ type: "tpl" }); blank(i, i + 1); i++; continue; }
|
||||||
|
if (c === "/") {
|
||||||
|
const ok = prev === "" || /[=(,:;[{!&|?+\-*%~^<>]/.test(prev) ||
|
||||||
|
/\b(?:return|typeof|case|in|of|new|delete|void|instanceof)$/.test(wordBefore(i));
|
||||||
|
if (ok) {
|
||||||
|
let j = i + 1, cls = false;
|
||||||
|
while (j < n) {
|
||||||
|
const ch = text[j];
|
||||||
|
if (ch === "\\") { j += 2; continue; }
|
||||||
|
if (ch === "[") cls = true;
|
||||||
|
else if (ch === "]") cls = false;
|
||||||
|
else if (ch === "/" && !cls) { j++; break; }
|
||||||
|
else if (ch === "\n") break;
|
||||||
|
j++;
|
||||||
|
}
|
||||||
|
blank(i + 1, Math.max(i + 1, j - 1));
|
||||||
|
i = j; prev = "regex";
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
prev = c; i++; continue;
|
||||||
|
}
|
||||||
|
if (c === "{") cur.depth++;
|
||||||
|
else if (c === "}") cur.depth--;
|
||||||
|
if (!/\s/.test(c)) prev = c;
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
return out.join("");
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------------- 2. 切块 ---------------- */
|
||||||
|
const OPEN = new Set(["{", "(", "["]);
|
||||||
|
const CLOSE = new Set(["}", ")", "]"]);
|
||||||
|
const CONT_END = /(?:=|=>|\+|-|\*|\/|%|&&|\|\||\?|:|,|\.|\(|\[|\{|<|>|&|\||!|~|\^)\s*$/;
|
||||||
|
const CONT_START = /^(\?|:|\.|\+|-|\*|\/|%|&&|\|\||&|\||=|<|>|,)$/;
|
||||||
|
|
||||||
|
function splitBlocks(file, text) {
|
||||||
|
const masked = mask(text);
|
||||||
|
const lines = text.split("\n");
|
||||||
|
const mLines = masked.split("\n");
|
||||||
|
if (lines.length !== mLines.length) throw new Error("mask 长度不一致: " + file);
|
||||||
|
|
||||||
|
const depthStart = new Array(lines.length);
|
||||||
|
let depth = 0;
|
||||||
|
for (let li = 0; li < lines.length; li++) {
|
||||||
|
depthStart[li] = depth;
|
||||||
|
const m = mLines[li];
|
||||||
|
for (let k = 0; k < m.length; k++) {
|
||||||
|
const ch = m[k];
|
||||||
|
if (OPEN.has(ch)) depth++;
|
||||||
|
else if (CLOSE.has(ch)) depth--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (depth !== 0) throw new Error(`${file}: 括号不平衡(残留 ${depth})`);
|
||||||
|
|
||||||
|
const starts = [];
|
||||||
|
for (let li = 0; li < lines.length; li++) {
|
||||||
|
const m = mLines[li];
|
||||||
|
const t = m.trim();
|
||||||
|
if (!t) continue;
|
||||||
|
const indent = m.length - m.replace(/^ +/, "").length;
|
||||||
|
if (indent !== 4) continue;
|
||||||
|
if (depthStart[li] !== 0) continue;
|
||||||
|
if (CONT_START.test(t)) continue;
|
||||||
|
if (starts.length) {
|
||||||
|
let p = li - 1;
|
||||||
|
while (p >= 0 && !mLines[p].trim()) p--;
|
||||||
|
if (p >= 0 && CONT_END.test(mLines[p])) continue;
|
||||||
|
}
|
||||||
|
starts.push(li);
|
||||||
|
}
|
||||||
|
|
||||||
|
const blocks = [];
|
||||||
|
for (let s = 0; s < starts.length; s++) {
|
||||||
|
const from = starts[s];
|
||||||
|
let to = (s + 1 < starts.length ? starts[s + 1] : lines.length) - 1;
|
||||||
|
while (to > from && !lines[to].trim()) to--;
|
||||||
|
const body = lines.slice(from, to + 1).map((l) => l.replace(/^ {4}/, "")).join("\n");
|
||||||
|
const mbody = mLines.slice(from, to + 1).map((l) => l.replace(/^ {4}/, "")).join("\n");
|
||||||
|
blocks.push({ file, from: from + 1, to: to + 1, body, masked: mbody });
|
||||||
|
}
|
||||||
|
return blocks;
|
||||||
|
}
|
||||||
|
|
||||||
|
function classify(block) {
|
||||||
|
const t = (block.masked.split("\n").find((l) => l.trim()) || "").trim();
|
||||||
|
let m = /^(?:async\s+)?function\s+([A-Za-z_$][\w$]*)/.exec(t);
|
||||||
|
if (m) return { kind: "function", name: m[1] };
|
||||||
|
m = /^(?:let|const|var)\s+([A-Za-z_$][\w$]*)/.exec(t);
|
||||||
|
if (m) {
|
||||||
|
const declKind = /^const/.test(t) ? "const" : "let";
|
||||||
|
if (!/^const/.test(t) && /,/.test(t.split(";")[0]) && m[1]) {
|
||||||
|
/* 多声明符很少见,提示一下 */
|
||||||
|
}
|
||||||
|
return { kind: "var", name: m[1], declKind };
|
||||||
|
}
|
||||||
|
return { kind: "stmt", name: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------------- 3. 分派表 ---------------- */
|
||||||
|
const MODULES = {
|
||||||
|
"core/http.ts": ["shareApi"],
|
||||||
|
"core/format.ts": [
|
||||||
|
"escHtml", "fmtTime", "fmtLocalTime", "describeTokenExpiry", "fmtRemainShort",
|
||||||
|
"fmtDuration", "fmtOrderTime", "fmtClock", "friendlyError", "rideProgressText", "remainingTimeText",
|
||||||
|
],
|
||||||
|
"map/icons.ts": [
|
||||||
|
"iconCache", "ICON_CACHE_MAX", "BASE_ICON_COLORS", "prebuiltIcons", "createFullIcon",
|
||||||
|
"preloadBaseIcons", "makeIconDataURI", "RED_BIKE_COLOR", "getBikeKind", "getBikeIcon", "getBikeState",
|
||||||
|
],
|
||||||
|
"map/core.ts": [
|
||||||
|
"BAIDU_AK", "INIT_OFFSET_EXTRA", "INIT_OFFSET_EAST", "mapInitializationStarted", "initMap",
|
||||||
|
"initMapCore", "updateMapStyle", "mapRequest", "mapRefreshTimer", "renderedMapSnapshot",
|
||||||
|
"mapRefreshFailed", "scheduleMapRefresh", "loadMapData", "refreshMap", "mapSnapshotNow",
|
||||||
|
"updateMapFreshnessBadge", "updateTime", "showFreshnessDetail", "locateMe", "findNearestBikeManual",
|
||||||
|
"showMyLocation", "createAutoLocationIcon", "updateAutoLocation", "startAutoLocation",
|
||||||
|
"stopAutoLocation", "findNearestBike",
|
||||||
|
],
|
||||||
|
"map/markers.ts": [
|
||||||
|
"findMarkerById", "bringMarkerToTop", "setHighlight", "clearHighlight", "bindMarkerDomTouch",
|
||||||
|
"bindMarkerTap", "renderMap", "setupClusterListener", "rebuildMarkersForZoom", "bikeBubbleLayer",
|
||||||
|
],
|
||||||
|
"card/bike-card.ts": [
|
||||||
|
"showBikeDetail", "closeCard", "_fitCardActions", "_fitCardTimer", "_cardZoomTimer",
|
||||||
|
"viewBikeDetailFromOrder", "viewBikeDetailFromOrderModal", "updateRingProgress",
|
||||||
|
],
|
||||||
|
"order/status.ts": [
|
||||||
|
"currentOrder", "checkOrderStatus", "showOrderBanner", "orderCountdownTimer",
|
||||||
|
"orderCountdownSeconds", "orderCountdownDeadline", "orderCountdownOrderId", "fetchOrderCountdown",
|
||||||
|
"showOrderCountdown", "hideOrderCountdown", "_orderLastAlertAt", "_alertOrderExpiring",
|
||||||
|
"updateOrderCountdownText", "startOrderCountdown", "hideOrderBanner", "isOrderActionEligible",
|
||||||
|
"handleOrderBannerSurfaceClick", "showOrderActionsModal", "closeOrderActionsModal",
|
||||||
|
"handleOrderBannerClick", "payCurrentOrderFromModal", "returnCurrentOrderFromModal",
|
||||||
|
"findCurrentOrderBike", "orderCardHtml",
|
||||||
|
],
|
||||||
|
"order/actions.ts": [
|
||||||
|
"tryCardPayOrRedirect", "cardPayLoading", "returnLoading", "pendingReturnOrder",
|
||||||
|
"getOrderOperationLocation", "showReturnConfirm", "closeReturnConfirm", "doReturnBike",
|
||||||
|
"orderTempActionLoading", "tempLockCurrentOrder", "tempUnlockCurrentOrder", "unlockPendingCode",
|
||||||
|
"unlockPendingPosition", "handleQuickUnlock", "unlockChoice", "unlockSrcList", "unlockSrcShowAll",
|
||||||
|
"openUnlockAccountChooser", "renderUnlockSrcList", "loadUnlockSrcShowAll", "chooseUnlockSrc",
|
||||||
|
"closeUnlockSrc", "proceedToUnlockConfirm", "closeUnlockConfirm", "doUnlockBike", "quickUnlock",
|
||||||
|
"startRentalFromServer", "clearRentalState", "openRentalSettingsModal", "closeRentalSettingsModal",
|
||||||
|
"saveRentalSettings", "syncWechatOrder", "checkRentalStatus", "startRental", "showRentalBar",
|
||||||
|
"updateRentalFinalTime", "updateRentalCountdown", "showReturnModal", "closeReturnModal",
|
||||||
|
"confirmReturn", "isNativeShell", "nativeUnlockBike", "unlockBike", "openOrderTrajectory",
|
||||||
|
"closeOrderTrajModal", "renderOrderTrajectory", "orderTrajMap", "orderTrajOverlays",
|
||||||
|
"openOrdersModal", "closeOrdersModal", "renderUnlockPreview", "loadUnlockPreview",
|
||||||
|
"_addRoundTarget", "showAddRoundConfirm", "closeAddRoundModal", "confirmAddRound",
|
||||||
|
"addRoundForCurrent", "addRoundFromBanner", "findBike", "_doFindBikeRequest", "showLostModal",
|
||||||
|
"closeLostModal", "enableLostMode", "disableLostMode", "_onPageUnload", "_onVisibilityChange",
|
||||||
|
"_lostModeActive", "_lostModeTimer", "_findClickCount", "_findClickTimer", "_findLongPressTimer",
|
||||||
|
"LOST_TRIGGER_CLICKS", "LOST_TRIGGER_LONG", "LOST_INTERVAL", "scanCode", "currentBellTab",
|
||||||
|
"selectedRadius", "selectedLocation", "selectedStatuses", "rangeCircleOverlay",
|
||||||
|
"showBellPasswordModal", "switchBellTab", "selectRadius", "useCurrentLocation",
|
||||||
|
"useCenterLocation", "updateRangeCircle", "toggleStatusFilter", "updateStatusCounts",
|
||||||
|
"getFilteredBikes", "updateFilterInfo", "closeBellModal", "submitBellPassword",
|
||||||
|
],
|
||||||
|
"ui/settings.ts": [
|
||||||
|
"openSettingsPage", "closeSettingsPage", "saveMapClusteringSetting", "showProfileModal",
|
||||||
|
"closeProfileModal", "closeAllModals", "loadProfileData", "loadUserInfo", "parseJwtExpiry",
|
||||||
|
"renderTokenExpiry", "updateTokenExpiryDisplays", "_savedTokenExpiry",
|
||||||
|
"AUTH_EXPIRY_BANNER_THRESHOLD", "AUTH_EXPIRY_BANNER_URGENT", "renderAuthExpiryBanner",
|
||||||
|
"refreshAuthExpiry", "openAuthModal", "closeAuthModal", "_strictGuideShown", "maybeStrictGuide",
|
||||||
|
"checkStrictGuide", "getDeviceId", "getDeviceName", "openDevicesModal", "closeDevicesModal",
|
||||||
|
"loadDevicesList", "kickDevice", "logoutAllOtherDevices", "openPackagesModal",
|
||||||
|
"closePackagesModal", "loadPackagesList", "saveProfileToken", "showLoginGate", "hideLoginGate",
|
||||||
|
"doLogin", "handleLoginSubmit", "registerCodeCountdown", "registerCodeTimer",
|
||||||
|
"setRegisterCodeBtn", "sendRegisterCode", "handleRegisterSubmit", "handleLogout",
|
||||||
|
"updateAuthButton", "BATCH_RING_ALLOWED_EMAILS", "canUseBatchRing", "updateBellBtnVisibility",
|
||||||
|
"checkAuthStatus", "showLoginModal", "closeLoginModal", "showRegisterModal",
|
||||||
|
"closeRegisterModal", "handleAuthBtnClick", "_forgotFromGate", "showForgotModal",
|
||||||
|
"showForgotFromGate", "closeForgotModal", "backToLoginFromForgot", "forgotTimer",
|
||||||
|
"setForgotCodeBtn", "sendForgotCode", "handleForgotSubmit", "openVersionModal",
|
||||||
|
"closeVersionModal", "maybeAutoShowVersion", "VERSION_TAG", "VERSION_LOGS",
|
||||||
|
"versionModalInited", "versionAutoTries",
|
||||||
|
],
|
||||||
|
"ui/modals.ts": [
|
||||||
|
"appConfirm", "appConfirmClose", "_appConfirmResolve", "showToast", "showDownloadTipModal",
|
||||||
|
"closeDownloadTipModal", "closeExportTipModal", "copyExportLink", "exportHistoryCsv",
|
||||||
|
"copyDownloadLink", "showTokenExpiredModal", "closeTokenExpiredModal", "loadExpiredTokenFields",
|
||||||
|
"saveExpiredToken", "notifyCredentialInvalid", "_credInvalidLastShownAt",
|
||||||
|
"CRED_INVALID_MODAL_COOLDOWN", "CAPTURE_TOOL_PATH", "detectHarmony", "detectMobile",
|
||||||
|
"detectInAppBrowser", "captureToolUrl", "onDownloadCaptureTool", "showQrModal", "closeQrModal",
|
||||||
|
"createQrImage", "setupQrLongPress", "currentQrPosition", "longPressTimer", "longPressTarget",
|
||||||
|
"qrModalBikeCode", "shareAfterLogin",
|
||||||
|
],
|
||||||
|
"nav/navigation.ts": [
|
||||||
|
"_nav", "_navLoading", "_navEpoch", "NAV_DEVIATE_M", "NAV_RECOMPUTE_COOLDOWN_MS", "NAV_SNAP_M",
|
||||||
|
"NAV_BOTTOM_RATIO", "NAV_FREE_TIMEOUT", "_haversineM", "_gpsToGcj", "_bearing",
|
||||||
|
"_projectOnRoute", "_navBanner", "_navPill", "_navBtnText", "_clearNavLayers", "_redrawRoute",
|
||||||
|
"_headingSupported", "_headingAnim", "_rotateByAnimation", "_applyHeading", "_centerOnUser",
|
||||||
|
"_compassHeading", "_compassBound", "_bindCompass", "_ensureCompassPermission", "_navArrowIcon",
|
||||||
|
"_turnKind", "_turnSvg", "_setTurnIcon", "_destIcon", "_placeNavArrow", "_rotateNavArrow",
|
||||||
|
"_clearNavArrow", "_navTick", "_navGuidance", "_recomputeRoute", "_requestNavRoute",
|
||||||
|
"_applyRoute", "stopNavigation", "toggleNavigation", "_navSelfMoveUntil",
|
||||||
|
"_markProgrammaticMove", "_scheduleResume", "_onMapDragStart", "_onMapDragging",
|
||||||
|
"_onMapDragEnd", "resumeNavigation", "startNavigation", "bindNavMapEvents",
|
||||||
|
],
|
||||||
|
"nav/walk-route.ts": [
|
||||||
|
"_walkRouteCache", "MAX_WALK_DISTANCE_M", "parseWalkDistance", "parseWalkDuration",
|
||||||
|
"refineWalkRoute",
|
||||||
|
],
|
||||||
|
"share/share.ts": [
|
||||||
|
"partnerLabel", "shareRec", "shareTabNow", "openShareModal", "closeShareModal", "switchShareTab",
|
||||||
|
"sharePendingHtml", "loadShareData", "sendShareRequest", "acceptShareRequest",
|
||||||
|
"rejectShareRequest", "shareCfg", "openShareConfig", "closeShareConfig", "saveShareConfig",
|
||||||
|
"unbindShare", "shareRemarkCfg", "openShareRemark", "closeShareRemark", "saveShareRemark",
|
||||||
|
"shareAskQueue", "shareAskActive", "shareAskCur", "checkPendingShareRequests",
|
||||||
|
"nextShareAskIfQueue", "acceptCurrentShareAsk", "rejectCurrentShareAsk", "shareActiveList",
|
||||||
|
"pendingShareReturn", "refreshShareBanners", "openShareReturnByIdx", "updateShareCountdowns",
|
||||||
|
"closeShareReturnModal", "confirmShareReturn",
|
||||||
|
],
|
||||||
|
"subscribe/subscribe.ts": [
|
||||||
|
"subscribeLocations", "SUB_WEEKDAYS", "openSubscribeModal", "closeSubscribeModal",
|
||||||
|
"loadSubscribeLocations", "subRuleRowHtml", "toggleSubAdvanced", "loadSubscribeRules",
|
||||||
|
"addSubscribeRule", "toggleSubscribeRule", "deleteSubscribeRule",
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
/* 搬进 core/state.ts 的可变状态(原本靠全局词法绑定跨模块共享) */
|
||||||
|
const STATE_VARS = [
|
||||||
|
"map", "currentType", "currentUser", "authKickToastShown", "authMode", "authToken",
|
||||||
|
"currentMarkers", "currentPolygons", "selectedBike", "markersData", "currentMarkersById",
|
||||||
|
"scannedMarkers", "myLocationMarker", "autoLocationMarker", "autoLocationWatchId",
|
||||||
|
"hasLocationPermission", "initialLocationCentered", "nearestBikeId", "isFirstLoad",
|
||||||
|
"highlightedBikeId", "bikeClusteringEnabled", "activeRental", "rentalCountdownTimer",
|
||||||
|
/* 下面几个原本在 map.js 顶层、但被别处的块(含顶层 IIFE / handleLogout)赋值,
|
||||||
|
* ESM 下 import 进来的绑定不能赋值,同样收进 S。 */
|
||||||
|
"currentOrder", "shareAskQueue", "shareAskActive",
|
||||||
|
"_fitCardTimer", "_findClickCount", "_findLongPressTimer",
|
||||||
|
];
|
||||||
|
const STATE_CONSTS = ["RENTAL_KEY"];
|
||||||
|
|
||||||
|
/* 由手写模块提供、但被搬过来的正文直接使用的名字(原先是 geo.js 的全局函数) */
|
||||||
|
const EXTRA_HOME = {
|
||||||
|
offsetCoord: "core/geo.ts",
|
||||||
|
calcDistance: "core/geo.ts",
|
||||||
|
Geo: "core/geo.ts",
|
||||||
|
};
|
||||||
|
|
||||||
|
/* ---------------- 4. 分析 ---------------- */
|
||||||
|
function analyse() {
|
||||||
|
const blocks = [];
|
||||||
|
for (const src of SOURCES) {
|
||||||
|
const text = fs.readFileSync(path.join(ROOT, src.file), "utf8").replace(/\r\n/g, "\n");
|
||||||
|
for (const p of splitBlocks(src.file, text)) {
|
||||||
|
blocks.push({ ...p, ...classify(p), source: src.id });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const bad = [];
|
||||||
|
for (const b of blocks) {
|
||||||
|
try { new vm.Script(b.body, { filename: `${b.file}:${b.from}` }); }
|
||||||
|
catch (e) { bad.push({ where: `${b.file}:${b.from}-${b.to}`, err: e.message, head: b.body.split("\n")[0] }); }
|
||||||
|
}
|
||||||
|
return { blocks, bad };
|
||||||
|
}
|
||||||
|
|
||||||
|
const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||||
|
|
||||||
|
function moduleOf(name) {
|
||||||
|
for (const [mod, names] of Object.entries(MODULES)) if (names.includes(name)) return mod;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function relSpecifier(fromModule, toModule) {
|
||||||
|
const from = path.posix.dirname(fromModule);
|
||||||
|
let rel = path.posix.relative(from, toModule).replace(/\.ts$/, "");
|
||||||
|
if (!rel.startsWith(".")) rel = "./" + rel;
|
||||||
|
return rel;
|
||||||
|
}
|
||||||
|
|
||||||
|
function main() {
|
||||||
|
const { blocks, bad } = analyse();
|
||||||
|
if (bad.length) {
|
||||||
|
console.log("=== 切块语法自检失败 ===");
|
||||||
|
for (const b of bad) console.log(` ${b.where} ${b.err}\n ${b.head}`);
|
||||||
|
process.exitCode = 1;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 去重(同名声明只保留第一份) */
|
||||||
|
const emitted = new Set();
|
||||||
|
const decls = [];
|
||||||
|
const dups = [];
|
||||||
|
for (const b of blocks) {
|
||||||
|
if (b.kind === "stmt") continue;
|
||||||
|
if (emitted.has(b.name)) { dups.push(`${b.name} @ ${b.file}:${b.from}`); continue; }
|
||||||
|
emitted.add(b.name);
|
||||||
|
decls.push(b);
|
||||||
|
}
|
||||||
|
const stmts = blocks.filter((b) => b.kind === "stmt");
|
||||||
|
|
||||||
|
const stateSet = new Set(STATE_VARS);
|
||||||
|
const stateConstSet = new Set(STATE_CONSTS);
|
||||||
|
const homeOf = new Map();
|
||||||
|
const unassigned = [];
|
||||||
|
for (const b of decls) {
|
||||||
|
if (stateSet.has(b.name) || stateConstSet.has(b.name)) homeOf.set(b.name, "core/state.ts");
|
||||||
|
else {
|
||||||
|
const m = moduleOf(b.name);
|
||||||
|
if (!m) unassigned.push(`${b.name} @ ${b.file}:${b.from}`);
|
||||||
|
else homeOf.set(b.name, m);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 引用 / 赋值统计 */
|
||||||
|
const nameSet = new Set([...decls.map((b) => b.name), ...Object.keys(EXTRA_HOME)]);
|
||||||
|
/** 某个名字的「家」:搬过来的块,或手写模块(core/geo.ts 之类)。 */
|
||||||
|
const homeOfExt = (n) => homeOf.get(n) || EXTRA_HOME[n];
|
||||||
|
const identRe = /(\.\.\.|^|[^.\w$])([A-Za-z_$][\w$]*)(?![\w$])/mg;
|
||||||
|
const refsBy = new Map();
|
||||||
|
const writeBy = new Map();
|
||||||
|
const units = [
|
||||||
|
...decls.map((b) => ({ module: homeOf.get(b.name), text: b.masked, where: `${b.file}:${b.from}` })),
|
||||||
|
...stmts.map((b) => ({ module: "__boot", text: b.masked, where: `${b.file}:${b.from}` })),
|
||||||
|
];
|
||||||
|
for (const u of units) {
|
||||||
|
let m;
|
||||||
|
identRe.lastIndex = 0;
|
||||||
|
while ((m = identRe.exec(u.text))) {
|
||||||
|
const n = m[2];
|
||||||
|
if (!nameSet.has(n)) continue;
|
||||||
|
if (!refsBy.has(n)) refsBy.set(n, new Set());
|
||||||
|
refsBy.get(n).add(u.module);
|
||||||
|
}
|
||||||
|
for (const n of nameSet) {
|
||||||
|
const re = new RegExp(`(^|[^.\\w$])${esc(n)}\\s*(=(?![=>])|\\+=|-=|\\*=|/=|\\+\\+|--)`, "g");
|
||||||
|
let mm;
|
||||||
|
while ((mm = re.exec(u.text))) {
|
||||||
|
if (!writeBy.has(n)) writeBy.set(n, new Set());
|
||||||
|
writeBy.get(n).add(u.module);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const crossRef = (n) => [...(refsBy.get(n) || [])].some((m) => m !== homeOf.get(n));
|
||||||
|
const foreignWriters = (n) => [...(writeBy.get(n) || [])].filter((m) => m !== homeOf.get(n));
|
||||||
|
|
||||||
|
/* 局部遮蔽检查(只查真·声明位置) */
|
||||||
|
const shadowOf = new Map();
|
||||||
|
for (const b of blocks) {
|
||||||
|
for (const n of stateSet) {
|
||||||
|
const pats = [
|
||||||
|
new RegExp(`\\(\\s*${esc(n)}\\s*[,)]`),
|
||||||
|
new RegExp(`,\\s*${esc(n)}\\s*[,)=]`),
|
||||||
|
new RegExp(`(?:let|const|var)\\s+${esc(n)}\\b`),
|
||||||
|
new RegExp(`catch\\s*\\(\\s*${esc(n)}\\b`),
|
||||||
|
new RegExp(`(?:^|[\\s(,])${esc(n)}\\s*=>`),
|
||||||
|
new RegExp(`\\(\\s*\\{[^)]*\\b${esc(n)}\\b[^)]*\\}\\s*\\)\\s*=`),
|
||||||
|
];
|
||||||
|
if (pats.some((r) => r.test(b.masked))) {
|
||||||
|
if (!shadowOf.has(n)) shadowOf.set(n, []);
|
||||||
|
shadowOf.get(n).push(`${b.file}:${b.from} (${b.name || "stmt"})`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ANALYZE_ONLY) {
|
||||||
|
console.log(`块 ${blocks.length} | 声明 ${decls.length} | 顶层语句 ${stmts.length} | 切块语法自检 ✓`);
|
||||||
|
/* 覆盖率:源文件里每一行「有代码但没被任何块覆盖」的都算漏搬 */
|
||||||
|
for (const src of SOURCES) {
|
||||||
|
const text = fs.readFileSync(path.join(ROOT, src.file), "utf8").replace(/\r\n/g, "\n");
|
||||||
|
const mLines = mask(text).split("\n");
|
||||||
|
const covered = new Set();
|
||||||
|
for (const b of blocks) {
|
||||||
|
if (b.file !== src.file) continue;
|
||||||
|
for (let l = b.from; l <= b.to; l++) covered.add(l);
|
||||||
|
}
|
||||||
|
const missing = [];
|
||||||
|
for (let l = 1; l <= mLines.length; l++) {
|
||||||
|
if (covered.has(l)) continue;
|
||||||
|
if (!mLines[l - 1].trim()) continue; // 空行 / 纯注释
|
||||||
|
missing.push(l);
|
||||||
|
}
|
||||||
|
console.log(`覆盖检查 ${src.file}: 共 ${mLines.length} 行,未被块覆盖的**代码**行 ${missing.length}` +
|
||||||
|
(missing.length ? ` -> ${missing.slice(0, 20).join(",")}` : " ✓"));
|
||||||
|
}
|
||||||
|
console.log(`\n未分派声明 ${unassigned.length}: ${unassigned.join(", ") || "无"}`);
|
||||||
|
console.log(`\n同名重复声明 ${dups.length}: ${dups.join("; ") || "无"}`);
|
||||||
|
console.log("\n状态变量的局部遮蔽候选:");
|
||||||
|
for (const [n, list] of shadowOf) console.log(` ${n}: ${list.join("; ")}`);
|
||||||
|
console.log("\n需要 setter 的跨模块赋值变量:");
|
||||||
|
for (const n of nameSet) {
|
||||||
|
const f = foreignWriters(n);
|
||||||
|
if (f.length) console.log(` ${n} home=${homeOf.get(n)} writers=${f.join(",")}`);
|
||||||
|
}
|
||||||
|
console.log("\n顶层语句(按原顺序):");
|
||||||
|
stmts.forEach((s) => console.log(` ${s.file}:${s.from}-${s.to} ${s.body.split("\n")[0].slice(0, 80)}`));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (unassigned.length) {
|
||||||
|
console.error("有声明没分派:" + unassigned.join(", "));
|
||||||
|
process.exitCode = 1;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------------- 5. 改写:状态变量 → S.xxx ---------------- */
|
||||||
|
const renameReport = [];
|
||||||
|
const skippedKeys = [];
|
||||||
|
function rewrite(text, masked) {
|
||||||
|
const spans = [];
|
||||||
|
for (const n of stateSet) {
|
||||||
|
const re = new RegExp(`(\\.\\.\\.|^|[^.\\w$])${esc(n)}(?![\\w$])`, "gm");
|
||||||
|
let m;
|
||||||
|
while ((m = re.exec(masked))) {
|
||||||
|
const start = m.index + m[1].length;
|
||||||
|
const end = start + n.length;
|
||||||
|
if (text.slice(start, end) !== n) continue;
|
||||||
|
const prevCh = masked.slice(0, start).replace(/\s+$/, "").slice(-1);
|
||||||
|
const nextCh = masked.slice(end).replace(/^\s+/, "").slice(0, 1);
|
||||||
|
/* 对象字面量的**键**位置({ name: ... })不动 */
|
||||||
|
if (nextCh === ":" && (prevCh === "{" || prevCh === "," || prevCh === "(")) {
|
||||||
|
skippedKeys.push(`${n} @ ${prevCh}${n}:`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
/* 对象字面量的**简写属性**(`{ map, ... }`):必须写成 `map: S.map`,
|
||||||
|
* 否则 `S.map` 在键位置不是合法语法。判断方式:该行(去掉缩进、去掉
|
||||||
|
* 行尾逗号)恰好只有这个名字。全仓只有 map.js:3242 一处。 */
|
||||||
|
const lineStart = masked.lastIndexOf("\n", start) + 1;
|
||||||
|
const nl = masked.indexOf("\n", end);
|
||||||
|
const lineEnd = nl < 0 ? masked.length : nl;
|
||||||
|
const lineCode = text.slice(lineStart, lineEnd).trim();
|
||||||
|
const lineMasked = masked.slice(lineStart, lineEnd).trim();
|
||||||
|
if ((lineMasked === n || lineMasked === n + ",") && lineCode === lineMasked) {
|
||||||
|
spans.push([start, end, `${n}: S.${n}`]);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
spans.push([start, end, `S.${n}`]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
spans.sort((a, b) => b[0] - a[0]);
|
||||||
|
let out = text;
|
||||||
|
for (const [s, e, rep] of spans) out = out.slice(0, s) + rep + out.slice(e);
|
||||||
|
if (spans.length) renameReport.push(spans.length);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
const n_of = (text, s, e) => text.slice(s, e);
|
||||||
|
|
||||||
|
const rewritten = new Map();
|
||||||
|
for (const b of blocks) {
|
||||||
|
rewritten.set(b, b.body);
|
||||||
|
}
|
||||||
|
function applyRewrite(b) { rewritten.set(b, rewrite(b.body, b.masked)); }
|
||||||
|
|
||||||
|
/* ---------------- 6. 生成 core/state.ts ---------------- */
|
||||||
|
const stateLines = [];
|
||||||
|
stateLines.push("/* 全局可变状态集中处。");
|
||||||
|
stateLines.push(" *");
|
||||||
|
stateLines.push(" * 原实现里 map.js 顶部那一堆 `let xxx = ...` 是**经典脚本的全局词法绑定**,");
|
||||||
|
stateLines.push(" * 被 navigation/share/subscribe/map 四个脚本一起读写。改成 ES 模块后,import 进来的");
|
||||||
|
stateLines.push(" * 绑定不可赋值,所以这里统一收进 S 对象;正文里的裸标识符写成 S.xxx(由 tools/gen.mjs 改写)。");
|
||||||
|
stateLines.push(" * 语义不变:同一个对象、同一份可变状态、初始化顺序仍在模块求值阶段。");
|
||||||
|
stateLines.push(" */");
|
||||||
|
stateLines.push("");
|
||||||
|
stateLines.push("/** 状态容器类型:字段按需增删,读取处一律 any。 */");
|
||||||
|
stateLines.push("export type AppState = Record<string, any>;");
|
||||||
|
stateLines.push("");
|
||||||
|
stateLines.push("export const S: AppState = {");
|
||||||
|
const stateBlocks = decls.filter((b) => stateSet.has(b.name));
|
||||||
|
for (const b of stateBlocks) {
|
||||||
|
const init = extractInitializer(b.body, b.name);
|
||||||
|
stateLines.push(` // ${b.file}:${b.from}`);
|
||||||
|
stateLines.push(` ${init},`);
|
||||||
|
}
|
||||||
|
stateLines.push("};");
|
||||||
|
stateLines.push("");
|
||||||
|
for (const b of decls.filter((x) => stateConstSet.has(x.name))) {
|
||||||
|
const masked = mask(b.body);
|
||||||
|
const semi = masked.lastIndexOf(";");
|
||||||
|
const decl = semi > 0 ? b.body.slice(0, semi + 1) : b.body;
|
||||||
|
stateLines.push(`// ${b.file}:${b.from}`);
|
||||||
|
stateLines.push(`export ${decl.replace(/^var\s+/, "const ")}`);
|
||||||
|
stateLines.push("");
|
||||||
|
}
|
||||||
|
const stateSrc = stateLines.join("\n") + "\n";
|
||||||
|
|
||||||
|
/* ---------------- 7. 生成各功能模块 ---------------- */
|
||||||
|
const moduleOrder = [
|
||||||
|
"core/http.ts", "core/format.ts", "map/icons.ts", "map/core.ts", "map/markers.ts",
|
||||||
|
"card/bike-card.ts", "order/status.ts", "order/actions.ts", "ui/settings.ts", "ui/modals.ts",
|
||||||
|
"nav/navigation.ts", "nav/walk-route.ts", "share/share.ts", "subscribe/subscribe.ts",
|
||||||
|
];
|
||||||
|
const byModule = new Map(moduleOrder.map((m) => [m, []]));
|
||||||
|
for (const b of decls) {
|
||||||
|
const home = homeOf.get(b.name);
|
||||||
|
if (home === "core/state.ts") { applyRewriteAlways(b); continue; }
|
||||||
|
byModule.get(home).push(b);
|
||||||
|
}
|
||||||
|
function applyRewriteAlways(b) {
|
||||||
|
/* state 变量在 state.ts 里是对象字段,不改写;但其它块要改 */
|
||||||
|
rewritten.set(b, b.body);
|
||||||
|
}
|
||||||
|
for (const [mod, list] of byModule) {
|
||||||
|
for (const b of list) applyRewrite(b);
|
||||||
|
}
|
||||||
|
for (const st of stmts) applyRewrite(st);
|
||||||
|
|
||||||
|
const fileOut = new Map();
|
||||||
|
for (const mod of moduleOrder) {
|
||||||
|
const list = byModule.get(mod);
|
||||||
|
const needS = list.some((b) => rewritten.get(b).includes("S."));
|
||||||
|
const imports = new Map();
|
||||||
|
const add = (target, name) => {
|
||||||
|
if (!imports.has(target)) imports.set(target, new Set());
|
||||||
|
imports.get(target).add(name);
|
||||||
|
};
|
||||||
|
for (const b of list) {
|
||||||
|
let m;
|
||||||
|
identRe.lastIndex = 0;
|
||||||
|
while ((m = identRe.exec(b.masked))) {
|
||||||
|
const n = m[2];
|
||||||
|
if (!nameSet.has(n)) continue;
|
||||||
|
const home = homeOfExt(n);
|
||||||
|
if (!home || home === mod) continue;
|
||||||
|
if (stateSet.has(n)) continue; /* S 的字段走 S.x;stateConstSet 是普通 const,仍需 import */
|
||||||
|
add(home, n);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const head = [];
|
||||||
|
head.push(`/* 由 static/js/{navigation,share,subscribe,map}.js 逐块搬运而来;正文与原实现一致。 */`);
|
||||||
|
head.push("");
|
||||||
|
if (needS) head.push(`import { S } from "${relSpecifier(mod, "core/state.ts")}";`);
|
||||||
|
const sc = [...(imports.get("core/state.ts") || [])];
|
||||||
|
if (sc.length) head.push(`import { ${sc.join(", ")} } from "${relSpecifier(mod, "core/state.ts")}";`);
|
||||||
|
for (const [target, names] of [...imports].sort((a, b) => a[0].localeCompare(b[0]))) {
|
||||||
|
if (target === "core/state.ts") continue;
|
||||||
|
head.push(`import { ${[...names].sort().join(", ")} } from "${relSpecifier(mod, target)}";`);
|
||||||
|
}
|
||||||
|
if (head[head.length - 1] !== "") head.push("");
|
||||||
|
|
||||||
|
const body = [];
|
||||||
|
for (const b of list) {
|
||||||
|
const txt = rewritten.get(b);
|
||||||
|
body.push(`// ${b.file}:${b.from}-${b.to}`);
|
||||||
|
if (b.kind === "function") body.push("export " + txt);
|
||||||
|
else if (b.kind === "var") {
|
||||||
|
const exp = crossRef(b.name) ? "export " : "";
|
||||||
|
/* 顶层 let 一律标 any:这些变量在原实现里是 JS 的动态变量,会被赋成别的类型 */
|
||||||
|
const annotated = b.declKind === "let" ? annotateLetAny(txt, b.name) : txt;
|
||||||
|
body.push(exp + annotated);
|
||||||
|
}
|
||||||
|
body.push("");
|
||||||
|
}
|
||||||
|
fileOut.set(mod, head.join("\n") + body.join("\n"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------------- 8. 生成 main.ts(bootstrap 顺序) ---------------- */
|
||||||
|
const bootImports = new Map();
|
||||||
|
for (const st of stmts) {
|
||||||
|
let m;
|
||||||
|
identRe.lastIndex = 0;
|
||||||
|
while ((m = identRe.exec(st.masked))) {
|
||||||
|
const n = m[2];
|
||||||
|
if (!nameSet.has(n)) continue;
|
||||||
|
const home = homeOfExt(n);
|
||||||
|
if (!home || stateSet.has(n)) continue;
|
||||||
|
if (!bootImports.has(home)) bootImports.set(home, new Set());
|
||||||
|
bootImports.get(home).add(n);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const bootNeedS = stmts.some((s) => rewritten.get(s).includes("S."));
|
||||||
|
const mainHead = [
|
||||||
|
"/* 入口:装配顺序 + 原先分散在各脚本顶层的「注册/定时器/首屏初始化」语句。",
|
||||||
|
" *",
|
||||||
|
" * 这些语句在原实现里按 [navigation → share → subscribe → map] 的脚本顺序,",
|
||||||
|
" * 在各文件中「按行号」执行;这里 1:1 按同一顺序搬进 bootstrap(),末尾立即调用。",
|
||||||
|
" */",
|
||||||
|
'import "./compat/globals";',
|
||||||
|
];
|
||||||
|
if (bootNeedS) mainHead.push(`import { S } from "./core/state";`);
|
||||||
|
const scBoot = [...(bootImports.get("core/state.ts") || [])];
|
||||||
|
if (scBoot.length) mainHead.push(`import { ${scBoot.join(", ")} } from "./core/state";`);
|
||||||
|
for (const [target, names] of [...bootImports].sort((a, b) => a[0].localeCompare(b[0]))) {
|
||||||
|
if (target === "core/state.ts") continue;
|
||||||
|
mainHead.push(`import { ${[...names].sort().join(", ")} } from "${relSpecifier("main.ts", target)}";`);
|
||||||
|
}
|
||||||
|
mainHead.push("");
|
||||||
|
mainHead.push("/** 原脚本顶层副作用:注册监听 / 起定时器 / 首屏 auth 与弹窗判定。 */");
|
||||||
|
mainHead.push("export function bootstrap(): void {");
|
||||||
|
for (const st of stmts) {
|
||||||
|
mainHead.push(` // ${st.file}:${st.from}-${st.to}`);
|
||||||
|
mainHead.push(rewritten.get(st).replace(/^/gm, " ").replace(/^ {4}$/gm, ""));
|
||||||
|
}
|
||||||
|
mainHead.push("}");
|
||||||
|
mainHead.push("");
|
||||||
|
mainHead.push("bootstrap();");
|
||||||
|
mainHead.push("");
|
||||||
|
fileOut.set("main.ts", mainHead.join("\n"));
|
||||||
|
|
||||||
|
/* ---------------- 9. 生成 compat/globals.ts ---------------- */
|
||||||
|
const fnNames = decls.filter((b) => b.kind === "function").map((b) => b.name).sort();
|
||||||
|
const compatImports = new Map();
|
||||||
|
for (const b of decls.filter((x) => x.kind === "function")) {
|
||||||
|
const home = homeOf.get(b.name);
|
||||||
|
if (!compatImports.has(home)) compatImports.set(home, new Set());
|
||||||
|
compatImports.get(home).add(b.name);
|
||||||
|
}
|
||||||
|
const compat = [];
|
||||||
|
compat.push("/* **唯一**把函数挂到 window 的地方。");
|
||||||
|
compat.push(" *");
|
||||||
|
compat.push(" * templates/map.html 里还有大量内联 onclick=\"foo()\",它们要求 foo 是全局函数。");
|
||||||
|
compat.push(" * 原实现是经典脚本(顶层 function 声明天然成为全局),bundle 之后必须显式挂回去。");
|
||||||
|
compat.push(" * 函数清单由 tools/gen.mjs 从源文件里抓,正常情况下与 map.js 的全局面 1:1 对应。");
|
||||||
|
compat.push(" */");
|
||||||
|
compat.push(`import { Geo, offsetCoord, calcDistance } from "${relSpecifier("compat/globals.ts", "core/geo.ts")}";`);
|
||||||
|
for (const [target, names] of [...compatImports].sort((a, b) => a[0].localeCompare(b[0]))) {
|
||||||
|
compat.push(`import { ${[...names].sort().join(", ")} } from "${relSpecifier("compat/globals.ts", target)}";`);
|
||||||
|
}
|
||||||
|
compat.push("");
|
||||||
|
compat.push("/* 直接写 window.X = X,便于正则核对与调试(Window 已加索引签名,见 types/api.d.ts) */");
|
||||||
|
compat.push("");
|
||||||
|
for (const n of fnNames) compat.push(`window.${n} = ${n};`);
|
||||||
|
compat.push("");
|
||||||
|
compat.push("/* 原 static/js/src/core/geo.js 也把这三个挂在 window 上,这里挂同一份实现。 */");
|
||||||
|
compat.push("window.Geo = Geo;");
|
||||||
|
compat.push("window.offsetCoord = offsetCoord;");
|
||||||
|
compat.push("window.calcDistance = calcDistance;");
|
||||||
|
compat.push("");
|
||||||
|
fileOut.set("compat/globals.ts", compat.join("\n") + "\n");
|
||||||
|
|
||||||
|
/* ---------------- 9.5 类型补丁(逐条登记,重跑生成会重新套用) ----------------
|
||||||
|
* 这些是「原文是原生 JS、在 TS 下需要显式类型」的最小改动,全部只影响类型:
|
||||||
|
* 没有一条改动运行时行为(String(n) / 类型标注 / 可选参数 / as any)。
|
||||||
|
*/
|
||||||
|
const TEXT_PATCHES = [
|
||||||
|
/* 通用:TS7 下 Object.values(any) 与 new Promise(...) 会推成 unknown[] / unknown */
|
||||||
|
{ mod: "*", find: /Object\.values\(/g, replace: "Object.values<any>(" },
|
||||||
|
{ mod: "*", find: /Object\.entries\(/g, replace: "Object.entries<any>(" },
|
||||||
|
{ mod: "*", find: /new Promise\(/g, replace: "new Promise<any>(" },
|
||||||
|
|
||||||
|
/* core/http.ts:opts 上要挂 body,shareApi 后两个参数可选(原实现就是这样调用的) */
|
||||||
|
{ mod: "core/http.ts", find: 'export function shareApi(url, method, body) {', replace: 'export function shareApi(url: string, method?: string, body?: any) {' },
|
||||||
|
{ mod: "core/http.ts", find: 'const opts = { method: method || "GET", headers: {} };', replace: 'const opts: any = { method: method || "GET", headers: {} };' },
|
||||||
|
|
||||||
|
/* card/bike-card.ts:SVG 属性与 textContent 只吃字符串 */
|
||||||
|
{ mod: "card/bike-card.ts", find: 'fill.setAttribute("width", w);', replace: 'fill.setAttribute("width", String(w));' },
|
||||||
|
{ mod: "card/bike-card.ts", find: 'document.getElementById("card-electric").textContent = Math.round(electric);', replace: 'document.getElementById("card-electric").textContent = String(Math.round(electric));' },
|
||||||
|
|
||||||
|
/* map/markers.ts:状态计数写进 textContent */
|
||||||
|
{ mod: "map/markers.ts", find: '.textContent = availableCount;', replace: '.textContent = String(availableCount);' },
|
||||||
|
{ mod: "map/markers.ts", find: '.textContent = usedCount;', replace: '.textContent = String(usedCount);' },
|
||||||
|
{ mod: "map/markers.ts", find: '.textContent = lockedCount;', replace: '.textContent = String(lockedCount);' },
|
||||||
|
{ mod: "map/markers.ts", find: '.textContent = reservedCount;', replace: '.textContent = String(reservedCount);' },
|
||||||
|
{ mod: "map/markers.ts", find: '.textContent = lowCount;', replace: '.textContent = String(lowCount);' },
|
||||||
|
|
||||||
|
/* order/actions.ts:同上(响铃筛选面板的计数) */
|
||||||
|
{ mod: "order/actions.ts", find: ".textContent = counts.available;", replace: ".textContent = String(counts.available);" },
|
||||||
|
{ mod: "order/actions.ts", find: ".textContent = counts.used;", replace: ".textContent = String(counts.used);" },
|
||||||
|
{ mod: "order/actions.ts", find: ".textContent = counts.locked;", replace: ".textContent = String(counts.locked);" },
|
||||||
|
{ mod: "order/actions.ts", find: ".textContent = counts.low;", replace: ".textContent = String(counts.low);" },
|
||||||
|
{ mod: "order/actions.ts", find: ".textContent = counts.reserved;", replace: ".textContent = String(counts.reserved);" },
|
||||||
|
/* 同一个对象后面才补字段,字面量类型收不住 */
|
||||||
|
{ mod: "order/actions.ts", find: 'const payload = {\n code: unlockPendingCode,', replace: 'const payload: any = {\n code: unlockPendingCode,' },
|
||||||
|
|
||||||
|
/* nav/navigation.ts */
|
||||||
|
{ mod: "nav/navigation.ts", find: 'const D = window.DeviceOrientationEvent;', replace: 'const D: any = (window as any).DeviceOrientationEvent;' },
|
||||||
|
{ mod: "nav/navigation.ts", find: 'const err = new Error(msg);', replace: 'const err: any = new Error(msg);' },
|
||||||
|
];
|
||||||
|
|
||||||
|
const patchWarnings = [];
|
||||||
|
for (const [mod, src] of fileOut) {
|
||||||
|
let out = src;
|
||||||
|
for (const p of TEXT_PATCHES) {
|
||||||
|
if (p.mod !== "*" && p.mod !== mod) continue;
|
||||||
|
if (typeof p.find === "string") {
|
||||||
|
if (!out.includes(p.find)) { patchWarnings.push(`${mod}: 未命中 -> ${p.find.split("\n")[0].slice(0, 60)}`); continue; }
|
||||||
|
out = out.split(p.find).join(p.replace);
|
||||||
|
} else {
|
||||||
|
out = out.replace(p.find, p.replace);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fileOut.set(mod, out);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------------- 10. 落盘 ---------------- */
|
||||||
|
const written = [];
|
||||||
|
for (const [mod, src] of fileOut) {
|
||||||
|
const target = path.join(SRC_TS, mod);
|
||||||
|
fs.mkdirSync(path.dirname(target), { recursive: true });
|
||||||
|
fs.writeFileSync(target, src, "utf8");
|
||||||
|
written.push({ mod, lines: src.split("\n").length });
|
||||||
|
}
|
||||||
|
const stateTarget = path.join(SRC_TS, "core/state.ts");
|
||||||
|
fs.mkdirSync(path.dirname(stateTarget), { recursive: true });
|
||||||
|
fs.writeFileSync(stateTarget, stateSrc, "utf8");
|
||||||
|
written.push({ mod: "core/state.ts", lines: stateSrc.split("\n").length });
|
||||||
|
|
||||||
|
/* 生成物语法自检:改写后的每一块都必须是合法 JS(块里没有 TS 语法,
|
||||||
|
* 所以可以直接用 vm 解析)。专门用来抓「改写把语法搞坏」——
|
||||||
|
* 例如对象简写属性 `{ map }` 被写成 `{ S.map }`。 */
|
||||||
|
const broken = [];
|
||||||
|
for (const b of blocks) {
|
||||||
|
const code = rewritten.get(b);
|
||||||
|
try {
|
||||||
|
new vm.Script(code, { filename: `${b.file}:${b.from}` });
|
||||||
|
} catch (e) {
|
||||||
|
broken.push(`${b.file}:${b.from}-${b.to} ${e.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log("生成结果:");
|
||||||
|
for (const w of written.sort((a, b) => a.mod.localeCompare(b.mod))) {
|
||||||
|
console.log(` src-ts/${w.mod.padEnd(24)} ${String(w.lines).padStart(5)} 行`);
|
||||||
|
}
|
||||||
|
console.log(`\nbootstrap 顶层语句 ${stmts.length} 条;S.xxx 改写 ${renameReport.reduce((a, b) => a + b, 0)} 处`);
|
||||||
|
if (skippedKeys.length) console.log(`对象键跳过 ${skippedKeys.length} 处: ${skippedKeys.slice(0, 20).join(" ")}`);
|
||||||
|
|
||||||
|
/* 保真度统计:把生成结果「反归一化」回原文写法后逐行比对 */
|
||||||
|
const norm = (s) =>
|
||||||
|
s
|
||||||
|
.split("\n")
|
||||||
|
.map((l) => l.replace(/^export\s+/, ""))
|
||||||
|
.join("\n")
|
||||||
|
.replace(/\bS\./g, "")
|
||||||
|
.replace(/\b(let\s+[A-Za-z_$][\w$]*)\s*:\s*any\b/g, "$1")
|
||||||
|
.replace(/\bString\(([^()]*)\)/g, "$1")
|
||||||
|
.replace(/<any>/g, "");
|
||||||
|
let origLines = 0, genLines = 0, diffLines = 0;
|
||||||
|
const diffSamples = [];
|
||||||
|
for (const b of blocks) {
|
||||||
|
const ol = norm(b.body).split("\n");
|
||||||
|
const gl = norm(rewritten.get(b)).split("\n");
|
||||||
|
origLines += ol.length;
|
||||||
|
genLines += gl.length;
|
||||||
|
const n = Math.max(ol.length, gl.length);
|
||||||
|
for (let i = 0; i < n; i++) {
|
||||||
|
if ((ol[i] || "") !== (gl[i] || "")) {
|
||||||
|
diffLines++;
|
||||||
|
if (diffSamples.length < 8) diffSamples.push(`${b.file}:${b.from} ${String(gl[i] || ol[i] || "").trim().slice(0, 76)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
console.log(`保真度:${blocks.length} 块 / 原文 ${origLines} 行 → 生成 ${genLines} 行;归一化后差异行 ${diffLines}`);
|
||||||
|
diffSamples.forEach((d) => console.log(" " + d));
|
||||||
|
const fw = [...nameSet].filter((n) => foreignWriters(n).length);
|
||||||
|
if (fw.length) console.log(`\n仍有跨模块赋值的变量(tsc 会报错,需手动换 setter):\n ${fw.join(", ")}`);
|
||||||
|
if (broken.length) {
|
||||||
|
console.log("\n生成物语法自检失败:");
|
||||||
|
for (const b of broken) console.log(" " + b);
|
||||||
|
process.exitCode = 1;
|
||||||
|
} else {
|
||||||
|
console.log("生成物语法自检 ✓(去掉 import/export 后逐文件可解析)");
|
||||||
|
}
|
||||||
|
if (patchWarnings.length) {
|
||||||
|
console.log("\n类型补丁未命中(说明原文变了,需要更新补丁表):");
|
||||||
|
for (const w of patchWarnings) console.log(" " + w);
|
||||||
|
} else {
|
||||||
|
console.log("类型补丁全部命中 ✓");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractInitializer(body, name) {
|
||||||
|
/* 用遮罩后的文本定位 `=` 与终止的 `;`,这样行尾注释不会混进初始值。 */
|
||||||
|
const masked = mask(body);
|
||||||
|
const eq = masked.indexOf("=");
|
||||||
|
const semi = masked.lastIndexOf(";");
|
||||||
|
if (eq < 0 || semi < eq) return `${name}: undefined`;
|
||||||
|
const init = body.slice(eq + 1, semi).trim();
|
||||||
|
if (!init) return `${name}: undefined`;
|
||||||
|
return `${name}: ${init}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 给顶层 `let NAME = ...` 补 `: any`(原实现这些变量是动态的)。 */
|
||||||
|
function annotateLetAny(text, name) {
|
||||||
|
const re = new RegExp(`^(let|var)\\s+${esc(name)}(\\s*)([:=])`);
|
||||||
|
const m = re.exec(text);
|
||||||
|
if (!m) return text;
|
||||||
|
if (m[3] === ":") return text; // 已有类型标注
|
||||||
|
return text.replace(re, `$1 ${name}: any$2$3`);
|
||||||
|
}
|
||||||
|
|
||||||
|
main();
|
||||||
@@ -0,0 +1,348 @@
|
|||||||
|
/* 冒烟测试:在 Node 里用一套极简 DOM/BMapGL 桩加载 static/dist/app.js,
|
||||||
|
* 只验证「模块图能求值 + bootstrap 能跑完」——用来抓 ES 模块化引入的
|
||||||
|
* ReferenceError / TDZ / 装错顺序问题。不做真实渲染。
|
||||||
|
*
|
||||||
|
* node src-ts/tools/smoke.cjs
|
||||||
|
*/
|
||||||
|
const fs = require("node:fs");
|
||||||
|
const path = require("node:path");
|
||||||
|
const vm = require("node:vm");
|
||||||
|
|
||||||
|
const ROOT = path.resolve(__dirname, "..", "..");
|
||||||
|
const code = fs.readFileSync(path.join(ROOT, "static", "dist", "app.js"), "utf8");
|
||||||
|
|
||||||
|
const errors = [];
|
||||||
|
function track(label, fn) {
|
||||||
|
try { return fn(); } catch (e) { errors.push(`${label}: ${e && e.message}`); }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------------- DOM 桩 ---------------- */
|
||||||
|
const listeners = [];
|
||||||
|
function makeEl(tag = "div") {
|
||||||
|
const el = {
|
||||||
|
tagName: String(tag).toUpperCase(),
|
||||||
|
style: { setProperty() {}, getPropertyValue() { return ""; }, removeProperty() {}, cssText: "" },
|
||||||
|
dataset: {},
|
||||||
|
classList: { add() {}, remove() {}, toggle() {}, contains() { return false; } },
|
||||||
|
children: [],
|
||||||
|
childNodes: [],
|
||||||
|
parentNode: null,
|
||||||
|
innerHTML: "",
|
||||||
|
innerText: "",
|
||||||
|
textContent: "",
|
||||||
|
value: "",
|
||||||
|
checked: false,
|
||||||
|
disabled: false,
|
||||||
|
hidden: false,
|
||||||
|
width: 0,
|
||||||
|
height: 0,
|
||||||
|
offsetWidth: 100,
|
||||||
|
offsetHeight: 100,
|
||||||
|
clientWidth: 100,
|
||||||
|
clientHeight: 100,
|
||||||
|
scrollTop: 0,
|
||||||
|
appendChild(c) { this.children.push(c); return c; },
|
||||||
|
removeChild(c) { this.children = this.children.filter((x) => x !== c); return c; },
|
||||||
|
insertBefore(c) { this.children.push(c); return c; },
|
||||||
|
addEventListener(n, f) { listeners.push([this, n, f]); },
|
||||||
|
removeEventListener() {},
|
||||||
|
setAttribute(k, v) { this[k] = v; },
|
||||||
|
getAttribute() { return null; },
|
||||||
|
removeAttribute() {},
|
||||||
|
hasAttribute() { return false; },
|
||||||
|
querySelector() { return makeEl(); },
|
||||||
|
querySelectorAll() { return []; },
|
||||||
|
getElementsByClassName() { return []; },
|
||||||
|
getElementsByTagName() { return []; },
|
||||||
|
append() {},
|
||||||
|
before() {},
|
||||||
|
after() {},
|
||||||
|
replaceWith() {},
|
||||||
|
normalize() {},
|
||||||
|
setPointerCapture() {},
|
||||||
|
releasePointerCapture() {},
|
||||||
|
closest() { return makeEl(); },
|
||||||
|
insertAdjacentHTML() {},
|
||||||
|
focus() {},
|
||||||
|
blur() {},
|
||||||
|
click() {},
|
||||||
|
cloneNode() { return makeEl(tag); },
|
||||||
|
getBoundingClientRect() { return { top: 0, left: 0, right: 100, bottom: 100, width: 100, height: 100, x: 0, y: 0 }; },
|
||||||
|
scrollIntoView() {},
|
||||||
|
animate() { return { finished: Promise.resolve(), cancel() {}, onfinish: null }; },
|
||||||
|
getContext() {
|
||||||
|
const noop = () => {};
|
||||||
|
return {
|
||||||
|
beginPath: noop, arc: noop, fill: noop, stroke: noop, fillText: noop,
|
||||||
|
measureText: () => ({ width: 10 }), clearRect: noop, drawImage: noop,
|
||||||
|
createLinearGradient: () => ({ addColorStop: noop }), save: noop, restore: noop,
|
||||||
|
translate: noop, rotate: noop, scale: noop, setTransform: noop,
|
||||||
|
moveTo: noop, lineTo: noop, closePath: noop, rect: noop, fillRect: noop,
|
||||||
|
strokeRect: noop, putImageData: noop, getImageData: () => ({ data: [] }),
|
||||||
|
set fillStyle(v) {}, set strokeStyle(v) {}, set lineWidth(v) {},
|
||||||
|
set font(v) {}, set textAlign(v) {}, set textBaseline(v) {},
|
||||||
|
set shadowColor(v) {}, set shadowBlur(v) {}, set lineCap(v) {},
|
||||||
|
set globalAlpha(v) {}, set lineJoin(v) {},
|
||||||
|
};
|
||||||
|
},
|
||||||
|
toDataURL() { return "data:image/png;base64,AAA"; },
|
||||||
|
};
|
||||||
|
return el;
|
||||||
|
}
|
||||||
|
|
||||||
|
const byId = new Map();
|
||||||
|
const document = {
|
||||||
|
readyState: "loading",
|
||||||
|
body: makeEl("body"),
|
||||||
|
head: makeEl("head"),
|
||||||
|
documentElement: makeEl("html"),
|
||||||
|
getElementById(id) {
|
||||||
|
if (!byId.has(id)) byId.set(id, makeEl());
|
||||||
|
return byId.get(id);
|
||||||
|
},
|
||||||
|
createElement: (t) => makeEl(t),
|
||||||
|
createElementNS: (ns, t) => makeEl(t),
|
||||||
|
createTextNode: () => makeEl("text"),
|
||||||
|
querySelector: () => makeEl(),
|
||||||
|
querySelectorAll: () => [],
|
||||||
|
addEventListener(n, f) { listeners.push(["document", n, f]); },
|
||||||
|
removeEventListener() {},
|
||||||
|
dispatchEvent() { return true; },
|
||||||
|
cookie: "",
|
||||||
|
};
|
||||||
|
|
||||||
|
/* ---------------- BMapGL 桩 ---------------- */
|
||||||
|
/** 未知方法一律返回空函数,避免桩漏方法就报错(真实 SDK 的方法我们并不校验) */
|
||||||
|
function tolerant(obj) {
|
||||||
|
return new Proxy(obj, {
|
||||||
|
get(t, k) {
|
||||||
|
if (k in t) return t[k];
|
||||||
|
if (typeof k === "string") return function () { return undefined; };
|
||||||
|
return undefined;
|
||||||
|
},
|
||||||
|
set(t, k, v) { t[k] = v; return true; },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function overlayStub(kind) {
|
||||||
|
return function (a, b, c) {
|
||||||
|
const self = this;
|
||||||
|
this.kind = kind;
|
||||||
|
this.args = [a, b, c];
|
||||||
|
this.addEventListener = () => {};
|
||||||
|
this.removeEventListener = () => {};
|
||||||
|
this.setPosition = () => {};
|
||||||
|
this.getPosition = () => ({ lng: 116.98, lat: 36.67 });
|
||||||
|
this.show = () => {};
|
||||||
|
this.hide = () => {};
|
||||||
|
this.setIcon = () => {};
|
||||||
|
this.setContent = () => {};
|
||||||
|
this.setOffset = () => {};
|
||||||
|
this.setTitle = () => {};
|
||||||
|
this.setSize = () => {};
|
||||||
|
this.setFillColor = () => {};
|
||||||
|
this.setStrokeColor = () => {};
|
||||||
|
this.setStrokeWeight = () => {};
|
||||||
|
this.setStrokeOpacity = () => {};
|
||||||
|
this.setFillOpacity = () => {};
|
||||||
|
this.setPath = () => {};
|
||||||
|
this.setRaiseOnDrag = () => {};
|
||||||
|
this.setTop = () => {};
|
||||||
|
this.getMap = () => null;
|
||||||
|
return tolerant(this);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const MapStub = function (container, opts) {
|
||||||
|
this.container = container;
|
||||||
|
this.opts = opts;
|
||||||
|
this._listeners = {};
|
||||||
|
};
|
||||||
|
MapStub.prototype.addEventListener = function (n, f) { (this._listeners[n] = this._listeners[n] || []).push(f); };
|
||||||
|
MapStub.prototype.removeEventListener = function () {};
|
||||||
|
MapStub.prototype.centerAndZoom = function () {};
|
||||||
|
MapStub.prototype.setCenter = function () {};
|
||||||
|
MapStub.prototype.getCenter = function () { return { lng: 116.98, lat: 36.67 }; };
|
||||||
|
MapStub.prototype.getZoom = function () { return 17; };
|
||||||
|
MapStub.prototype.setZoom = function () {};
|
||||||
|
MapStub.prototype.enableScrollWheelZoom = function () {};
|
||||||
|
MapStub.prototype.disableScrollWheelZoom = function () {};
|
||||||
|
MapStub.prototype.enableDragging = function () {};
|
||||||
|
MapStub.prototype.disableDragging = function () {};
|
||||||
|
MapStub.prototype.enableDoubleClickZoom = function () {};
|
||||||
|
MapStub.prototype.addOverlay = function (o) { return o; };
|
||||||
|
MapStub.prototype.removeOverlay = function () {};
|
||||||
|
MapStub.prototype.clearOverlays = function () {};
|
||||||
|
MapStub.prototype.getOverlays = function () { return []; };
|
||||||
|
MapStub.prototype.addControl = function () {};
|
||||||
|
MapStub.prototype.setMapStyleV2 = function () {};
|
||||||
|
MapStub.prototype.setMapStyle = function () {};
|
||||||
|
MapStub.prototype.setViewport = function () {};
|
||||||
|
MapStub.prototype.getViewport = function () { return {}; };
|
||||||
|
MapStub.prototype.panTo = function () {};
|
||||||
|
MapStub.prototype.panBy = function () {};
|
||||||
|
MapStub.prototype.setHeading = function () {};
|
||||||
|
MapStub.prototype.getHeading = function () { return 0; };
|
||||||
|
MapStub.prototype.setTilt = function () {};
|
||||||
|
MapStub.prototype.startViewAnimation = function () {};
|
||||||
|
MapStub.prototype.pixelToPoint = function () { return { lng: 0, lat: 0 }; };
|
||||||
|
MapStub.prototype.pointToPixel = function () { return { x: 0, y: 0 }; };
|
||||||
|
MapStub.prototype.openInfoWindow = function () {};
|
||||||
|
MapStub.prototype.closeInfoWindow = function () {};
|
||||||
|
|
||||||
|
const BMapGL = {
|
||||||
|
Map: function (container, opts) { return tolerant(new MapStub(container, opts)); },
|
||||||
|
Point: function (lng, lat) { this.lng = lng; this.lat = lat; this.equals = (o) => o && o.lng === lng && o.lat === lat; },
|
||||||
|
Size: function (w, h) { this.width = w; this.height = h; },
|
||||||
|
Icon: overlayStub("Icon"),
|
||||||
|
Marker: overlayStub("Marker"),
|
||||||
|
Polyline: overlayStub("Polyline"),
|
||||||
|
Polygon: overlayStub("Polygon"),
|
||||||
|
Circle: overlayStub("Circle"),
|
||||||
|
Overlay: overlayStub("Overlay"),
|
||||||
|
ScaleControl: overlayStub("ScaleControl"),
|
||||||
|
ViewAnimation: overlayStub("ViewAnimation"),
|
||||||
|
Convertor: overlayStub("Convertor"),
|
||||||
|
WalkingRoute: function (map, opts) { this.map = map; this.opts = opts || {}; this.search = () => {}; },
|
||||||
|
};
|
||||||
|
|
||||||
|
/* ---------------- 其它外部全局 ---------------- */
|
||||||
|
const storage = {
|
||||||
|
_d: new Map(),
|
||||||
|
getItem(k) { return this._d.has(k) ? this._d.get(k) : null; },
|
||||||
|
setItem(k, v) { this._d.set(k, String(v)); },
|
||||||
|
removeItem(k) { this._d.delete(k); },
|
||||||
|
clear() { this._d.clear(); },
|
||||||
|
};
|
||||||
|
const noopTimer = () => 0;
|
||||||
|
const requests = [];
|
||||||
|
const sandbox = {
|
||||||
|
console,
|
||||||
|
document,
|
||||||
|
navigator: { userAgent: "node-smoke", geolocation: { getCurrentPosition(cb) { cb({ coords: { latitude: 36.67, longitude: 116.98 } }); }, watchPosition() { return 1; }, clearWatch() {} }, deviceMemory: 4, language: "zh-CN" },
|
||||||
|
location: { href: "http://127.0.0.1/", origin: "http://127.0.0.1", hostname: "127.0.0.1", protocol: "http:", search: "", pathname: "/", replace() {}, assign() {} },
|
||||||
|
history: { replaceState() {}, pushState() {}, back() {} },
|
||||||
|
localStorage: storage,
|
||||||
|
sessionStorage: storage,
|
||||||
|
performance: { now: () => Date.now() },
|
||||||
|
setTimeout: noopTimer,
|
||||||
|
clearTimeout: () => {},
|
||||||
|
setInterval: noopTimer,
|
||||||
|
clearInterval: () => {},
|
||||||
|
requestAnimationFrame: () => 0,
|
||||||
|
cancelAnimationFrame: () => {},
|
||||||
|
matchMedia: () => ({ matches: false, addEventListener() {}, removeEventListener() {}, addListener() {}, removeListener() {} }),
|
||||||
|
fetch: (url) => {
|
||||||
|
requests.push(String(url));
|
||||||
|
return Promise.resolve({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
headers: { get: () => null },
|
||||||
|
json: () => Promise.resolve({ rtn_code: 0, data: { logged_in: true, email: "smoke@example.com", nickname: "smoke" }, results: [], has_order: false, message: "", map_snapshot: { server_time: Math.floor(Date.now() / 1000) }, center_lat: 36.67, center_lng: 116.98 }),
|
||||||
|
text: () => Promise.resolve(""),
|
||||||
|
});
|
||||||
|
},
|
||||||
|
alert: () => {},
|
||||||
|
confirm: () => true,
|
||||||
|
prompt: () => null,
|
||||||
|
Image: function () { this.src = ""; this.onload = null; },
|
||||||
|
Event: function (t) { this.type = t; },
|
||||||
|
CustomEvent: function (t, o) { this.type = t; this.detail = o && o.detail; },
|
||||||
|
DeviceOrientationEvent: Object.assign(function () {}, { requestPermission: () => Promise.resolve("granted") }),
|
||||||
|
BMapGL,
|
||||||
|
QRCode: { CorrectLevel: { L: 1, M: 0, Q: 3, H: 2 }, toCanvas() {}, toDataURL() { return "data:image/png;base64,AAA"; } },
|
||||||
|
coordtransform: {
|
||||||
|
gcj02tobd09: (lng, lat) => [lng + 0.0065, lat + 0.006],
|
||||||
|
bd09togcj02: (lng, lat) => [lng - 0.0065, lat - 0.006],
|
||||||
|
wgs84togcj02: (lng, lat) => [lng, lat],
|
||||||
|
wgs84tobd09: (lng, lat) => [lng + 0.0065, lat + 0.006],
|
||||||
|
},
|
||||||
|
SettingsPages: { open() {}, back() {}, requestBack() {}, close() {}, hide() {}, restore() {}, isOpen: () => false },
|
||||||
|
BikeClusters: {
|
||||||
|
PREFERENCE_KEY: "xbniu_bike_clustering",
|
||||||
|
readClusteringPreference: () => true,
|
||||||
|
writeClusteringPreference: () => true,
|
||||||
|
normalizeBikes: (b) => b || [],
|
||||||
|
bikeId: (b) => (b && (b.bike_code || b.id)) || "",
|
||||||
|
clusterBikes: () => ({ singles: [], clusters: [] }),
|
||||||
|
createLayer: () => ({
|
||||||
|
render() {}, destroy() {}, setSelected() {}, setClusteringEnabled() {},
|
||||||
|
regroup() {}, requestRegroup() {}, expand() {}, listen() {},
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
sandbox.window = sandbox;
|
||||||
|
sandbox.self = sandbox;
|
||||||
|
sandbox.globalThis = sandbox;
|
||||||
|
sandbox.window.top = sandbox;
|
||||||
|
sandbox.window.parent = sandbox;
|
||||||
|
sandbox.window.close = () => {};
|
||||||
|
sandbox.window.open = () => null;
|
||||||
|
sandbox.window.scrollTo = () => {};
|
||||||
|
sandbox.window.addEventListener = (n, f) => listeners.push(["window", n, f]);
|
||||||
|
sandbox.window.removeEventListener = () => {};
|
||||||
|
sandbox.window.dispatchEvent = () => true;
|
||||||
|
sandbox.window.isSecureContext = true;
|
||||||
|
sandbox.window.innerWidth = 390;
|
||||||
|
sandbox.window.innerHeight = 844;
|
||||||
|
sandbox.window.screen = { width: 390, height: 844 };
|
||||||
|
sandbox.window.devicePixelRatio = 2;
|
||||||
|
|
||||||
|
const unhandled = [];
|
||||||
|
process.on("unhandledRejection", (e) => unhandled.push(String((e && e.message) || e)));
|
||||||
|
|
||||||
|
/* 先塞一个 token,让 bootstrap 里的 auth/order/rental 分支都真的跑起来 */
|
||||||
|
storage.setItem("auth_token", "eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE5MDAwMDAwMDAsInVpZCI6MX0.sig");
|
||||||
|
|
||||||
|
|
||||||
|
const ctx = vm.createContext(sandbox);
|
||||||
|
track("bundle 求值", () => new vm.Script(code, { filename: "static/dist/app.js" }).runInContext(ctx));
|
||||||
|
|
||||||
|
(async () => {
|
||||||
|
for (let i = 0; i < 8; i++) await new Promise((r) => setImmediate(r));
|
||||||
|
|
||||||
|
/* 触发首屏初始化:DOMContentLoaded + xbniu-map-ready(原实现就是这么起来的) */
|
||||||
|
const call = (label, pred) => {
|
||||||
|
for (const [target, name, fn] of listeners.slice()) {
|
||||||
|
if (pred(target, name) && typeof fn === "function") track(label + ":" + name, () => fn({ type: name }));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
call("DOMContentLoaded", (t, n) => (t === "document" || t === sandbox.window) && n === "DOMContentLoaded");
|
||||||
|
for (let i = 0; i < 8; i++) await new Promise((r) => setImmediate(r));
|
||||||
|
call("xbniu-map-ready", (t, n) => (t === "window" || t === sandbox.window) && n === "xbniu-map-ready");
|
||||||
|
for (let i = 0; i < 12; i++) await new Promise((r) => setImmediate(r));
|
||||||
|
|
||||||
|
/* ---------------- 断言 ---------------- */
|
||||||
|
const checks = [
|
||||||
|
["window.initMap 是函数", typeof sandbox.initMap === "function"],
|
||||||
|
["window.showBikeDetail 是函数", typeof sandbox.showBikeDetail === "function"],
|
||||||
|
["window.doUnlockBike 是函数", typeof sandbox.doUnlockBike === "function"],
|
||||||
|
["window.toggleNavigation 是函数", typeof sandbox.toggleNavigation === "function"],
|
||||||
|
["window.openShareModal 是函数", typeof sandbox.openShareModal === "function"],
|
||||||
|
["window.offsetCoord 是函数", typeof sandbox.offsetCoord === "function"],
|
||||||
|
["offsetCoord 结果正确", (() => { const r = sandbox.offsetCoord(36.67, 116.98); return Math.abs(r.lat - 36.676) < 1e-6 && Math.abs(r.lng - 116.9865) < 1e-6; })()],
|
||||||
|
["calcDistance 有值", typeof sandbox.calcDistance(36.67, 116.98, 36.68, 116.99) === "number"],
|
||||||
|
["注册了 document 监听", listeners.some((l) => l[0] === "document")],
|
||||||
|
["注册了 window 监听", listeners.some((l) => l[0] === "window")],
|
||||||
|
["发了 /api 请求(带 token 时)", requests.some((u) => u.includes("/api/"))],
|
||||||
|
["异步链没有未捕获异常", unhandled.length === 0],
|
||||||
|
["initMap 后注册了地图监听", listeners.filter((l) => l[0] && l[0]._listeners).length >= 0],
|
||||||
|
["渲染流程拿到 /api/map", requests.some((u) => u.includes("/api/map"))],
|
||||||
|
["元素监听总数 >= 20(含卡片/扫码/寻车长按)", listeners.length >= 20],
|
||||||
|
];
|
||||||
|
|
||||||
|
console.log("=== bundle 冒烟测试 ===");
|
||||||
|
let failed = 0;
|
||||||
|
for (const [name, ok] of checks) {
|
||||||
|
console.log(` ${ok ? "✓" : "✗"} ${name}`);
|
||||||
|
if (!ok) failed++;
|
||||||
|
}
|
||||||
|
if (errors.length) {
|
||||||
|
console.log("\n求值期错误:");
|
||||||
|
for (const e of errors) console.log(" " + e);
|
||||||
|
}
|
||||||
|
console.log(`\n窗口监听数 ${listeners.filter((l) => l[0] === "window").length},document 监听数 ${listeners.filter((l) => l[0] === "document").length},元素监听数 ${listeners.length}`);
|
||||||
|
console.log(`fetch 请求:${[...new Set(requests)].join(", ") || "无"}`);
|
||||||
|
if (unhandled.length) console.log("未捕获的 promise 异常:\n " + unhandled.join("\n "));
|
||||||
|
process.exitCode = failed || errors.length ? 1 : 0;
|
||||||
|
})();
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
/* 验证 4:模板里的内联事件函数名,必须全部能在 bundle 里找到 window.X = X。
|
||||||
|
*
|
||||||
|
* node src-ts/tools/verify-globals.mjs
|
||||||
|
*
|
||||||
|
* 做法:
|
||||||
|
* 1) 从 templates/map.html 抓所有 on*="..." 内联事件,抽出被调用的标识符
|
||||||
|
* 2) 从 static/dist/app.js 抓 `window.X = X` 的赋值集合
|
||||||
|
* 3) 从**仍然单独加载**的静态脚本里抓它们的 window 赋值(ui-motion.js 等),
|
||||||
|
* 这些不是 bundle 的责任,单独列出来
|
||||||
|
* 4) 差集必须为空;同时反查 bundle 里多挂的全局(仅供参考)
|
||||||
|
*
|
||||||
|
* 退出码:差集非空 → 1
|
||||||
|
*/
|
||||||
|
import fs from "node:fs";
|
||||||
|
import path from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
|
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||||
|
const ROOT = path.resolve(HERE, "..", "..");
|
||||||
|
|
||||||
|
const TEMPLATE = path.join(ROOT, "templates", "map.html");
|
||||||
|
const BUNDLE = path.join(ROOT, "static", "dist", "app.js");
|
||||||
|
const ORIGIN_SCRIPTS = [
|
||||||
|
"static/js/map.js",
|
||||||
|
"static/js/navigation.js",
|
||||||
|
"static/js/share.js",
|
||||||
|
"static/js/subscribe.js",
|
||||||
|
];
|
||||||
|
/** 切换到 bundle 之后仍然保留的独立脚本(它们的全局不算 bundle 的缺口) */
|
||||||
|
const STILL_LOADED = [
|
||||||
|
"static/js/ui-motion.js",
|
||||||
|
"static/js/coordtransform.js",
|
||||||
|
"static/js/settings-pages.js",
|
||||||
|
"static/js/bike-clusters.js",
|
||||||
|
"static/js/qrcode.min.js",
|
||||||
|
"static/js/src/core/geo.js",
|
||||||
|
];
|
||||||
|
|
||||||
|
const EVENT_ATTR = /on(?:click|input|change|submit|keydown|keyup|keypress|blur|focus|dblclick|contextmenu|mouseover|mouseout|mouseenter|mouseleave|mousedown|mouseup|touchstart|touchmove|touchend|scroll|load|error|reset|select)\s*=\s*"([^"]*)"/g;
|
||||||
|
const JS_KEYWORDS = new Set([
|
||||||
|
"if", "else", "for", "while", "do", "switch", "case", "break", "continue", "return",
|
||||||
|
"new", "delete", "typeof", "instanceof", "in", "of", "var", "let", "const", "function",
|
||||||
|
"true", "false", "null", "undefined", "this", "void", "try", "catch", "finally", "throw",
|
||||||
|
"await", "async", "yield", "class", "super", "default", "export", "import", "static",
|
||||||
|
]);
|
||||||
|
const DOM_GLOBALS = new Set([
|
||||||
|
"window", "document", "event", "this", "navigator", "location", "console", "JSON", "Math",
|
||||||
|
"Date", "Number", "String", "Boolean", "Array", "Object", "Map", "Set", "Promise", "Error",
|
||||||
|
"parseInt", "parseFloat", "isNaN", "setTimeout", "clearTimeout", "setInterval",
|
||||||
|
"clearInterval", "fetch", "alert", "confirm", "prompt", "localStorage", "sessionStorage",
|
||||||
|
"encodeURIComponent", "decodeURIComponent", "history", "BMapGL", "QRCode", "SettingsPages",
|
||||||
|
"BikeClusters", "coordtransform", "Geo",
|
||||||
|
]);
|
||||||
|
|
||||||
|
const read = (rel) => fs.readFileSync(path.join(ROOT, rel), "utf8");
|
||||||
|
|
||||||
|
/* 1) 模板里的内联事件名 */
|
||||||
|
const html = read("templates/map.html");
|
||||||
|
const handlerCalls = new Set();
|
||||||
|
const handlerAny = new Set();
|
||||||
|
let handlerCount = 0;
|
||||||
|
{
|
||||||
|
let m;
|
||||||
|
EVENT_ATTR.lastIndex = 0;
|
||||||
|
while ((m = EVENT_ATTR.exec(html))) {
|
||||||
|
handlerCount++;
|
||||||
|
const code = m[1];
|
||||||
|
for (const c of code.matchAll(/(?:^|[^\w$.'"-])([A-Za-z_$][\w$]*)\s*\(/g)) handlerCalls.add(c[1]);
|
||||||
|
for (const c of code.matchAll(/(?:^|[^\w$.'"-])([A-Za-z_$][\w$]*)(?![\w$(])/g)) handlerAny.add(c[1]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 2) bundle 里的 window 赋值 */
|
||||||
|
const bundle = read("static/dist/app.js");
|
||||||
|
const bundleGlobals = new Set();
|
||||||
|
for (const m of bundle.matchAll(/window\.([A-Za-z_$][\w$]*)\s*=/g)) bundleGlobals.add(m[1]);
|
||||||
|
|
||||||
|
/* 3) 仍单独加载的脚本提供的全局 */
|
||||||
|
const externalGlobals = new Map();
|
||||||
|
for (const rel of STILL_LOADED) {
|
||||||
|
let src;
|
||||||
|
try { src = read(rel); } catch { continue; }
|
||||||
|
for (const m of src.matchAll(/(?:window|root|global)\.([A-Za-z_$][\w$]*)\s*=/g)) {
|
||||||
|
if (!externalGlobals.has(m[1])) externalGlobals.set(m[1], rel);
|
||||||
|
}
|
||||||
|
for (const m of src.matchAll(/^(?:function\s+|const\s+|var\s+|let\s+)([A-Za-z_$][\w$]*)/gm)) {
|
||||||
|
if (!externalGlobals.has(m[1])) externalGlobals.set(m[1], rel);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 4) 原 4 个脚本里声明过的顶层函数名(判断某个内联名到底该谁提供) */
|
||||||
|
const originNames = new Set();
|
||||||
|
for (const rel of ORIGIN_SCRIPTS) {
|
||||||
|
for (const m of read(rel).matchAll(/^\s{0,6}(?:async\s+)?function\s+([A-Za-z_$][\w$]*)/gm)) originNames.add(m[1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
const relevant = (n) => !JS_KEYWORDS.has(n) && !DOM_GLOBALS.has(n);
|
||||||
|
const wanted = new Set([...handlerCalls, ...handlerAny].filter(relevant));
|
||||||
|
|
||||||
|
const missing = [];
|
||||||
|
const fromExternal = [];
|
||||||
|
const unknown = [];
|
||||||
|
for (const n of [...wanted].sort()) {
|
||||||
|
if (bundleGlobals.has(n)) continue;
|
||||||
|
if (externalGlobals.has(n)) { fromExternal.push(`${n} (<- ${externalGlobals.get(n)})`); continue; }
|
||||||
|
if (originNames.has(n)) { missing.push(n); continue; }
|
||||||
|
unknown.push(n);
|
||||||
|
}
|
||||||
|
|
||||||
|
const extras = [...bundleGlobals].filter((n) => !wanted.has(n)).sort();
|
||||||
|
|
||||||
|
console.log("=== 全局函数核对 ===");
|
||||||
|
console.log(`模板内联事件处数 : ${handlerCount}`);
|
||||||
|
console.log(`其中被调用的不同标识符 : ${handlerCalls.size}`);
|
||||||
|
console.log(`连裸标识符一起算 : ${handlerAny.size}`);
|
||||||
|
console.log(`筛选后需要全局的候选名 : ${wanted.size}`);
|
||||||
|
console.log(`bundle 里 window.X = X : ${bundleGlobals.size}`);
|
||||||
|
console.log("");
|
||||||
|
console.log(`由 bundle 提供的 : ${[...wanted].filter((n) => bundleGlobals.has(n)).length}`);
|
||||||
|
console.log(`由仍加载的静态脚本提供 : ${fromExternal.length}`);
|
||||||
|
fromExternal.forEach((n) => console.log(" " + n));
|
||||||
|
console.log("");
|
||||||
|
console.log(`★ 差集(模板要、bundle 没挂):${missing.length}`);
|
||||||
|
missing.forEach((n) => console.log(" MISSING " + n));
|
||||||
|
console.log("");
|
||||||
|
console.log(`模板里既不在原脚本、也不在静态脚本里的名字(人工确认,多为 DOM/事件变量):${unknown.length}`);
|
||||||
|
unknown.forEach((n) => console.log(" ? " + n));
|
||||||
|
console.log("");
|
||||||
|
console.log(`bundle 多挂的全局(原实现也是全局,属正常):${extras.length}`);
|
||||||
|
console.log(" " + extras.join(", "));
|
||||||
|
|
||||||
|
if (missing.length) {
|
||||||
|
console.error("\n失败:有内联事件函数名没有挂到 window 上");
|
||||||
|
process.exitCode = 1;
|
||||||
|
} else {
|
||||||
|
console.log("\n通过:模板内联事件所需函数名,bundle + 仍加载脚本合起来无缝覆盖(差集为空)");
|
||||||
|
}
|
||||||
Vendored
+162
@@ -0,0 +1,162 @@
|
|||||||
|
/* 后端 JSON 契约类型(Flask 侧 routes/ + app.py 提供)。
|
||||||
|
*
|
||||||
|
* 这些类型**只用来标注与自检**,不改变运行时行为:搬过来的正文仍然按 any 处理,
|
||||||
|
* 但接口路径 / 字段名在这里集中写清楚,后续改动有据可依。
|
||||||
|
*
|
||||||
|
* 约定(与后端一致):所有接口返回体顶层都有 rtn_code(0 = 成功)与 message。
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare global {
|
||||||
|
/** 让 window.foo = foo 这类兼容层赋值无需逐个声明(内联事件用得到)。 */
|
||||||
|
interface Window {
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ApiEnvelope {
|
||||||
|
/** 0 = 成功;401 = 未登录/凭证失效;其余见后端 message */
|
||||||
|
rtn_code?: number;
|
||||||
|
message?: string;
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------------- /api/map ---------------- */
|
||||||
|
export interface BikeRecord {
|
||||||
|
bike_code?: string;
|
||||||
|
latitude?: number;
|
||||||
|
longitude?: number;
|
||||||
|
electric_quantity?: number;
|
||||||
|
electricQuantity?: number;
|
||||||
|
/** 1 = 正常 2 = 损坏 4 = 欠压 10 = 低电量 */
|
||||||
|
state?: number;
|
||||||
|
/** 0 = 空闲 1 = 使用中 */
|
||||||
|
status?: number;
|
||||||
|
distance?: number;
|
||||||
|
/** 扫码/搜索补点来源标记 */
|
||||||
|
scan_type?: string;
|
||||||
|
is_shared?: boolean;
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MapSnapshot {
|
||||||
|
/** 快照生成时间(秒) */
|
||||||
|
server_time?: number;
|
||||||
|
/** 下次刷新间隔(秒) */
|
||||||
|
refresh_seconds?: number;
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MapApiResponse extends ApiEnvelope {
|
||||||
|
/** 车辆列表(renderMap 逐条渲染) */
|
||||||
|
results?: BikeRecord[];
|
||||||
|
/** 地图初始中心(GCJ02,前端逐点转 BD09) */
|
||||||
|
center_lat?: number;
|
||||||
|
center_lng?: number;
|
||||||
|
/** 校园边界 [[lat, lng], ...] */
|
||||||
|
boundary?: number[][];
|
||||||
|
/** 停车区 [{ boundary: [[lat,lng],...], name? }, ...] */
|
||||||
|
parking_areas?: Array<{ boundary?: number[][]; name?: string; [key: string]: any }>;
|
||||||
|
map_snapshot?: MapSnapshot;
|
||||||
|
/** 失败时建议的重试间隔(秒) */
|
||||||
|
retry_after?: number;
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------------- /api/order/status ---------------- */
|
||||||
|
export interface OrderRecord {
|
||||||
|
rental_id?: number;
|
||||||
|
bike_code?: string;
|
||||||
|
latitude?: number;
|
||||||
|
longitude?: number;
|
||||||
|
/** 秒级时间戳 */
|
||||||
|
start_time?: number;
|
||||||
|
end_time?: number;
|
||||||
|
duration_minutes?: number;
|
||||||
|
total_rounds?: number;
|
||||||
|
used_rounds?: number;
|
||||||
|
/** 0 = 进行中 */
|
||||||
|
status?: number;
|
||||||
|
shared?: boolean;
|
||||||
|
owner_email?: string;
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OrderStatusResponse extends ApiEnvelope {
|
||||||
|
has_order?: boolean;
|
||||||
|
order?: OrderRecord;
|
||||||
|
/** 骑行摘要(里程/时长等,展示在横幅上) */
|
||||||
|
summary?: Record<string, any>;
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------------- /api/nav_route ---------------- */
|
||||||
|
export interface NavRouteResponse extends ApiEnvelope {
|
||||||
|
/** 路线总长(米) */
|
||||||
|
distance?: number;
|
||||||
|
/** 预计耗时(秒) */
|
||||||
|
duration?: number;
|
||||||
|
/** 路径点(GCJ02 [lat, lng] 或 {lat,lng},按后端实现为准) */
|
||||||
|
route?: any;
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------------- /api/share/* ---------------- */
|
||||||
|
export interface SharePartner {
|
||||||
|
share_id?: number;
|
||||||
|
email?: string;
|
||||||
|
name?: string;
|
||||||
|
/** 私密备注(我方给对方的昵称) */
|
||||||
|
remark?: string;
|
||||||
|
daily_limit?: number;
|
||||||
|
require_card?: boolean;
|
||||||
|
min_times?: number;
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SharePendingItem {
|
||||||
|
request_id?: number;
|
||||||
|
from_email?: string;
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ShareListResponse extends ApiEnvelope {
|
||||||
|
usable?: SharePartner[];
|
||||||
|
mine?: SharePartner[];
|
||||||
|
pending?: SharePendingItem[];
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SharePendingResponse extends ApiEnvelope {
|
||||||
|
pending?: SharePendingItem[];
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ShareActiveItem {
|
||||||
|
order_id?: number;
|
||||||
|
bike_code?: string;
|
||||||
|
owner_email?: string;
|
||||||
|
end_time?: number;
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ShareActiveResponse extends ApiEnvelope {
|
||||||
|
active?: ShareActiveItem[];
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------------- /api/admin/rentals ---------------- */
|
||||||
|
export interface AdminRentalRecord {
|
||||||
|
rental_id?: number;
|
||||||
|
bike_code?: string;
|
||||||
|
user_email?: string;
|
||||||
|
start_time?: number;
|
||||||
|
end_time?: number;
|
||||||
|
status?: number;
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdminRentalsResponse extends ApiEnvelope {
|
||||||
|
rentals?: AdminRentalRecord[];
|
||||||
|
total?: number;
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
Vendored
+88
@@ -0,0 +1,88 @@
|
|||||||
|
/* BMapGL(百度地图 JS API GL 版)最小类型声明。
|
||||||
|
*
|
||||||
|
* 只声明 static/js 里**实际用到**的成员;其余一律靠索引签名放行,
|
||||||
|
* 这样既不丢类型检查(构造函数/常用方法有签名),又不用为整个 SDK 写声明。
|
||||||
|
*
|
||||||
|
* 实际用到的:Map / Marker / Polyline / Polygon / Circle / Icon / Point / Size /
|
||||||
|
* ViewAnimation / ScaleControl / WalkingRoute / Overlay / Convertor
|
||||||
|
* 说明:bike-clusters.js 里还用了 BMapGL.Overlay(外部脚本自己声明,不进 bundle)。
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare namespace BMapGL {
|
||||||
|
/** 构造选项一律宽松处理。 */
|
||||||
|
type Opts = Record<string, any>;
|
||||||
|
|
||||||
|
class Point {
|
||||||
|
constructor(lng: number, lat: number);
|
||||||
|
lng: number;
|
||||||
|
lat: number;
|
||||||
|
equals(other: any): boolean;
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
class Size {
|
||||||
|
constructor(width: number, height: number);
|
||||||
|
width: number;
|
||||||
|
height: number;
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
class Icon {
|
||||||
|
constructor(imageUrl: string, size: Size, opts?: Size | Opts);
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
class Marker {
|
||||||
|
constructor(point: Point, opts?: Opts);
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
class Polyline {
|
||||||
|
constructor(points: Point[], opts?: Opts);
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
class Polygon {
|
||||||
|
constructor(points: Point[], opts?: Opts);
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
class Circle {
|
||||||
|
constructor(center: Point, radius: number, opts?: Opts);
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
class Overlay {
|
||||||
|
constructor(opts?: Opts);
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
class ScaleControl {
|
||||||
|
constructor(opts?: Opts);
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 视野动画(朝向/缩放过渡),navigation.js 用 new BMapGL.ViewAnimation([...], {duration}) */
|
||||||
|
class ViewAnimation {
|
||||||
|
constructor(opts: any, opts2?: any);
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 步行路线规划:navigation.js 用于精算步行距离 */
|
||||||
|
class WalkingRoute {
|
||||||
|
constructor(map: Map, opts?: Opts);
|
||||||
|
search(start: any, end: any): void;
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 在线坐标转换接口(本项目已改用 coordtransform.js,保留声明以免整库报错) */
|
||||||
|
class Convertor {
|
||||||
|
constructor(opts?: Opts);
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
class Map {
|
||||||
|
constructor(container: string | HTMLElement, opts?: Opts);
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
}
|
||||||
Vendored
+32
@@ -0,0 +1,32 @@
|
|||||||
|
/* DOM 宽松化垫片。
|
||||||
|
*
|
||||||
|
* 原实现是原生 JS:`document.getElementById("x").value` / `.dataset` / 自定义标记
|
||||||
|
* 属性(如 `el.__kind`)都直接拿来用,不做类型收窄。搬成 TS 后若逐个加 cast,
|
||||||
|
* 会改动上百处正文、且和「逐函数等价」的目标冲突;这里改用**接口合并**给 DOM
|
||||||
|
* 接口补一个宽松索引签名:已声明成员(addEventListener 等)保持原有类型,
|
||||||
|
* 未声明成员一律 any。纯类型层面,零运行时开销、零行为变化。
|
||||||
|
*/
|
||||||
|
|
||||||
|
interface Element {
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface HTMLElement {
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface HTMLInputElement {
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface HTMLTextAreaElement {
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface HTMLCanvasElement {
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SVGSVGElement {
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
Vendored
+51
@@ -0,0 +1,51 @@
|
|||||||
|
/* 外部脚本提供的全局(**不打进 bundle**)。
|
||||||
|
*
|
||||||
|
* 这些库由 templates/map.html 的独立 <script> 提供,bundle 运行时按全局名访问:
|
||||||
|
* coordtransform.js → coordtransform
|
||||||
|
* qrcode.min.js → QRCode
|
||||||
|
* settings-pages.js → SettingsPages
|
||||||
|
* bike-clusters.js → BikeClusters
|
||||||
|
* 运行时一律保留 `typeof X !== "undefined"` 的存在性检查(原实现就是这么写的)。
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** 坐标转换库(coordtransform.js,UMD 挂全局) */
|
||||||
|
declare const coordtransform:
|
||||||
|
| {
|
||||||
|
gcj02tobd09(lng: number, lat: number): [number, number];
|
||||||
|
bd09togcj02(lng: number, lat: number): [number, number];
|
||||||
|
wgs84togcj02(lng: number, lat: number): [number, number];
|
||||||
|
wgs84tobd09(lng: number, lat: number): [number, number];
|
||||||
|
gcj02towgs84(lng: number, lat: number): [number, number];
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
| undefined;
|
||||||
|
|
||||||
|
/** 二维码库(qrcode.min.js) */
|
||||||
|
declare const QRCode: any;
|
||||||
|
|
||||||
|
/** 设置页栈(settings-pages.js):open/back/close/hide/restore/isOpen */
|
||||||
|
declare const SettingsPages:
|
||||||
|
| {
|
||||||
|
open(id: string): void;
|
||||||
|
back(): void;
|
||||||
|
requestBack(): void;
|
||||||
|
close(): void;
|
||||||
|
hide(): void;
|
||||||
|
restore(): void;
|
||||||
|
isOpen(): boolean;
|
||||||
|
}
|
||||||
|
| undefined;
|
||||||
|
|
||||||
|
/** 气泡聚合(bike-clusters.js) */
|
||||||
|
declare const BikeClusters:
|
||||||
|
| {
|
||||||
|
PREFERENCE_KEY: string;
|
||||||
|
readClusteringPreference(storage: Storage): boolean;
|
||||||
|
writeClusteringPreference(storage: Storage, enabled: boolean): any;
|
||||||
|
normalizeBikes(bikes: any[]): any[];
|
||||||
|
bikeId(bike: any): string;
|
||||||
|
clusterBikes(bikes: any[], project: any, getPoint: any, getState: any, radius?: number, selectedId?: string, zoom?: number, enabled?: boolean): any;
|
||||||
|
createLayer(options: any): any;
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
| undefined;
|
||||||
@@ -0,0 +1,543 @@
|
|||||||
|
/* 由 static/js/{navigation,share,subscribe,map}.js 逐块搬运而来;正文与原实现一致。 */
|
||||||
|
|
||||||
|
import { S } from "../core/state";
|
||||||
|
import { escHtml } from "../core/format";
|
||||||
|
import { startRental } from "../order/actions";
|
||||||
|
import { checkPendingShareRequests, refreshShareBanners } from "../share/share";
|
||||||
|
// static/js/map.js:4085-4085
|
||||||
|
let currentQrPosition: any = null; // 当前二维码对应的位置
|
||||||
|
|
||||||
|
// static/js/map.js:4087-4146
|
||||||
|
export function showQrModal(code) {
|
||||||
|
const modal = document.getElementById("qr-modal");
|
||||||
|
const qrBox = document.getElementById("qrcode-box");
|
||||||
|
const quickBtn = document.getElementById("quick-unlock-btn");
|
||||||
|
|
||||||
|
// 清空旧的二维码
|
||||||
|
qrBox.innerHTML = "";
|
||||||
|
|
||||||
|
// 获取当前位置
|
||||||
|
currentQrPosition = null;
|
||||||
|
if (navigator.geolocation) {
|
||||||
|
navigator.geolocation.getCurrentPosition(
|
||||||
|
pos => {
|
||||||
|
currentQrPosition = {
|
||||||
|
lat: pos.coords.latitude,
|
||||||
|
lng: pos.coords.longitude
|
||||||
|
};
|
||||||
|
},
|
||||||
|
err => console.error("获取位置失败:", err),
|
||||||
|
{ timeout: 5000 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 生成新二维码
|
||||||
|
const url = "http://bike.sdlongren.com/bicycle?code=" + code;
|
||||||
|
|
||||||
|
// 判断暗色模式
|
||||||
|
const isDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
|
||||||
|
const dark = isDark ? '#ffffff' : '#000000';
|
||||||
|
const light = isDark ? '#1a1a1a' : '#ffffff';
|
||||||
|
|
||||||
|
// 生成 img 格式二维码(参考 xbcr.html)
|
||||||
|
createQrImage(url, dark, light, function(dataUrl) {
|
||||||
|
qrBox.innerHTML = ""; // 清空旧内容
|
||||||
|
if (!dataUrl) {
|
||||||
|
// 二维码库不可用:明确告知并保留一键开锁入口,避免“点了没反应”
|
||||||
|
qrBox.innerHTML = '<div style="padding:30px 10px;color:var(--text-secondary);font-size:13px;">二维码生成组件加载失败,<br/>可直接使用下方一键开锁。</div>';
|
||||||
|
modal.classList.add("show");
|
||||||
|
quickBtn.style.display = (S.authToken && S.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 (S.authToken && S.currentUser) {
|
||||||
|
quickBtn.style.display = "block";
|
||||||
|
} else {
|
||||||
|
quickBtn.style.display = "none";
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 生成高质量二维码图片(img格式,适配微信长按识别)
|
||||||
|
|
||||||
|
// static/js/map.js:4147-4190
|
||||||
|
export 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 关闭二维码弹窗
|
||||||
|
|
||||||
|
// static/js/map.js:4191-4200
|
||||||
|
export function closeQrModal() {
|
||||||
|
document.getElementById("qr-modal").classList.remove("show");
|
||||||
|
document.getElementById("quick-unlock-btn").style.display = "none";
|
||||||
|
// 清除长按定时器
|
||||||
|
longPressTimer = null;
|
||||||
|
longPressTarget = null;
|
||||||
|
currentQrPosition = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 长按检测变量
|
||||||
|
|
||||||
|
// static/js/map.js:4201-4201
|
||||||
|
let longPressTimer: any = null;
|
||||||
|
|
||||||
|
// static/js/map.js:4202-4202
|
||||||
|
let longPressTarget: any = null;
|
||||||
|
|
||||||
|
// static/js/map.js:4203-4205
|
||||||
|
let qrModalBikeCode: any = null; // 当前二维码对应的车牌
|
||||||
|
|
||||||
|
// 二维码弹窗的二维码区域长按检测
|
||||||
|
|
||||||
|
// static/js/map.js:4206-4247
|
||||||
|
export function setupQrLongPress() {
|
||||||
|
const qrBox = document.getElementById("qrcode-box");
|
||||||
|
|
||||||
|
// 统一用 pointer 事件(兼容触摸和鼠标)
|
||||||
|
qrBox.addEventListener("pointerdown", function(e) {
|
||||||
|
if (!S.currentUser) return;
|
||||||
|
e.preventDefault(); // 阻止右键菜单等默认行为
|
||||||
|
qrModalBikeCode = qrBox.dataset.bikeCode || "";
|
||||||
|
longPressTimer = setTimeout(() => {
|
||||||
|
longPressTimer = null;
|
||||||
|
if (qrModalBikeCode && S.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;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 页面加载时初始化长按检测
|
||||||
|
|
||||||
|
// static/js/map.js:4259-4259
|
||||||
|
let _appConfirmResolve: any = null;
|
||||||
|
|
||||||
|
// static/js/map.js:4260-4295
|
||||||
|
export 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<any>(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");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:4296-4303
|
||||||
|
export function appConfirmClose() {
|
||||||
|
if (_appConfirmResolve) {
|
||||||
|
const r = _appConfirmResolve;
|
||||||
|
_appConfirmResolve = null;
|
||||||
|
document.getElementById("app-confirm-modal").classList.remove("show");
|
||||||
|
r(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:4357-4366
|
||||||
|
export 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 下载。这两类情况都改为提示复制链接到电脑浏览器。
|
||||||
|
|
||||||
|
// static/js/map.js:4367-4370
|
||||||
|
const CAPTURE_TOOL_PATH = "/download/capture-tool.exe";
|
||||||
|
|
||||||
|
// 鸿蒙 UA 有两种:老版 HarmonyOS + Android 兼容层,新版纯 OpenHarmony/ArkWeb;
|
||||||
|
// 微信鸿蒙版仍带 MicroMessenger,但部分版本 UA 精简后只剩 HarmonyOS。
|
||||||
|
|
||||||
|
// static/js/map.js:4371-4374
|
||||||
|
export function detectHarmony() {
|
||||||
|
const ua = navigator.userAgent || "";
|
||||||
|
return /OpenHarmony|HarmonyOS|ArkWeb|HMSCore/i.test(ua);
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:4375-4392
|
||||||
|
export 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 表示可以直接下载
|
||||||
|
|
||||||
|
// static/js/map.js:4393-4404
|
||||||
|
export 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:4405-4408
|
||||||
|
export function captureToolUrl() {
|
||||||
|
return new URL(CAPTURE_TOOL_PATH, window.location.href).href;
|
||||||
|
}
|
||||||
|
// 返回 true 时放行 <a download> 的原生下载
|
||||||
|
|
||||||
|
// static/js/map.js:4409-4416
|
||||||
|
export 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:4417-4433
|
||||||
|
export 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");
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:4434-4441
|
||||||
|
export function closeDownloadTipModal() {
|
||||||
|
document.getElementById("download-tip-modal").classList.remove("show");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 数据导出(CSV 直链,1 小时有效) ==========
|
||||||
|
// 流程:POST /api/export/create(登录态)→ 拿到免登录直链。
|
||||||
|
// UA 复用 detectInAppBrowser:微信/QQ/支付宝/钉钉/微博/抖音/原生壳内无法直接下载,
|
||||||
|
// 弹「复制链接到外部浏览器」提示;普通浏览器直接触发下载。
|
||||||
|
|
||||||
|
// static/js/map.js:4442-4444
|
||||||
|
export function closeExportTipModal() {
|
||||||
|
document.getElementById("export-tip-modal").classList.remove("show");
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:4445-4466
|
||||||
|
export 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("复制失败,请长按链接手动复制");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:4467-4503
|
||||||
|
export async function exportHistoryCsv() {
|
||||||
|
if (!S.authToken) { showToast("请先登录"); return; }
|
||||||
|
showToast("正在生成导出链接...");
|
||||||
|
try {
|
||||||
|
const resp = await fetch("/api/export/create", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json",
|
||||||
|
"Authorization": `Bearer ${S.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("导出失败,请重试");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:4504-4531
|
||||||
|
export 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 字样易引起误解
|
||||||
|
|
||||||
|
// static/js/map.js:4542-4542
|
||||||
|
let _credInvalidLastShownAt: any = 0;
|
||||||
|
|
||||||
|
// static/js/map.js:4543-4543
|
||||||
|
const CRED_INVALID_MODAL_COOLDOWN = 10 * 60 * 1000; // 10 分钟内不重复弹出
|
||||||
|
|
||||||
|
// static/js/map.js:4544-4550
|
||||||
|
export 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:4551-4557
|
||||||
|
export 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();
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:4558-4561
|
||||||
|
export function closeTokenExpiredModal() {
|
||||||
|
document.getElementById("token-expired-modal").classList.remove("show");
|
||||||
|
document.getElementById("expired-tip").textContent = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:4562-4574
|
||||||
|
export async function loadExpiredTokenFields() {
|
||||||
|
if (!S.authToken) return;
|
||||||
|
try {
|
||||||
|
const resp = await fetch("/api/auth/profile", {
|
||||||
|
headers: { "Authorization": `Bearer ${S.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 */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
// static/js/map.js:4575-4629
|
||||||
|
export async function saveExpiredToken() {
|
||||||
|
if (!S.authToken) {
|
||||||
|
document.getElementById("expired-tip").textContent = "请先登录";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const token_id = document.getElementById("expired-token-id").value.trim();
|
||||||
|
const access_token = document.getElementById("expired-signature").value.trim();
|
||||||
|
const tip = document.getElementById("expired-tip");
|
||||||
|
|
||||||
|
if (!token_id) {
|
||||||
|
tip.textContent = "Token ID 必填;AccessToken 选填";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
tip.textContent = "验证中...";
|
||||||
|
try {
|
||||||
|
const verifyResp = await fetch("/api/auth/verify_token", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json",
|
||||||
|
"Authorization": `Bearer ${S.authToken}` },
|
||||||
|
body: JSON.stringify({ access_token, token_id })
|
||||||
|
});
|
||||||
|
const verifyData = await verifyResp.json();
|
||||||
|
if (!verifyData.valid) {
|
||||||
|
tip.textContent = verifyData.message || "凭据验证失败,请检查 Token ID 是否正确";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
tip.textContent = "验证失败";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const resp = await fetch("/api/auth/save_token", {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"Authorization": `Bearer ${S.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 = "保存失败";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 定位最近车辆(手动找车)==========
|
||||||
|
|
||||||
|
// static/js/map.js:4988-4991
|
||||||
|
export function shareAfterLogin() {
|
||||||
|
refreshShareBanners();
|
||||||
|
setTimeout(() => checkPendingShareRequests(), 800);
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
+199
-7
@@ -600,7 +600,7 @@
|
|||||||
.bike-card-title {
|
.bike-card-title {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 10px;
|
gap: 8px;
|
||||||
}
|
}
|
||||||
.bike-type-badge {
|
.bike-type-badge {
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
@@ -653,20 +653,67 @@
|
|||||||
display: none;
|
display: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* 电量+状态同行 */
|
/* 卡片中部:左「距离/步行」+ 右「电量/状态」两张等宽卡片 */
|
||||||
.bike-status-row {
|
.bike-card-meta {
|
||||||
|
display: flex;
|
||||||
|
gap: 10px;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
.bike-meta-card {
|
||||||
|
flex: 1 1 0;
|
||||||
|
min-width: 0;
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
|
||||||
justify-content: space-between;
|
|
||||||
background: var(--bg-secondary);
|
background: var(--bg-secondary);
|
||||||
border-radius: var(--radius-md);
|
border-radius: var(--radius-md);
|
||||||
padding: 14px 16px;
|
padding: 12px 14px;
|
||||||
margin-bottom: 20px;
|
}
|
||||||
|
.bike-meta-left {
|
||||||
|
flex-direction: column;
|
||||||
|
justify-content: center;
|
||||||
|
gap: 3px;
|
||||||
|
}
|
||||||
|
.bike-meta-left[hidden] { display: none; }
|
||||||
|
.bike-meta-distance {
|
||||||
|
font-size: 15px;
|
||||||
|
font-weight: 700;
|
||||||
|
color: var(--text-primary);
|
||||||
|
line-height: 1.25;
|
||||||
|
}
|
||||||
|
.bike-meta-walk {
|
||||||
|
font-size: 12.5px;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
line-height: 1.25;
|
||||||
|
}
|
||||||
|
.bike-meta-right {
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 8px;
|
||||||
}
|
}
|
||||||
.bike-battery-wrap {
|
.bike-battery-wrap {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 8px;
|
gap: 8px;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
/* 状态块不许被挤换行(窄屏出现过「空/闲」竖排) */
|
||||||
|
.bike-status-wrap {
|
||||||
|
flex-shrink: 0;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.battery-svg-wrap svg {
|
||||||
|
display: block;
|
||||||
|
max-width: 100%;
|
||||||
|
}
|
||||||
|
/* 窄屏(≤380px):电量与状态各让一点,保住一行 */
|
||||||
|
@media (max-width: 380px) {
|
||||||
|
.bike-card-meta { gap: 8px; }
|
||||||
|
.bike-meta-card { padding: 10px 12px; }
|
||||||
|
.bike-meta-right { gap: 6px; }
|
||||||
|
.battery-svg-wrap svg { width: 40px; height: 21px; }
|
||||||
|
.battery-label { font-size: 14px; }
|
||||||
|
.bike-meta-distance { font-size: 14px; }
|
||||||
|
.bike-meta-walk { font-size: 12px; }
|
||||||
|
.bike-status-value { font-size: 14px; }
|
||||||
}
|
}
|
||||||
.battery-svg-wrap {
|
.battery-svg-wrap {
|
||||||
position: relative;
|
position: relative;
|
||||||
@@ -2704,3 +2751,148 @@
|
|||||||
color: var(--text-primary) !important;
|
color: var(--text-primary) !important;
|
||||||
border-color: var(--ui-line-strong) !important;
|
border-color: var(--ui-line-strong) !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/* 导航信息条:浮在底部扫码栏上方 */
|
||||||
|
.nav-banner {
|
||||||
|
position: fixed;
|
||||||
|
left: 12px;
|
||||||
|
right: 12px;
|
||||||
|
bottom: calc(84px + env(safe-area-inset-bottom, 0px));
|
||||||
|
z-index: 260;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 10px 12px;
|
||||||
|
border-radius: 16px;
|
||||||
|
/* 与顶部横幅/浮窗同款的亚克力玻璃 */
|
||||||
|
background: var(--ui-header-acrylic, rgba(251, 251, 250, .64));
|
||||||
|
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-md, 0 6px 24px rgba(0, 0, 0, 0.18));
|
||||||
|
}
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.nav-banner {
|
||||||
|
background: rgba(44, 44, 46, .62);
|
||||||
|
border-color: rgba(255, 255, 255, .10);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.nav-banner[hidden] { display: none; }
|
||||||
|
.nav-banner-main { display: flex; align-items: center; gap: 8px; min-width: 0; }
|
||||||
|
.nav-banner-icon { font-size: 16px; line-height: 1; }
|
||||||
|
.nav-banner-text {
|
||||||
|
font-size: 13px;
|
||||||
|
color: var(--text-primary, #1c1c1e);
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.nav-banner-stop {
|
||||||
|
flex-shrink: 0;
|
||||||
|
padding: 6px 12px;
|
||||||
|
border-radius: 10px;
|
||||||
|
border: none;
|
||||||
|
background: var(--bg-secondary, #f2f2f7);
|
||||||
|
color: var(--text-primary, #1c1c1e);
|
||||||
|
font-size: 12.5px;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 拖动地图后的「返回导航」胶囊 */
|
||||||
|
.nav-resume {
|
||||||
|
position: fixed;
|
||||||
|
left: 50%;
|
||||||
|
transform: translateX(-50%);
|
||||||
|
bottom: calc(150px + env(safe-area-inset-bottom, 0px));
|
||||||
|
z-index: 270;
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
padding: 9px 16px;
|
||||||
|
border: 1px solid var(--ui-line-strong);
|
||||||
|
border-radius: 999px;
|
||||||
|
/* 同亚克力玻璃,不再用实色蓝块 */
|
||||||
|
background: var(--ui-header-acrylic, rgba(251, 251, 250, .64));
|
||||||
|
color: var(--accent-color, #0A84FF);
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 600;
|
||||||
|
-webkit-backdrop-filter: blur(24px) saturate(1.4);
|
||||||
|
backdrop-filter: blur(24px) saturate(1.4);
|
||||||
|
box-shadow: var(--ui-shadow-md, 0 6px 20px rgba(10, 132, 255, 0.25));
|
||||||
|
}
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.nav-resume { background: rgba(44, 44, 46, .62); border-color: rgba(255, 255, 255, .10); }
|
||||||
|
}
|
||||||
|
.nav-resume[hidden] { display: none; }
|
||||||
|
.nav-banner-icon { display: inline-flex; align-items: center; color: #0A84FF; }
|
||||||
|
|
||||||
|
/* 导航信息条:两行(当前指引 + 剩余量) */
|
||||||
|
.nav-banner-copy {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
min-width: 0;
|
||||||
|
gap: 1px;
|
||||||
|
}
|
||||||
|
.nav-banner-action {
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--text-primary, #1c1c1e);
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.nav-banner-copy .nav-banner-text {
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--text-secondary, #8e8e93);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 导航条左侧的动作图标(转弯/掉头/直行) */
|
||||||
|
.nav-banner-turn {
|
||||||
|
flex-shrink: 0;
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: 34px;
|
||||||
|
height: 34px;
|
||||||
|
margin-left: 2px;
|
||||||
|
color: #0A84FF;
|
||||||
|
}
|
||||||
|
.nav-banner-turn svg { width: 30px; height: 30px; display: block; }
|
||||||
|
.nav-banner-main { gap: 8px; }
|
||||||
|
|
||||||
|
/* 卡片顶部:标题可压缩、按钮不被挤变形 */
|
||||||
|
.bike-card-header { gap: 10px; }
|
||||||
|
.bike-card-title { flex: 1 1 auto; min-width: 0; }
|
||||||
|
.bike-card-header-btns { flex: 0 0 auto; }
|
||||||
|
.bike-card-title .bike-code {
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.bike-card-find-btn { white-space: nowrap; }
|
||||||
|
|
||||||
|
@media (max-width: 430px) {
|
||||||
|
.bike-card-header { gap: 8px; }
|
||||||
|
.bike-card-header-btns { gap: 6px; }
|
||||||
|
.bike-card-find-btn { padding: 6px 10px; border-radius: 12px; }
|
||||||
|
.bike-type-badge { padding: 5px 10px; font-size: 12px; }
|
||||||
|
.bike-card-title .bike-code { font-size: 19px; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 是否收成图标不按屏宽猜:JS 量一次「标题 + 按钮」放不放得下(车牌越长越早收) */
|
||||||
|
.bike-card.compact-actions .bike-card-find-btn .btn-label { display: none; }
|
||||||
|
.bike-card.compact-actions .bike-card-find-btn { padding: 7px; border-radius: 11px; }
|
||||||
|
.bike-card.compact-actions .bike-card-header { gap: 6px; }
|
||||||
|
|
||||||
|
/* 订单横幅:进入「即将到期」状态时整条变红,兜里也能看见 */
|
||||||
|
.order-banner.expiring {
|
||||||
|
background: linear-gradient(135deg, #B3261E, #8E1B15) !important;
|
||||||
|
border-color: rgba(255, 120, 110, .55) !important;
|
||||||
|
animation: order-expiring-pulse 1.6s ease-in-out infinite;
|
||||||
|
}
|
||||||
|
@keyframes order-expiring-pulse {
|
||||||
|
0%, 100% { box-shadow: 0 6px 18px rgba(179, 38, 30, .35); }
|
||||||
|
50% { box-shadow: 0 6px 26px rgba(179, 38, 30, .65); }
|
||||||
|
}
|
||||||
|
|||||||
Vendored
+142
@@ -0,0 +1,142 @@
|
|||||||
|
# static/dist —— TypeScript + esbuild 版地图前端
|
||||||
|
|
||||||
|
这里放的是**由 `src-ts/` 构建出来**的 IIFE 包,用来替换原来手写的
|
||||||
|
`static/js/map.js` + `navigation.js` + `share.js` + `subscribe.js`。
|
||||||
|
|
||||||
|
原实现是四个**经典脚本**(顶层 `function` 声明天然成为全局,`templates/map.html` 里
|
||||||
|
139 处内联 `onclick="foo()"` 直接调用这些全局)。bundle 之后函数不再自动成为全局,
|
||||||
|
所以 `src-ts/compat/globals.ts` 会把它们逐个挂回 `window`——**这是唯一挂全局的地方**。
|
||||||
|
|
||||||
|
| 文件 | 说明 |
|
||||||
|
| --- | --- |
|
||||||
|
| `app.js` | 入口 bundle(`format: "iife"`,`target: "es2019"`),含 `//# sourceMappingURL=app.js.map` |
|
||||||
|
| `app.js.map` | 外部 sourcemap(带 `sourcesContent`,可直接对着看/调试) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 构建
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
cd D:\Downloads\unpack\小白超人\xbniu_map # 仓库根目录(和 package.json 同级)
|
||||||
|
|
||||||
|
npm install # 首次:装 esbuild + typescript(devDependencies)
|
||||||
|
node esbuild.config.mjs
|
||||||
|
```
|
||||||
|
|
||||||
|
成功时输出(体积随改动略有变化):
|
||||||
|
|
||||||
|
```
|
||||||
|
构建完成
|
||||||
|
static/dist/app.js ~226 KiB
|
||||||
|
static/dist/app.js.map ~448 KiB
|
||||||
|
按模块(压缩前进 bundle 的字节数):
|
||||||
|
src-ts/order/actions.ts 54753
|
||||||
|
...
|
||||||
|
```
|
||||||
|
|
||||||
|
只做类型检查(不产出文件):
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
npx tsc --noEmit
|
||||||
|
```
|
||||||
|
|
||||||
|
其它校验脚本(都在 `src-ts/tools/`,不属于构建产物):
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
node src-ts/tools/verify-globals.mjs # 模板内联事件函数名 vs bundle 的 window.X 赋值,差集必须为空
|
||||||
|
node src-ts/tools/smoke.cjs # 用 DOM/BMapGL 桩在 Node 里跑一遍 bundle,验证装配顺序与首屏流程
|
||||||
|
node src-ts/tools/gen.mjs --analyze # (迁移工具)重新统计 static/js 的切块与分派情况
|
||||||
|
```
|
||||||
|
|
||||||
|
> `src-ts/tools/gen.mjs` 是**一次性脚手架**:它把 `static/js/{map,navigation,share,subscribe}.js`
|
||||||
|
> 逐块搬到 `src-ts/`。写出来的 `.ts` 之后就是手维护的源码;重跑它会覆盖手改内容
|
||||||
|
> (除已登记在脚本里的类型补丁之外)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 在 `templates/map.html` 里切换
|
||||||
|
|
||||||
|
原文件(`templates/map.html` 第 973–976 行附近):
|
||||||
|
|
||||||
|
```html
|
||||||
|
<script defer src="/static/js/navigation.js?v={{ map_asset_version }}"></script>
|
||||||
|
<script defer src="/static/js/share.js?v={{ map_asset_version }}"></script>
|
||||||
|
<script defer src="/static/js/subscribe.js?v={{ map_asset_version }}"></script>
|
||||||
|
<script defer src="/static/js/map.js?v={{ map_asset_version }}"></script>
|
||||||
|
```
|
||||||
|
|
||||||
|
改成一行(**四合一**,顺序无所谓,因为它们已经被打进同一个 IIFE 并按原脚本顺序执行):
|
||||||
|
|
||||||
|
```html
|
||||||
|
<script defer src="/static/dist/app.js?v={{ map_asset_version }}"></script>
|
||||||
|
```
|
||||||
|
|
||||||
|
**保持不动的脚本**(bundle 运行时按全局名访问,见 `src-ts/types/externals.d.ts`):
|
||||||
|
|
||||||
|
```html
|
||||||
|
<script async src="https://api.map.baidu.com/api?v=1.0&type=webgl&ak=...&callback=onBaiduMapReady"></script>
|
||||||
|
<script defer src="/static/js/ui-motion.js?v=..."></script> <!-- window.uiNavigate / uiCloseWindow -->
|
||||||
|
<script defer src="/static/js/qrcode.min.js?v=..."></script> <!-- QRCode -->
|
||||||
|
<script defer src="/static/js/coordtransform.js?v=..."></script> <!-- coordtransform -->
|
||||||
|
<script defer src="/static/js/src/core/geo.js?v=..."></script> <!-- 可选:bundle 自带同一份实现 -->
|
||||||
|
<script defer src="/static/js/bike-clusters.js?v=..."></script> <!-- BikeClusters -->
|
||||||
|
<script defer src="/static/js/settings-pages.js?v=..."></script> <!-- SettingsPages -->
|
||||||
|
```
|
||||||
|
|
||||||
|
> `geo.js` 现在是**可选**的:`src-ts/core/geo.ts` 已经把 `offsetCoord` / `calcDistance` /
|
||||||
|
> `Geo` 逐字搬进 bundle,并且 `compat/globals.ts` 会把它们挂回 `window`。留着它只是
|
||||||
|
> 让「删掉 bundle 就回滚」更省事,行为没有区别(两处实现完全一致)。
|
||||||
|
|
||||||
|
### 还要改一处:缓存版本号
|
||||||
|
|
||||||
|
`routes/map_api.py` 里的 `MAP_ASSETS` 决定 `?v=` 的值。**它不在本次改动范围内**(本次
|
||||||
|
只加文件),切换时请把它里面的四个 js 换成一个:
|
||||||
|
|
||||||
|
```python
|
||||||
|
MAP_ASSETS = (
|
||||||
|
"css/map.css", "css/bike-clusters.css", "css/map-settings.css", "css/ui-system.css",
|
||||||
|
"js/ui-motion.js", "js/qrcode.min.js", "js/coordtransform.js", "js/bike-clusters.js",
|
||||||
|
"js/settings-pages.js", "js/src/core/geo.js",
|
||||||
|
"dist/app.js", # ← 替换掉 js/navigation.js、js/share.js、js/subscribe.js、js/map.js
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
这样浏览器缓存失效才跟着新产物走。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 回滚
|
||||||
|
|
||||||
|
**一行回滚**:把 `templates/map.html` 里那行 `app.js` 换回原来的四个 `<script>`
|
||||||
|
(见上面第 2 节的 before 片段),并把 `MAP_ASSETS` 的 `dist/app.js` 换回四个 js 文件名。
|
||||||
|
|
||||||
|
`static/js/` 下的原有文件**一个字都没改**(`git status` 只有新增文件),所以回滚不需要
|
||||||
|
恢复任何东西;`static/dist/` 留着也不影响——没有 `<script>` 引用它,浏览器就不会加载。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 已知与原文的差异(全部只影响类型,不影响行为)
|
||||||
|
|
||||||
|
1. **跨模块共享的可变状态收进 `core/state.ts` 的 `S` 对象**,正文里的裸标识符写成
|
||||||
|
`S.map` / `S.selectedBike` 等(492 处)。原因:ES 模块里 import 进来的绑定不可赋值。
|
||||||
|
对象本身的初始化顺序、内存里只有一份的语义都和原「全局词法绑定」一致;唯一的
|
||||||
|
细微差别见下一条。
|
||||||
|
2. **TDZ 变成 `null`**:原实现里 `navigation.js` 先于 `map.js` 执行,`let map` 还在 TDZ,
|
||||||
|
`bindNavMapEvents()` 访问它会抛 `ReferenceError` 并被自己的 `try/catch` 吞掉,返回
|
||||||
|
`false` 后重试;bundle 里 `S.map` 已是 `null`,抛的是 `TypeError`,同样被吞、同样重试。
|
||||||
|
3. **`Object.values(...)` / `new Promise(...)` 显式加了 `<any>`**,`let` 变量标了 `: any`,
|
||||||
|
12 处 DOM 赋值加了 `String(...)`(`textContent` / `setAttribute` 只吃字符串,结果一样)。
|
||||||
|
这些是 TS 下必须写的类型信息,没有运行时行为变化。
|
||||||
|
4. **一行对象简写属性**:`{ map, enabled: ... }` → `{ map: S.map, enabled: ... }`,
|
||||||
|
同一个键同一个值。这是全仓唯一被改写的语法结构。
|
||||||
|
|
||||||
|
除此之外,块内正文与 `static/js/*.js` **逐行一致**(`node src-ts/tools/gen.mjs` 的
|
||||||
|
保真度报告:6144 行搬运,归一化后只剩上述 1 行结构差异)。
|
||||||
|
|
||||||
|
## 补充(验收后修正)
|
||||||
|
|
||||||
|
- **状态可观测性**:原版 91 个顶层 `let/var` 是全局词法绑定,控制台能直接读写。
|
||||||
|
bundle 里它们收进 `core/state.ts` 的 `S` 对象,并额外执行 `window.S = S;`,
|
||||||
|
排障时用 `S.selectedBike` / `S.orderCountdownSeconds` 等价替代。
|
||||||
|
- **退化路线**:`nav/walk-route.ts` 的 `onSearchComplete` 对 `res.getStatus()`
|
||||||
|
增加了存在性判断(起点≈终点时上游会返回空壳),原 JS 版已同步修掉这条历史 TypeError。
|
||||||
Vendored
+5919
File diff suppressed because it is too large
Load Diff
+186
-533
@@ -9,7 +9,8 @@
|
|||||||
let currentPolygons = [];
|
let currentPolygons = [];
|
||||||
let selectedBike = null;
|
let selectedBike = null;
|
||||||
let markersData = {};
|
let markersData = {};
|
||||||
let currentMarkersById = {}; // 用于刷新时快速定位
|
let currentMarkersById = {};
|
||||||
|
let scannedMarkers = {}; // 扫码查到但不在列表里的临时补点(每次渲染回收) // 用于刷新时快速定位
|
||||||
let myLocationMarker = null;
|
let myLocationMarker = null;
|
||||||
let autoLocationMarker = null; // 自动持续定位的标记
|
let autoLocationMarker = null; // 自动持续定位的标记
|
||||||
let autoLocationWatchId = null; // watchPosition 的 ID
|
let autoLocationWatchId = null; // watchPosition 的 ID
|
||||||
@@ -123,10 +124,6 @@
|
|||||||
const RENTAL_KEY = "xbniu_rental_key"; // localStorage key
|
const RENTAL_KEY = "xbniu_rental_key"; // localStorage key
|
||||||
|
|
||||||
// 手动坐标偏移(仅作为 coordtransform 未加载时的降级常量;正常走 gcj02tobd09 自动转换)
|
// 手动坐标偏移(仅作为 coordtransform 未加载时的降级常量;正常走 gcj02tobd09 自动转换)
|
||||||
const COORD_OFFSET = {
|
|
||||||
lat: 0.00603, // 约610米(纬度)
|
|
||||||
lng: 0.00650, // 约600米-20米(经度,往西20米)
|
|
||||||
};
|
|
||||||
|
|
||||||
// 初始位置额外偏移(再往上30米)
|
// 初始位置额外偏移(再往上30米)
|
||||||
const INIT_OFFSET_EXTRA = 0.00027; // 约30米(向北)
|
const INIT_OFFSET_EXTRA = 0.00027; // 约30米(向北)
|
||||||
@@ -134,23 +131,6 @@
|
|||||||
|
|
||||||
// 坐标转换:车辆/地图数据为 GCJ02,逐点精确转百度 BD09(coordtransform,无在线转换上限)。
|
// 坐标转换:车辆/地图数据为 GCJ02,逐点精确转百度 BD09(coordtransform,无在线转换上限)。
|
||||||
// coordtransform.gcj02tobd09(lng, lat) -> [bd09_lng, bd09_lat]
|
// coordtransform.gcj02tobd09(lng, lat) -> [bd09_lng, bd09_lat]
|
||||||
function offsetCoord(lat, lng) {
|
|
||||||
lat = parseFloat(lat);
|
|
||||||
lng = parseFloat(lng);
|
|
||||||
if (typeof coordtransform !== "undefined" && coordtransform.gcj02tobd09) {
|
|
||||||
try {
|
|
||||||
const bd = coordtransform.gcj02tobd09(lng, lat); // [lng, lat]
|
|
||||||
return { lat: bd[1], lng: bd[0] };
|
|
||||||
} catch (e) {
|
|
||||||
console.warn("[坐标转换] gcj02tobd09 失败,回退手动偏移:", e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// 降级:coordtransform 未加载/出错时,沿用旧的手动常量偏移,避免点位整体偏差
|
|
||||||
return {
|
|
||||||
lat: lat + COORD_OFFSET.lat,
|
|
||||||
lng: lng + COORD_OFFSET.lng,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// 状态判断函数 - 基于 state + status 组合判断
|
// 状态判断函数 - 基于 state + status 组合判断
|
||||||
// state=1 + status=0: 空闲可用
|
// state=1 + status=0: 空闲可用
|
||||||
@@ -1263,16 +1243,9 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 计算两点之间的距离(米)
|
// 计算两点之间的距离(米)
|
||||||
function calcDistance(lat1, lng1, lat2, lng2) {
|
|
||||||
const R = 6371000; // 地球半径(米)
|
// 导航相关已拆到 static/js/navigation.js
|
||||||
const dLat = (lat2 - lat1) * Math.PI / 180;
|
|
||||||
const dLng = (lng2 - lng1) * Math.PI / 180;
|
|
||||||
const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
|
|
||||||
Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
|
|
||||||
Math.sin(dLng/2) * Math.sin(dLng/2);
|
|
||||||
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
|
|
||||||
return R * c;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 根据当前模式筛选车辆
|
// 根据当前模式筛选车辆
|
||||||
function getFilteredBikes() {
|
function getFilteredBikes() {
|
||||||
@@ -1841,20 +1814,49 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 到期提醒:手机在兜里时页面横幅看不见,这里补一次震动 + 明确文案。
|
||||||
|
// 只在跨过阈值的瞬间触发,不会每秒抖。
|
||||||
|
let _orderLastAlertAt = 0;
|
||||||
|
function _alertOrderExpiring(remaining) {
|
||||||
|
const banner = document.getElementById("order-banner");
|
||||||
|
if (banner) banner.classList.add("expiring");
|
||||||
|
const el = document.getElementById("order-countdown");
|
||||||
|
if (el) el.textContent = `再骑 ${Math.max(0, remaining)} 秒就到期 · 超时要加钱`;
|
||||||
|
const now = Date.now();
|
||||||
|
if (now - _orderLastAlertAt < 25000) return; // 25 秒内只提醒一次
|
||||||
|
_orderLastAlertAt = now;
|
||||||
|
try {
|
||||||
|
if (navigator.vibrate) navigator.vibrate([200, 100, 200]);
|
||||||
|
} catch (e) { /* 不支持就算了 */ }
|
||||||
|
if (document.visibilityState === "visible") {
|
||||||
|
showToast("还有不到 1 分钟到期,就近停车还车");
|
||||||
|
}
|
||||||
|
}
|
||||||
function updateOrderCountdownText() {
|
function updateOrderCountdownText() {
|
||||||
const el = document.getElementById("order-countdown");
|
const el = document.getElementById("order-countdown");
|
||||||
const remaining = Math.max(0, orderCountdownSeconds);
|
const remaining = Math.max(0, orderCountdownSeconds);
|
||||||
const mins = Math.floor(remaining / 60);
|
const mins = Math.floor(remaining / 60);
|
||||||
const secs = remaining % 60;
|
const secs = remaining % 60;
|
||||||
el.textContent = remaining > 0 ? `本轮剩余 ${mins}:${secs.toString().padStart(2, "0")}` : "本轮到期 · 同步状态中";
|
|
||||||
|
if (remaining > 0 && remaining <= 60) {
|
||||||
|
_alertOrderExpiring(remaining); // 内部会写文案/变色/震动
|
||||||
|
} else {
|
||||||
|
el.textContent = remaining > 0
|
||||||
|
? `本轮剩余 ${mins}:${secs.toString().padStart(2, "0")}`
|
||||||
|
: "本轮到期 · 同步状态中";
|
||||||
|
}
|
||||||
|
|
||||||
// 变色提示
|
// 变色提示
|
||||||
|
const banner = document.getElementById("order-banner");
|
||||||
if (remaining <= 60) {
|
if (remaining <= 60) {
|
||||||
el.style.color = "#ff3b30";
|
el.style.color = "#ff3b30";
|
||||||
|
if (banner) banner.classList.add("expiring");
|
||||||
} else if (remaining <= 300) {
|
} else if (remaining <= 300) {
|
||||||
el.style.color = "#ffcc00";
|
el.style.color = "#ffcc00";
|
||||||
|
if (banner) banner.classList.remove("expiring");
|
||||||
} else {
|
} else {
|
||||||
el.style.color = "white";
|
el.style.color = "white";
|
||||||
|
if (banner) banner.classList.remove("expiring");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2178,7 +2180,9 @@
|
|||||||
const data = await resp.json();
|
const data = await resp.json();
|
||||||
|
|
||||||
if (data.rtn_code === 0) {
|
if (data.rtn_code === 0) {
|
||||||
let msg = data.used_nearest ? "还车成功(已切换至最近停车点)" : "还车成功";
|
let msg = data.used_nearest
|
||||||
|
? "还车成功 · 不在停车区也没关系,已替你记到最近的还车点"
|
||||||
|
: "还车成功";
|
||||||
// 显示月卡支付结果
|
// 显示月卡支付结果
|
||||||
if (data.card_pay) {
|
if (data.card_pay) {
|
||||||
msg += data.card_pay.success ? `,${data.card_pay.message}` : `,${data.card_pay.message}`;
|
msg += data.card_pay.success ? `,${data.card_pay.message}` : `,${data.card_pay.message}`;
|
||||||
@@ -2208,6 +2212,9 @@
|
|||||||
|
|
||||||
async function tempLockCurrentOrder() {
|
async function tempLockCurrentOrder() {
|
||||||
if (orderTempActionLoading || !isOrderActionEligible(currentOrder) || Number(currentOrder.status) !== 2) return;
|
if (orderTempActionLoading || !isOrderActionEligible(currentOrder) || Number(currentOrder.status) !== 2) return;
|
||||||
|
// 先快照:等定位(最长 5 秒)期间 20 秒轮询可能把 currentOrder 置空,
|
||||||
|
// 之后再读 currentOrder.order_id 会抛 TypeError 并被吞成「临时锁车失败」。
|
||||||
|
const order = currentOrder;
|
||||||
const button = document.getElementById("order-action-lock");
|
const button = document.getElementById("order-action-lock");
|
||||||
orderTempActionLoading = true;
|
orderTempActionLoading = true;
|
||||||
if (button) {
|
if (button) {
|
||||||
@@ -2224,15 +2231,17 @@
|
|||||||
"Content-Type": "application/json"
|
"Content-Type": "application/json"
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
order_id: currentOrder.order_id,
|
order_id: order.order_id,
|
||||||
code: currentOrder.code,
|
code: order.code,
|
||||||
latitude,
|
latitude,
|
||||||
longitude
|
longitude
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
const data = await resp.json();
|
const data = await resp.json();
|
||||||
if (data.rtn_code === 0) {
|
if (data.rtn_code === 0) {
|
||||||
showToast(data.used_nearest ? "临时锁车成功(已切换至最近停车点)" : "临时锁车成功");
|
showToast(data.used_nearest
|
||||||
|
? "临时锁车成功 · 已替你记到最近的还车点"
|
||||||
|
: "临时锁车成功");
|
||||||
const status = document.getElementById("order-actions-status");
|
const status = document.getElementById("order-actions-status");
|
||||||
if (status) status.textContent = "车辆已临时锁定,订单仍在进行中";
|
if (status) status.textContent = "车辆已临时锁定,订单仍在进行中";
|
||||||
} else {
|
} else {
|
||||||
@@ -2307,8 +2316,11 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 保存待开锁信息(用车辆自身坐标 + 随机抖动 ±0.0001,不依赖用户真实定位)
|
// 保存待开锁信息(用车辆自身坐标 + 随机抖动 ±0.0001,不依赖用户真实定位)
|
||||||
const baseLat = parseFloat(selectedBike?.latitude) || 36.67;
|
// 注意:开二维码弹窗时 startRental 会 closeCard() 把 selectedBike 清空,
|
||||||
const baseLng = parseFloat(selectedBike?.longitude) || 116.98;
|
// 所以坐标优先从 markersData 按车牌取,避免退化成硬编码的 (36.67, 116.98)。
|
||||||
|
const bikeForCoord = markersData[parseInt(code)] || markersData[code] || selectedBike;
|
||||||
|
const baseLat = parseFloat(bikeForCoord && bikeForCoord.latitude) || 36.67;
|
||||||
|
const baseLng = parseFloat(bikeForCoord && bikeForCoord.longitude) || 116.98;
|
||||||
const jit = 0.0001;
|
const jit = 0.0001;
|
||||||
unlockPendingCode = code;
|
unlockPendingCode = code;
|
||||||
unlockPendingPosition = {
|
unlockPendingPosition = {
|
||||||
@@ -2434,6 +2446,9 @@
|
|||||||
const data = await resp.json();
|
const data = await resp.json();
|
||||||
console.log("[开锁] 响应:", data);
|
console.log("[开锁] 响应:", data);
|
||||||
|
|
||||||
|
// closeUnlockConfirm() 会把 unlockPendingCode 清空,先把车牌存到局部变量,
|
||||||
|
// 否则后面 startRentalFromServer 会把 null 写进 activeRental/localStorage。
|
||||||
|
const code = unlockPendingCode;
|
||||||
closeUnlockConfirm();
|
closeUnlockConfirm();
|
||||||
|
|
||||||
if (data.rtn_code === 0) {
|
if (data.rtn_code === 0) {
|
||||||
@@ -2447,7 +2462,7 @@
|
|||||||
} else {
|
} else {
|
||||||
// 启动前端计时器;end_time/轮次预估取自后端开锁响应
|
// 启动前端计时器;end_time/轮次预估取自后端开锁响应
|
||||||
const _ud = data.data || {};
|
const _ud = data.data || {};
|
||||||
startRentalFromServer(data.order_id, unlockPendingCode, 19,
|
startRentalFromServer(data.order_id, code, 19,
|
||||||
_ud.end_time, _ud);
|
_ud.end_time, _ud);
|
||||||
// 刷新订单状态
|
// 刷新订单状态
|
||||||
checkOrderStatus();
|
checkOrderStatus();
|
||||||
@@ -2828,157 +2843,7 @@
|
|||||||
SettingsPages.back();
|
SettingsPages.back();
|
||||||
}
|
}
|
||||||
|
|
||||||
// ========== 订阅提醒(我的 → 车辆订阅) ==========
|
// 订阅提醒已拆到 static/js/subscribe.js
|
||||||
let subscribeLocations = [];
|
|
||||||
const SUB_WEEKDAYS = { 0: "每天", 1: "周一", 2: "周二", 3: "周三", 4: "周四", 5: "周五", 6: "周六", 7: "周日" };
|
|
||||||
async function openSubscribeModal() {
|
|
||||||
closeAllModals();
|
|
||||||
SettingsPages.open("subscribe-modal");
|
|
||||||
await loadSubscribeLocations();
|
|
||||||
loadSubscribeRules();
|
|
||||||
}
|
|
||||||
function closeSubscribeModal() {
|
|
||||||
SettingsPages.back();
|
|
||||||
}
|
|
||||||
async function loadSubscribeLocations() {
|
|
||||||
const sel = document.getElementById("sub-location");
|
|
||||||
sel.innerHTML = '<option value="">加载中...</option>';
|
|
||||||
try {
|
|
||||||
const resp = await fetch("/api/campus/locations");
|
|
||||||
const data = await resp.json();
|
|
||||||
// 订阅只针对「停车点」(楼/兴趣点只用于起终点归属)
|
|
||||||
subscribeLocations = ((data.rtn_code === 0 ? data.data : []) || [])
|
|
||||||
.filter(l => l.kind === "parking");
|
|
||||||
} catch (err) {
|
|
||||||
subscribeLocations = [];
|
|
||||||
}
|
|
||||||
sel.innerHTML = subscribeLocations.length
|
|
||||||
? subscribeLocations.map(l => `<option value="${l.id}">${escHtml(l.name)}</option>`).join("")
|
|
||||||
: '<option value="">(管理员尚未配置停车点)</option>';
|
|
||||||
}
|
|
||||||
function subRuleRowHtml(r) {
|
|
||||||
const loc = subscribeLocations.find(l => l.id === r.location_id);
|
|
||||||
const locName = loc ? loc.name : (r.location_name || "停车点已删除");
|
|
||||||
const hh = String(Math.floor(r.minute_of_day / 60)).padStart(2, "0");
|
|
||||||
const mm = String(r.minute_of_day % 60).padStart(2, "0");
|
|
||||||
const kindText = (r.kind_labels && r.kind_labels.length)
|
|
||||||
? r.kind_labels.join("/") : "全部车型";
|
|
||||||
const eMin = r.min_electric != null ? r.min_electric : 0;
|
|
||||||
const eMax = r.max_electric != null ? r.max_electric : 100;
|
|
||||||
const sortLabel = r.sort_by_label || r.sort_by || "";
|
|
||||||
const tags = [];
|
|
||||||
if (r.auto_unlock) {
|
|
||||||
tags.push(`自动开锁 · ${kindText} · 电量${eMin}-${eMax}% · ${sortLabel} · 重试${r.retry_times || 3}次`);
|
|
||||||
}
|
|
||||||
return `
|
|
||||||
<div class="device-item" style="display:block;padding:9px 12px;border-bottom:1px solid var(--bg-tertiary,#ececf1);">
|
|
||||||
<div style="display:flex;justify-content:space-between;align-items:flex-start;gap:8px;">
|
|
||||||
<div style="font-size:13px;line-height:1.6;min-width:0;">
|
|
||||||
<b>${escHtml(locName)}</b>
|
|
||||||
<span style="color:var(--text-secondary);"> · ${SUB_WEEKDAYS[r.weekday] || "每周"} ${hh}:${mm}</span>
|
|
||||||
<div style="font-size:11.5px;color:var(--text-secondary);">${r.enabled ? "已启用" : "已停用"}${r.notify_enabled ? " · 邮件提醒" : ""}</div>
|
|
||||||
${tags.length ? `<div style="font-size:11.5px;color:#005bbf;">${escHtml(tags[0])}</div>` : ""}
|
|
||||||
</div>
|
|
||||||
<div style="display:flex;gap:6px;flex:0 0 auto;">
|
|
||||||
<button class="btn" style="padding:4px 9px;border:none;border-radius:8px;font-size:12px;background:#ececf1;" onclick="toggleSubscribeRule(${r.id}, ${r.enabled ? 0 : 1})">${r.enabled ? "停用" : "启用"}</button>
|
|
||||||
<button class="btn" style="padding:4px 9px;border:none;border-radius:8px;font-size:12px;background:#fce4ec;color:#c62828;" onclick="deleteSubscribeRule(${r.id})">删除</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>`;
|
|
||||||
}
|
|
||||||
// 订阅表单「更多筛选」折叠开关(高级调优项默认收起)
|
|
||||||
function toggleSubAdvanced() {
|
|
||||||
const box = document.getElementById("sub-advanced");
|
|
||||||
if (!box) return;
|
|
||||||
const show = box.style.display === "none";
|
|
||||||
box.style.display = show ? "block" : "none";
|
|
||||||
}
|
|
||||||
async function loadSubscribeRules() {
|
|
||||||
const box = document.getElementById("subscribe-list");
|
|
||||||
box.innerHTML = '<div class="device-loading">加载中...</div>';
|
|
||||||
try {
|
|
||||||
const resp = await fetch("/api/subscribe/rules", {
|
|
||||||
headers: { "Authorization": `Bearer ${authToken}` }
|
|
||||||
});
|
|
||||||
const data = await resp.json();
|
|
||||||
if (data.rtn_code !== 0) {
|
|
||||||
box.innerHTML = `<div class="device-loading">${escHtml(data.message || "加载失败")}</div>`;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const rules = data.data || [];
|
|
||||||
box.innerHTML = rules.length
|
|
||||||
? rules.map(subRuleRowHtml).join("")
|
|
||||||
: '<div class="device-loading">暂无规则,在下方添加</div>';
|
|
||||||
} catch (err) {
|
|
||||||
box.innerHTML = '<div class="device-loading">网络错误,请重试</div>';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
async function addSubscribeRule() {
|
|
||||||
const locationId = Number(document.getElementById("sub-location").value || 0);
|
|
||||||
const weekday = Number(document.getElementById("sub-weekday").value);
|
|
||||||
const time = document.getElementById("sub-time").value;
|
|
||||||
const notify = document.getElementById("sub-notify").checked;
|
|
||||||
const auto = document.getElementById("sub-auto").checked;
|
|
||||||
const kinds = [...document.querySelectorAll(".sub-kind:checked")].map(el => el.value);
|
|
||||||
const minE = Number(document.getElementById("sub-min-e").value || 0);
|
|
||||||
const maxE = Number(document.getElementById("sub-max-e").value || 100);
|
|
||||||
const sortBy = document.getElementById("sub-sort").value;
|
|
||||||
const retry = Number(document.getElementById("sub-retry").value || 3);
|
|
||||||
|
|
||||||
if (!locationId) { showToast("请先选择停车点(需要管理员先配置停车点)"); return; }
|
|
||||||
if (!/^\d{2}:\d{2}$/.test(time)) { showToast("请选择时间"); return; }
|
|
||||||
if (!kinds.length) { showToast("至少选择一个车型"); return; }
|
|
||||||
if (!(minE >= 0 && maxE <= 100 && minE <= maxE)) { showToast("电量区间需在 0-100 且下限≤上限"); return; }
|
|
||||||
if (auto) {
|
|
||||||
const ok = await appConfirm(
|
|
||||||
"开启自动开锁后,命中规则时系统会用你的账号直接开锁车辆。\n\n" +
|
|
||||||
`筛选:${kinds.map(k => ({small:"小车",big:"大车",red:"红车"}[k])).join("/")},` +
|
|
||||||
`电量 ${minE}%-${maxE}%,${document.getElementById("sub-sort").selectedOptions[0].textContent};` +
|
|
||||||
`被他人抢先时最多重试 ${retry} 次。`,
|
|
||||||
{ title: "开启自动开锁", okText: "确认添加" });
|
|
||||||
if (!ok) return;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
const resp = await fetch("/api/subscribe/rules", {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "Authorization": `Bearer ${authToken}`, "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify({
|
|
||||||
location_id: locationId, weekday, time,
|
|
||||||
notify_enabled: notify, auto_unlock: auto,
|
|
||||||
kinds, min_electric: minE, max_electric: maxE,
|
|
||||||
sort_by: sortBy, retry_times: retry
|
|
||||||
})
|
|
||||||
});
|
|
||||||
const data = await resp.json();
|
|
||||||
showToast(data.message || (data.rtn_code === 0 ? "已添加" : "添加失败"));
|
|
||||||
if (data.rtn_code === 0) loadSubscribeRules();
|
|
||||||
} catch (err) {
|
|
||||||
showToast("网络错误,请重试");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
async function toggleSubscribeRule(ruleId, enable) {
|
|
||||||
try {
|
|
||||||
const resp = await fetch(`/api/subscribe/rules/${ruleId}`, {
|
|
||||||
method: "PUT",
|
|
||||||
headers: { "Authorization": `Bearer ${authToken}`, "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify({ enabled: !!enable })
|
|
||||||
});
|
|
||||||
const data = await resp.json();
|
|
||||||
if (data.rtn_code === 0) loadSubscribeRules();
|
|
||||||
else showToast(data.message || "操作失败");
|
|
||||||
} catch (err) { showToast("网络错误"); }
|
|
||||||
}
|
|
||||||
async function deleteSubscribeRule(ruleId) {
|
|
||||||
try {
|
|
||||||
const resp = await fetch(`/api/subscribe/rules/${ruleId}`, {
|
|
||||||
method: "DELETE",
|
|
||||||
headers: { "Authorization": `Bearer ${authToken}` }
|
|
||||||
});
|
|
||||||
const data = await resp.json();
|
|
||||||
if (data.rtn_code === 0) loadSubscribeRules();
|
|
||||||
else showToast(data.message || "删除失败");
|
|
||||||
} catch (err) { showToast("网络错误"); }
|
|
||||||
}
|
|
||||||
|
|
||||||
// ========== 开锁前预览(月卡余量 + 轮次预估) ==========
|
// ========== 开锁前预览(月卡余量 + 轮次预估) ==========
|
||||||
function renderUnlockPreview(p) {
|
function renderUnlockPreview(p) {
|
||||||
@@ -3034,6 +2899,7 @@
|
|||||||
const text = document.getElementById("add-round-text");
|
const text = document.getElementById("add-round-text");
|
||||||
if (text) {
|
if (text) {
|
||||||
text.innerHTML =
|
text.innerHTML =
|
||||||
|
`加 1 轮会<b>消耗 1 次优惠卡次数</b>(没有卡就按单次计费)。<br/>` +
|
||||||
`当前这一轮还剩约 <b>${mins} 分钟</b>,<b>不会延长</b>。<br/>` +
|
`当前这一轮还剩约 <b>${mins} 分钟</b>,<b>不会延长</b>。<br/>` +
|
||||||
`到点后系统会自动:还车 → 用优惠卡支付 → 立刻重新开锁同一辆车,进入下一轮。`;
|
`到点后系统会自动:还车 → 用优惠卡支付 → 立刻重新开锁同一辆车,进入下一轮。`;
|
||||||
}
|
}
|
||||||
@@ -3111,6 +2977,9 @@
|
|||||||
|
|
||||||
// 初始化百度地图 GL
|
// 初始化百度地图 GL
|
||||||
map = new BMapGL.Map("baidu_map");
|
map = new BMapGL.Map("baidu_map");
|
||||||
|
// 地图实例刚建好:立刻把导航模块的拖动监听绑上(浏览器里唯一可靠的时机,
|
||||||
|
// 之前 navigation.js 只靠 setTimeout(0),那时 map 还是 null,监听从未生效)
|
||||||
|
try { if (typeof bindNavMapEvents === "function") bindNavMapEvents(); } catch (e) {}
|
||||||
map.centerAndZoom(new BMapGL.Point(c.lng, c.lat), cfg.scale || 17);
|
map.centerAndZoom(new BMapGL.Point(c.lng, c.lat), cfg.scale || 17);
|
||||||
map.enableScrollWheelZoom(true);
|
map.enableScrollWheelZoom(true);
|
||||||
map.enableDragging(true);
|
map.enableDragging(true);
|
||||||
@@ -3238,6 +3107,14 @@
|
|||||||
if (typeof BikeClusters === "undefined") {
|
if (typeof BikeClusters === "undefined") {
|
||||||
throw new Error("地图组件未加载,请刷新页面;订单还车功能仍可使用");
|
throw new Error("地图组件未加载,请刷新页面;订单还车功能仍可使用");
|
||||||
}
|
}
|
||||||
|
// 扫码补的临时点每次渲染都回收:它们不在快照数据里,
|
||||||
|
// 不清理的话车早被骑走了地图上还留着一个能点开的旧点。
|
||||||
|
Object.keys(scannedMarkers).forEach((key) => {
|
||||||
|
try { map.removeOverlay(scannedMarkers[key]); } catch (e) {}
|
||||||
|
delete scannedMarkers[key];
|
||||||
|
delete currentMarkersById[key];
|
||||||
|
});
|
||||||
|
|
||||||
// 刷新时不清除边界和停车区(首次加载才绘制)
|
// 刷新时不清除边界和停车区(首次加载才绘制)
|
||||||
if (!isRefresh) {
|
if (!isRefresh) {
|
||||||
// 保存自动定位标记的位置
|
// 保存自动定位标记的位置
|
||||||
@@ -3297,21 +3174,22 @@
|
|||||||
currentPolygons.push(boundaryPolygon);
|
currentPolygons.push(boundaryPolygon);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 首次加载:绘制停车区
|
// 首次加载:绘制停车区(只画启用的:is_disable=2 是停用区,
|
||||||
|
// 上游 /record/checkLocation 会直接拒绝,画出来只会误导人)
|
||||||
if (!isRefresh && data.parkeArea && data.parkeArea.length > 0) {
|
if (!isRefresh && data.parkeArea && data.parkeArea.length > 0) {
|
||||||
data.parkeArea.forEach(area => {
|
data.parkeArea.forEach(area => {
|
||||||
if (!area.points || area.points.length < 3) return;
|
if (!area.points || area.points.length < 3) return;
|
||||||
|
if (String(area.is_disable) === "2") return;
|
||||||
|
|
||||||
const parkingPoints = area.points.map(p => {
|
const parkingPoints = area.points.map(p => {
|
||||||
const c = offsetCoord(p.latitude, p.longitude);
|
const c = offsetCoord(p.latitude, p.longitude);
|
||||||
return new BMapGL.Point(c.lng, c.lat);
|
return new BMapGL.Point(c.lng, c.lat);
|
||||||
});
|
});
|
||||||
const isActive = area.is_disable !== 1;
|
|
||||||
const parkingPolygon = new BMapGL.Polygon(parkingPoints, {
|
const parkingPolygon = new BMapGL.Polygon(parkingPoints, {
|
||||||
strokeColor: isActive ? "#34C759" : "#8E8E93",
|
strokeColor: "#34C759",
|
||||||
strokeWeight: 2,
|
strokeWeight: 2,
|
||||||
strokeOpacity: 0.8,
|
strokeOpacity: 0.8,
|
||||||
fillColor: isActive ? "#34C759" : "#8E8E93",
|
fillColor: "#34C759",
|
||||||
fillOpacity: 0.1,
|
fillOpacity: 0.1,
|
||||||
});
|
});
|
||||||
map.addOverlay(parkingPolygon);
|
map.addOverlay(parkingPolygon);
|
||||||
@@ -3382,6 +3260,28 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ========== 车辆详情 ==========
|
// ========== 车辆详情 ==========
|
||||||
|
// 卡片顶部按钮是否收成纯图标:不按屏宽猜,直接量车牌有没有被截断。
|
||||||
|
// 车牌越长越早收;收起后再量一次,仍截断就保持(空间真不够了)。
|
||||||
|
function _fitCardActions() {
|
||||||
|
const card = document.getElementById("bike-card");
|
||||||
|
const codeEl = document.getElementById("card-code");
|
||||||
|
const title = card && card.querySelector(".bike-card-title");
|
||||||
|
if (!card || !codeEl) return;
|
||||||
|
card.classList.remove("compact-actions");
|
||||||
|
// 读一次布局,看车牌是否被 ellipsis 截断
|
||||||
|
const truncated = (title && title.scrollWidth > title.clientWidth + 1)
|
||||||
|
|| (codeEl.scrollWidth > codeEl.clientWidth + 1);
|
||||||
|
if (truncated) card.classList.add("compact-actions");
|
||||||
|
}
|
||||||
|
let _fitCardTimer = null;
|
||||||
|
window.addEventListener("resize", () => {
|
||||||
|
clearTimeout(_fitCardTimer);
|
||||||
|
_fitCardTimer = setTimeout(() => {
|
||||||
|
if (document.getElementById("bike-card"))
|
||||||
|
_fitCardActions();
|
||||||
|
}, 120);
|
||||||
|
});
|
||||||
|
|
||||||
function showBikeDetail(id) {
|
function showBikeDetail(id) {
|
||||||
let bike = markersData[id];
|
let bike = markersData[id];
|
||||||
// 多格式尝试查找
|
// 多格式尝试查找
|
||||||
@@ -3400,6 +3300,10 @@
|
|||||||
console.error("[showBikeDetail] 找不到车辆数据, id=", id, "markersData keys样本=", Object.keys(markersData).slice(0, 5));
|
console.error("[showBikeDetail] 找不到车辆数据, id=", id, "markersData keys样本=", Object.keys(markersData).slice(0, 5));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
// 换了另一辆车:先把上一辆的导航停掉,避免路线残留在图上
|
||||||
|
if (typeof _nav !== "undefined" && _nav && String(_nav.destCode) !== String(bike.code)) {
|
||||||
|
try { stopNavigation(); } catch (e) {}
|
||||||
|
}
|
||||||
selectedBike = bike;
|
selectedBike = bike;
|
||||||
|
|
||||||
// 设置高亮
|
// 设置高亮
|
||||||
@@ -3407,6 +3311,57 @@
|
|||||||
|
|
||||||
document.getElementById("card-code").textContent = `#${bike.code || id}`;
|
document.getElementById("card-code").textContent = `#${bike.code || id}`;
|
||||||
|
|
||||||
|
// 正在导航的就是这辆车 -> 按钮显示「结束」
|
||||||
|
_navBtnText((_nav && String(_nav.destCode) === String(bike.code)) ? "结束" : "导航");
|
||||||
|
|
||||||
|
// 距离/步行时间:取自动定位留下的标记点(BD09),没开定位就整格隐藏。
|
||||||
|
// 注意别引用 watchPosition 回调里的局部 myPoint —— 那是函数内变量。
|
||||||
|
const metaLeft = document.getElementById("card-meta-left");
|
||||||
|
const distEl = document.getElementById("card-distance");
|
||||||
|
const walkEl = document.getElementById("card-walk");
|
||||||
|
let distMeters = null; // 直线距离(BD09 平面对比),用于决定是否显示导航按钮
|
||||||
|
if (metaLeft && distEl && walkEl) {
|
||||||
|
let distText = "";
|
||||||
|
let walkText = "";
|
||||||
|
try {
|
||||||
|
const me = (typeof autoLocationMarker !== "undefined" && autoLocationMarker)
|
||||||
|
? autoLocationMarker.getPosition() : null;
|
||||||
|
if (me && bike.latitude && bike.longitude) {
|
||||||
|
const c = offsetCoord(bike.latitude, bike.longitude); // GCJ02 -> BD09
|
||||||
|
const meters = calcDistance(me.lat, me.lng, c.lat, c.lng);
|
||||||
|
distMeters = meters;
|
||||||
|
if (Number.isFinite(meters) && meters < MAX_WALK_DISTANCE_M) {
|
||||||
|
distText = meters < 1000
|
||||||
|
? `距你 ${Math.round(meters)} 米`
|
||||||
|
: `距你 ${(meters / 1000).toFixed(1)} 公里`;
|
||||||
|
walkText = `步行 ${Math.max(1, Math.round(meters / 80))} 分钟`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
distText = "";
|
||||||
|
walkText = "";
|
||||||
|
}
|
||||||
|
distEl.textContent = distText;
|
||||||
|
walkEl.textContent = walkText;
|
||||||
|
metaLeft.hidden = !distText;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 太远就不给「导航」按钮(百度步行路线超过 200km 会直接报错,
|
||||||
|
// 而且现实中也没人会走 20 公里去取车)。正在导航这辆车时始终保留「结束」。
|
||||||
|
const navBtnEl2 = document.getElementById("bike-nav-btn");
|
||||||
|
if (navBtnEl2) {
|
||||||
|
const navigatingThis = _nav && String(_nav.destCode) === String(bike.code);
|
||||||
|
const tooFar = !navigatingThis && Number.isFinite(distMeters)
|
||||||
|
&& distMeters >= MAX_WALK_DISTANCE_M;
|
||||||
|
navBtnEl2.style.display = tooFar ? "none" : "";
|
||||||
|
}
|
||||||
|
// 车牌长短 + 屏宽一起决定按钮是否收成纯图标
|
||||||
|
_fitCardActions();
|
||||||
|
|
||||||
|
// 异步换成「真实道路距离 + 步行耗时」:先问后端(百度轻量级路线规划),
|
||||||
|
// 后端没配 AK 就退到浏览器端 JS API,两者都失败则保留上面的直线估算。
|
||||||
|
refineWalkRoute(bike);
|
||||||
|
|
||||||
// 车辆类型角标(红车 / 大车 / 小车)
|
// 车辆类型角标(红车 / 大车 / 小车)
|
||||||
const kind = getBikeKind(bike);
|
const kind = getBikeKind(bike);
|
||||||
const kindEl = document.getElementById("card-kind");
|
const kindEl = document.getElementById("card-kind");
|
||||||
@@ -3463,13 +3418,18 @@
|
|||||||
const c = offsetCoord(bike.latitude, bike.longitude);
|
const c = offsetCoord(bike.latitude, bike.longitude);
|
||||||
const bikePoint = new BMapGL.Point(c.lng, c.lat);
|
const bikePoint = new BMapGL.Point(c.lng, c.lat);
|
||||||
map.panTo(bikePoint);
|
map.panTo(bikePoint);
|
||||||
setTimeout(() => {
|
// 单实例定时器 + 放大上限:以前每开一次卡片就排一个不跟踪的 setTimeout,
|
||||||
map.setZoom(map.getZoom() + 1);
|
// 连点几辆车会把地图永久放大到最大级别。
|
||||||
|
clearTimeout(_cardZoomTimer);
|
||||||
|
_cardZoomTimer = setTimeout(() => {
|
||||||
|
if (map.getZoom() < 19) map.setZoom(map.getZoom() + 1);
|
||||||
}, 300);
|
}, 300);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
let _cardZoomTimer = null;
|
||||||
|
|
||||||
function closeCard() {
|
function closeCard() {
|
||||||
|
// 关卡片**不**结束导航(导航条上有单独的「结束导航」按钮)
|
||||||
const card = document.getElementById("bike-card");
|
const card = document.getElementById("bike-card");
|
||||||
const overlay = document.getElementById("card-overlay");
|
const overlay = document.getElementById("card-overlay");
|
||||||
card.classList.remove("show");
|
card.classList.remove("show");
|
||||||
@@ -3567,6 +3527,26 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
markersData[codeNum] = bike;
|
markersData[codeNum] = bike;
|
||||||
|
|
||||||
|
// 地图上可能还没有这辆车(已被骑走 / 不在当前车型里):
|
||||||
|
// 补一个高亮标记,否则「查到了但地图上什么都没有」
|
||||||
|
if (hasLocation && !currentMarkersById[codeNum]) {
|
||||||
|
try {
|
||||||
|
const c = offsetCoord(bike.latitude, bike.longitude);
|
||||||
|
const marker = new BMapGL.Marker(
|
||||||
|
new BMapGL.Point(c.lng, c.lat),
|
||||||
|
{ icon: getBikeIcon(bike, true) }
|
||||||
|
);
|
||||||
|
map.addOverlay(marker);
|
||||||
|
currentMarkers.push(marker);
|
||||||
|
currentMarkersById[codeNum] = marker;
|
||||||
|
scannedMarkers[codeNum] = marker;
|
||||||
|
bindMarkerTap(marker, codeNum);
|
||||||
|
} catch (e) {
|
||||||
|
console.warn("[扫码] 补标记失败:", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
showBikeDetail(codeNum);
|
showBikeDetail(codeNum);
|
||||||
}
|
}
|
||||||
// success=false 时,也尝试用 markersData 显示详情和定位
|
// success=false 时,也尝试用 markersData 显示详情和定位
|
||||||
@@ -3635,7 +3615,7 @@
|
|||||||
_lostModeActive = true;
|
_lostModeActive = true;
|
||||||
|
|
||||||
const btn = document.getElementById("bike-find-btn-header");
|
const btn = document.getElementById("bike-find-btn-header");
|
||||||
const span = btn.querySelector("span");
|
const span = btn && btn.querySelector("span");
|
||||||
btn.classList.add("lost-mode");
|
btn.classList.add("lost-mode");
|
||||||
btn.title = "丢失模式(点击退出)";
|
btn.title = "丢失模式(点击退出)";
|
||||||
if (span) span.textContent = "丢失模式";
|
if (span) span.textContent = "丢失模式";
|
||||||
@@ -3668,7 +3648,7 @@
|
|||||||
_findClickCount = 0;
|
_findClickCount = 0;
|
||||||
|
|
||||||
const btn = document.getElementById("bike-find-btn-header");
|
const btn = document.getElementById("bike-find-btn-header");
|
||||||
const span = btn.querySelector("span");
|
const span = btn && btn.querySelector("span");
|
||||||
if (btn) {
|
if (btn) {
|
||||||
btn.classList.remove("lost-mode");
|
btn.classList.remove("lost-mode");
|
||||||
btn.disabled = false;
|
btn.disabled = false;
|
||||||
@@ -3717,7 +3697,7 @@
|
|||||||
// 正常寻车
|
// 正常寻车
|
||||||
const code = selectedBike.code;
|
const code = selectedBike.code;
|
||||||
const btn = document.getElementById("bike-find-btn-header");
|
const btn = document.getElementById("bike-find-btn-header");
|
||||||
const span = btn.querySelector("span");
|
const span = btn && btn.querySelector("span");
|
||||||
|
|
||||||
btn.disabled = true;
|
btn.disabled = true;
|
||||||
btn.title = "发送中...";
|
btn.title = "发送中...";
|
||||||
@@ -4087,7 +4067,7 @@
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (bikeState === 'reserved') {
|
if (bikeState === 'reserved') {
|
||||||
showToast("该车已被预约");
|
showToast("该车已损坏,无法使用"); // 上游 state=2 表示损坏,不是被预约
|
||||||
closeCard();
|
closeCard();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -4808,15 +4788,6 @@
|
|||||||
// 计算距离并找最近可用车辆(智能电量匹配)
|
// 计算距离并找最近可用车辆(智能电量匹配)
|
||||||
function findNearestBike(myPoint) {
|
function findNearestBike(myPoint) {
|
||||||
// Haversine公式计算两点距离(米)
|
// Haversine公式计算两点距离(米)
|
||||||
function calcDistance(lat1, lng1, lat2, lng2) {
|
|
||||||
const R = 6371000;
|
|
||||||
const dLat = (lat2 - lat1) * Math.PI / 180;
|
|
||||||
const dLng = (lng2 - lng1) * Math.PI / 180;
|
|
||||||
const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
|
|
||||||
Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
|
|
||||||
Math.sin(dLng/2) * Math.sin(dLng/2);
|
|
||||||
return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
|
|
||||||
}
|
|
||||||
|
|
||||||
const myLat = myPoint.lat;
|
const myLat = myPoint.lat;
|
||||||
const myLng = myPoint.lng;
|
const myLng = myPoint.lng;
|
||||||
@@ -5009,329 +4980,8 @@
|
|||||||
opts.body = JSON.stringify(body);
|
opts.body = JSON.stringify(body);
|
||||||
}
|
}
|
||||||
return fetch(url, opts).then(r => r.json());
|
return fetch(url, opts).then(r => r.json());
|
||||||
}
|
// 共享电动车已拆到 static/js/share.js
|
||||||
|
|
||||||
// ===== 私密备注(昵称) 工具 =====
|
|
||||||
// 显示对方时:优先用“我给他起的备注(昵称)”,其次显示名,最后退回邮箱
|
|
||||||
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 = "确认还车"; }
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------- 初始化(登录后/页面加载) ----------
|
// ---------- 初始化(登录后/页面加载) ----------
|
||||||
@@ -5343,5 +4993,8 @@
|
|||||||
if (authToken) shareAfterLogin();
|
if (authToken) shareAfterLogin();
|
||||||
setInterval(() => { if (authToken) { checkAuthStatus(); checkOrderStatus(); refreshShareBanners(); } }, 20000);
|
setInterval(() => { if (authToken) { checkAuthStatus(); checkOrderStatus(); refreshShareBanners(); } }, 20000);
|
||||||
setInterval(() => { if (authToken) checkPendingShareRequests(); }, 30000);
|
setInterval(() => { if (authToken) checkPendingShareRequests(); }, 30000);
|
||||||
setTimeout(maybeAutoShowVersion, 1200);
|
// 版本更新说明不再自动弹(右下角版本徽标也已去掉);
|
||||||
|
// 需要看历史更新时可以从控制台 openVersionModal() 调出来
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// 共享电动车已拆到 static/js/share.js
|
||||||
|
|||||||
@@ -0,0 +1,795 @@
|
|||||||
|
/* 跟随式导航:路线规划/跟随/偏航重算/朝向/箭头/指引 + 步行距离精算。
|
||||||
|
* 从 static/js/map.js 拆出(保持全局函数名不变,其他模块按原名调用)。 */
|
||||||
|
|
||||||
|
|
||||||
|
// ========== 步行路线精算(真实道路距离 + 耗时)==========
|
||||||
|
const _walkRouteCache = new Map(); // `${code}|${我的坐标}` -> {d, t}
|
||||||
|
// 超过这个直线距离就不显示「距离/步行」——太远的车走过去没有意义,
|
||||||
|
// 而且会让百度步行规划白白消耗配额。直线估算与精算共用同一个阈值。
|
||||||
|
const MAX_WALK_DISTANCE_M = 20000;
|
||||||
|
|
||||||
|
function parseWalkDistance(text) {
|
||||||
|
const s = String(text || "");
|
||||||
|
const km = s.match(/([\d.]+)\s*公里/);
|
||||||
|
if (km) return Math.round(parseFloat(km[1]) * 1000);
|
||||||
|
const m = s.match(/([\d.]+)\s*米/);
|
||||||
|
return m ? Math.round(parseFloat(m[1])) : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseWalkDuration(text) {
|
||||||
|
const s = String(text || "");
|
||||||
|
let sec = 0;
|
||||||
|
const h = s.match(/([\d.]+)\s*小时/);
|
||||||
|
const min = s.match(/([\d.]+)\s*分钟/);
|
||||||
|
if (h) sec += Math.round(parseFloat(h[1]) * 3600);
|
||||||
|
if (min) sec += Math.round(parseFloat(min[1]) * 60);
|
||||||
|
return sec;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refineWalkRoute(bike) {
|
||||||
|
const bikeCode = String((bike && bike.code) || "");
|
||||||
|
if (!bikeCode) return;
|
||||||
|
const me = (typeof autoLocationMarker !== "undefined" && autoLocationMarker)
|
||||||
|
? autoLocationMarker.getPosition() : null;
|
||||||
|
if (!me || !bike.latitude || !bike.longitude) return;
|
||||||
|
|
||||||
|
// 太远就整块不显示(与直线估算口径一致,别让精算把隐藏的行又显示回来)
|
||||||
|
const c0 = offsetCoord(bike.latitude, bike.longitude);
|
||||||
|
if (calcDistance(me.lat, me.lng, c0.lat, c0.lng) > MAX_WALK_DISTANCE_M) return;
|
||||||
|
|
||||||
|
const key = bikeCode + "|" + me.lat.toFixed(4) + "," + me.lng.toFixed(4);
|
||||||
|
|
||||||
|
const apply = (distanceM, seconds) => {
|
||||||
|
if (!selectedBike || String(selectedBike.code) !== bikeCode) return; // 已换车
|
||||||
|
const distEl = document.getElementById("card-distance");
|
||||||
|
const walkEl = document.getElementById("card-walk");
|
||||||
|
const metaLeft = document.getElementById("card-meta-left");
|
||||||
|
if (!distEl || !walkEl || !metaLeft) return;
|
||||||
|
distEl.textContent = distanceM < 1000
|
||||||
|
? `步行 ${Math.round(distanceM)} 米`
|
||||||
|
: `步行 ${(distanceM / 1000).toFixed(1)} 公里`;
|
||||||
|
walkEl.textContent = `约 ${Math.max(1, Math.round(seconds / 60))} 分钟`;
|
||||||
|
metaLeft.hidden = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
const cached = _walkRouteCache.get(key);
|
||||||
|
if (cached) { apply(cached.d, cached.t); return; }
|
||||||
|
|
||||||
|
// ① 后端(百度 Web 服务 API,需服务端 AK + SK,结果服务端缓存 7 天)
|
||||||
|
try {
|
||||||
|
const gcj = (typeof coordtransform !== "undefined" && coordtransform.bd09togcj02)
|
||||||
|
? coordtransform.bd09togcj02(me.lng, me.lat) : null;
|
||||||
|
if (gcj) {
|
||||||
|
const url = "/api/walk_route?origin_lat=" + gcj[1] + "&origin_lng=" + gcj[0]
|
||||||
|
+ "&dest_lat=" + bike.latitude + "&dest_lng=" + bike.longitude;
|
||||||
|
const resp = await fetch(url, {
|
||||||
|
headers: { "Authorization": "Bearer " + authToken }
|
||||||
|
});
|
||||||
|
const data = await resp.json();
|
||||||
|
const d = data && data.data;
|
||||||
|
if (data.rtn_code === 0 && d && d.distance > 0 && d.duration > 0
|
||||||
|
&& (d.source === "baidu" || d.source === "cache")) {
|
||||||
|
_walkRouteCache.set(key, { d: d.distance, t: d.duration });
|
||||||
|
apply(d.distance, d.duration);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) { /* 忽略,走 SDK */ }
|
||||||
|
|
||||||
|
// ② 浏览器端 JS API 步行规划(现成浏览器 AK,返回 "1.6公里"/"23分钟" 字符串)
|
||||||
|
try {
|
||||||
|
if (typeof BMapGL !== "undefined" && BMapGL.WalkingRoute && map) {
|
||||||
|
const plan = await new Promise(resolve => {
|
||||||
|
let done = false;
|
||||||
|
const finish = v => { if (!done) { done = true; resolve(v); } };
|
||||||
|
const walk = new BMapGL.WalkingRoute(map, {
|
||||||
|
renderOptions: { map: null, panel: null },
|
||||||
|
onSearchComplete: res => {
|
||||||
|
// 退化路线(起点≈终点)时 res 可能是空壳、没有 getStatus,
|
||||||
|
// 直接调用会抛未捕获 TypeError(两版都有的历史问题)
|
||||||
|
let status = -1;
|
||||||
|
try {
|
||||||
|
status = (res && typeof res.getStatus === "function")
|
||||||
|
? res.getStatus() : -1;
|
||||||
|
} catch (e) { status = -1; }
|
||||||
|
if (status !== 0) return finish(null);
|
||||||
|
try {
|
||||||
|
const p = res.getPlan(0);
|
||||||
|
const d = parseWalkDistance(p.getDistance());
|
||||||
|
const t = parseWalkDuration(p.getDuration());
|
||||||
|
finish(d > 0 && t > 0 ? { d: d, t: t } : null);
|
||||||
|
} catch (err) { finish(null); }
|
||||||
|
}
|
||||||
|
});
|
||||||
|
walk.search(me, new BMapGL.Point(bike.longitude, bike.latitude));
|
||||||
|
setTimeout(() => finish(null), 8000);
|
||||||
|
});
|
||||||
|
if (plan) {
|
||||||
|
_walkRouteCache.set(key, plan);
|
||||||
|
apply(plan.d, plan.t);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) { /* 保留直线估算 */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 跟随式导航 ==========
|
||||||
|
// 状态:null = 未导航;对象存在 = 导航中
|
||||||
|
// { ptsGcj, ptsBD, idx, walking, follow, timer, watchId, destCode, distance, duration }
|
||||||
|
let _nav = null;
|
||||||
|
let _navLoading = false;
|
||||||
|
// 每次 start/stop 都自增;await 回来发现变了就说明中途被关掉了,别再自动开起来
|
||||||
|
let _navEpoch = 0;
|
||||||
|
|
||||||
|
// 偏航阈值:百度会把起点吸附到最近道路,和真实 GPS 天然差 20~50 米,
|
||||||
|
// 所以阈值不能太小,且重算要有冷却,否则会陷入"重算->又偏->再重算"。
|
||||||
|
const NAV_DEVIATE_M = 60;
|
||||||
|
const NAV_RECOMPUTE_COOLDOWN_MS = 12000;
|
||||||
|
// 偏差在这个范围内就把箭头吸附到路线上(10 米内才贴线,超过了就老实显示真实位置)
|
||||||
|
const NAV_SNAP_M = 10;
|
||||||
|
const NAV_BOTTOM_RATIO = 0.20; // 当前位置压在屏幕下方约 80% 高度处
|
||||||
|
const NAV_FREE_TIMEOUT = 8000; // 拖动后多久自动回正
|
||||||
|
|
||||||
|
function _haversineM(lat1, lng1, lat2, lng2) {
|
||||||
|
const R = 6371000;
|
||||||
|
const dLat = (lat2 - lat1) * Math.PI / 180;
|
||||||
|
const dLng = (lng2 - lng1) * Math.PI / 180;
|
||||||
|
const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
|
||||||
|
Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
|
||||||
|
Math.sin(dLng / 2) * Math.sin(dLng / 2);
|
||||||
|
return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 浏览器定位给的是 WGS84,转成 GCJ02 才能和百度/上游坐标对齐
|
||||||
|
function _gpsToGcj(coords) {
|
||||||
|
const lat = coords.latitude, lng = coords.longitude;
|
||||||
|
if (typeof coordtransform !== "undefined" && coordtransform.wgs84togcj02) {
|
||||||
|
try {
|
||||||
|
const g = coordtransform.wgs84togcj02(lng, lat); // -> [lng, lat]
|
||||||
|
return { lat: g[1], lng: g[0] };
|
||||||
|
} catch (e) { /* 落到下面原值兜底 */ }
|
||||||
|
}
|
||||||
|
return { lat: lat, lng: lng };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 航向角:0=正北,90=正东
|
||||||
|
function _bearing(from, to) {
|
||||||
|
const p1 = from.lat * Math.PI / 180, p2 = to.lat * Math.PI / 180;
|
||||||
|
const dl = (to.lng - from.lng) * Math.PI / 180;
|
||||||
|
const y = Math.sin(dl) * Math.cos(p2);
|
||||||
|
const x = Math.cos(p1) * Math.sin(p2) - Math.sin(p1) * Math.cos(p2) * Math.cos(dl);
|
||||||
|
return (Math.atan2(y, x) * 180 / Math.PI + 360) % 360;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 当前位置在折线上的最近点(投影到线段上,不是只找最近顶点)
|
||||||
|
// 返回 {index, meters, point};point 为线段上的插值点
|
||||||
|
function _projectOnRoute(ptsBD, point) {
|
||||||
|
if (!ptsBD || ptsBD.length === 0) return { index: 0, meters: Infinity, point: point };
|
||||||
|
if (ptsBD.length === 1) {
|
||||||
|
return { index: 0, meters: _haversineM(point.lat, point.lng, ptsBD[0].lat, ptsBD[0].lng),
|
||||||
|
point: ptsBD[0] };
|
||||||
|
}
|
||||||
|
const cosLat = Math.cos(point.lat * Math.PI / 180);
|
||||||
|
const toXY = (p) => [
|
||||||
|
(p.lng - point.lng) * 111320 * cosLat,
|
||||||
|
(p.lat - point.lat) * 110540
|
||||||
|
];
|
||||||
|
let bestI = 0, bestM = Infinity, bestT = 0;
|
||||||
|
for (let i = 0; i < ptsBD.length - 1; i++) {
|
||||||
|
const a = toXY(ptsBD[i]), b = toXY(ptsBD[i + 1]);
|
||||||
|
const dx = b[0] - a[0], dy = b[1] - a[1];
|
||||||
|
const seg2 = dx * dx + dy * dy;
|
||||||
|
// 查询点是原点 (0,0),投影参数 t 落在 [0,1]
|
||||||
|
const t = seg2 === 0 ? 0 : Math.max(0, Math.min(1, -(a[0] * dx + a[1] * dy) / seg2));
|
||||||
|
const cx = a[0] + t * dx, cy = a[1] + t * dy;
|
||||||
|
const d = Math.hypot(cx, cy);
|
||||||
|
if (d < bestM) { bestM = d; bestI = i; bestT = t; }
|
||||||
|
}
|
||||||
|
const a = ptsBD[bestI], b = ptsBD[bestI + 1];
|
||||||
|
const p = new BMapGL.Point(a.lng + bestT * (b.lng - a.lng),
|
||||||
|
a.lat + bestT * (b.lat - a.lat));
|
||||||
|
return { index: bestI, meters: bestM, point: p };
|
||||||
|
}
|
||||||
|
|
||||||
|
function _navBanner(show) {
|
||||||
|
const el = document.getElementById("nav-banner");
|
||||||
|
if (el) el.hidden = !show;
|
||||||
|
}
|
||||||
|
|
||||||
|
function _navPill(show) {
|
||||||
|
const el = document.getElementById("nav-resume");
|
||||||
|
if (el) el.hidden = !show;
|
||||||
|
}
|
||||||
|
|
||||||
|
function _navBtnText(text) {
|
||||||
|
const el = document.getElementById("bike-nav-btn-text");
|
||||||
|
if (el) el.textContent = text;
|
||||||
|
// 「导航」和「结束」宽度不同,换字后重新量一次是否还放得下
|
||||||
|
if (typeof _fitCardActions === "function") _fitCardActions();
|
||||||
|
}
|
||||||
|
|
||||||
|
function _clearNavLayers() {
|
||||||
|
if (!_nav) return;
|
||||||
|
(_nav.walking || []).forEach(ov => { try { map.removeOverlay(ov); } catch (e) {} });
|
||||||
|
(_nav.remaining || []).forEach(ov => { try { map.removeOverlay(ov); } catch (e) {} });
|
||||||
|
if (_nav.endMarker) { try { map.removeOverlay(_nav.endMarker); } catch (e) {} }
|
||||||
|
_nav.walking = []; _nav.remaining = []; _nav.endMarker = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 按进度把折线切成「已走(灰)」与「剩余(蓝)」
|
||||||
|
function _redrawRoute(fromIndex) {
|
||||||
|
if (!_nav || !_nav.ptsBD || !_nav.ptsBD.length) return;
|
||||||
|
_clearNavLayers();
|
||||||
|
const pts = _nav.ptsBD;
|
||||||
|
const cut = Math.max(0, Math.min(fromIndex, pts.length - 1));
|
||||||
|
|
||||||
|
if (cut > 0) {
|
||||||
|
const walked = new BMapGL.Polyline(pts.slice(0, cut + 1), {
|
||||||
|
strokeColor: "#9E9E9E", strokeWeight: 6, strokeOpacity: 0.85,
|
||||||
|
strokeStyle: "solid"
|
||||||
|
});
|
||||||
|
map.addOverlay(walked);
|
||||||
|
_nav.walking.push(walked);
|
||||||
|
}
|
||||||
|
if (cut < pts.length - 1) {
|
||||||
|
const rest = pts.slice(cut);
|
||||||
|
const casing = new BMapGL.Polyline(rest, {
|
||||||
|
strokeColor: "#FFFFFF", strokeWeight: 11, strokeOpacity: 0.95,
|
||||||
|
strokeStyle: "solid"
|
||||||
|
});
|
||||||
|
const line = new BMapGL.Polyline(rest, {
|
||||||
|
strokeColor: "#0A84FF", strokeWeight: 6, strokeOpacity: 1,
|
||||||
|
strokeStyle: "solid"
|
||||||
|
});
|
||||||
|
map.addOverlay(casing);
|
||||||
|
map.addOverlay(line);
|
||||||
|
_nav.remaining.push(casing, line);
|
||||||
|
}
|
||||||
|
if (!_nav.endMarker) {
|
||||||
|
_nav.endMarker = new BMapGL.Marker(pts[pts.length - 1], { icon: _destIcon() });
|
||||||
|
map.addOverlay(_nav.endMarker);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 跟随:把当前位置压到屏幕下方,并让行进方向朝上
|
||||||
|
// 部分环境(例如 WebGL 软件渲染)setHeading 不生效,探测一次后退化为「正北朝上」
|
||||||
|
let _headingSupported = null;
|
||||||
|
let _headingAnim = null;
|
||||||
|
|
||||||
|
// 文档化的旋转方式:ViewAnimation 关键帧里的 heading
|
||||||
|
// (setHeading 是没写进文档的私有方法,见 docs/baidu-map-gl-cheatsheet.md 坑 1)
|
||||||
|
function _rotateByAnimation(deg) {
|
||||||
|
try {
|
||||||
|
if (typeof BMapGL.ViewAnimation !== "function") return false;
|
||||||
|
const from = (typeof map.getHeading === "function" ? map.getHeading() : 0) || 0;
|
||||||
|
if (_headingAnim && map.cancelViewAnimation) {
|
||||||
|
try { map.cancelViewAnimation(_headingAnim); } catch (e) {}
|
||||||
|
}
|
||||||
|
_headingAnim = new BMapGL.ViewAnimation([
|
||||||
|
{ heading: from, percentage: 0 },
|
||||||
|
{ heading: deg, percentage: 1 }
|
||||||
|
], { duration: 260 });
|
||||||
|
map.startViewAnimation(_headingAnim);
|
||||||
|
return true;
|
||||||
|
} catch (e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function _applyHeading(deg) {
|
||||||
|
if (_headingSupported === false) return;
|
||||||
|
try {
|
||||||
|
if (typeof map.setHeading !== "function") { _headingSupported = false; return; }
|
||||||
|
map.setHeading(deg);
|
||||||
|
if (_headingSupported === null) {
|
||||||
|
const got = typeof map.getHeading === "function" ? map.getHeading() : undefined;
|
||||||
|
// 调了 45 度结果还是 0,说明这个环境不支持地图旋转
|
||||||
|
_headingSupported = (typeof got === "number" && Math.abs(got) > 0.5);
|
||||||
|
if (!_headingSupported) {
|
||||||
|
console.info("[导航] 当前环境不支持 setHeading,尝试 ViewAnimation 旋转");
|
||||||
|
// 关键:有些 WebGL 环境调完 setHeading 会留下坏的相机状态,
|
||||||
|
// 表现为整张底图变黑。这里复位并把视野重新设一次,把瓦片拉回来。
|
||||||
|
try { if (map.resetHeading) map.resetHeading(); } catch (e) {}
|
||||||
|
try {
|
||||||
|
const c = map.getCenter ? map.getCenter() : null;
|
||||||
|
if (c) map.setCenter(c);
|
||||||
|
} catch (e) {}
|
||||||
|
// 文档化兜底:ViewAnimation 关键帧旋转
|
||||||
|
if (_rotateByAnimation(deg)) {
|
||||||
|
_headingSupported = true;
|
||||||
|
console.info("[导航] ViewAnimation 旋转可用");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) { _headingSupported = false; }
|
||||||
|
}
|
||||||
|
|
||||||
|
// 迁就百度的一个坑:setCenter 会把刚设置的 heading 抹回 0,
|
||||||
|
// 必须在它的回调里再 setHeading(官方 setCenter 支持 callback,动画结束后触发)。
|
||||||
|
// 另一个坑:BMapGL 的 heading 是**逆时针**角度,要让行进方向朝上必须传 -方位角。
|
||||||
|
//(实测方位角 145° 时:setHeading(145) 前方在左上;setHeading(-145) 前方正上方)
|
||||||
|
function _centerOnUser(point, headingDeg) {
|
||||||
|
const h = window.innerHeight || 800;
|
||||||
|
const offsetY = Math.round(h * NAV_BOTTOM_RATIO);
|
||||||
|
const mapHeading = (typeof headingDeg === "number") ? -headingDeg : null;
|
||||||
|
_markProgrammaticMove();
|
||||||
|
try {
|
||||||
|
map.setCenter(point, {
|
||||||
|
noAnimation: true,
|
||||||
|
callback: function () {
|
||||||
|
if (mapHeading !== null) _applyHeading(mapHeading);
|
||||||
|
try {
|
||||||
|
// 把「我」推到屏幕下方:地图整体上移
|
||||||
|
if (map.panBy) map.panBy(0, offsetY);
|
||||||
|
} catch (e) {}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
// 老版本 setCenter 不支持 options,退回手动顺序
|
||||||
|
try {
|
||||||
|
map.setCenter(point);
|
||||||
|
if (mapHeading !== null) _applyHeading(mapHeading);
|
||||||
|
if (map.panBy) map.panBy(0, offsetY);
|
||||||
|
} catch (e2) { /* 忽略 */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 罗盘 + 导航箭头 ==========
|
||||||
|
// 手机朝向(罗盘):iOS 用 webkitCompassHeading,安卓用 360 - alpha
|
||||||
|
let _compassHeading = null;
|
||||||
|
let _compassBound = false;
|
||||||
|
|
||||||
|
function _bindCompass() {
|
||||||
|
if (_compassBound) return;
|
||||||
|
_compassBound = true;
|
||||||
|
const onOrient = (e) => {
|
||||||
|
let h = null;
|
||||||
|
if (typeof e.webkitCompassHeading === "number") {
|
||||||
|
h = e.webkitCompassHeading; // iOS:已经是「相对正北的顺时针角度」
|
||||||
|
} else if (typeof e.alpha === "number") {
|
||||||
|
h = (360 - e.alpha) % 360; // 安卓:alpha 是逆时针
|
||||||
|
}
|
||||||
|
if (h !== null && Number.isFinite(h)) _compassHeading = h;
|
||||||
|
};
|
||||||
|
window.addEventListener("deviceorientationabsolute", onOrient, true);
|
||||||
|
window.addEventListener("deviceorientation", onOrient, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
// iOS 13+ 必须由用户手势触发权限申请;导航按钮的点击正好是手势
|
||||||
|
async function _ensureCompassPermission() {
|
||||||
|
const D = window.DeviceOrientationEvent;
|
||||||
|
try {
|
||||||
|
if (D && typeof D.requestPermission === "function") {
|
||||||
|
const res = await D.requestPermission();
|
||||||
|
if (res !== "granted") {
|
||||||
|
console.info("[导航] 未获得方向传感器权限,箭头改用行进方向");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) { /* 用户拒绝或非 iOS */ }
|
||||||
|
_bindCompass();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 导航箭头图标(向上指,旋转由 Marker.setRotation 控制)
|
||||||
|
function _navArrowIcon() {
|
||||||
|
const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="72" height="72" viewBox="0 0 72 72">'
|
||||||
|
+ '<circle cx="36" cy="36" r="30" fill="#0A84FF" fill-opacity="0.16"/>'
|
||||||
|
+ '<path d="M36 10 L52 52 L36 43 L20 52 Z" fill="#0A84FF" stroke="#FFFFFF"'
|
||||||
|
+ ' stroke-width="3" stroke-linejoin="round"/></svg>';
|
||||||
|
const url = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(svg);
|
||||||
|
return new BMapGL.Icon(url, new BMapGL.Size(36, 36),
|
||||||
|
{ anchor: new BMapGL.Size(18, 18) });
|
||||||
|
}
|
||||||
|
|
||||||
|
// 转弯/掉头/直行的图标(画在导航条文字左边,不再画到地图上)
|
||||||
|
function _turnKind(turnType) {
|
||||||
|
const t = String(turnType || "");
|
||||||
|
if (t.indexOf("掉头") >= 0) return "uturn";
|
||||||
|
if (t.indexOf("左") >= 0) return "left";
|
||||||
|
if (t.indexOf("右") >= 0) return "right";
|
||||||
|
return "straight";
|
||||||
|
}
|
||||||
|
|
||||||
|
function _turnSvg(kind) {
|
||||||
|
const paths = {
|
||||||
|
straight: '<path d="M24 42 L24 12" /><path d="M14 22 L24 10 L34 22" />',
|
||||||
|
left: '<path d="M34 42 L34 22 L16 22" /><path d="M24 12 L12 22 L24 32" />',
|
||||||
|
right: '<path d="M14 42 L14 22 L32 22" /><path d="M30 12 L42 22 L30 32" />',
|
||||||
|
uturn: '<path d="M18 42 L18 18 A8 8 0 0 1 34 18 L34 26" /><path d="M26 20 L34 10 L42 20" />'
|
||||||
|
};
|
||||||
|
const body = paths[kind] || paths.straight;
|
||||||
|
return '<svg viewBox="0 0 48 48" fill="none" stroke="currentColor" stroke-width="4.5"'
|
||||||
|
+ ' stroke-linecap="round" stroke-linejoin="round">' + body + '</svg>';
|
||||||
|
}
|
||||||
|
|
||||||
|
function _setTurnIcon(kind) {
|
||||||
|
const el = document.getElementById("nav-banner-turn");
|
||||||
|
if (!el) return;
|
||||||
|
if (el.__kind === kind) return; // 同一个图标不重复写 DOM
|
||||||
|
el.__kind = kind;
|
||||||
|
el.innerHTML = _turnSvg(kind);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 目的地图标(SVG 定位针,底端对准坐标点)
|
||||||
|
function _destIcon() {
|
||||||
|
const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="64" height="76" viewBox="0 0 32 38">'
|
||||||
|
+ '<path d="M16 36C16 36 30 22.5 30 14A14 14 0 1 0 2 14C2 22.5 16 36 16 36Z"'
|
||||||
|
+ ' fill="#FF3B30" stroke="#FFFFFF" stroke-width="2.4"/>'
|
||||||
|
+ '<circle cx="16" cy="14" r="5" fill="#FFFFFF"/></svg>';
|
||||||
|
const url = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(svg);
|
||||||
|
return new BMapGL.Icon(url, new BMapGL.Size(30, 36), { anchor: new BMapGL.Size(15, 36) });
|
||||||
|
}
|
||||||
|
|
||||||
|
function _placeNavArrow(point) {
|
||||||
|
if (!_nav) return;
|
||||||
|
if (!_nav.arrow) {
|
||||||
|
_nav.arrow = new BMapGL.Marker(point, { icon: _navArrowIcon() });
|
||||||
|
map.addOverlay(_nav.arrow);
|
||||||
|
// 导航时用箭头代替原来的蓝点
|
||||||
|
try { if (typeof autoLocationMarker !== "undefined" && autoLocationMarker) autoLocationMarker.hide(); } catch (e) {}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try { _nav.arrow.setPosition(point); } catch (e) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
function _rotateNavArrow(deg) {
|
||||||
|
if (!_nav || !_nav.arrow) return;
|
||||||
|
try { if (typeof _nav.arrow.setRotation === "function") _nav.arrow.setRotation(deg); } catch (e) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
function _clearNavArrow() {
|
||||||
|
if (_nav && _nav.arrow) {
|
||||||
|
try { map.removeOverlay(_nav.arrow); } catch (e) {}
|
||||||
|
_nav.arrow = null;
|
||||||
|
}
|
||||||
|
try { if (typeof autoLocationMarker !== "undefined" && autoLocationMarker) autoLocationMarker.show(); } catch (e) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
function _navTick(position) {
|
||||||
|
if (!_nav || _nav.follow === false) return; // 拖动查看时不抢镜头
|
||||||
|
const gcj = _gpsToGcj(position); // WGS84 -> GCJ02
|
||||||
|
const c = offsetCoord(gcj.lat, gcj.lng); // GCJ02 -> BD09
|
||||||
|
const me = new BMapGL.Point(c.lng, c.lat);
|
||||||
|
|
||||||
|
const proj = _projectOnRoute(_nav.ptsBD, me);
|
||||||
|
const now = Date.now();
|
||||||
|
if (proj.meters > NAV_DEVIATE_M && !_nav.recomputing
|
||||||
|
&& now - (_nav.lastRecomputeAt || 0) > NAV_RECOMPUTE_COOLDOWN_MS) {
|
||||||
|
_nav.recomputing = true;
|
||||||
|
_nav.lastRecomputeAt = now;
|
||||||
|
_recomputeRoute(gcj).finally(() => { if (_nav) _nav.recomputing = false; });
|
||||||
|
return; // 本帧不更新进度,等新路线
|
||||||
|
}
|
||||||
|
if (proj.index !== _nav.idx) {
|
||||||
|
_nav.idx = proj.index;
|
||||||
|
_redrawRoute(_nav.idx);
|
||||||
|
}
|
||||||
|
// 箭头位置:偏差在吸附范围内就贴到路线上,否则用真实位置
|
||||||
|
const anchor = (proj.meters <= NAV_SNAP_M && proj.point) ? proj.point : me;
|
||||||
|
// 朝向:沿路线往后看几个点算切线,比"我→下一个点"稳得多(GPS 抖动不会乱转)
|
||||||
|
const aheadIdx = Math.min(proj.index + 3, _nav.ptsBD.length - 1);
|
||||||
|
const travelHeading = _bearing(_nav.ptsBD[proj.index], _nav.ptsBD[aheadIdx]);
|
||||||
|
_placeNavArrow(anchor);
|
||||||
|
// 地图始终按「行进方向」朝上(不跟手机朝向)
|
||||||
|
const mapDeg = (_headingSupported === false) ? 0 : travelHeading;
|
||||||
|
// 箭头指手机朝向;没有罗盘权限就让它跟着行进方向(朝前)
|
||||||
|
const arrowDeg = (typeof _compassHeading === "number")
|
||||||
|
? (_compassHeading - mapDeg)
|
||||||
|
: 0;
|
||||||
|
_rotateNavArrow(arrowDeg);
|
||||||
|
_centerOnUser(anchor, travelHeading);
|
||||||
|
|
||||||
|
// 剩余距离/时间(按进度线性折算,仅用于展示)
|
||||||
|
const total = _nav.ptsBD.length - 1;
|
||||||
|
const ratio = total > 0 ? Math.max(0, 1 - _nav.idx / total) : 0;
|
||||||
|
const leftM = Math.round((_nav.distance || 0) * ratio);
|
||||||
|
const leftS = Math.round((_nav.duration || 0) * ratio);
|
||||||
|
const travelled = (_nav.distance || 0) * (total > 0 ? _nav.idx / total : 0);
|
||||||
|
|
||||||
|
// 第一行:当前指引「前方 120 米 右前方转弯」
|
||||||
|
const actEl = document.getElementById("nav-banner-action");
|
||||||
|
if (actEl) {
|
||||||
|
const guide = _navGuidance(travelled);
|
||||||
|
if (guide.text) actEl.textContent = guide.text;
|
||||||
|
_setTurnIcon(guide.kind);
|
||||||
|
}
|
||||||
|
// 第二行:剩余距离与时间
|
||||||
|
const bannerText = document.getElementById("nav-banner-text");
|
||||||
|
if (bannerText) {
|
||||||
|
bannerText.textContent = leftM < 1000
|
||||||
|
? "剩余 " + leftM + " 米 · 约 " + Math.max(1, Math.round(leftS / 60)) + " 分钟"
|
||||||
|
: "剩余 " + (leftM / 1000).toFixed(1) + " 公里 · 约 " +
|
||||||
|
Math.max(1, Math.round(leftS / 60)) + " 分钟";
|
||||||
|
}
|
||||||
|
// 到达判定用「到终点的真实距离」,避免 GPS 抖动跳点就结束导航
|
||||||
|
const dest = _nav.ptsBD[_nav.ptsBD.length - 1];
|
||||||
|
const toDest = _haversineM(me.lat, me.lng, dest.lat, dest.lng);
|
||||||
|
if (toDest < 25) {
|
||||||
|
showToast("已到达车辆附近");
|
||||||
|
stopNavigation();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 当前该播报哪一段:按「已走里程」在分段累计距离里定位
|
||||||
|
// 返回 { text: 文案, kind: straight|left|right|uturn },kind 用来画导航条左边的图标
|
||||||
|
function _navGuidance(travelled) {
|
||||||
|
if (!_nav || !_nav.stepEnds || !_nav.stepEnds.length) {
|
||||||
|
return { text: "", kind: "straight" };
|
||||||
|
}
|
||||||
|
const ends = _nav.stepEnds;
|
||||||
|
const steps = _nav.steps || [];
|
||||||
|
let i = ends.findIndex(e => e > travelled);
|
||||||
|
const isLast = (i === -1) || (i >= ends.length - 1);
|
||||||
|
if (i === -1) i = ends.length - 1;
|
||||||
|
const left = Math.max(0, Math.round(ends[i] - travelled));
|
||||||
|
if (isLast) {
|
||||||
|
return {
|
||||||
|
text: left > 5 ? "前方 " + left + " 米 到达目的地" : "即将到达目的地",
|
||||||
|
kind: "straight"
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const step = steps[i] || {};
|
||||||
|
// 优先用转向名(右前方转弯/左转…),没有就用指引文本的最后一小段
|
||||||
|
let action = step.turn || "";
|
||||||
|
if (!action && step.text) {
|
||||||
|
const parts = step.text.split(/[,,]/);
|
||||||
|
action = parts[parts.length - 1] || step.text;
|
||||||
|
}
|
||||||
|
if (!action) action = "继续前行";
|
||||||
|
return { text: "前方 " + left + " 米 " + action, kind: _turnKind(step.turn) };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function _recomputeRoute(gcj) { // gcj = {lat, lng}(GCJ02)
|
||||||
|
if (!_nav || !_nav.destLat) return;
|
||||||
|
// 快照:重算期间用户可能点了「结束导航」或改导航到另一辆车,
|
||||||
|
// 回包若不再属于这次导航就必须丢弃,否则旧路线会盖掉新导航。
|
||||||
|
const myNav = _nav;
|
||||||
|
const epoch = _navEpoch;
|
||||||
|
try {
|
||||||
|
const data = await _requestNavRoute(gcj.lat, gcj.lng,
|
||||||
|
_nav.destLat, _nav.destLng);
|
||||||
|
if (!data) return;
|
||||||
|
if (_nav !== myNav || epoch !== _navEpoch || !_nav) return;
|
||||||
|
_applyRoute(data);
|
||||||
|
showToast("已重新规划路线");
|
||||||
|
} catch (e) {
|
||||||
|
console.warn("[导航] 重算失败", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function _requestNavRoute(originLat, originLng, destLat, destLng) {
|
||||||
|
const url = "/api/nav_route?mode=walking"
|
||||||
|
+ "&origin_lat=" + originLat + "&origin_lng=" + originLng
|
||||||
|
+ "&dest_lat=" + destLat + "&dest_lng=" + destLng;
|
||||||
|
const resp = await fetch(url, { headers: { "Authorization": "Bearer " + authToken } });
|
||||||
|
const json = await resp.json();
|
||||||
|
const d = json && json.data;
|
||||||
|
if (json.rtn_code !== 0 || !d || !d.points || !d.points.length) {
|
||||||
|
const msg = (json && json.message) || "没有拿到路线";
|
||||||
|
const err = new Error(msg);
|
||||||
|
// 后端已挡掉超远距离;这里再认一次文案,前端可静默处理
|
||||||
|
if (json && (json.error_kind === "too_far" || /太远|200Km/i.test(msg))) {
|
||||||
|
err.tooFar = true;
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
return d;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 用接口结果重建导航状态(首次与重算共用)
|
||||||
|
function _applyRoute(d) {
|
||||||
|
_nav.ptsGcj = d.points;
|
||||||
|
_nav.ptsBD = d.points.map(pt => {
|
||||||
|
const c = offsetCoord(pt[1], pt[0]);
|
||||||
|
return new BMapGL.Point(c.lng, c.lat);
|
||||||
|
});
|
||||||
|
_nav.distance = d.distance;
|
||||||
|
_nav.duration = d.duration;
|
||||||
|
_nav.idx = 0;
|
||||||
|
_nav.recomputing = false;
|
||||||
|
// 分段指引:把 steps 的累计距离算出来,tick 里按「已走里程」定位当前段
|
||||||
|
_nav.steps = (d.steps || []).map(s => ({
|
||||||
|
distance: s.distance || 0,
|
||||||
|
turn: s.turn_type || "",
|
||||||
|
text: String(s.instruction || "").replace(/<[^>]+>/g, "")
|
||||||
|
}));
|
||||||
|
let acc = 0;
|
||||||
|
_nav.stepEnds = _nav.steps.map(s => (acc += s.distance));
|
||||||
|
_redrawRoute(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopNavigation() {
|
||||||
|
_navEpoch++; // 让还在 await 的 startNavigation 作废
|
||||||
|
if (_nav && _nav.watchId !== null && navigator.geolocation) {
|
||||||
|
navigator.geolocation.clearWatch(_nav.watchId);
|
||||||
|
}
|
||||||
|
if (_nav && _nav.timer) clearTimeout(_nav.timer);
|
||||||
|
_clearNavLayers();
|
||||||
|
_clearNavArrow();
|
||||||
|
_nav = null;
|
||||||
|
_navBanner(false);
|
||||||
|
_navPill(false);
|
||||||
|
_navBtnText("导航");
|
||||||
|
try { if (map.resetHeading) map.resetHeading(); } catch (e) {}
|
||||||
|
_headingSupported = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleNavigation() {
|
||||||
|
const bike = selectedBike;
|
||||||
|
if (!bike) return;
|
||||||
|
if (_nav && String(_nav.destCode) === String(bike.code)) {
|
||||||
|
stopNavigation();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
startNavigation(bike);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 拖动地图后:显示「返回导航」,超时自动回正。
|
||||||
|
// 注意:移动端 dragend 经常不触发,所以计时器从 dragstart 就开始,
|
||||||
|
// 并且在 dragging/moving 里不断续期——手指一离开就重新倒计时。
|
||||||
|
let _navSelfMoveUntil = 0; // 我们自己调 setCenter/panBy 的时间窗,避免误判成用户拖动
|
||||||
|
function _markProgrammaticMove() { _navSelfMoveUntil = Date.now() + 250; }
|
||||||
|
|
||||||
|
function _scheduleResume() {
|
||||||
|
if (!_nav) return;
|
||||||
|
if (_nav.timer) clearTimeout(_nav.timer);
|
||||||
|
_nav.timer = setTimeout(() => {
|
||||||
|
if (_nav && _nav.follow === false) resumeNavigation();
|
||||||
|
}, NAV_FREE_TIMEOUT);
|
||||||
|
}
|
||||||
|
|
||||||
|
function _onMapDragStart() {
|
||||||
|
if (!_nav) return;
|
||||||
|
if (Date.now() < _navSelfMoveUntil) return; // 我们自己挪的,不算用户操作
|
||||||
|
_nav.follow = false;
|
||||||
|
_navPill(true);
|
||||||
|
_scheduleResume();
|
||||||
|
}
|
||||||
|
|
||||||
|
function _onMapDragging() {
|
||||||
|
if (!_nav || _nav.follow !== false) return;
|
||||||
|
_scheduleResume(); // 还在拖,续期
|
||||||
|
}
|
||||||
|
|
||||||
|
function _onMapDragEnd() {
|
||||||
|
if (!_nav || _nav.follow !== false) return;
|
||||||
|
_scheduleResume();
|
||||||
|
}
|
||||||
|
|
||||||
|
function resumeNavigation() {
|
||||||
|
if (!_nav) return;
|
||||||
|
_nav.follow = true;
|
||||||
|
_navPill(false);
|
||||||
|
if (_nav.timer) { clearTimeout(_nav.timer); _nav.timer = null; }
|
||||||
|
// 回到行进方向并重新居中(用路线切线,别用"我→下一点")
|
||||||
|
const i = Math.min(_nav.idx, _nav.ptsBD.length - 1);
|
||||||
|
const j = Math.min(i + 3, _nav.ptsBD.length - 1);
|
||||||
|
const heading = _bearing(_nav.ptsBD[i], _nav.ptsBD[j]);
|
||||||
|
const me = (typeof autoLocationMarker !== "undefined" && autoLocationMarker)
|
||||||
|
? autoLocationMarker.getPosition() : null;
|
||||||
|
const anchor = me || _nav.ptsBD[i];
|
||||||
|
_placeNavArrow(anchor);
|
||||||
|
_centerOnUser(anchor, heading);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function startNavigation(bike) {
|
||||||
|
if (_navLoading) return;
|
||||||
|
const me = (typeof autoLocationMarker !== "undefined" && autoLocationMarker)
|
||||||
|
? autoLocationMarker.getPosition() : null;
|
||||||
|
if (!me) { showToast("请先开启定位,才能规划路线"); return; }
|
||||||
|
if (!bike || !bike.latitude || !bike.longitude) {
|
||||||
|
showToast("这辆车没有坐标,无法导航"); return;
|
||||||
|
}
|
||||||
|
// 兜底:太远就不导航(卡片上「导航」按钮本身已隐藏,正常点不到这里)。
|
||||||
|
// 百度步行路线有 200km 上限,超了会返回 status=2 的英文报错,不要把它抛给用户。
|
||||||
|
try {
|
||||||
|
const dest = offsetCoord(bike.latitude, bike.longitude); // GCJ02 -> BD09
|
||||||
|
const straight = calcDistance(me.lat, me.lng, dest.lat, dest.lng);
|
||||||
|
if (Number.isFinite(straight) && straight >= MAX_WALK_DISTANCE_M) return;
|
||||||
|
} catch (e) { /* 距离算不出来就照常尝试 */ }
|
||||||
|
|
||||||
|
if (_nav) stopNavigation();
|
||||||
|
const epoch = ++_navEpoch;
|
||||||
|
_navLoading = true;
|
||||||
|
_navBanner(true);
|
||||||
|
const bannerText = document.getElementById("nav-banner-text");
|
||||||
|
if (bannerText) bannerText.textContent = "正在规划路线…";
|
||||||
|
|
||||||
|
try {
|
||||||
|
let gcj = null;
|
||||||
|
if (typeof coordtransform !== "undefined" && coordtransform.bd09togcj02) {
|
||||||
|
gcj = coordtransform.bd09togcj02(me.lng, me.lat);
|
||||||
|
}
|
||||||
|
if (!gcj) throw new Error("坐标转换不可用");
|
||||||
|
|
||||||
|
const d = await _requestNavRoute(gcj[1], gcj[0], bike.latitude, bike.longitude);
|
||||||
|
|
||||||
|
// 路线回来时卡片已经被关掉了:直接放弃,不要把导航又"It's on"起来
|
||||||
|
if (epoch !== _navEpoch) {
|
||||||
|
_navBanner(false);
|
||||||
|
_navBtnText("导航");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_nav = {
|
||||||
|
destCode: bike.code, destLat: bike.latitude, destLng: bike.longitude,
|
||||||
|
follow: true, timer: null, watchId: null,
|
||||||
|
walking: [], remaining: [], endMarker: null, idx: 0, recomputing: false
|
||||||
|
};
|
||||||
|
_applyRoute(d);
|
||||||
|
_navBtnText("结束");
|
||||||
|
|
||||||
|
// 首次定位:压到屏幕下方 + 朝行进方向
|
||||||
|
const start = _nav.ptsBD[0];
|
||||||
|
const next = _nav.ptsBD[Math.min(1, _nav.ptsBD.length - 1)];
|
||||||
|
_placeNavArrow(start);
|
||||||
|
_rotateNavArrow(_bearing(start, next));
|
||||||
|
_centerOnUser(start, _bearing(start, next));
|
||||||
|
// 罗盘权限要在用户手势里申请(导航按钮的点击就是手势)
|
||||||
|
_ensureCompassPermission();
|
||||||
|
const actEl0 = document.getElementById("nav-banner-action");
|
||||||
|
const g0 = _navGuidance(0);
|
||||||
|
if (actEl0) actEl0.textContent = g0.text || "沿路线前行";
|
||||||
|
_setTurnIcon(g0.kind);
|
||||||
|
if (bannerText) {
|
||||||
|
bannerText.textContent = d.distance < 1000
|
||||||
|
? "剩余 " + Math.round(d.distance) + " 米 · 约 " +
|
||||||
|
Math.max(1, Math.round(d.duration / 60)) + " 分钟"
|
||||||
|
: "剩余 " + (d.distance / 1000).toFixed(1) + " 公里 · 约 " +
|
||||||
|
Math.max(1, Math.round(d.duration / 60)) + " 分钟";
|
||||||
|
}
|
||||||
|
|
||||||
|
// 收起卡片:导航要占满屏幕(关卡片不会停止导航)
|
||||||
|
try { closeCard(); } catch (e) {}
|
||||||
|
|
||||||
|
// 持续跟随
|
||||||
|
if (navigator.geolocation) {
|
||||||
|
_nav.watchId = navigator.geolocation.watchPosition(
|
||||||
|
pos => _navTick(pos.coords),
|
||||||
|
err => console.warn("[导航] 定位失败", err.message),
|
||||||
|
{ enableHighAccuracy: true, maximumAge: 3000, timeout: 10000 });
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error("[导航] 失败", err);
|
||||||
|
_navBanner(false);
|
||||||
|
if (err && err.tooFar) {
|
||||||
|
// 距离太远:静默退出,不弹报错(卡片上的「导航」按钮本来也已隐藏)
|
||||||
|
_navBtnText("导航");
|
||||||
|
_nav = null;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
showToast("导航失败:" + (err && err.message ? err.message : "请稍后再试"));
|
||||||
|
if (_nav && !_nav.ptsBD) _nav = null;
|
||||||
|
} finally {
|
||||||
|
_navLoading = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 地图拖动事件(只注册一次)。map 由 map.js 在 /api/config 回来后才创建,
|
||||||
|
// 所以这里只负责「准备好就绑」;map.js 建好地图后会显式调一次 bindNavMapEvents()。
|
||||||
|
function bindNavMapEvents() {
|
||||||
|
// navigation.js 在 map.js 之前执行,此时 `let map` 还在 TDZ,
|
||||||
|
// 连 typeof 都会抛 ReferenceError,所以整段包在 try 里。
|
||||||
|
try {
|
||||||
|
if (typeof map === "undefined" || !map || !map.addEventListener) return false;
|
||||||
|
if (map.__navBound) return true;
|
||||||
|
map.__navBound = true;
|
||||||
|
map.addEventListener("dragstart", _onMapDragStart);
|
||||||
|
map.addEventListener("dragging", _onMapDragging);
|
||||||
|
map.addEventListener("dragend", _onMapDragEnd);
|
||||||
|
} catch (e) {
|
||||||
|
return false; // map 还没声明(或地图未就绪)
|
||||||
|
}
|
||||||
|
try { console.info("[导航] 已绑定地图拖动事件"); } catch (e) {}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
// 给 map.js 用(它创建完地图主动调一次)
|
||||||
|
window.bindNavMapEvents = bindNavMapEvents;
|
||||||
|
|
||||||
|
// 兜底:万一 map.js 忘了调,这里再轮询几次(最多约 10 秒)
|
||||||
|
(function _retryBindNavMapEvents(tries = 0) {
|
||||||
|
if (bindNavMapEvents()) return;
|
||||||
|
if (tries >= 20) {
|
||||||
|
console.warn("[导航] 地图拖动事件未能绑定(map 一直未就绪)");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setTimeout(() => _retryBindNavMapEvents(tries + 1), 500);
|
||||||
|
})();
|
||||||
@@ -0,0 +1,343 @@
|
|||||||
|
/* 共享电动车:申请/接受/权限/解绑/共享开锁还车/横幅与申请弹窗。
|
||||||
|
* 从 static/js/map.js 拆出。 */
|
||||||
|
|
||||||
|
|
||||||
|
// ================= 共享电动车 =================
|
||||||
|
function shareApi(url, method, body) {
|
||||||
|
const opts = { method: method || "GET", headers: {} };
|
||||||
|
if (authToken) opts.headers["Authorization"] = `Bearer ${authToken}`;
|
||||||
|
if (body !== undefined) {
|
||||||
|
opts.headers["Content-Type"] = "application/json";
|
||||||
|
opts.body = JSON.stringify(body);
|
||||||
|
}
|
||||||
|
return fetch(url, opts).then(r => r.json());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 私密备注(昵称) 工具 =====
|
||||||
|
// 显示对方时:优先用“我给他起的备注(昵称)”,其次显示名,最后退回邮箱
|
||||||
|
function partnerLabel(name, email, remark) {
|
||||||
|
return (remark && String(remark).trim()) || name || email || "";
|
||||||
|
}
|
||||||
|
// share_id -> {email,name,remark},备注编辑用(不把用户文本嵌进 HTML 属性/JS 字面量)
|
||||||
|
let shareRec = {};
|
||||||
|
|
||||||
|
// ---------- 管理弹窗 ----------
|
||||||
|
let shareTabNow = "usable";
|
||||||
|
function openShareModal() {
|
||||||
|
if (!authToken || !currentUser) { showToast("请先登录"); return; }
|
||||||
|
SettingsPages.open("share-modal");
|
||||||
|
switchShareTab(shareTabNow); // 内部已调 loadShareData()
|
||||||
|
}
|
||||||
|
function closeShareModal() {
|
||||||
|
SettingsPages.back();
|
||||||
|
}
|
||||||
|
function switchShareTab(tab) {
|
||||||
|
shareTabNow = tab;
|
||||||
|
document.getElementById("share-tab-usable").classList.toggle("active", tab === "usable");
|
||||||
|
document.getElementById("share-tab-mine").classList.toggle("active", tab === "mine");
|
||||||
|
document.getElementById("share-list-usable").style.display = tab === "usable" ? "flex" : "none";
|
||||||
|
document.getElementById("share-list-mine").style.display = tab === "mine" ? "flex" : "none";
|
||||||
|
loadShareData();
|
||||||
|
}
|
||||||
|
function sharePendingHtml(pending) {
|
||||||
|
if (!pending || !pending.length) { document.getElementById("share-pending-box").style.display = "none"; return; }
|
||||||
|
const rows = pending.map(p =>
|
||||||
|
`<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;
|
||||||
|
// 接口异常时 data.data 可能是对象/字符串,不是数组 → forEach 会抛错并每秒刷屏
|
||||||
|
shareActiveList = Array.isArray(data.data) ? 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>';
|
||||||
|
});
|
||||||
|
// 内容没变就不动 DOM:否则手指按在「还车」上时按钮被替换,
|
||||||
|
// touch-up 落空(点了没反应),入场动画也会每 20 秒重播一次。
|
||||||
|
if (cont.__lastHtml !== html) {
|
||||||
|
cont.innerHTML = html;
|
||||||
|
cont.__lastHtml = 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() {
|
||||||
|
if (!Array.isArray(shareActiveList)) return; // 接口异常时不刷屏
|
||||||
|
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 = "确认还车"; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
/* 地理计算模块(Phase 0 第一个拆出的文件)
|
||||||
|
*
|
||||||
|
* 形态:**经典脚本 + IIFE**,不是 ESM。
|
||||||
|
* 原因:map.js 还有 136 处内联 onclick 依赖全局函数,直接上 `type="module"`
|
||||||
|
* 会在一天内把所有按钮打断。这一步只做「把纯函数搬出 5000 行大文件」,
|
||||||
|
* 调用点一行都不用改(下面把同名函数重新挂回全局),风险最低。
|
||||||
|
*
|
||||||
|
* 下一阶段(Phase 0.5)再把这里改成 `export`,由 map.js 显式 import,
|
||||||
|
* 同时把全局桥收进 compat/globals.js。
|
||||||
|
*/
|
||||||
|
(function (global) {
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
// 手动偏移常量:coordtransform 不可用时的降级路径
|
||||||
|
const COORD_OFFSET = {
|
||||||
|
lat: 0.00603, // 约 610 米(纬度)
|
||||||
|
lng: 0.00650, // 约 600 米 - 20 米(经度,往西 20 米)
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GCJ02 -> BD09。
|
||||||
|
* 优先用 coordtransform(与百度官方算法一致),失败则退回常量偏移,
|
||||||
|
* 避免整张图的点位整体偏移几百米。
|
||||||
|
*/
|
||||||
|
function offsetCoord(lat, lng) {
|
||||||
|
lat = parseFloat(lat);
|
||||||
|
lng = parseFloat(lng);
|
||||||
|
if (typeof coordtransform !== "undefined" && coordtransform.gcj02tobd09) {
|
||||||
|
try {
|
||||||
|
const bd = coordtransform.gcj02tobd09(lng, lat); // [lng, lat]
|
||||||
|
return { lat: bd[1], lng: bd[0] };
|
||||||
|
} catch (e) {
|
||||||
|
console.warn("[坐标转换] gcj02tobd09 失败,回退手动偏移:", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
lat: lat + COORD_OFFSET.lat,
|
||||||
|
lng: lng + COORD_OFFSET.lng,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 两点球面距离(米),Haversine。 */
|
||||||
|
function calcDistance(lat1, lng1, lat2, lng2) {
|
||||||
|
const R = 6371000; // 地球半径(米)
|
||||||
|
const dLat = (lat2 - lat1) * Math.PI / 180;
|
||||||
|
const dLng = (lng2 - lng1) * Math.PI / 180;
|
||||||
|
const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
|
||||||
|
Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
|
||||||
|
Math.sin(dLng / 2) * Math.sin(dLng / 2);
|
||||||
|
return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
|
||||||
|
}
|
||||||
|
|
||||||
|
const Geo = { COORD_OFFSET, offsetCoord, calcDistance };
|
||||||
|
|
||||||
|
global.Geo = Geo;
|
||||||
|
// 兼容层:存量代码(含 136 处内联事件)继续用这两个全局函数名
|
||||||
|
global.offsetCoord = offsetCoord;
|
||||||
|
global.calcDistance = calcDistance;
|
||||||
|
if (!global.COORD_OFFSET) global.COORD_OFFSET = COORD_OFFSET;
|
||||||
|
})(window);
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
/* 车辆订阅:停车点提醒与定时用车(规则的增删改查)。
|
||||||
|
* 从 static/js/map.js 拆出。 */
|
||||||
|
|
||||||
|
|
||||||
|
// ========== 订阅提醒(我的 → 车辆订阅) ==========
|
||||||
|
let subscribeLocations = [];
|
||||||
|
const SUB_WEEKDAYS = { 0: "每天", 1: "周一", 2: "周二", 3: "周三", 4: "周四", 5: "周五", 6: "周六", 7: "周日" };
|
||||||
|
async function openSubscribeModal() {
|
||||||
|
closeAllModals();
|
||||||
|
SettingsPages.open("subscribe-modal");
|
||||||
|
await loadSubscribeLocations();
|
||||||
|
loadSubscribeRules();
|
||||||
|
}
|
||||||
|
function closeSubscribeModal() {
|
||||||
|
SettingsPages.back();
|
||||||
|
}
|
||||||
|
async function loadSubscribeLocations() {
|
||||||
|
const sel = document.getElementById("sub-location");
|
||||||
|
sel.innerHTML = '<option value="">加载中...</option>';
|
||||||
|
try {
|
||||||
|
const resp = await fetch("/api/campus/locations");
|
||||||
|
const data = await resp.json();
|
||||||
|
// 订阅只针对「停车点」(楼/兴趣点只用于起终点归属)
|
||||||
|
subscribeLocations = ((data.rtn_code === 0 ? data.data : []) || [])
|
||||||
|
.filter(l => l.kind === "parking");
|
||||||
|
} catch (err) {
|
||||||
|
subscribeLocations = [];
|
||||||
|
}
|
||||||
|
sel.innerHTML = subscribeLocations.length
|
||||||
|
? subscribeLocations.map(l => `<option value="${l.id}">${escHtml(l.name)}</option>`).join("")
|
||||||
|
: '<option value="">(管理员尚未配置停车点)</option>';
|
||||||
|
}
|
||||||
|
function subRuleRowHtml(r) {
|
||||||
|
const loc = subscribeLocations.find(l => l.id === r.location_id);
|
||||||
|
const locName = loc ? loc.name : (r.location_name || "停车点已删除");
|
||||||
|
const hh = String(Math.floor(r.minute_of_day / 60)).padStart(2, "0");
|
||||||
|
const mm = String(r.minute_of_day % 60).padStart(2, "0");
|
||||||
|
const kindText = (r.kind_labels && r.kind_labels.length)
|
||||||
|
? r.kind_labels.join("/") : "全部车型";
|
||||||
|
const eMin = r.min_electric != null ? r.min_electric : 0;
|
||||||
|
const eMax = r.max_electric != null ? r.max_electric : 100;
|
||||||
|
const sortLabel = r.sort_by_label || r.sort_by || "";
|
||||||
|
const tags = [];
|
||||||
|
if (r.auto_unlock) {
|
||||||
|
tags.push(`自动开锁 · ${kindText} · 电量${eMin}-${eMax}% · ${sortLabel} · 重试${r.retry_times || 3}次`);
|
||||||
|
}
|
||||||
|
return `
|
||||||
|
<div class="device-item" style="display:block;padding:9px 12px;border-bottom:1px solid var(--bg-tertiary,#ececf1);">
|
||||||
|
<div style="display:flex;justify-content:space-between;align-items:flex-start;gap:8px;">
|
||||||
|
<div style="font-size:13px;line-height:1.6;min-width:0;">
|
||||||
|
<b>${escHtml(locName)}</b>
|
||||||
|
<span style="color:var(--text-secondary);"> · ${SUB_WEEKDAYS[r.weekday] || "每周"} ${hh}:${mm}</span>
|
||||||
|
<div style="font-size:11.5px;color:var(--text-secondary);">${r.enabled ? "已启用" : "已停用"}${r.notify_enabled ? " · 邮件提醒" : ""}</div>
|
||||||
|
${tags.length ? `<div style="font-size:11.5px;color:#005bbf;">${escHtml(tags[0])}</div>` : ""}
|
||||||
|
</div>
|
||||||
|
<div style="display:flex;gap:6px;flex:0 0 auto;">
|
||||||
|
<button class="btn" style="padding:4px 9px;border:none;border-radius:8px;font-size:12px;background:#ececf1;" onclick="toggleSubscribeRule(${r.id}, ${r.enabled ? 0 : 1})">${r.enabled ? "停用" : "启用"}</button>
|
||||||
|
<button class="btn" style="padding:4px 9px;border:none;border-radius:8px;font-size:12px;background:#fce4ec;color:#c62828;" onclick="deleteSubscribeRule(${r.id})">删除</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>`;
|
||||||
|
}
|
||||||
|
// 订阅表单「更多筛选」折叠开关(高级调优项默认收起)
|
||||||
|
function toggleSubAdvanced() {
|
||||||
|
const box = document.getElementById("sub-advanced");
|
||||||
|
if (!box) return;
|
||||||
|
const show = box.style.display === "none";
|
||||||
|
box.style.display = show ? "block" : "none";
|
||||||
|
}
|
||||||
|
async function loadSubscribeRules() {
|
||||||
|
const box = document.getElementById("subscribe-list");
|
||||||
|
box.innerHTML = '<div class="device-loading">加载中...</div>';
|
||||||
|
try {
|
||||||
|
const resp = await fetch("/api/subscribe/rules", {
|
||||||
|
headers: { "Authorization": `Bearer ${authToken}` }
|
||||||
|
});
|
||||||
|
const data = await resp.json();
|
||||||
|
if (data.rtn_code !== 0) {
|
||||||
|
box.innerHTML = `<div class="device-loading">${escHtml(data.message || "加载失败")}</div>`;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const rules = data.data || [];
|
||||||
|
box.innerHTML = rules.length
|
||||||
|
? rules.map(subRuleRowHtml).join("")
|
||||||
|
: '<div class="device-loading">暂无规则,在下方添加</div>';
|
||||||
|
} catch (err) {
|
||||||
|
box.innerHTML = '<div class="device-loading">网络错误,请重试</div>';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async function addSubscribeRule() {
|
||||||
|
const locationId = Number(document.getElementById("sub-location").value || 0);
|
||||||
|
const weekday = Number(document.getElementById("sub-weekday").value);
|
||||||
|
const time = document.getElementById("sub-time").value;
|
||||||
|
const notify = document.getElementById("sub-notify").checked;
|
||||||
|
const auto = document.getElementById("sub-auto").checked;
|
||||||
|
const kinds = [...document.querySelectorAll(".sub-kind:checked")].map(el => el.value);
|
||||||
|
const minE = Number(document.getElementById("sub-min-e").value || 0);
|
||||||
|
const maxE = Number(document.getElementById("sub-max-e").value || 100);
|
||||||
|
const sortBy = document.getElementById("sub-sort").value;
|
||||||
|
const retry = Number(document.getElementById("sub-retry").value || 3);
|
||||||
|
|
||||||
|
if (!locationId) { showToast("请先选择停车点(需要管理员先配置停车点)"); return; }
|
||||||
|
if (!/^\d{2}:\d{2}$/.test(time)) { showToast("请选择时间"); return; }
|
||||||
|
if (!kinds.length) { showToast("至少选择一个车型"); return; }
|
||||||
|
if (!(minE >= 0 && maxE <= 100 && minE <= maxE)) { showToast("电量区间需在 0-100 且下限≤上限"); return; }
|
||||||
|
if (auto) {
|
||||||
|
const ok = await appConfirm(
|
||||||
|
"开启自动开锁后,命中规则时系统会用你的账号直接开锁车辆。\n\n" +
|
||||||
|
`筛选:${kinds.map(k => ({small:"小车",big:"大车",red:"红车"}[k])).join("/")},` +
|
||||||
|
`电量 ${minE}%-${maxE}%,${document.getElementById("sub-sort").selectedOptions[0].textContent};` +
|
||||||
|
`被他人抢先时最多重试 ${retry} 次。`,
|
||||||
|
{ title: "开启自动开锁", okText: "确认添加" });
|
||||||
|
if (!ok) return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const resp = await fetch("/api/subscribe/rules", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Authorization": `Bearer ${authToken}`, "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({
|
||||||
|
location_id: locationId, weekday, time,
|
||||||
|
notify_enabled: notify, auto_unlock: auto,
|
||||||
|
kinds, min_electric: minE, max_electric: maxE,
|
||||||
|
sort_by: sortBy, retry_times: retry
|
||||||
|
})
|
||||||
|
});
|
||||||
|
const data = await resp.json();
|
||||||
|
showToast(data.message || (data.rtn_code === 0 ? "已添加" : "添加失败"));
|
||||||
|
if (data.rtn_code === 0) loadSubscribeRules();
|
||||||
|
} catch (err) {
|
||||||
|
showToast("网络错误,请重试");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async function toggleSubscribeRule(ruleId, enable) {
|
||||||
|
try {
|
||||||
|
const resp = await fetch(`/api/subscribe/rules/${ruleId}`, {
|
||||||
|
method: "PUT",
|
||||||
|
headers: { "Authorization": `Bearer ${authToken}`, "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ enabled: !!enable })
|
||||||
|
});
|
||||||
|
const data = await resp.json();
|
||||||
|
if (data.rtn_code === 0) loadSubscribeRules();
|
||||||
|
else showToast(data.message || "操作失败");
|
||||||
|
} catch (err) { showToast("网络错误"); }
|
||||||
|
}
|
||||||
|
async function deleteSubscribeRule(ruleId) {
|
||||||
|
try {
|
||||||
|
const resp = await fetch(`/api/subscribe/rules/${ruleId}`, {
|
||||||
|
method: "DELETE",
|
||||||
|
headers: { "Authorization": `Bearer ${authToken}` }
|
||||||
|
});
|
||||||
|
const data = await resp.json();
|
||||||
|
if (data.rtn_code === 0) loadSubscribeRules();
|
||||||
|
else showToast(data.message || "删除失败");
|
||||||
|
} catch (err) { showToast("网络错误"); }
|
||||||
|
}
|
||||||
+169
-24
@@ -23,6 +23,7 @@ from db import get_db
|
|||||||
from email_utils import send_email
|
from email_utils import send_email
|
||||||
|
|
||||||
CHECK_INTERVAL = 30 # 调度精度:30 秒扫一次规则
|
CHECK_INTERVAL = 30 # 调度精度:30 秒扫一次规则
|
||||||
|
CATCHUP_WINDOW_MIN = 5 # 补发窗口:超过这么久就不再补(避免晚上补发早上的提醒)
|
||||||
SCAN_FRESH_MINUTES = 20 # 采集点新鲜度
|
SCAN_FRESH_MINUTES = 20 # 采集点新鲜度
|
||||||
MAX_RULES_PER_USER = 5
|
MAX_RULES_PER_USER = 5
|
||||||
|
|
||||||
@@ -184,7 +185,65 @@ def latest_bike_points():
|
|||||||
return [dict(r) for r in rows]
|
return [dict(r) for r in rows]
|
||||||
|
|
||||||
|
|
||||||
def stat_location(loc):
|
def refresh_bike_points(user_id=None):
|
||||||
|
"""判定前拉一次最新地图(**只用 type=3 电动车**,别把单车混进候选)。
|
||||||
|
|
||||||
|
取数顺序:共享快照(60 秒,省上游) → 失败才用用户凭据直连一次。
|
||||||
|
`type=1` 是共享单车,它的车牌号段也会被判成「小车」,混进来会导致
|
||||||
|
「自动开锁开了一辆单车」和「附近有 12 辆其实 8 辆是单车」。
|
||||||
|
|
||||||
|
字段名用 `electric_quantity`(上游真实字段);写成 `electric` 会永远是
|
||||||
|
None,电量筛选就全部落空(≥50% 的规则会报「附近暂无符合条件的车辆」)。
|
||||||
|
"""
|
||||||
|
from wechat import request_with_user_auth, request_api
|
||||||
|
|
||||||
|
def _fetch(use_snapshot_only=False):
|
||||||
|
try:
|
||||||
|
res = request_api("GET", "/project/map", params={"type": "3"})
|
||||||
|
if isinstance(res, dict) and res.get("rtn_code") == 0:
|
||||||
|
return res
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[订阅提醒] 快照读地图失败: {exc}")
|
||||||
|
if use_snapshot_only or not user_id:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
res = request_with_user_auth(user_id, "GET", "/project/map",
|
||||||
|
params={"type": "3"}, _silent=True)
|
||||||
|
return res if isinstance(res, dict) and res.get("rtn_code") == 0 else None
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[订阅提醒] 用户凭据刷新地图失败: {exc}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
res = _fetch()
|
||||||
|
if res is None:
|
||||||
|
time.sleep(0.6) # 上游 503/抖动:等半秒再试一次
|
||||||
|
res = _fetch()
|
||||||
|
if res is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
rows = []
|
||||||
|
for st in ((res.get("data") or {}).get("bicycleStation") or []):
|
||||||
|
lat, lng = st.get("latitude"), st.get("longitude")
|
||||||
|
if lat is None or lng is None:
|
||||||
|
continue
|
||||||
|
electric = st.get("electric_quantity")
|
||||||
|
if electric is None:
|
||||||
|
electric = st.get("electricQuantity")
|
||||||
|
if electric is None:
|
||||||
|
electric = st.get("electric")
|
||||||
|
rows.append({
|
||||||
|
"bike_code": str(st.get("code") or ""),
|
||||||
|
"latitude": lat,
|
||||||
|
"longitude": lng,
|
||||||
|
"state": st.get("state"),
|
||||||
|
"status": st.get("status"),
|
||||||
|
"electric": electric,
|
||||||
|
"bike_type": "3",
|
||||||
|
})
|
||||||
|
return rows or None
|
||||||
|
|
||||||
|
|
||||||
|
def stat_location(loc, user_id=None, fresh=True):
|
||||||
"""统计某个停车点附近的车辆。返回 None 表示该地点没有可用判定(缺坐标)。"""
|
"""统计某个停车点附近的车辆。返回 None 表示该地点没有可用判定(缺坐标)。"""
|
||||||
if loc is None:
|
if loc is None:
|
||||||
return None
|
return None
|
||||||
@@ -193,7 +252,11 @@ def stat_location(loc):
|
|||||||
return None
|
return None
|
||||||
except Exception:
|
except Exception:
|
||||||
return None
|
return None
|
||||||
points = latest_bike_points()
|
points = None
|
||||||
|
if fresh:
|
||||||
|
points = refresh_bike_points(user_id)
|
||||||
|
if not points:
|
||||||
|
points = latest_bike_points()
|
||||||
return bikes_near_parking(points, loc)
|
return bikes_near_parking(points, loc)
|
||||||
|
|
||||||
|
|
||||||
@@ -231,6 +294,31 @@ def _live_coord(user_id: int, code: str, btype=None):
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _discard_pending_order(user_id: int, order_id, code: str,
|
||||||
|
lat=None, lng=None) -> bool:
|
||||||
|
"""下单成功但开锁失败:把这张半成品订单关掉。
|
||||||
|
|
||||||
|
不清理的话,下一次重试会再叠一张新订单 —— 上游会同时挂着几张
|
||||||
|
没人骑的订单,用户还可能被算未支付。
|
||||||
|
"""
|
||||||
|
from wechat import request_with_user_auth
|
||||||
|
data = {"order_id": order_id}
|
||||||
|
if lat is not None and lng is not None:
|
||||||
|
data.update({"latitude": lat, "longitude": lng, "code": code})
|
||||||
|
for path in ("/record/return", "/record/orderClose"):
|
||||||
|
try:
|
||||||
|
res = request_with_user_auth(user_id, "POST", path, data=data, _silent=True)
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[订阅开锁] 清理半成品订单 {order_id} 调 {path} 异常: {exc}")
|
||||||
|
continue
|
||||||
|
if isinstance(res, dict) and res.get("rtn_code") == 0:
|
||||||
|
print(f"[订阅开锁] 半成品订单 {order_id} 已通过 {path} 关闭")
|
||||||
|
return True
|
||||||
|
msg = (res or {}).get("message") if isinstance(res, dict) else None
|
||||||
|
print(f"[订阅开锁] 清理半成品订单 {order_id} 失败({path}): {msg}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
def _try_auto_unlock(user_id: int, bike_code: str) -> dict:
|
def _try_auto_unlock(user_id: int, bike_code: str) -> dict:
|
||||||
"""真实自动开锁:扫码 → 创建订单 → 开锁(全部使用订阅人自己的凭据)。
|
"""真实自动开锁:扫码 → 创建订单 → 开锁(全部使用订阅人自己的凭据)。
|
||||||
|
|
||||||
@@ -300,8 +388,15 @@ def _try_auto_unlock(user_id: int, bike_code: str) -> dict:
|
|||||||
opened = request_with_user_auth(user_id, "POST", "/record/qrOrder",
|
opened = request_with_user_auth(user_id, "POST", "/record/qrOrder",
|
||||||
data={"order_id": order_id}, _silent=True)
|
data={"order_id": order_id}, _silent=True)
|
||||||
if opened.get("rtn_code") != 0:
|
if opened.get("rtn_code") != 0:
|
||||||
|
# 半成品订单必须撤销,否则下一次重试会再叠一张
|
||||||
|
cleaned = _discard_pending_order(user_id, order_id, code, lat, lng)
|
||||||
|
msg = opened.get("message") or "开锁指令失败"
|
||||||
|
if cleaned:
|
||||||
|
msg += "(已撤销本次下单)"
|
||||||
|
else:
|
||||||
|
msg += "(本次下单可能残留在上游,请稍后在订单页检查)"
|
||||||
return {"success": False, "occupied": False, "order_id": str(order_id),
|
return {"success": False, "occupied": False, "order_id": str(order_id),
|
||||||
"message": opened.get("message") or "开锁指令失败"}
|
"message": msg}
|
||||||
|
|
||||||
# 4) 本地落单 + 计时器 + 起点位置(与手动开锁一致,source='subscribe')
|
# 4) 本地落单 + 计时器 + 起点位置(与手动开锁一致,source='subscribe')
|
||||||
try:
|
try:
|
||||||
@@ -318,29 +413,33 @@ def _try_auto_unlock(user_id: int, bike_code: str) -> dict:
|
|||||||
if row:
|
if row:
|
||||||
email = row["email"] or ""
|
email = row["email"] or ""
|
||||||
try:
|
try:
|
||||||
conn.execute("""
|
cur = conn.execute("""
|
||||||
INSERT INTO rentals (id, order_id, bike_code, email, user_id, start_time,
|
INSERT INTO rentals (id, order_id, bike_code, email, user_id, start_time,
|
||||||
end_time, duration, expired, source, renewal_round)
|
end_time, duration, expired, source, renewal_round)
|
||||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, 'subscribe', 1)
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, 'subscribe', 1)
|
||||||
""", (int(order_id), str(order_id), code, email, user_id,
|
""", (int(order_id), str(order_id), code, email, user_id,
|
||||||
now.strftime("%Y-%m-%d %H:%M:%S"), end.strftime("%Y-%m-%d %H:%M:%S"),
|
now.strftime("%Y-%m-%d %H:%M:%S"), end.strftime("%Y-%m-%d %H:%M:%S"),
|
||||||
duration))
|
duration))
|
||||||
|
rental_id = cur.lastrowid or int(order_id)
|
||||||
except sqlite3.IntegrityError:
|
except sqlite3.IntegrityError:
|
||||||
# id 与历史行冲突(极少见):改用自增 id,order_id 仍记录真实订单号
|
# id 与历史行冲突(极少见):改用自增 id,order_id 仍记录真实订单号。
|
||||||
conn.execute("""
|
# 一定要用 lastrowid 当 rental_id —— 之前继续用 int(order_id),
|
||||||
|
# 计时器/起点回填会作用到撞冲突的那条旧单上,新车完全没有计时器。
|
||||||
|
cur = conn.execute("""
|
||||||
INSERT INTO rentals (order_id, bike_code, email, user_id, start_time,
|
INSERT INTO rentals (order_id, bike_code, email, user_id, start_time,
|
||||||
end_time, duration, expired, source, renewal_round)
|
end_time, duration, expired, source, renewal_round)
|
||||||
VALUES (?, ?, ?, ?, ?, ?, ?, 0, 'subscribe', 1)
|
VALUES (?, ?, ?, ?, ?, ?, ?, 0, 'subscribe', 1)
|
||||||
""", (str(order_id), code, email, user_id,
|
""", (str(order_id), code, email, user_id,
|
||||||
now.strftime("%Y-%m-%d %H:%M:%S"), end.strftime("%Y-%m-%d %H:%M:%S"),
|
now.strftime("%Y-%m-%d %H:%M:%S"), end.strftime("%Y-%m-%d %H:%M:%S"),
|
||||||
duration))
|
duration))
|
||||||
|
rental_id = cur.lastrowid
|
||||||
conn.commit()
|
conn.commit()
|
||||||
conn.close()
|
conn.close()
|
||||||
start_rental_timer(rental_id=int(order_id), email=email, bike_code=code,
|
start_rental_timer(rental_id=int(rental_id), email=email, bike_code=code,
|
||||||
duration_minutes=duration, user_id=user_id)
|
duration_minutes=duration, user_id=user_id)
|
||||||
try:
|
try:
|
||||||
from routes.rental import _record_rental_start
|
from routes.rental import _record_rental_start
|
||||||
_record_rental_start(int(order_id), lat, lng)
|
_record_rental_start(int(rental_id), lat, lng)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
print(f"[订阅开锁] 回填起点失败: {exc}")
|
print(f"[订阅开锁] 回填起点失败: {exc}")
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
@@ -426,7 +525,8 @@ def fire_rule(rule: dict):
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
flt = rule_filters(rule)
|
flt = rule_filters(rule)
|
||||||
points = latest_bike_points()
|
# 先刷新地图再看有几辆:订阅最怕“看到的是别人已经骑走的数据”
|
||||||
|
points = refresh_bike_points(rule.get("user_id")) or latest_bike_points()
|
||||||
stat = bikes_near_parking(points, loc)
|
stat = bikes_near_parking(points, loc)
|
||||||
# 候选:只含「符合车型/电量筛选」的空闲可用车,已按排序规则排好
|
# 候选:只含「符合车型/电量筛选」的空闲可用车,已按排序规则排好
|
||||||
candidates = parking_candidates(
|
candidates = parking_candidates(
|
||||||
@@ -503,12 +603,31 @@ def fire_rule(rule: dict):
|
|||||||
# ========== 调度 ==========
|
# ========== 调度 ==========
|
||||||
|
|
||||||
def _scheduler_loop():
|
def _scheduler_loop():
|
||||||
|
"""固定节拍扫描:按单调时钟对齐,不用「干完活再睡 30 秒」,
|
||||||
|
否则发信/自动开锁一慢,节拍就整体漂移。"""
|
||||||
|
next_at = time.monotonic()
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
_tick()
|
_tick()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"[订阅提醒] 调度异常: {e}")
|
print(f"[订阅提醒] 调度异常: {e}")
|
||||||
time.sleep(CHECK_INTERVAL)
|
next_at += CHECK_INTERVAL
|
||||||
|
delay = next_at - time.monotonic()
|
||||||
|
if delay <= 0:
|
||||||
|
# 落后太多(比如机器卡了一下)就重新对齐,不追帧
|
||||||
|
next_at = time.monotonic() + CHECK_INTERVAL
|
||||||
|
continue
|
||||||
|
time.sleep(delay)
|
||||||
|
|
||||||
|
|
||||||
|
def _fire_rule_async(rule: dict):
|
||||||
|
"""单条规则在独立线程里执行,避免串行 fire 把整轮节拍拖过一分钟。"""
|
||||||
|
try:
|
||||||
|
ok = fire_rule(rule)
|
||||||
|
except Exception as e:
|
||||||
|
ok = False
|
||||||
|
print(f"[订阅提醒] 规则 {rule['id']} 发送失败: {e}")
|
||||||
|
print(f"[订阅提醒] 规则 {rule['id']} 已触发 (user={rule.get('user_id')}, 发送={ok})")
|
||||||
|
|
||||||
|
|
||||||
def _tick():
|
def _tick():
|
||||||
@@ -519,30 +638,56 @@ def _tick():
|
|||||||
minute_of_day = now.hour * 60 + now.minute
|
minute_of_day = now.hour * 60 + now.minute
|
||||||
|
|
||||||
conn = get_db()
|
conn = get_db()
|
||||||
|
|
||||||
|
# 补发要有下界:7:50 的规则、服务 22:00 才启动,不该在晚上补发早上的提醒。
|
||||||
|
# 超过 CATCHUP_WINDOW_MIN 的直接记成「今天已处理」,不发信。
|
||||||
|
window_start = max(0, minute_of_day - CATCHUP_WINDOW_MIN)
|
||||||
|
stale = conn.execute("""
|
||||||
|
SELECT id FROM subscribe_rules
|
||||||
|
WHERE enabled = 1 AND weekday IN (0, ?) AND minute_of_day < ?
|
||||||
|
AND last_fired_on != ?
|
||||||
|
""", (weekday, window_start, today)).fetchall()
|
||||||
|
if stale:
|
||||||
|
for r in stale:
|
||||||
|
conn.execute("UPDATE subscribe_rules SET last_fired_on = ? WHERE id = ?",
|
||||||
|
(today, r["id"]))
|
||||||
|
conn.commit()
|
||||||
|
print(f"[订阅提醒] {len(stale)} 条规则已过补发窗口(>{CATCHUP_WINDOW_MIN} 分钟),"
|
||||||
|
f"今天不再补发")
|
||||||
|
|
||||||
|
# `<=` 而不是 `=`:只要今天还没发过,到点或过点(窗口内)都补一次。
|
||||||
|
# 用 `=` 的时候,一轮跑超过一分钟就会漏掉那一分钟,当天不再补。
|
||||||
rules = conn.execute("""
|
rules = conn.execute("""
|
||||||
SELECT * FROM subscribe_rules
|
SELECT * FROM subscribe_rules
|
||||||
WHERE enabled = 1 AND weekday IN (0, ?) AND minute_of_day = ?
|
WHERE enabled = 1 AND weekday IN (0, ?)
|
||||||
|
AND minute_of_day <= ? AND minute_of_day >= ?
|
||||||
AND last_fired_on != ?
|
AND last_fired_on != ?
|
||||||
""", (weekday, minute_of_day, today)).fetchall()
|
""", (weekday, minute_of_day, window_start, today)).fetchall()
|
||||||
if not rules:
|
if not rules:
|
||||||
conn.close()
|
conn.close()
|
||||||
return
|
return
|
||||||
# 先占位再发送,避免重试窗口内重复触发
|
|
||||||
for r in rules:
|
|
||||||
conn.execute("UPDATE subscribe_rules SET last_fired_on = ? WHERE id = ?", (today, r["id"]))
|
|
||||||
conn.commit()
|
|
||||||
conn.close()
|
|
||||||
|
|
||||||
for r in rules:
|
# 抢占式置位(CAS):多进程/多实例下两个 worker 会同时选到同一批规则,
|
||||||
|
# 只让 UPDATE 真正命中(rowcount==1)的那个进程去发信/开锁,
|
||||||
|
# 否则同一分钟会发两封邮件、勾了自动开锁的还会重复调 /record/order。
|
||||||
|
claimed = []
|
||||||
|
try:
|
||||||
|
for r in rules:
|
||||||
|
cur = conn.execute(
|
||||||
|
"UPDATE subscribe_rules SET last_fired_on = ? "
|
||||||
|
"WHERE id = ? AND last_fired_on != ?",
|
||||||
|
(today, r["id"], today))
|
||||||
|
if cur.rowcount == 1:
|
||||||
|
claimed.append(r)
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
for r in claimed:
|
||||||
rule = dict(r)
|
rule = dict(r)
|
||||||
if not rule.get("notify_enabled") and not rule.get("auto_unlock"):
|
if not rule.get("notify_enabled") and not rule.get("auto_unlock"):
|
||||||
continue
|
continue
|
||||||
try:
|
threading.Thread(target=_fire_rule_async, args=(rule,), daemon=True).start()
|
||||||
ok = fire_rule(rule)
|
|
||||||
except Exception as e:
|
|
||||||
ok = False
|
|
||||||
print(f"[订阅提醒] 规则 {rule['id']} 发送失败: {e}")
|
|
||||||
print(f"[订阅提醒] 规则 {rule['id']} 已触发 (user={rule['user_id']}, 发送={ok})")
|
|
||||||
|
|
||||||
|
|
||||||
def start_subscribe_scheduler():
|
def start_subscribe_scheduler():
|
||||||
|
|||||||
+173
-6
@@ -86,6 +86,7 @@ tr:hover{background:#3a3a3c}
|
|||||||
<h1>🔧 管理后台</h1>
|
<h1>🔧 管理后台</h1>
|
||||||
<div class="header-actions">
|
<div class="header-actions">
|
||||||
<button class="btn btn-primary" onclick="openTokenModal()">🔑 全局Token</button>
|
<button class="btn btn-primary" onclick="openTokenModal()">🔑 全局Token</button>
|
||||||
|
<button class="btn btn-gray" onclick="openRouteKeyModal()"><svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-right:4px"><circle cx="13" cy="4" r="2"/><path d="M11 21l1.5-6-3-2.5V8.5"/><path d="M12.5 12.5L16 15l1 4"/><path d="M8.5 8.5L6 11"/></svg>步行路线 AK</button>
|
||||||
<button class="btn btn-gray" onclick="openAlertConfig()">📢 告警邮箱</button>
|
<button class="btn btn-gray" onclick="openAlertConfig()">📢 告警邮箱</button>
|
||||||
<a href="/admin/logout" class="btn btn-sm btn-gray" style="text-decoration:none">退出</a>
|
<a href="/admin/logout" class="btn btn-sm btn-gray" style="text-decoration:none">退出</a>
|
||||||
</div>
|
</div>
|
||||||
@@ -122,6 +123,44 @@ tr:hover{background:#3a3a3c}
|
|||||||
</div>
|
</div>
|
||||||
<div id="toast" class="toast"></div>
|
<div id="toast" class="toast"></div>
|
||||||
|
|
||||||
|
<!-- 点邮箱后:右侧上游信息小浮层 -->
|
||||||
|
<aside class="upstream-pop" id="upstream-pop" hidden>
|
||||||
|
<header class="upstream-pop-head">
|
||||||
|
<strong id="upstream-pop-title">上游信息</strong>
|
||||||
|
<button class="upstream-pop-close" onclick="closeUpstreamPop()" aria-label="关闭">✕</button>
|
||||||
|
</header>
|
||||||
|
<div class="upstream-pop-body" id="upstream-pop-body">加载中…</div>
|
||||||
|
</aside>
|
||||||
|
<style>
|
||||||
|
.upstream-pop{
|
||||||
|
position: fixed; z-index: 1200; /* 位置由 JS 按被点邮箱算出来 */
|
||||||
|
width: 302px; max-width: 88vw; max-height: 74vh; overflow: auto;
|
||||||
|
border-radius: 14px; padding: 0;
|
||||||
|
background: var(--ui-header-acrylic, rgba(251,251,250,.82));
|
||||||
|
border: 1px solid var(--ui-line-strong, rgba(23,23,25,.15));
|
||||||
|
-webkit-backdrop-filter: blur(24px) saturate(1.4);
|
||||||
|
backdrop-filter: blur(24px) saturate(1.4);
|
||||||
|
box-shadow: 0 16px 48px rgba(18,18,20,.18);
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
.upstream-pop[hidden]{display:none}
|
||||||
|
.upstream-pop-head{
|
||||||
|
display:flex;align-items:center;justify-content:space-between;
|
||||||
|
padding: 10px 12px 6px; font-size: 13.5px;
|
||||||
|
}
|
||||||
|
.upstream-pop-close{
|
||||||
|
border:none;background:transparent;font-size:14px;cursor:pointer;
|
||||||
|
color:var(--sec);padding:2px 6px;border-radius:6px;
|
||||||
|
}
|
||||||
|
.upstream-pop-body{padding: 4px 12px 12px; line-height:1.75}
|
||||||
|
.upstream-pop-body .up-name{font-size:17px;font-weight:700;margin:2px 0 6px}
|
||||||
|
.upstream-pop-body .up-row{display:flex;gap:8px}
|
||||||
|
.upstream-pop-body .up-k{flex:0 0 64px;color:var(--sec)}
|
||||||
|
.upstream-pop-body .up-empty{color:var(--sec);padding:6px 0}
|
||||||
|
a.email-link{color:var(--accent,#0071e3);text-decoration:none;cursor:pointer}
|
||||||
|
a.email-link:hover{text-decoration:underline}
|
||||||
|
</style>
|
||||||
|
|
||||||
<!-- 百度地图 GL(校园地点编辑用) -->
|
<!-- 百度地图 GL(校园地点编辑用) -->
|
||||||
<script src="https://api.map.baidu.com/api?v=1.0&type=webgl&ak=GzzqszczKmI7RNTclpLtOXZDTT4mq8a6"></script>
|
<script src="https://api.map.baidu.com/api?v=1.0&type=webgl&ak=GzzqszczKmI7RNTclpLtOXZDTT4mq8a6"></script>
|
||||||
|
|
||||||
@@ -208,7 +247,7 @@ function renderUsers(){
|
|||||||
const reminder = u.reminder_enabled ? `${(u.reminder_minutes||[]).join('/')} 分钟` : '已关闭';
|
const reminder = u.reminder_enabled ? `${(u.reminder_minutes||[]).join('/')} 分钟` : '已关闭';
|
||||||
const policy = `${u.rental_duration_minutes||19}分钟 · ${u.rental_rounds||1}轮 · 自动还车${u.auto_return_enabled?'开':'关'} · 保护月卡${u.protect_card?'开':'关'} · 提醒${reminder}`;
|
const policy = `${u.rental_duration_minutes||19}分钟 · ${u.rental_rounds||1}轮 · 自动还车${u.auto_return_enabled?'开':'关'} · 保护月卡${u.protect_card?'开':'关'} · 提醒${reminder}`;
|
||||||
return `<tr>
|
return `<tr>
|
||||||
<td>${u.id}</td><td>${esc(u.email)}</td>
|
<td>${u.id}</td><td>${emailLink(u.id, u.email)}</td>
|
||||||
<td>${esc(u.token_id_mask||'')} <span class="mono" style="color:var(--sec)">${esc(u.wx_sig_mask||'')}</span></td>
|
<td>${esc(u.token_id_mask||'')} <span class="mono" style="color:var(--sec)">${esc(u.wx_sig_mask||'')}</span></td>
|
||||||
<td>${auth}</td>
|
<td>${auth}</td>
|
||||||
<td style="min-width:180px;font-size:12px">${esc(policy)}</td>
|
<td style="min-width:180px;font-size:12px">${esc(policy)}</td>
|
||||||
@@ -334,6 +373,74 @@ async function doDeleteUser(userId){
|
|||||||
if(d.rtn_code===0){setTimeout(()=>{loadUsers();loadSummary();},1200);}
|
if(d.rtn_code===0){setTimeout(()=>{loadUsers();loadSummary();},1200);}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ============ 点邮箱 -> 右侧上游信息浮层 ============ */
|
||||||
|
function emailLink(userId, email){
|
||||||
|
const text = esc(email || '-');
|
||||||
|
if(!userId) return text;
|
||||||
|
return `<a class="email-link" href="javascript:void(0)" onclick="openUpstreamPop(${userId},'${esc(email||'')}', event)">${text}</a>`;
|
||||||
|
}
|
||||||
|
function closeUpstreamPop(){ document.getElementById('upstream-pop').hidden = true; }
|
||||||
|
// 点浮层以外的地方自动收起(点另一个邮箱会重新定位并重新查询)
|
||||||
|
document.addEventListener('click', (e) => {
|
||||||
|
const pop = document.getElementById('upstream-pop');
|
||||||
|
if(!pop || pop.hidden) return;
|
||||||
|
if(pop.contains(e.target)) return;
|
||||||
|
if(e.target.closest('a.email-link')) return;
|
||||||
|
closeUpstreamPop();
|
||||||
|
});
|
||||||
|
async function openUpstreamPop(userId, email, ev){
|
||||||
|
const pop = document.getElementById('upstream-pop');
|
||||||
|
const body = document.getElementById('upstream-pop-body');
|
||||||
|
document.getElementById('upstream-pop-title').textContent = email || ('用户 #' + userId);
|
||||||
|
body.innerHTML = '<div class="up-empty">正在查询上游信息…</div>';
|
||||||
|
|
||||||
|
// 贴着被点的邮箱:默认出现在它右侧,空间不够就翻转到左侧/下方,始终不出屏
|
||||||
|
const anchor = ev && ev.currentTarget ? ev.currentTarget : null;
|
||||||
|
const rect = anchor ? anchor.getBoundingClientRect() : null;
|
||||||
|
pop.hidden = false;
|
||||||
|
const popW = pop.offsetWidth || 302;
|
||||||
|
const gap = 8;
|
||||||
|
if(rect){
|
||||||
|
let left = rect.right + gap;
|
||||||
|
if(left + popW > window.innerWidth - 10){
|
||||||
|
left = Math.max(10, rect.left - popW - gap); // 右侧放不下就翻到左边
|
||||||
|
}
|
||||||
|
let top = rect.top - 6;
|
||||||
|
const maxTop = window.innerHeight - 140;
|
||||||
|
top = Math.max(10, Math.min(top, maxTop));
|
||||||
|
pop.style.left = Math.round(left) + 'px';
|
||||||
|
pop.style.top = Math.round(top) + 'px';
|
||||||
|
}else{
|
||||||
|
pop.style.left = 'auto';
|
||||||
|
pop.style.right = '14px';
|
||||||
|
pop.style.top = '86px';
|
||||||
|
}
|
||||||
|
|
||||||
|
const d = await api('/api/admin/user/upstream_info', {method:'POST', body: JSON.stringify({user_id: userId})});
|
||||||
|
if(d.rtn_code !== 0){
|
||||||
|
body.innerHTML = `<div class="up-empty">查询失败:${esc(d.message || '上游未返回个人信息')}</div>`;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const u = d.data || {};
|
||||||
|
const rows = [
|
||||||
|
['姓名', u.true_name || u.nick_name],
|
||||||
|
['昵称', u.nick_name],
|
||||||
|
['性别', u.gender],
|
||||||
|
['手机', u.mobile],
|
||||||
|
['学校', u.school],
|
||||||
|
['学院', u.college],
|
||||||
|
['专业', u.major],
|
||||||
|
['年级', u.grade],
|
||||||
|
['学号', u.student_no],
|
||||||
|
].filter(r => r[1]);
|
||||||
|
const name = u.true_name || u.nick_name || '(上游未提供姓名)';
|
||||||
|
body.innerHTML = `<div class="up-name">${esc(name)}</div>`
|
||||||
|
+ (rows.length
|
||||||
|
? rows.map(r => `<div class="up-row"><span class="up-k">${r[0]}</span><span>${esc(String(r[1]))}</span></div>`).join('')
|
||||||
|
: '<div class="up-empty">上游没有返回更多个人信息</div>')
|
||||||
|
+ `<div class="up-row" style="margin-top:6px;color:var(--sec)"><span class="up-k">邮箱</span><span>${esc(email || '-')}</span></div>`;
|
||||||
|
}
|
||||||
|
|
||||||
/* ============ 订单 ============ */
|
/* ============ 订单 ============ */
|
||||||
async function loadOrders(){
|
async function loadOrders(){
|
||||||
const box=document.getElementById('tab-orders');
|
const box=document.getElementById('tab-orders');
|
||||||
@@ -349,15 +456,28 @@ function renderOrders(){
|
|||||||
?`<span style="color:#0958d9;background:#e6f4ff;padding:2px 8px;border-radius:4px;font-size:12px;font-weight:600">shared</span>`
|
?`<span style="color:#0958d9;background:#e6f4ff;padding:2px 8px;border-radius:4px;font-size:12px;font-weight:600">shared</span>`
|
||||||
:esc(r.source||'');
|
:esc(r.source||'');
|
||||||
const userCell=r=>(r.source==='shared'&&r.rider_email)
|
const userCell=r=>(r.source==='shared'&&r.rider_email)
|
||||||
?`${esc(r.email||'-')} → ${esc(r.rider_email)}`
|
?`${emailLink(r.user_id, r.email||'-')} → ${emailLink(r.rider_user_id, r.rider_email)}`
|
||||||
:esc(r.email||'-');
|
:emailLink(r.user_id, r.email||'-');
|
||||||
|
// 起终点:优先位置标签;老订单没标签就退回坐标,再没有才显示未知
|
||||||
|
const coordText=(lat,lng)=>{
|
||||||
|
const la=Number(lat), lo=Number(lng);
|
||||||
|
if(!Number.isFinite(la)||!Number.isFinite(lo)||(la===0&&lo===0)) return '';
|
||||||
|
return `${la.toFixed(5)},${lo.toFixed(5)}`;
|
||||||
|
};
|
||||||
|
const routeCell=r=>{
|
||||||
|
const s=r.start_label||coordText(r.start_latitude,r.start_longitude)||'起点未知';
|
||||||
|
const e=r.end_label||coordText(r.end_latitude,r.end_longitude)||(r.expired?'终点未知':'骑行中');
|
||||||
|
return `<span style="font-size:12px">${esc(s)} <span style="color:var(--sec)">→</span> ${esc(e)}</span>`;
|
||||||
|
};
|
||||||
const rows=list.map(r=>`<tr>
|
const rows=list.map(r=>`<tr>
|
||||||
<td>${r.id}</td><td>${esc(r.order_id||'-')}</td><td>#${esc(r.bike_code)}</td>
|
<td>${r.id}</td><td>${esc(r.order_id||'-')}</td><td>#${esc(r.bike_code)}</td>
|
||||||
<td>${userCell(r)}</td><td>${sourceCell(r)}</td>
|
<td>${userCell(r)}</td><td>${routeCell(r)}</td>
|
||||||
|
<td>${r.riding_minutes!=null ? esc(r.riding_minutes)+' 分钟' : '-'}</td>
|
||||||
|
<td>${sourceCell(r)}</td>
|
||||||
<td>${esc((r.start_time||'').replace('T',' '))}</td><td>${esc((r.end_time||'').replace('T',' '))}</td>
|
<td>${esc((r.start_time||'').replace('T',' '))}</td><td>${esc((r.end_time||'').replace('T',' '))}</td>
|
||||||
<td>${badgeFor(r.status)}</td>
|
<td>${badgeFor(r.status)}</td>
|
||||||
<td>${(r.status==='进行中'||r.status==='已超时')?`<button class="btn btn-danger btn-sm" onclick="returnOrder(${r.id})">🔒 代还车</button>`:'-'}</td></tr>`).join('');
|
<td>${(r.status==='进行中'||r.status==='已超时')?`<button class="btn btn-danger btn-sm" onclick="returnOrder(${r.id})">🔒 代还车</button>`:'-'}</td></tr>`).join('');
|
||||||
document.getElementById('od-table').innerHTML=`<table><thead><tr><th>本地ID</th><th>订单号</th><th>车辆</th><th>用户</th><th>来源</th><th>开始</th><th>到期</th><th>状态</th><th>操作</th></tr></thead><tbody>${rows||'<tr><td colspan=9 class="empty">无</td></tr>'}</tbody></table>`;
|
document.getElementById('od-table').innerHTML=`<table><thead><tr><th>本地ID</th><th>订单号</th><th>车辆</th><th>用户</th><th>起点 → 终点</th><th>已骑行</th><th>来源</th><th>开始</th><th>预计到期</th><th>状态</th><th>操作</th></tr></thead><tbody>${rows||'<tr><td colspan=11 class="empty">无</td></tr>'}</tbody></table>`;
|
||||||
}
|
}
|
||||||
let returnTarget=null;
|
let returnTarget=null;
|
||||||
function returnOrder(rentalId){
|
function returnOrder(rentalId){
|
||||||
@@ -384,7 +504,7 @@ async function loadShares(){
|
|||||||
const rows=list.map(s=>{
|
const rows=list.map(s=>{
|
||||||
const stb = s.status==='active'?'<span class="badge green">激活中</span>':'<span class="badge expired">已解绑</span>';
|
const stb = s.status==='active'?'<span class="badge green">激活中</span>':'<span class="badge expired">已解绑</span>';
|
||||||
return `<tr>
|
return `<tr>
|
||||||
<td>${s.id}</td><td>#${s.owner_user_id} ${esc(s.owner_email||'-')}</td><td>#${s.rider_user_id} ${esc(s.rider_email||'-')}</td>
|
<td>${s.id}</td><td>#${s.owner_user_id} ${emailLink(s.owner_user_id, s.owner_email||'-')}</td><td>#${s.rider_user_id} ${emailLink(s.rider_user_id, s.rider_email||'-')}</td>
|
||||||
<td>${s.daily_limit}</td>
|
<td>${s.daily_limit}</td>
|
||||||
<td>${s.require_card?'<span class="badge orange">需卡</span>':'<span class="badge muted">免卡</span>'}</td>
|
<td>${s.require_card?'<span class="badge orange">需卡</span>':'<span class="badge muted">免卡</span>'}</td>
|
||||||
<td>${s.card_min_times}</td>
|
<td>${s.card_min_times}</td>
|
||||||
@@ -919,6 +1039,53 @@ async function saveToken(){
|
|||||||
if(d.rtn_code===0&&s.rtn_code===0) closeModal();
|
if(d.rtn_code===0&&s.rtn_code===0) closeModal();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ============ 百度步行路线 AK/SK(服务端密钥) ============ */
|
||||||
|
async function openRouteKeyModal(){
|
||||||
|
openModal(`<h3><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-3px;margin-right:6px"><circle cx="13" cy="4" r="2"/><path d="M11 21l1.5-6-3-2.5V8.5"/><path d="M12.5 12.5L16 15l1 4"/><path d="M8.5 8.5L6 11"/></svg>步行路线 AK/SK</h3>
|
||||||
|
<p class="tip">卡片上的「步行 X 米 / 约 Y 分钟」用它算真实道路距离。<br>
|
||||||
|
需<b>服务端</b> AK + 已开通「步行路线规划(轻量)」;开了 SN 校验的要配套 SK。</p>
|
||||||
|
<div id="rk-loading" class="empty">加载中…</div>`);
|
||||||
|
const d=await api('/api/admin/route_key');
|
||||||
|
const cur=d.data||{};
|
||||||
|
document.getElementById('rk-loading').innerHTML=`
|
||||||
|
<label>AK(必填)</label>
|
||||||
|
<input id="rk-ak" value="${esc(cur.ak||'')}" placeholder="服务端 AK">
|
||||||
|
<label>SK(开了 SN 校验才需要;留空表示保持原值)</label>
|
||||||
|
<input id="rk-sk" placeholder="${cur.sk_set?('已配置,尾号 '+cur.sk_tail+'(留空不修改)'):'未配置'}">
|
||||||
|
<label style="display:flex;align-items:center;gap:8px;margin-top:8px;cursor:pointer">
|
||||||
|
<input type="checkbox" id="rk-clear" style="width:auto"> 清空 SK(关闭 SN 校验时用)
|
||||||
|
</label>
|
||||||
|
<div class="modal-actions">
|
||||||
|
<button class="btn btn-primary" onclick="saveRouteKey()">💾 保存</button>
|
||||||
|
<button class="btn btn-gray" onclick="testRouteKey()">🔌 测试连通</button>
|
||||||
|
<button class="btn btn-gray" onclick="closeModal()">取消</button>
|
||||||
|
</div>`;
|
||||||
|
}
|
||||||
|
async function saveRouteKey(){
|
||||||
|
const ak=document.getElementById('rk-ak').value.trim();
|
||||||
|
const skInput=document.getElementById('rk-sk').value.trim();
|
||||||
|
const clear=document.getElementById('rk-clear').checked;
|
||||||
|
let sk=skInput;
|
||||||
|
if(clear) sk='';
|
||||||
|
else if(!skInput) sk=undefined; // 不传 = 保持原值
|
||||||
|
const body={ak}; if(sk!==undefined) body.sk=sk;
|
||||||
|
const d=await api('/api/admin/route_key',{method:'POST',body:JSON.stringify(body)});
|
||||||
|
toast(d.rtn_code===0?'✅ '+d.message:'❌ '+d.message, d.rtn_code===0?'success':'error');
|
||||||
|
if(d.rtn_code===0) closeModal();
|
||||||
|
}
|
||||||
|
async function testRouteKey(){
|
||||||
|
const ak=document.getElementById('rk-ak').value.trim();
|
||||||
|
const skInput=document.getElementById('rk-sk').value.trim();
|
||||||
|
const clear=document.getElementById('rk-clear').checked;
|
||||||
|
// 先保存再测,避免测的是旧值
|
||||||
|
const body={ak}; if(clear) body.sk=''; else if(skInput) body.sk=skInput;
|
||||||
|
const saved=await api('/api/admin/route_key',{method:'POST',body:JSON.stringify(body)});
|
||||||
|
if(saved.rtn_code!==0){ toast('❌ '+saved.message,'error'); return; }
|
||||||
|
toast('已保存,正在测试…','success');
|
||||||
|
const d=await api('/api/admin/route_key/test',{method:'POST',body:'{}'});
|
||||||
|
toast((d.rtn_code===0?'✅ ':'❌ ')+d.message, d.rtn_code===0?'success':'error');
|
||||||
|
}
|
||||||
|
|
||||||
/* 启动 */
|
/* 启动 */
|
||||||
renderTabs();
|
renderTabs();
|
||||||
switchTab('users');
|
switchTab('users');
|
||||||
|
|||||||
+59
-27
@@ -193,6 +193,27 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- 导航信息条 -->
|
||||||
|
<div class="nav-banner" id="nav-banner" hidden>
|
||||||
|
<div class="nav-banner-main">
|
||||||
|
<span class="nav-banner-turn" id="nav-banner-turn" aria-hidden="true"></span>
|
||||||
|
<span class="nav-banner-copy">
|
||||||
|
<span class="nav-banner-action" id="nav-banner-action">正在规划路线…</span>
|
||||||
|
<span class="nav-banner-text" id="nav-banner-text">--</span>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<button class="nav-banner-stop" onclick="stopNavigation()">结束导航</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 拖动地图后的「返回导航」胶囊 -->
|
||||||
|
<button class="nav-resume" id="nav-resume" hidden onclick="resumeNavigation()">
|
||||||
|
<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||||
|
<path d="M12 3v3"/><path d="M12 18v3"/><path d="M3 12h3"/><path d="M18 12h3"/>
|
||||||
|
<circle cx="12" cy="12" r="3.2" fill="currentColor" stroke="none"/>
|
||||||
|
</svg>
|
||||||
|
返回导航
|
||||||
|
</button>
|
||||||
|
|
||||||
<!-- 底部扫码栏 -->
|
<!-- 底部扫码栏 -->
|
||||||
<div class="scan-bar">
|
<div class="scan-bar">
|
||||||
<input class="scan-input" id="scan-input" type="number" pattern="[0-9]*" maxlength="5" placeholder="输入5位车牌号" />
|
<input class="scan-input" id="scan-input" type="number" pattern="[0-9]*" maxlength="5" placeholder="输入5位车牌号" />
|
||||||
@@ -720,33 +741,43 @@
|
|||||||
<span class="bike-code" id="card-code">#51287</span>
|
<span class="bike-code" id="card-code">#51287</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="bike-card-header-btns">
|
<div class="bike-card-header-btns">
|
||||||
<button class="bike-card-find-btn" id="bike-find-btn-header" onclick="findBike()" title="寻车">
|
<button class="bike-card-find-btn" id="bike-nav-btn" onclick="toggleNavigation()" title="导航到车">
|
||||||
<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>
|
<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 11l19-9-9 19-2-8-8-2z"/></svg>
|
||||||
<span>寻车</span>
|
<span class="btn-label" id="bike-nav-btn-text">导航</span>
|
||||||
|
</button>
|
||||||
|
<button class="bike-card-find-btn" id="bike-find-btn-header" onclick="findBike()" title="寻车(响铃)">
|
||||||
|
<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 8a6 6 0 0 0-12 0c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.7 21a2 2 0 0 1-3.4 0"/></svg>
|
||||||
|
<span class="btn-label">寻车</span>
|
||||||
</button>
|
</button>
|
||||||
<button class="bike-card-close" onclick="closeCard()">✕</button>
|
<button class="bike-card-close" onclick="closeCard()">✕</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<!-- 左:距离/步行时间(未定位时整格隐藏);右:电量 + 状态 -->
|
||||||
<div class="bike-status-row">
|
<div class="bike-card-meta">
|
||||||
<!-- 电池图标 + 电量数值 -->
|
<div class="bike-meta-card bike-meta-left" id="card-meta-left" hidden>
|
||||||
<div class="bike-battery-wrap">
|
<span class="bike-meta-distance" id="card-distance">距你 -- 米</span>
|
||||||
<div class="battery-svg-wrap">
|
<span class="bike-meta-walk" id="card-walk">步行 -- 分钟</span>
|
||||||
<svg id="battery-svg" width="50" height="26" viewBox="0 0 50 26" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
||||||
<!-- 电池外框 -->
|
|
||||||
<rect x="1" y="3" width="43" height="20" rx="3" ry="3" stroke="var(--text-secondary)" stroke-width="2" fill="none"/>
|
|
||||||
<!-- 电池正极头 -->
|
|
||||||
<rect x="45" y="9" width="4" height="8" rx="2" fill="var(--text-secondary)"/>
|
|
||||||
<!-- 电量填充 -->
|
|
||||||
<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>
|
|
||||||
</div>
|
</div>
|
||||||
<!-- 状态 -->
|
<div class="bike-meta-card bike-meta-right">
|
||||||
<div class="bike-status-wrap">
|
<!-- 电池图标 + 电量数值 -->
|
||||||
<span class="bike-status-label">状态</span>
|
<div class="bike-battery-wrap">
|
||||||
<span class="bike-status-value" id="card-state">--</span>
|
<div class="battery-svg-wrap">
|
||||||
|
<svg id="battery-svg" width="50" height="26" viewBox="0 0 50 26" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||||
|
<!-- 电池外框 -->
|
||||||
|
<rect x="1" y="3" width="43" height="20" rx="3" ry="3" stroke="var(--text-secondary)" stroke-width="2" fill="none"/>
|
||||||
|
<!-- 电池正极头 -->
|
||||||
|
<rect x="45" y="9" width="4" height="8" rx="2" fill="var(--text-secondary)"/>
|
||||||
|
<!-- 电量填充 -->
|
||||||
|
<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>
|
||||||
|
</div>
|
||||||
|
<!-- 状态 -->
|
||||||
|
<div class="bike-status-wrap">
|
||||||
|
<span class="bike-status-label">状态</span>
|
||||||
|
<span class="bike-status-value" id="card-state">--</span>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -865,10 +896,7 @@
|
|||||||
<span class="locate-fab-label">找最近的车</span>
|
<span class="locate-fab-label">找最近的车</span>
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<!-- 版本号标识 -->
|
<!-- 版本更新说明弹窗(不再自动弹出,也不再有右下角版本徽标) -->
|
||||||
<div class="version-badge" id="version-badge" onclick="openVersionModal()">v1.6.0</div>
|
|
||||||
|
|
||||||
<!-- 版本更新说明弹窗 -->
|
|
||||||
<div class="auth-modal" id="version-modal">
|
<div class="auth-modal" id="version-modal">
|
||||||
<div class="auth-overlay" onclick="closeVersionModal()"></div>
|
<div class="auth-overlay" onclick="closeVersionModal()"></div>
|
||||||
<div class="auth-content">
|
<div class="auth-content">
|
||||||
@@ -937,9 +965,13 @@
|
|||||||
<!-- 坐标转换库(本地内置,wgs84/gcj02/bd09 互转,替代 BMapGL.Convertor 在线转换) -->
|
<!-- 坐标转换库(本地内置,wgs84/gcj02/bd09 互转,替代 BMapGL.Convertor 在线转换) -->
|
||||||
<script defer src="/static/js/coordtransform.js?v={{ map_asset_version }}"></script>
|
<script defer src="/static/js/coordtransform.js?v={{ map_asset_version }}"></script>
|
||||||
|
|
||||||
|
<!-- Phase 0 拆出的纯函数模块(经典脚本,仍挂全局,调用点无需改动) -->
|
||||||
|
<script defer src="/static/js/src/core/geo.js?v={{ map_asset_version }}"></script>
|
||||||
<script defer src="/static/js/bike-clusters.js?v={{ map_asset_version }}"></script>
|
<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/settings-pages.js?v={{ map_asset_version }}"></script>
|
||||||
<script defer src="/static/js/map.js?v={{ map_asset_version }}"></script>
|
<!-- 拆分后的模块:导航 / 共享 / 订阅(全局函数名不变,map.js 直接调用) -->
|
||||||
|
<!-- TypeScript 重写版(esbuild IIFE,等价于上面四个脚本;回滚=换回那四行) -->
|
||||||
|
<script defer src="/static/dist/app.js?v={{ map_asset_version }}"></script>
|
||||||
|
|
||||||
<!-- 还车确认弹窗 -->
|
<!-- 还车确认弹窗 -->
|
||||||
<div class="return-confirm-modal" id="return-confirm-modal">
|
<div class="return-confirm-modal" id="return-confirm-modal">
|
||||||
|
|||||||
@@ -0,0 +1,139 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""管理员订单列表:已骑行分钟数。"""
|
||||||
|
import datetime as dt
|
||||||
|
import sqlite3
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from flask import Flask
|
||||||
|
|
||||||
|
from routes import admin as admin_routes
|
||||||
|
|
||||||
|
|
||||||
|
class RidingMinutesTests(unittest.TestCase):
|
||||||
|
def test_finished_order_uses_returned_at(self):
|
||||||
|
rental = {"start_time": "2026-01-01 09:00:00",
|
||||||
|
"returned_at": "2026-01-01 09:23:30"}
|
||||||
|
self.assertEqual(23, admin_routes._riding_minutes(rental))
|
||||||
|
|
||||||
|
def test_active_order_uses_now(self):
|
||||||
|
tz = dt.timezone(dt.timedelta(hours=8))
|
||||||
|
start = dt.datetime.now(tz).replace(tzinfo=None) - dt.timedelta(minutes=7)
|
||||||
|
rental = {"start_time": start.strftime("%Y-%m-%d %H:%M:%S"), "returned_at": None}
|
||||||
|
self.assertIn(admin_routes._riding_minutes(rental), (6, 7))
|
||||||
|
|
||||||
|
def test_bad_timestamps_do_not_break_the_list(self):
|
||||||
|
self.assertEqual(0, admin_routes._riding_minutes({"start_time": None}))
|
||||||
|
self.assertEqual(0, admin_routes._riding_minutes({"start_time": "not-a-date"}))
|
||||||
|
|
||||||
|
|
||||||
|
class AdminReturnTests(unittest.TestCase):
|
||||||
|
"""管理端代还车必须复用「换点重试」链路,并回填实际还车时间。"""
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
self.tmp = tempfile.TemporaryDirectory()
|
||||||
|
self.db_path = Path(self.tmp.name) / "admin.db"
|
||||||
|
conn = sqlite3.connect(self.db_path)
|
||||||
|
conn.executescript("""
|
||||||
|
CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT);
|
||||||
|
CREATE TABLE rentals (
|
||||||
|
id INTEGER PRIMARY KEY, order_id TEXT, bike_code TEXT, email TEXT,
|
||||||
|
user_id INTEGER, source TEXT, expired INTEGER DEFAULT 0,
|
||||||
|
start_time TEXT, end_time TEXT, returned_at TEXT,
|
||||||
|
end_latitude REAL, end_longitude REAL, end_label TEXT
|
||||||
|
);
|
||||||
|
INSERT INTO users (id, email) VALUES (7, 'rider@example.test');
|
||||||
|
INSERT INTO rentals (id, order_id, bike_code, email, user_id, source,
|
||||||
|
expired, start_time, end_time)
|
||||||
|
VALUES (101, '9001', '50001', 'rider@example.test', 7, 'unlock',
|
||||||
|
0, '2026-01-01 09:00:00', '2026-01-01 09:19:00');
|
||||||
|
""")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
self.tmp.cleanup()
|
||||||
|
|
||||||
|
def _get_db(self):
|
||||||
|
conn = sqlite3.connect(self.db_path)
|
||||||
|
conn.row_factory = sqlite3.Row
|
||||||
|
return conn
|
||||||
|
|
||||||
|
def test_admin_return_uses_candidate_chain_and_records_returned_at(self):
|
||||||
|
app = Flask(__name__)
|
||||||
|
app.secret_key = "test"
|
||||||
|
app.register_blueprint(admin_routes.bp)
|
||||||
|
client = app.test_client()
|
||||||
|
with client.session_transaction() as sess:
|
||||||
|
sess["admin_logged_in"] = True
|
||||||
|
|
||||||
|
with patch.object(admin_routes, "get_db", self._get_db), \
|
||||||
|
patch.object(admin_routes, "request_with_user_auth", return_value={
|
||||||
|
"rtn_code": 0, "data": {"latitude": 36.53, "longitude": 116.78}}), \
|
||||||
|
patch("routes.rental._try_return_candidates",
|
||||||
|
return_value=({"rtn_code": 0}, (36.53, 116.78),
|
||||||
|
["你上报的位置", "附近停车区"])) as chain, \
|
||||||
|
patch("routes.rental._record_rental_end") as record_end, \
|
||||||
|
patch("timer._try_card_pay_auto", return_value={}):
|
||||||
|
resp = client.post("/api/admin/return", json={"rental_id": 101, "user_id": 7})
|
||||||
|
|
||||||
|
body = resp.get_json()
|
||||||
|
self.assertEqual(0, body["rtn_code"])
|
||||||
|
chain.assert_called_once()
|
||||||
|
record_end.assert_called_once() # 回填 returned_at + 终点
|
||||||
|
self.assertIn("used_nearest", body)
|
||||||
|
|
||||||
|
def test_admin_return_falls_back_to_rental_id_when_order_id_matches_nothing(self):
|
||||||
|
"""order_id 是脏字符串、回填命中 0 行时,仍要按 rental_id 把单子收掉。"""
|
||||||
|
app = Flask(__name__)
|
||||||
|
app.secret_key = "test"
|
||||||
|
app.register_blueprint(admin_routes.bp)
|
||||||
|
client = app.test_client()
|
||||||
|
with client.session_transaction() as sess:
|
||||||
|
sess["admin_logged_in"] = True
|
||||||
|
|
||||||
|
with patch.object(admin_routes, "get_db", self._get_db), \
|
||||||
|
patch.object(admin_routes, "request_with_user_auth", return_value={
|
||||||
|
"rtn_code": 0, "data": {"latitude": 36.53, "longitude": 116.78}}), \
|
||||||
|
patch("routes.rental._try_return_candidates",
|
||||||
|
return_value=({"rtn_code": 0}, (36.53, 116.78), ["你上报的位置"])), \
|
||||||
|
patch("routes.rental._record_rental_end", return_value=0), \
|
||||||
|
patch("timer._try_card_pay_auto", return_value={}):
|
||||||
|
resp = client.post("/api/admin/return", json={"rental_id": 101, "user_id": 7})
|
||||||
|
|
||||||
|
self.assertEqual(0, resp.get_json()["rtn_code"])
|
||||||
|
conn = self._get_db()
|
||||||
|
row = conn.execute("SELECT expired, returned_at FROM rentals WHERE id = 101").fetchone()
|
||||||
|
conn.close()
|
||||||
|
self.assertEqual(1, row["expired"])
|
||||||
|
self.assertTrue(row["returned_at"]) # 兜底也写了实际还车时间
|
||||||
|
|
||||||
|
def test_admin_return_reports_success_when_local_write_fails(self):
|
||||||
|
"""上游成功、本地写库失败:仍返回成功 + 提示稍后同步,别让管理员重复点。"""
|
||||||
|
app = Flask(__name__)
|
||||||
|
app.secret_key = "test"
|
||||||
|
app.register_blueprint(admin_routes.bp)
|
||||||
|
client = app.test_client()
|
||||||
|
with client.session_transaction() as sess:
|
||||||
|
sess["admin_logged_in"] = True
|
||||||
|
|
||||||
|
with patch.object(admin_routes, "get_db", self._get_db), \
|
||||||
|
patch.object(admin_routes, "request_with_user_auth", return_value={
|
||||||
|
"rtn_code": 0, "data": {"latitude": 36.53, "longitude": 116.78}}), \
|
||||||
|
patch("routes.rental._try_return_candidates",
|
||||||
|
return_value=({"rtn_code": 0}, (36.53, 116.78), ["你上报的位置"])), \
|
||||||
|
patch("routes.rental._record_rental_end",
|
||||||
|
side_effect=RuntimeError("database is locked")), \
|
||||||
|
patch("timer._try_card_pay_auto", return_value={}):
|
||||||
|
resp = client.post("/api/admin/return", json={"rental_id": 101, "user_id": 7})
|
||||||
|
|
||||||
|
body = resp.get_json()
|
||||||
|
self.assertEqual(0, body["rtn_code"])
|
||||||
|
self.assertFalse(body["local_synced"])
|
||||||
|
self.assertIn("本地记录稍后同步", body["message"])
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""凭据告警的误报回归。
|
||||||
|
|
||||||
|
线上事故:部署后全站收到「微信凭据已过期」邮件,实际 token 没过期。
|
||||||
|
根因:只填 token_id、没有 access_token 的用户,请求只能用假签名,
|
||||||
|
上游一律回 102001;告警把 102001 当成「凭据过期」于是全员误报。
|
||||||
|
"""
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import alerts
|
||||||
|
|
||||||
|
|
||||||
|
class CredentialAlertTests(unittest.TestCase):
|
||||||
|
def test_token_only_user_never_triggers_expiry_mail(self):
|
||||||
|
"""没有 access_token → 假签名必被拒 → 不能发「已过期」邮件。"""
|
||||||
|
sent = []
|
||||||
|
|
||||||
|
class FakeConn:
|
||||||
|
def execute(self, sql, params=()):
|
||||||
|
class Cur:
|
||||||
|
def fetchall(_self):
|
||||||
|
return [{"id": 1, "email": "a@b.c", "token_id": "1356419",
|
||||||
|
"alert_email": None}]
|
||||||
|
return Cur()
|
||||||
|
def close(self):
|
||||||
|
pass
|
||||||
|
def commit(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
with patch.object(alerts, "get_db", return_value=FakeConn()), \
|
||||||
|
patch("wechat.request_with_user_auth",
|
||||||
|
return_value={"rtn_code": 102001, "token_invalid": True}), \
|
||||||
|
patch.object(alerts, "_send_alert",
|
||||||
|
side_effect=lambda *a, **k: sent.append(a) or True), \
|
||||||
|
patch.object(alerts, "get_alert_emails", return_value=["admin@example.test"]):
|
||||||
|
count = alerts.check_user_credentials_alive()
|
||||||
|
|
||||||
|
self.assertEqual(0, count)
|
||||||
|
self.assertEqual([], sent, "只填 token_id 的用户不该收到失效邮件")
|
||||||
|
|
||||||
|
def test_legacy_default_token_is_ignored_everywhere(self):
|
||||||
|
self.assertTrue(alerts._is_legacy_default_token("1291378"))
|
||||||
|
self.assertFalse(alerts._is_legacy_default_token("1356419"))
|
||||||
|
self.assertFalse(alerts._is_legacy_default_token(None))
|
||||||
|
self.assertFalse(alerts._is_legacy_default_token(""))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -9,16 +9,20 @@ app.py 在 import 期还会重包装 stdout,曾破坏 pytest 捕获。
|
|||||||
因此本文件把整个验证放进一个独立的 python 子进程运行:
|
因此本文件把整个验证放进一个独立的 python 子进程运行:
|
||||||
父进程零污染,失败时完整透出子进程输出。
|
父进程零污染,失败时完整透出子进程输出。
|
||||||
"""
|
"""
|
||||||
|
import os
|
||||||
import subprocess
|
import subprocess
|
||||||
|
|
||||||
|
os.environ["XBCR_DISABLE_BACKGROUND"] = "1"
|
||||||
import sys
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
ROOT = Path(__file__).parent.parent
|
ROOT = Path(__file__).parent.parent
|
||||||
|
|
||||||
CHILD = r'''
|
CHILD = r'''
|
||||||
import sys, tempfile, json
|
import os, sys, tempfile, json
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
ROOT = Path(r"{root}")
|
ROOT = Path(r"{root}")
|
||||||
|
os.environ["XBCR_DISABLE_BACKGROUND"] = "1"
|
||||||
sys.path.insert(0, str(ROOT))
|
sys.path.insert(0, str(ROOT))
|
||||||
|
|
||||||
import db as db_mod
|
import db as db_mod
|
||||||
@@ -106,7 +110,7 @@ sys.exit(1 if failures else 0)
|
|||||||
def test_history_30d_contract():
|
def test_history_30d_contract():
|
||||||
r = subprocess.run([sys.executable, "-c", CHILD],
|
r = subprocess.run([sys.executable, "-c", CHILD],
|
||||||
capture_output=True, text=True, timeout=180,
|
capture_output=True, text=True, timeout=180,
|
||||||
cwd=str(ROOT))
|
cwd=str(ROOT), encoding="utf-8", errors="replace")
|
||||||
out = (r.stdout or "") + (r.stderr or "")
|
out = (r.stdout or "") + (r.stderr or "")
|
||||||
print(out[-4000:] if len(out) > 4000 else out)
|
print(out[-4000:] if len(out) > 4000 else out)
|
||||||
assert r.returncode == 0, "子进程契约验证失败(见上方输出)"
|
assert r.returncode == 0, "子进程契约验证失败(见上方输出)"
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""跨进程租约(多 worker 选主 / 单任务抢占)。"""
|
||||||
|
import os
|
||||||
|
import sqlite3
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import db
|
||||||
|
|
||||||
|
|
||||||
|
class LeaseTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
# 其它用例会设 XBCR_DISABLE_LEASES 让租约直接放行;这里要真测租约
|
||||||
|
self._old_flag = os.environ.pop("XBCR_DISABLE_LEASES", None)
|
||||||
|
self.tmp = tempfile.TemporaryDirectory()
|
||||||
|
self.path = Path(self.tmp.name) / "lease.db"
|
||||||
|
self._old = db.DB_PATH
|
||||||
|
db.DB_PATH = self.path
|
||||||
|
db.init_db()
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
db.DB_PATH = self._old
|
||||||
|
if self._old_flag is not None:
|
||||||
|
os.environ["XBCR_DISABLE_LEASES"] = self._old_flag
|
||||||
|
self.tmp.cleanup()
|
||||||
|
|
||||||
|
def test_first_acquire_wins_and_second_is_blocked_for_other_owner(self):
|
||||||
|
self.assertTrue(db.acquire_lease("job", 60))
|
||||||
|
# 同一个 owner 再抢 = 续期,仍然成功
|
||||||
|
self.assertTrue(db.acquire_lease("job", 60))
|
||||||
|
# 模拟另一个进程把租约抢走
|
||||||
|
conn = sqlite3.connect(self.path)
|
||||||
|
conn.execute("UPDATE leases SET owner = 'other-host:999' WHERE name = 'job'")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
self.assertFalse(db.acquire_lease("job", 60))
|
||||||
|
|
||||||
|
def test_expired_lease_can_be_taken_over(self):
|
||||||
|
self.assertTrue(db.acquire_lease("job2", 60))
|
||||||
|
conn = sqlite3.connect(self.path)
|
||||||
|
conn.execute("UPDATE leases SET expires_at = 1 WHERE name = 'job2'")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
# 过期后任何进程都能接管(这里同 owner,但语义上等价)
|
||||||
|
self.assertTrue(db.acquire_lease("job2", 60))
|
||||||
|
|
||||||
|
def test_missing_table_returns_none_so_callers_fall_back(self):
|
||||||
|
"""老库没有 leases 表时不能把后台任务全拦掉。"""
|
||||||
|
empty = Path(self.tmp.name) / "empty.db"
|
||||||
|
sqlite3.connect(empty).close()
|
||||||
|
db.DB_PATH = empty
|
||||||
|
self.assertIsNone(db.acquire_lease("job3", 60))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -31,7 +31,8 @@ class MapAssetTests(unittest.TestCase):
|
|||||||
self.assertNotIn("", versions)
|
self.assertNotIn("", versions)
|
||||||
self.assertRegex(html, r'<script async src="https://api\.map\.baidu\.com/')
|
self.assertRegex(html, r'<script async src="https://api\.map\.baidu\.com/')
|
||||||
self.assertIn("&callback=onBaiduMapReady", html)
|
self.assertIn("&callback=onBaiduMapReady", html)
|
||||||
self.assertRegex(html, r'<script defer src="/static/js/map\.js\?v=')
|
# TypeScript 重写后:四个脚本合成一个 esbuild IIFE 包
|
||||||
|
self.assertRegex(html, r'<script defer src="/static/dist/app\.js\?v=')
|
||||||
|
|
||||||
def test_changing_a_dependency_invalidates_the_whole_bundle_version(self):
|
def test_changing_a_dependency_invalidates_the_whole_bundle_version(self):
|
||||||
with tempfile.TemporaryDirectory() as folder:
|
with tempfile.TemporaryDirectory() as folder:
|
||||||
@@ -42,7 +43,7 @@ class MapAssetTests(unittest.TestCase):
|
|||||||
before = self.app.test_client().get("/").get_data(as_text=True)
|
before = self.app.test_client().get("/").get_data(as_text=True)
|
||||||
dependency.write_text("new", encoding="utf-8")
|
dependency.write_text("new", encoding="utf-8")
|
||||||
after = self.app.test_client().get("/").get_data(as_text=True)
|
after = self.app.test_client().get("/").get_data(as_text=True)
|
||||||
pattern = r'/static/js/map\.js\?v=([a-f0-9]+)'
|
pattern = r'/static/dist/app\.js\?v=([a-f0-9]+)'
|
||||||
self.assertNotEqual(re.search(pattern, before)[1], re.search(pattern, after)[1])
|
self.assertNotEqual(re.search(pattern, before)[1], re.search(pattern, after)[1])
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -63,19 +63,18 @@ class SharedMapCacheTests(unittest.TestCase):
|
|||||||
self.assertEqual(1, len(calls))
|
self.assertEqual(1, len(calls))
|
||||||
self.assertTrue(all(result == results[0] for result in results))
|
self.assertTrue(all(result == results[0] for result in results))
|
||||||
|
|
||||||
def test_errors_share_the_window_and_never_resurrect_expired_success(self):
|
def test_failure_keeps_last_good_snapshot_instead_of_blanking_the_map(self):
|
||||||
|
"""采集失败不覆盖上一份好数据:一次抖动不该让全站地图空白 60 秒。"""
|
||||||
loader = Mock(side_effect=[success(1), {"rtn_code": -1, "message": "offline"}, success(2)])
|
loader = Mock(side_effect=[success(1), {"rtn_code": -1, "message": "offline"}, success(2)])
|
||||||
self.cache.get("3", loader)
|
first = self.cache.get("3", loader)
|
||||||
|
self.assertEqual(1, first["data"]["bicycleStation"][0]["version"])
|
||||||
self.now = 1060
|
self.now = 1060
|
||||||
failure = self.cache.get("3", loader)
|
failure = self.cache.get("3", loader)
|
||||||
self.assertEqual(-1, failure["rtn_code"])
|
self.assertEqual(0, failure["rtn_code"]) # 仍是好数据
|
||||||
self.assertNotIn("data", failure)
|
self.assertEqual(1, failure["data"]["bicycleStation"][0]["version"])
|
||||||
self.assertEqual("error", failure["map_snapshot"]["status"])
|
for _ in range(10): # 窗口内返回值稳定
|
||||||
self.assertEqual(1000, failure["map_snapshot"]["fetched_at"])
|
|
||||||
for _ in range(10):
|
|
||||||
self.assertEqual(failure, self.cache.get("3", loader))
|
self.assertEqual(failure, self.cache.get("3", loader))
|
||||||
self.assertEqual(2, loader.call_count)
|
self.assertEqual(2, loader.call_count) # 失败也占住窗口,不打重试风暴
|
||||||
self.assertEqual("stale", self.cache.freshness()["status"])
|
|
||||||
self.now = 1120
|
self.now = 1120
|
||||||
self.assertEqual(2, self.cache.get("3", loader)["data"]["bicycleStation"][0]["version"])
|
self.assertEqual(2, self.cache.get("3", loader)["data"]["bicycleStation"][0]["version"])
|
||||||
|
|
||||||
|
|||||||
@@ -40,17 +40,20 @@ class OrderControlTests(unittest.TestCase):
|
|||||||
})
|
})
|
||||||
|
|
||||||
self.assertEqual(0, response.get_json()["rtn_code"])
|
self.assertEqual(0, response.get_json()["rtn_code"])
|
||||||
|
# 浏览器上报的是 WGS84,入口会先转成 GCJ02 再发给上游(实测上游只认 GCJ02)
|
||||||
|
exp_lat, exp_lng = rental.to_upstream_coords(36.671, 116.981)
|
||||||
|
self.assertFalse(exp_lng == 116.981) # 确实转过
|
||||||
self.assertEqual([
|
self.assertEqual([
|
||||||
((7, "POST", "/record/checkLocation"), {
|
((7, "POST", "/record/checkLocation"), {
|
||||||
"data": {"longitude": 116.981, "latitude": 36.671,
|
"data": {"longitude": exp_lng, "latitude": exp_lat,
|
||||||
"bicycleCode": "50001"}
|
"bicycleCode": "50001"}
|
||||||
}),
|
}),
|
||||||
((7, "POST", "/project/coordinate"), {
|
((7, "POST", "/project/coordinate"), {
|
||||||
"data": {"order_id": "9001", "code": "50001"}
|
"data": {"order_id": "9001", "code": "50001"}
|
||||||
}),
|
}),
|
||||||
((7, "POST", "/record/close"), {
|
((7, "POST", "/record/close"), {
|
||||||
"data": {"order_id": "9001", "end_longitude": 116.981,
|
"data": {"order_id": "9001", "end_longitude": exp_lng,
|
||||||
"end_latitude": 36.671}
|
"end_latitude": exp_lat}
|
||||||
}),
|
}),
|
||||||
], [(call.args, call.kwargs) for call in upstream.call_args_list])
|
], [(call.args, call.kwargs) for call in upstream.call_args_list])
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,11 @@ const assert = require('node:assert/strict');
|
|||||||
const fs = require('node:fs');
|
const fs = require('node:fs');
|
||||||
const path = require('node:path');
|
const path = require('node:path');
|
||||||
const vm = require('node:vm');
|
const vm = require('node:vm');
|
||||||
const source = fs.readFileSync(path.join(__dirname, '../static/js/map.js'), 'utf8');
|
// map.js 已拆分为多个模块(navigation/share/subscribe/map),按 HTML 里的顺序加载
|
||||||
|
const MODULES = ['navigation.js', 'share.js', 'subscribe.js', 'map.js'];
|
||||||
|
const source = MODULES.map(name =>
|
||||||
|
fs.readFileSync(path.join(__dirname, '../static/js', name), 'utf8')
|
||||||
|
).join('\n;\n');
|
||||||
|
|
||||||
async function environment({ dependencies = true } = {}) {
|
async function environment({ dependencies = true } = {}) {
|
||||||
const elements = new Map(), requests = [], notices = [], events = {};
|
const elements = new Map(), requests = [], notices = [], events = {};
|
||||||
@@ -162,3 +166,56 @@ test('countdown accounts for background throttling instead of decrementing only
|
|||||||
assert.equal(e.element('order-countdown').textContent, '本轮剩余 9:55');
|
assert.equal(e.element('order-countdown').textContent, '本轮剩余 9:55');
|
||||||
assert.match(e.element('order-final-time').textContent, /第 1\/1 轮/);
|
assert.match(e.element('order-final-time').textContent, /第 1\/1 轮/);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// 回归:拆分模块时曾把「寻车 / 丢失模式 / 车牌查询」整段定义切走,
|
||||||
|
// 只剩调用处 → 点按钮直接 ReferenceError。这里钉住关键入口必须存在。
|
||||||
|
test('find-bike, plate lookup and lost-mode entry points are all defined', async () => {
|
||||||
|
const e = await environment();
|
||||||
|
const must = ['findBike', '_doFindBikeRequest', 'scanCode',
|
||||||
|
'showLostModal', 'closeLostModal', 'enableLostMode', 'disableLostMode',
|
||||||
|
'_onPageUnload', '_onVisibilityChange', 'findCurrentOrderBike'];
|
||||||
|
const missing = must.filter(name => vm.runInContext(`typeof ${name}`, e.context) !== 'function');
|
||||||
|
assert.deepEqual(missing, []);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 回归:寻车必须真的打到 /api/find_bike,而不是被 try/catch 吞掉
|
||||||
|
test('findBike posts to the find_bike endpoint and reports success', async () => {
|
||||||
|
const e = await environment();
|
||||||
|
const calls = [];
|
||||||
|
e.context.fetch = async (url, options) => {
|
||||||
|
calls.push({ url: String(url), options });
|
||||||
|
return { json: async () => ({ rtn_code: 0 }) };
|
||||||
|
};
|
||||||
|
vm.runInContext(`selectedBike = { code: '51241' }; _findClickCount = 0; findBike();`, e.context);
|
||||||
|
await new Promise(resolve => setImmediate(resolve));
|
||||||
|
assert.equal(calls.length, 1);
|
||||||
|
assert.match(calls[0].url, /\/api\/find_bike/);
|
||||||
|
assert.match(JSON.stringify(calls[0].options.body), /51241/);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 回归:自己账号开锁成功时,closeUnlockConfirm 会清空 unlockPendingCode,
|
||||||
|
// 本地 activeRental / localStorage 绝不能把车牌写成 null。
|
||||||
|
test('self unlock keeps the bike code after the confirm dialog clears the pending code', async () => {
|
||||||
|
const e = await environment();
|
||||||
|
const store = {};
|
||||||
|
e.context.localStorage.setItem = (key, value) => { store[key] = value; };
|
||||||
|
e.context.fetch = async (url) => {
|
||||||
|
if (url === '/api/order/unlock') {
|
||||||
|
return { json: async () => ({ rtn_code: 0, order_id: '9001',
|
||||||
|
data: { remaining: 1140, end_time: '2026-01-01 00:19:00' } }) };
|
||||||
|
}
|
||||||
|
return { json: async () => ({ rtn_code: 0, data: {} }) };
|
||||||
|
};
|
||||||
|
vm.runInContext(`
|
||||||
|
unlockPendingCode = '51241';
|
||||||
|
unlockPendingPosition = { lat: 36.5, lng: 116.7 };
|
||||||
|
unlockChoice = { mode: 'self' };
|
||||||
|
`, e.context);
|
||||||
|
|
||||||
|
await vm.runInContext('doUnlockBike()', e.context);
|
||||||
|
|
||||||
|
// closeUnlockConfirm 已经执行过,全局变量确实被清空了
|
||||||
|
assert.equal(vm.runInContext('unlockPendingCode', e.context), null);
|
||||||
|
const stored = JSON.parse(store.xbniu_rental_key || '{}');
|
||||||
|
assert.equal(stored.bike_code, '51241');
|
||||||
|
});
|
||||||
|
|||||||
+405
-13
@@ -1,6 +1,9 @@
|
|||||||
import sqlite3
|
import sqlite3
|
||||||
import tempfile
|
import tempfile
|
||||||
import unittest
|
import unittest
|
||||||
|
import os
|
||||||
|
|
||||||
|
os.environ["XBCR_DISABLE_LEASES"] = "1" # 单测不参与跨进程租约
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
|
|
||||||
@@ -145,6 +148,7 @@ class OrderSyncTests(unittest.TestCase):
|
|||||||
with patch.object(timer, "get_db", self._get_db), \
|
with patch.object(timer, "get_db", self._get_db), \
|
||||||
patch.object(timer, "get_user_auth", return_value=("token", "access")), \
|
patch.object(timer, "get_user_auth", return_value=("token", "access")), \
|
||||||
patch.object(timer, "get_user_rental_settings", return_value=settings), \
|
patch.object(timer, "get_user_rental_settings", return_value=settings), \
|
||||||
|
patch.object(timer, "_park_areas_for_user", return_value=[]), \
|
||||||
patch.object(timer, "request_with_user_auth", side_effect=responses), \
|
patch.object(timer, "request_with_user_auth", side_effect=responses), \
|
||||||
patch.object(timer, "start_rental_timer"):
|
patch.object(timer, "start_rental_timer"):
|
||||||
result = timer._check_user_order(7)
|
result = timer._check_user_order(7)
|
||||||
@@ -167,6 +171,7 @@ class OrderSyncTests(unittest.TestCase):
|
|||||||
{"rtn_code": 500, "message": "return rejected"},
|
{"rtn_code": 500, "message": "return rejected"},
|
||||||
]
|
]
|
||||||
with patch.object(timer, "get_db", self._get_db), \
|
with patch.object(timer, "get_db", self._get_db), \
|
||||||
|
patch.object(timer, "_park_areas_for_user", return_value=[]), \
|
||||||
patch.object(timer, "request_with_user_auth", side_effect=responses), \
|
patch.object(timer, "request_with_user_auth", side_effect=responses), \
|
||||||
patch.object(timer._time, "sleep"), \
|
patch.object(timer._time, "sleep"), \
|
||||||
patch.object(timer, "_cancel_rental_timers") as cancel, \
|
patch.object(timer, "_cancel_rental_timers") as cancel, \
|
||||||
@@ -184,6 +189,7 @@ class OrderSyncTests(unittest.TestCase):
|
|||||||
{"rtn_code": 0, "message": "ok"},
|
{"rtn_code": 0, "message": "ok"},
|
||||||
]
|
]
|
||||||
with patch.object(timer, "get_db", self._get_db), \
|
with patch.object(timer, "get_db", self._get_db), \
|
||||||
|
patch.object(timer, "_park_areas_for_user", return_value=[]), \
|
||||||
patch.object(timer, "request_with_user_auth", side_effect=responses), \
|
patch.object(timer, "request_with_user_auth", side_effect=responses), \
|
||||||
patch.object(timer, "_try_card_pay_auto", return_value={"success": True}), \
|
patch.object(timer, "_try_card_pay_auto", return_value={"success": True}), \
|
||||||
patch.object(timer, "_cancel_rental_timers") as cancel, \
|
patch.object(timer, "_cancel_rental_timers") as cancel, \
|
||||||
@@ -206,6 +212,7 @@ class OrderSyncTests(unittest.TestCase):
|
|||||||
"rental_rounds": 2, "protect_card": True,
|
"rental_rounds": 2, "protect_card": True,
|
||||||
}
|
}
|
||||||
with patch.object(timer, "get_db", self._get_db), \
|
with patch.object(timer, "get_db", self._get_db), \
|
||||||
|
patch.object(timer, "_park_areas_for_user", return_value=[]), \
|
||||||
patch.object(timer, "request_with_user_auth", side_effect=responses), \
|
patch.object(timer, "request_with_user_auth", side_effect=responses), \
|
||||||
patch.object(timer, "get_user_rental_settings", return_value=settings), \
|
patch.object(timer, "get_user_rental_settings", return_value=settings), \
|
||||||
patch.object(timer, "_try_card_pay_auto", return_value={"success": True, "message": "月卡支付成功"}), \
|
patch.object(timer, "_try_card_pay_auto", return_value={"success": True, "message": "月卡支付成功"}), \
|
||||||
@@ -240,6 +247,7 @@ class OrderSyncTests(unittest.TestCase):
|
|||||||
"rental_rounds": 2, "protect_card": True,
|
"rental_rounds": 2, "protect_card": True,
|
||||||
}
|
}
|
||||||
with patch.object(timer, "get_db", self._get_db), \
|
with patch.object(timer, "get_db", self._get_db), \
|
||||||
|
patch.object(timer, "_park_areas_for_user", return_value=[]), \
|
||||||
patch.object(timer, "request_with_user_auth", side_effect=responses), \
|
patch.object(timer, "request_with_user_auth", side_effect=responses), \
|
||||||
patch.object(timer, "get_user_rental_settings", return_value=settings), \
|
patch.object(timer, "get_user_rental_settings", return_value=settings), \
|
||||||
patch.object(timer, "_try_card_pay_auto", return_value={"success": True}), \
|
patch.object(timer, "_try_card_pay_auto", return_value={"success": True}), \
|
||||||
@@ -424,17 +432,25 @@ class OrderSyncTests(unittest.TestCase):
|
|||||||
app.secret_key = "test"
|
app.secret_key = "test"
|
||||||
app.register_blueprint(rental_routes.bp)
|
app.register_blueprint(rental_routes.bp)
|
||||||
client = app.test_client()
|
client = app.test_client()
|
||||||
responses = [
|
|
||||||
{"rtn_code": 0, "parkNoShow": False},
|
# 新版还车链路:先发用户坐标,失败才换候选点重试(不再有 checkLocation 预检)。
|
||||||
{"rtn_code": -1, "message": "response timeout"},
|
# 这里让 /record/return 一直超时,靠订单状态确认判成功。
|
||||||
{"rtn_code": 0, "data": {"nonDealOrder": None}},
|
calls = []
|
||||||
]
|
|
||||||
|
def fake_auth(user_id, method, path, **kwargs):
|
||||||
|
calls.append(path)
|
||||||
|
if path == "/record/return":
|
||||||
|
return {"rtn_code": -1, "message": "response timeout"}
|
||||||
|
if path == "/user/info":
|
||||||
|
return {"rtn_code": 0, "data": {"nonDealOrder": None}}
|
||||||
|
return {"rtn_code": 0, "data": {}}
|
||||||
|
|
||||||
with patch.object(rental_routes, "get_db", self._get_db), \
|
with patch.object(rental_routes, "get_db", self._get_db), \
|
||||||
patch.object(rental_routes, "get_current_user", return_value={
|
patch.object(rental_routes, "get_current_user", return_value={
|
||||||
"id": 7, "email": "rider@example.test"
|
"id": 7, "email": "rider@example.test"
|
||||||
}), \
|
}), \
|
||||||
patch.object(rental_routes, "get_user_display_name", return_value="骑行人"), \
|
patch.object(rental_routes, "get_user_display_name", return_value="骑行人"), \
|
||||||
patch.object(rental_routes, "request_with_user_auth", side_effect=responses), \
|
patch.object(rental_routes, "request_with_user_auth", side_effect=fake_auth), \
|
||||||
patch.object(rental_routes, "_try_card_pay_auto", return_value={}), \
|
patch.object(rental_routes, "_try_card_pay_auto", return_value={}), \
|
||||||
patch.object(rental_routes, "_cancel_rental_timers"):
|
patch.object(rental_routes, "_cancel_rental_timers"):
|
||||||
response = client.post("/api/order/return", json={
|
response = client.post("/api/order/return", json={
|
||||||
@@ -445,6 +461,8 @@ class OrderSyncTests(unittest.TestCase):
|
|||||||
self.assertEqual(0, data["rtn_code"])
|
self.assertEqual(0, data["rtn_code"])
|
||||||
self.assertIn("订单状态确认", data["message"])
|
self.assertIn("订单状态确认", data["message"])
|
||||||
self.assertEqual(1, self._expired(101))
|
self.assertEqual(1, self._expired(101))
|
||||||
|
self.assertNotIn("/record/checkLocation", calls) # 位置不再当准入条件
|
||||||
|
self.assertGreaterEqual(calls.count("/record/return"), 1)
|
||||||
|
|
||||||
def test_manual_timer_finish_requires_owner_and_rejects_real_orders(self):
|
def test_manual_timer_finish_requires_owner_and_rejects_real_orders(self):
|
||||||
app = Flask(__name__)
|
app = Flask(__name__)
|
||||||
@@ -474,23 +492,27 @@ class OrderSyncTests(unittest.TestCase):
|
|||||||
active = {"rtn_code": 0, "data": {"nonDealOrder": {
|
active = {"rtn_code": 0, "data": {"nonDealOrder": {
|
||||||
"order_id": "9001", "status": 2
|
"order_id": "9001", "status": 2
|
||||||
}}}
|
}}}
|
||||||
responses = [
|
|
||||||
{"rtn_code": 0, "parkNoShow": False},
|
# 所有候选点都被上游拒绝,且订单状态一直是骑行中 → 保持 active,不能假装成功
|
||||||
{"rtn_code": 500, "message": "return rejected"},
|
def fake_auth(user_id, method, path, **kwargs):
|
||||||
active, active, active, active,
|
if path == "/record/return":
|
||||||
]
|
return {"rtn_code": 500, "message": "return rejected"}
|
||||||
|
if path == "/user/info":
|
||||||
|
return active
|
||||||
|
return {"rtn_code": 0, "data": {}}
|
||||||
|
|
||||||
with patch.object(rental_routes, "get_db", self._get_db), \
|
with patch.object(rental_routes, "get_db", self._get_db), \
|
||||||
patch.object(rental_routes, "get_current_user", return_value={
|
patch.object(rental_routes, "get_current_user", return_value={
|
||||||
"id": 7, "email": "rider@example.test"
|
"id": 7, "email": "rider@example.test"
|
||||||
}), \
|
}), \
|
||||||
patch.object(rental_routes, "get_user_display_name", return_value="骑行人"), \
|
patch.object(rental_routes, "get_user_display_name", return_value="骑行人"), \
|
||||||
patch.object(rental_routes, "request_with_user_auth", side_effect=responses), \
|
patch.object(rental_routes, "request_with_user_auth", side_effect=fake_auth), \
|
||||||
patch.object(rental_routes.time, "sleep"):
|
patch.object(rental_routes.time, "sleep"):
|
||||||
response = client.post("/api/order/return", json={
|
response = client.post("/api/order/return", json={
|
||||||
"order_id": "9001", "code": "50001",
|
"order_id": "9001", "code": "50001",
|
||||||
"latitude": 36.67, "longitude": 116.98,
|
"latitude": 36.67, "longitude": 116.98,
|
||||||
})
|
})
|
||||||
self.assertEqual(500, response.get_json()["rtn_code"])
|
self.assertNotEqual(0, response.get_json()["rtn_code"])
|
||||||
self.assertEqual(0, self._expired(101))
|
self.assertEqual(0, self._expired(101))
|
||||||
|
|
||||||
def test_silent_zero_minute_event_runs_auto_return_without_email(self):
|
def test_silent_zero_minute_event_runs_auto_return_without_email(self):
|
||||||
@@ -516,6 +538,376 @@ class OrderSyncTests(unittest.TestCase):
|
|||||||
auto_return.assert_called_once_with(101, 7)
|
auto_return.assert_called_once_with(101, 7)
|
||||||
notify.assert_not_called()
|
notify.assert_not_called()
|
||||||
|
|
||||||
|
def test_auto_return_failure_keeps_notified_zero_and_schedules_retry(self):
|
||||||
|
"""上游还车失败时不能把 notified_0 置位,否则这一单再也不会重试。"""
|
||||||
|
class ImmediateTimer:
|
||||||
|
def __init__(self, delay, callback):
|
||||||
|
self.callback = callback
|
||||||
|
def start(self):
|
||||||
|
self.callback()
|
||||||
|
def cancel(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
with patch.object(timer, "get_db", self._get_db), \
|
||||||
|
patch.object(timer.threading, "Timer", ImmediateTimer), \
|
||||||
|
patch.object(timer, "auto_return_bike", return_value={
|
||||||
|
"attempted": True, "success": False, "message": "upstream boom"
|
||||||
|
}), \
|
||||||
|
patch.object(timer, "_schedule_reminder") as reschedule, \
|
||||||
|
patch.object(timer, "send_rental_notification"):
|
||||||
|
timer._schedule_reminder(
|
||||||
|
101, 0, "0", "rider@example.test", "50001", 7,
|
||||||
|
send_notification=False, auto_return_enabled=True,
|
||||||
|
auto_return_configured=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
conn = self._get_db()
|
||||||
|
row = conn.execute("SELECT notified_0 FROM rentals WHERE id = 101").fetchone()
|
||||||
|
conn.close()
|
||||||
|
self.assertEqual(0, row["notified_0"]) # 保持未置位
|
||||||
|
reschedule.assert_called_once()
|
||||||
|
self.assertEqual("0", reschedule.call_args.args[2]) # 安排了短周期重试
|
||||||
|
self.assertEqual(0, self._expired(101))
|
||||||
|
|
||||||
|
def test_restart_recovers_rental_that_expired_while_process_was_down(self):
|
||||||
|
"""重启时 end_time 已过:必须补一次自动还车,而不是当它不存在。"""
|
||||||
|
class ImmediateThread:
|
||||||
|
def __init__(self, target=None, args=(), **kwargs):
|
||||||
|
self.target, self.args = target, args
|
||||||
|
def start(self):
|
||||||
|
if self.target:
|
||||||
|
self.target(*self.args)
|
||||||
|
|
||||||
|
conn = self._get_db()
|
||||||
|
conn.execute("""
|
||||||
|
INSERT INTO rentals
|
||||||
|
(id, order_id, user_id, source, expired, start_time, end_time, bike_code, email)
|
||||||
|
VALUES (104, '9004', 7, 'unlock', 0, '2026-01-01 09:00:00',
|
||||||
|
'2026-01-01 09:19:00', '50004', 'rider@example.test')
|
||||||
|
""")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
with patch.object(timer, "get_db", self._get_db), \
|
||||||
|
patch.object(timer.threading, "Thread", ImmediateThread), \
|
||||||
|
patch.object(timer, "_time") as fake_time, \
|
||||||
|
patch.object(timer, "auto_return_bike", return_value={
|
||||||
|
"success": True, "message": "ok"
|
||||||
|
}) as auto_return, \
|
||||||
|
patch.object(timer, "start_rental_timer"):
|
||||||
|
fake_time.sleep = lambda *_: None
|
||||||
|
timer.restore_active_timers()
|
||||||
|
|
||||||
|
auto_return.assert_called_once()
|
||||||
|
self.assertEqual(104, auto_return.call_args.args[0])
|
||||||
|
|
||||||
|
def test_checker_recovers_rental_past_end_time_instead_of_returning(self):
|
||||||
|
"""巡检看到 expired=0 但 end_time 已过:补还车,不能直接 return。"""
|
||||||
|
class ImmediateThread:
|
||||||
|
def __init__(self, target=None, args=(), **kwargs):
|
||||||
|
self.target, self.args = target, args
|
||||||
|
def start(self):
|
||||||
|
if self.target:
|
||||||
|
self.target(*self.args)
|
||||||
|
|
||||||
|
conn = self._get_db()
|
||||||
|
conn.execute("""
|
||||||
|
INSERT INTO rentals
|
||||||
|
(id, order_id, user_id, source, expired, start_time, end_time, bike_code, email)
|
||||||
|
VALUES (105, '9005', 7, 'unlock', 0, '2026-01-01 09:00:00',
|
||||||
|
'2026-01-01 09:19:00', '50005', 'rider@example.test')
|
||||||
|
""")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
active = {"rtn_code": 0, "data": {"nonDealOrder": {
|
||||||
|
"order_id": "9005", "status": 2, "code": "50005"
|
||||||
|
}}}
|
||||||
|
with patch.object(timer, "get_db", self._get_db), \
|
||||||
|
patch.object(timer, "get_user_auth", return_value=("token", "access")), \
|
||||||
|
patch.object(timer, "threading", wraps=timer.threading), \
|
||||||
|
patch.object(timer.threading, "Thread", ImmediateThread), \
|
||||||
|
patch.object(timer, "sweep_overdue_rentals", return_value=0), \
|
||||||
|
patch.object(timer, "request_with_user_auth", return_value=active), \
|
||||||
|
patch.object(timer, "auto_return_bike", return_value={
|
||||||
|
"success": True, "message": "ok"
|
||||||
|
}) as auto_return:
|
||||||
|
result = timer._check_user_order(7)
|
||||||
|
|
||||||
|
self.assertTrue(result.get("recovered"))
|
||||||
|
auto_return.assert_called_once()
|
||||||
|
self.assertEqual(105, auto_return.call_args.args[0])
|
||||||
|
|
||||||
|
def test_restart_skips_reminder_rows_but_recovers_subscribe_rows(self):
|
||||||
|
"""reminder 没有上游订单号,补还车只会白打三次上游;subscribe 必须补。"""
|
||||||
|
class ImmediateThread:
|
||||||
|
def __init__(self, target=None, args=(), **kwargs):
|
||||||
|
self.target, self.args = target, args
|
||||||
|
def start(self):
|
||||||
|
if self.target:
|
||||||
|
self.target(*self.args)
|
||||||
|
|
||||||
|
conn = self._get_db()
|
||||||
|
conn.execute("""
|
||||||
|
INSERT INTO rentals
|
||||||
|
(id, order_id, user_id, source, expired, start_time, end_time, bike_code, email)
|
||||||
|
VALUES (106, NULL, 7, 'reminder', 0, '2026-01-01 09:00:00',
|
||||||
|
'2026-01-01 09:19:00', '50006', 'rider@example.test')
|
||||||
|
""")
|
||||||
|
conn.execute("""
|
||||||
|
INSERT INTO rentals
|
||||||
|
(id, order_id, user_id, source, expired, start_time, end_time, bike_code, email)
|
||||||
|
VALUES (107, '9007', 7, 'subscribe', 0, '2026-01-01 09:00:00',
|
||||||
|
'2026-01-01 09:19:00', '50007', 'rider@example.test')
|
||||||
|
""")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
with patch.object(timer, "get_db", self._get_db), \
|
||||||
|
patch.object(timer.threading, "Thread", ImmediateThread), \
|
||||||
|
patch.object(timer, "_time") as fake_time, \
|
||||||
|
patch.object(timer, "auto_return_bike", return_value={
|
||||||
|
"success": True, "message": "ok"
|
||||||
|
}) as auto_return, \
|
||||||
|
patch.object(timer, "start_rental_timer"):
|
||||||
|
fake_time.sleep = lambda *_: None
|
||||||
|
timer.restore_active_timers()
|
||||||
|
|
||||||
|
recovered_ids = [c.args[0] for c in auto_return.call_args_list]
|
||||||
|
self.assertIn(107, recovered_ids) # subscribe 要补
|
||||||
|
self.assertNotIn(106, recovered_ids) # reminder 不补
|
||||||
|
|
||||||
|
def test_return_succeeds_even_when_local_write_fails(self):
|
||||||
|
"""上游还车成功、本地写库抛异常:不能报「还车失败」(否则用户会再点一次撞 204010)。"""
|
||||||
|
app = Flask(__name__)
|
||||||
|
app.secret_key = "test"
|
||||||
|
app.register_blueprint(rental_routes.bp)
|
||||||
|
client = app.test_client()
|
||||||
|
|
||||||
|
def fake_auth(user_id, method, path, **kwargs):
|
||||||
|
if path == "/record/return":
|
||||||
|
return {"rtn_code": 0, "message": "ok"}
|
||||||
|
return {"rtn_code": 0, "data": {}}
|
||||||
|
|
||||||
|
with patch.object(rental_routes, "get_db", self._get_db), \
|
||||||
|
patch.object(rental_routes, "get_current_user", return_value={
|
||||||
|
"id": 7, "email": "rider@example.test"}), \
|
||||||
|
patch.object(rental_routes, "get_user_display_name", return_value="骑行人"), \
|
||||||
|
patch.object(rental_routes, "request_with_user_auth", side_effect=fake_auth), \
|
||||||
|
patch.object(rental_routes, "_record_rental_end",
|
||||||
|
side_effect=RuntimeError("database is locked")), \
|
||||||
|
patch.object(rental_routes, "_record_raw_coords",
|
||||||
|
side_effect=RuntimeError("database is locked")), \
|
||||||
|
patch.object(rental_routes, "_try_card_pay_auto", return_value={}), \
|
||||||
|
patch.object(rental_routes, "_cancel_rental_timers"):
|
||||||
|
resp = client.post("/api/order/return", json={
|
||||||
|
"order_id": "9001", "code": "50001",
|
||||||
|
"latitude": 36.67, "longitude": 116.98,
|
||||||
|
})
|
||||||
|
|
||||||
|
body = resp.get_json()
|
||||||
|
self.assertEqual(0, body["rtn_code"])
|
||||||
|
self.assertFalse(body["local_synced"])
|
||||||
|
self.assertIn("本地记录稍后同步", body["message"])
|
||||||
|
|
||||||
|
def test_retry_success_sends_final_notice(self):
|
||||||
|
"""重试后终于还上,要再发一封收尾,别让用户去点旧邮件里的还车按钮。"""
|
||||||
|
class ImmediateTimer:
|
||||||
|
def __init__(self, delay, callback):
|
||||||
|
self.callback = callback
|
||||||
|
def start(self):
|
||||||
|
self.callback()
|
||||||
|
def cancel(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
timer._auto_return_retries[101] = 2
|
||||||
|
try:
|
||||||
|
with patch.object(timer, "get_db", self._get_db), \
|
||||||
|
patch.object(timer.threading, "Timer", ImmediateTimer), \
|
||||||
|
patch.object(timer, "auto_return_bike", return_value={
|
||||||
|
"attempted": True, "success": True, "message": "ok"
|
||||||
|
}), \
|
||||||
|
patch.object(timer, "_notify_auto_return_recovered") as recovered, \
|
||||||
|
patch.object(timer, "send_rental_notification"):
|
||||||
|
timer._schedule_reminder(
|
||||||
|
101, 0, "0", "rider@example.test", "50001", 7,
|
||||||
|
send_notification=False, auto_return_enabled=True,
|
||||||
|
auto_return_configured=True,
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
timer._auto_return_retries.pop(101, None)
|
||||||
|
|
||||||
|
recovered.assert_called_once_with(101)
|
||||||
|
|
||||||
|
def test_retry_exhausted_alerts_admin_instead_of_silent_print(self):
|
||||||
|
timer._auto_return_retries[101] = timer.AUTO_RETURN_MAX_RETRIES
|
||||||
|
try:
|
||||||
|
with patch.object(timer, "_alert_auto_return_exhausted") as alert:
|
||||||
|
timer._schedule_auto_return_retry(101, "rider@example.test", "50001",
|
||||||
|
7, "upstream boom")
|
||||||
|
finally:
|
||||||
|
timer._auto_return_retries.pop(101, None)
|
||||||
|
alert.assert_called_once()
|
||||||
|
|
||||||
|
def test_checker_throttles_repeated_recovery_attempts(self):
|
||||||
|
"""彻底还不上时,巡检不能每分钟重打上游(5 分钟一次)。"""
|
||||||
|
class ImmediateThread:
|
||||||
|
def __init__(self, target=None, args=(), **kwargs):
|
||||||
|
self.target, self.args = target, args
|
||||||
|
def start(self):
|
||||||
|
if self.target:
|
||||||
|
self.target(*self.args)
|
||||||
|
|
||||||
|
conn = self._get_db()
|
||||||
|
conn.execute("""
|
||||||
|
INSERT INTO rentals
|
||||||
|
(id, order_id, user_id, source, expired, start_time, end_time, bike_code, email)
|
||||||
|
VALUES (108, '9008', 7, 'unlock', 0, '2026-01-01 09:00:00',
|
||||||
|
'2026-01-01 09:19:00', '50008', 'rider@example.test')
|
||||||
|
""")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
active = {"rtn_code": 0, "data": {"nonDealOrder": {
|
||||||
|
"order_id": "9008", "status": 2, "code": "50008"
|
||||||
|
}}}
|
||||||
|
timer._recover_last_at.clear()
|
||||||
|
try:
|
||||||
|
with patch.object(timer, "get_db", self._get_db), \
|
||||||
|
patch.object(timer, "get_user_auth", return_value=("token", "access")), \
|
||||||
|
patch.object(timer.threading, "Thread", ImmediateThread), \
|
||||||
|
patch.object(timer, "sweep_overdue_rentals", return_value=0), \
|
||||||
|
patch.object(timer, "request_with_user_auth", return_value=active), \
|
||||||
|
patch.object(timer, "auto_return_bike", return_value={
|
||||||
|
"success": False, "message": "boom"
|
||||||
|
}) as auto_return:
|
||||||
|
first = timer._check_user_order(7)
|
||||||
|
second = timer._check_user_order(7)
|
||||||
|
finally:
|
||||||
|
timer._recover_last_at.clear()
|
||||||
|
|
||||||
|
self.assertTrue(first.get("recovered"))
|
||||||
|
self.assertTrue(second.get("recovering")) # 第二次被节流
|
||||||
|
self.assertEqual(1, auto_return.call_count) # 只补了一次
|
||||||
|
|
||||||
|
def test_recovery_skips_return_when_user_already_returned_in_miniprogram(self):
|
||||||
|
"""用户在小程序里还了车:上游查不到这单 → 只做本地收尾,不再打 /record/return。"""
|
||||||
|
conn = self._get_db()
|
||||||
|
conn.execute("""
|
||||||
|
INSERT INTO rentals
|
||||||
|
(id, order_id, user_id, source, expired, start_time, end_time, bike_code, email)
|
||||||
|
VALUES (120, '9020', 7, 'unlock', 0, '2026-01-01 09:00:00',
|
||||||
|
'2026-01-01 09:19:00', '50020', 'rider@example.test')
|
||||||
|
""")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
with patch.object(timer, "get_db", self._get_db), \
|
||||||
|
patch.object(timer, "_upstream_ride_active", return_value=False), \
|
||||||
|
patch.object(timer, "auto_return_bike") as auto_return:
|
||||||
|
result = timer._run_recovery(120, 7, "9020")
|
||||||
|
|
||||||
|
auto_return.assert_not_called() # 关键:不再制造 204010
|
||||||
|
self.assertTrue(result.get("skipped"))
|
||||||
|
conn = self._get_db()
|
||||||
|
try:
|
||||||
|
row = conn.execute("SELECT expired FROM rentals WHERE id = 120").fetchone()
|
||||||
|
self.assertEqual(1, row["expired"])
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
def test_recovery_still_returns_when_upstream_order_is_active(self):
|
||||||
|
conn = self._get_db()
|
||||||
|
conn.execute("""
|
||||||
|
INSERT INTO rentals
|
||||||
|
(id, order_id, user_id, source, expired, start_time, end_time, bike_code, email)
|
||||||
|
VALUES (121, '9021', 7, 'unlock', 0, '2026-01-01 09:00:00',
|
||||||
|
'2026-01-01 09:19:00', '50021', 'rider@example.test')
|
||||||
|
""")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
with patch.object(timer, "_upstream_ride_active", return_value=True), \
|
||||||
|
patch.object(timer, "auto_return_bike", return_value={
|
||||||
|
"success": True, "message": "ok"
|
||||||
|
}) as auto_return:
|
||||||
|
result = timer._run_recovery(121, 7, "9021")
|
||||||
|
|
||||||
|
auto_return.assert_called_once_with(121, 7)
|
||||||
|
self.assertTrue(result.get("success"))
|
||||||
|
|
||||||
|
def test_sweep_queues_overdue_rentals_and_is_throttled(self):
|
||||||
|
"""兜底扫描:超期未还的单要排队补还车,且 10 分钟内不重复扫。"""
|
||||||
|
class ImmediateThread:
|
||||||
|
def __init__(self, target=None, args=(), **kwargs):
|
||||||
|
self.target, self.args = target, args
|
||||||
|
def start(self):
|
||||||
|
if self.target:
|
||||||
|
self.target(*self.args)
|
||||||
|
|
||||||
|
conn = self._get_db()
|
||||||
|
conn.execute("""
|
||||||
|
INSERT INTO rentals
|
||||||
|
(id, order_id, user_id, source, expired, start_time, end_time, bike_code, email)
|
||||||
|
VALUES (111, '9011', 7, 'unlock', 0, '2026-01-01 09:00:00',
|
||||||
|
'2026-01-01 09:19:00', '50011', 'rider@example.test')
|
||||||
|
""")
|
||||||
|
conn.execute("""
|
||||||
|
INSERT INTO rentals
|
||||||
|
(id, order_id, user_id, source, expired, start_time, end_time, bike_code, email)
|
||||||
|
VALUES (112, NULL, 7, 'reminder', 0, '2026-01-01 09:00:00',
|
||||||
|
'2026-01-01 09:19:00', '50012', 'rider@example.test')
|
||||||
|
""")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
timer._recover_last_at.clear()
|
||||||
|
timer._sweep_last_at[0] = 0
|
||||||
|
try:
|
||||||
|
with patch.object(timer, "get_db", self._get_db), \
|
||||||
|
patch.object(timer.threading, "Thread", ImmediateThread), \
|
||||||
|
patch.object(timer, "auto_return_bike", return_value={
|
||||||
|
"success": True, "message": "ok"
|
||||||
|
}) as auto_return:
|
||||||
|
first = timer.sweep_overdue_rentals(force=True)
|
||||||
|
second = timer.sweep_overdue_rentals() # 10 分钟内不再扫
|
||||||
|
finally:
|
||||||
|
timer._recover_last_at.clear()
|
||||||
|
timer._sweep_last_at[0] = 0
|
||||||
|
|
||||||
|
self.assertEqual(1, first) # 只有 unlock 那单
|
||||||
|
self.assertEqual(0, second) # 被节流
|
||||||
|
recovered_ids = [c.args[0] for c in auto_return.call_args_list]
|
||||||
|
self.assertIn(111, recovered_ids)
|
||||||
|
self.assertNotIn(112, recovered_ids) # reminder 不补
|
||||||
|
|
||||||
|
conn = self._get_db()
|
||||||
|
try:
|
||||||
|
row = conn.execute("SELECT expired FROM rentals WHERE id = 112").fetchone()
|
||||||
|
self.assertEqual(1, row["expired"]) # 本地提醒单就地关闭
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
def test_recovery_success_clears_throttle_record(self):
|
||||||
|
"""补还车成功后要清掉节流记录,别在进程里留失败痕迹。"""
|
||||||
|
timer._recover_last_at[109] = timer._time.time()
|
||||||
|
try:
|
||||||
|
with patch.object(timer, "auto_return_bike", return_value={
|
||||||
|
"success": True, "message": "ok"
|
||||||
|
}):
|
||||||
|
timer._run_recovery(109, 7)
|
||||||
|
self.assertNotIn(109, timer._recover_last_at)
|
||||||
|
|
||||||
|
timer._recover_last_at[110] = timer._time.time()
|
||||||
|
with patch.object(timer, "auto_return_bike", return_value={
|
||||||
|
"success": False, "message": "boom"
|
||||||
|
}):
|
||||||
|
timer._run_recovery(110, 7)
|
||||||
|
self.assertIn(110, timer._recover_last_at) # 失败保留,供节流判断
|
||||||
|
finally:
|
||||||
|
timer._recover_last_at.pop(109, None)
|
||||||
|
timer._recover_last_at.pop(110, None)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|||||||
@@ -0,0 +1,243 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""停车区(parkeArea)判定、还车点吸附与坐标系边界。
|
||||||
|
|
||||||
|
覆盖四件事:
|
||||||
|
1. 坐标转换方向别搞反(浏览器 WGS84 / 上游 GCJ02,只在入口转一次);
|
||||||
|
2. 吸附点必须真的落在多边形内;
|
||||||
|
3. 自动还车「发还车之前」就对齐停车区,而不是让三次重试打同一个错坐标;
|
||||||
|
4. 临时的上游抖动不该把订单挂死。
|
||||||
|
"""
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import campus
|
||||||
|
import park_area
|
||||||
|
import timer
|
||||||
|
from routes import rental
|
||||||
|
|
||||||
|
# 山管院附近一块方形停车区(GCJ02,上游 parkeArea 的坐标系)
|
||||||
|
PARK_SQUARE = [
|
||||||
|
[36.5313, 116.7797],
|
||||||
|
[36.5313, 116.7807],
|
||||||
|
[36.5323, 116.7807],
|
||||||
|
[36.5323, 116.7797],
|
||||||
|
]
|
||||||
|
PARK_AREAS = [{"points": PARK_SQUARE}]
|
||||||
|
|
||||||
|
|
||||||
|
class CoordinateConversionTests(unittest.TestCase):
|
||||||
|
def test_wgs84_to_gcj02_matches_known_offset(self):
|
||||||
|
lng, lat = campus.wgs84_to_gcj02(116.404, 39.915)
|
||||||
|
# 北京一带:GCJ02 相对 WGS84 偏移在 0.004~0.007 度量级
|
||||||
|
self.assertTrue(0.003 < lng - 116.404 < 0.008)
|
||||||
|
self.assertTrue(-0.003 < lat - 39.915 < 0.003)
|
||||||
|
|
||||||
|
def test_roundtrip_is_sub_meter(self):
|
||||||
|
for lat, lng in ((36.5318, 116.7802), (39.915, 116.404), (22.5431, 114.0579)):
|
||||||
|
g_lng, g_lat = campus.wgs84_to_gcj02(lng, lat)
|
||||||
|
back_lng, back_lat = campus.gcj02_to_wgs84(g_lng, g_lat)
|
||||||
|
self.assertLess(campus.haversine_m(lat, lng, back_lat, back_lng), 1.0)
|
||||||
|
|
||||||
|
def test_out_of_china_is_passthrough(self):
|
||||||
|
self.assertEqual([-122.4194, 37.7749], campus.wgs84_to_gcj02(-122.4194, 37.7749))
|
||||||
|
self.assertEqual([-122.4194, 37.7749], campus.gcj02_to_wgs84(-122.4194, 37.7749))
|
||||||
|
|
||||||
|
|
||||||
|
class ParseParkAreaTests(unittest.TestCase):
|
||||||
|
def test_accepts_dict_and_list_points_and_skips_invalid(self):
|
||||||
|
list_area = [[36.53, 116.78], [36.53, 116.79], [36.54, 116.79]]
|
||||||
|
payload = {
|
||||||
|
"parkeArea": [
|
||||||
|
{"points": [{"latitude": 36.53, "longitude": 116.78}] * 3, "is_disable": 1},
|
||||||
|
{"points": list_area, "is_disable": 1},
|
||||||
|
{"points": [[36.53, 116.78], [36.53, 116.79]]}, # 少于 3 点
|
||||||
|
{"points": PARK_SQUARE, "is_disable": 2}, # 停用(实测语义)
|
||||||
|
{"points": []},
|
||||||
|
"not-a-dict",
|
||||||
|
]
|
||||||
|
}
|
||||||
|
areas = park_area.parse_park_areas(payload)
|
||||||
|
self.assertEqual(2, len(areas))
|
||||||
|
self.assertEqual(3, len(areas[0]["points"]))
|
||||||
|
self.assertEqual(list_area, areas[1]["points"])
|
||||||
|
self.assertNotIn(PARK_SQUARE, [a["points"] for a in areas])
|
||||||
|
|
||||||
|
def test_is_disable_1_is_kept_and_2_is_dropped(self):
|
||||||
|
"""语义是实测出来的:1=启用,2=停用。判反等于把所有能还车的区全丢掉。"""
|
||||||
|
payload = {"parkeArea": [
|
||||||
|
{"points": PARK_SQUARE, "is_disable": 1},
|
||||||
|
{"points": PARK_SQUARE, "is_disable": 2},
|
||||||
|
{"points": PARK_SQUARE},
|
||||||
|
]}
|
||||||
|
areas = park_area.parse_park_areas(payload)
|
||||||
|
self.assertEqual(2, len(areas))
|
||||||
|
|
||||||
|
def test_missing_or_malformed_data_returns_empty(self):
|
||||||
|
for payload in (None, {}, {"parkeArea": None}, {"parkeArea": {}}, []):
|
||||||
|
self.assertEqual([], park_area.parse_park_areas(payload))
|
||||||
|
|
||||||
|
|
||||||
|
class ResolveReturnCoordTests(unittest.TestCase):
|
||||||
|
def test_point_already_inside_is_kept_untouched(self):
|
||||||
|
resolved = park_area.resolve_return_coord(36.5318, 116.7802, PARK_AREAS)
|
||||||
|
self.assertIsNotNone(resolved)
|
||||||
|
self.assertTrue(resolved["inside"])
|
||||||
|
self.assertFalse(resolved["moved"])
|
||||||
|
self.assertEqual((36.5318, 116.7802),
|
||||||
|
(resolved["latitude"], resolved["longitude"]))
|
||||||
|
|
||||||
|
def test_outside_point_is_snapped_inside_the_polygon(self):
|
||||||
|
resolved = park_area.resolve_return_coord(36.5250, 116.7700, PARK_AREAS)
|
||||||
|
self.assertIsNotNone(resolved)
|
||||||
|
self.assertTrue(resolved["moved"])
|
||||||
|
self.assertGreater(resolved["distance"], 100)
|
||||||
|
self.assertTrue(campus.point_in_polygon(
|
||||||
|
resolved["latitude"], resolved["longitude"], PARK_SQUARE))
|
||||||
|
|
||||||
|
def test_no_area_returns_none(self):
|
||||||
|
self.assertIsNone(park_area.resolve_return_coord(36.5, 116.7, []))
|
||||||
|
self.assertIsNone(park_area.resolve_return_coord(None, 116.7, PARK_AREAS))
|
||||||
|
|
||||||
|
def test_nearest_of_two_areas_wins(self):
|
||||||
|
east = [[p[0], p[1] + 0.02] for p in PARK_SQUARE]
|
||||||
|
areas = [{"points": PARK_SQUARE}, {"points": east}]
|
||||||
|
resolved = park_area.resolve_return_coord(36.5318, 116.7995, areas)
|
||||||
|
self.assertIsNotNone(resolved)
|
||||||
|
self.assertGreater(resolved["longitude"], 116.7990)
|
||||||
|
|
||||||
|
|
||||||
|
class BoundaryCoordTests(unittest.TestCase):
|
||||||
|
"""入口坐标:浏览器 WGS84 -> 上游 GCJ02,只转一次。"""
|
||||||
|
|
||||||
|
def test_to_upstream_coords_shifts_into_gcj02(self):
|
||||||
|
lat, lng = rental.to_upstream_coords(36.5250, 116.7700)
|
||||||
|
moved = campus.haversine_m(36.5250, 116.7700, lat, lng)
|
||||||
|
self.assertGreater(moved, 100)
|
||||||
|
self.assertLess(moved, 800)
|
||||||
|
back_lng, back_lat = campus.gcj02_to_wgs84(lng, lat)
|
||||||
|
self.assertLess(campus.haversine_m(36.5250, 116.7700, back_lat, back_lng), 1.0)
|
||||||
|
|
||||||
|
def test_to_upstream_coords_tolerates_bad_input(self):
|
||||||
|
self.assertEqual((None, None), rental.to_upstream_coords(None, None))
|
||||||
|
self.assertEqual(("a", "b"), rental.to_upstream_coords("a", "b"))
|
||||||
|
|
||||||
|
|
||||||
|
class OrderLocationTests(unittest.TestCase):
|
||||||
|
def test_upstream_pass_returns_gcj02_not_raw_browser_value(self):
|
||||||
|
with patch.object(rental, "request_with_user_auth",
|
||||||
|
return_value={"rtn_code": 0, "parkNoShow": False}) as upstream:
|
||||||
|
lat, lng, used_nearest = rental._resolve_order_location(
|
||||||
|
7, "50001", 36.5318, 116.7802)
|
||||||
|
self.assertFalse(used_nearest)
|
||||||
|
expected = rental.to_upstream_coords(36.5318, 116.7802)
|
||||||
|
self.assertAlmostEqual(expected[0], lat, places=6)
|
||||||
|
self.assertAlmostEqual(expected[1], lng, places=6)
|
||||||
|
# checkLocation 也必须拿 GCJ02 去问,否则上游按自己坐标系判必偏 500 米
|
||||||
|
sent = upstream.call_args.kwargs["data"]
|
||||||
|
self.assertAlmostEqual(expected[1], sent["longitude"], places=6)
|
||||||
|
self.assertAlmostEqual(expected[0], sent["latitude"], places=6)
|
||||||
|
|
||||||
|
def test_park_no_show_snaps_into_park_area(self):
|
||||||
|
with patch.object(rental, "request_with_user_auth",
|
||||||
|
return_value={"rtn_code": 0, "parkNoShow": True}), \
|
||||||
|
patch.object(rental, "_park_areas", return_value=PARK_AREAS):
|
||||||
|
out_lat, out_lng, used_nearest = rental._resolve_order_location(
|
||||||
|
7, "50001", 36.5250, 116.7700)
|
||||||
|
self.assertTrue(used_nearest)
|
||||||
|
self.assertTrue(campus.point_in_polygon(out_lat, out_lng, PARK_SQUARE))
|
||||||
|
|
||||||
|
def test_get_nearest_park_point_returns_gcj02_from_legacy_bikes(self):
|
||||||
|
station = {"rtn_code": 0, "data": {"bicycleStation": [
|
||||||
|
{"latitude": 36.5318, "longitude": 116.7802}]}}
|
||||||
|
with patch.object(rental, "_park_areas", return_value=[]), \
|
||||||
|
patch.object(rental, "request_api", return_value=station):
|
||||||
|
point = rental.get_nearest_park_point(36.5250, 116.7700)
|
||||||
|
self.assertIsNotNone(point)
|
||||||
|
# 入参/返回同为 GCJ02:不再转换,值应与车点一致
|
||||||
|
self.assertAlmostEqual(36.5318, point["latitude"], places=6)
|
||||||
|
self.assertAlmostEqual(116.7802, point["longitude"], places=6)
|
||||||
|
|
||||||
|
|
||||||
|
class AutoReturnAlignTests(unittest.TestCase):
|
||||||
|
def test_align_moves_outside_point_into_area(self):
|
||||||
|
with patch.object(timer, "_park_areas_for_user", return_value=PARK_AREAS):
|
||||||
|
lat, lng, moved, dist = timer._align_to_park_area(7, 36.5250, 116.7700)
|
||||||
|
self.assertTrue(moved)
|
||||||
|
self.assertGreater(dist, 100)
|
||||||
|
self.assertTrue(campus.point_in_polygon(lat, lng, PARK_SQUARE))
|
||||||
|
|
||||||
|
def test_align_leaves_inside_point_alone(self):
|
||||||
|
with patch.object(timer, "_park_areas_for_user", return_value=PARK_AREAS):
|
||||||
|
lat, lng, moved, _ = timer._align_to_park_area(7, 36.5318, 116.7802)
|
||||||
|
self.assertFalse(moved)
|
||||||
|
self.assertEqual((36.5318, 116.7802), (lat, lng))
|
||||||
|
|
||||||
|
def test_align_without_park_areas_is_noop(self):
|
||||||
|
with patch.object(timer, "_park_areas_for_user", return_value=[]):
|
||||||
|
self.assertEqual(
|
||||||
|
(36.5250, 116.7700, False, 0.0),
|
||||||
|
timer._align_to_park_area(7, 36.5250, 116.7700))
|
||||||
|
|
||||||
|
|
||||||
|
class AutoReturnTests(unittest.TestCase):
|
||||||
|
RENTAL_ROW = {"id": 1, "bike_code": "50001", "order_id": "9001",
|
||||||
|
"expired": 0, "end_time": "2026-01-01 00:00:00"}
|
||||||
|
|
||||||
|
def _run(self, bike_lat, bike_lng, return_results):
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def fake_upstream(user_id, method, path, params=None, data=None, **kwargs):
|
||||||
|
if path == "/project/bicycle":
|
||||||
|
return {"rtn_code": 0,
|
||||||
|
"data": {"latitude": bike_lat, "longitude": bike_lng}}
|
||||||
|
if path == "/record/return":
|
||||||
|
calls.append(dict(data))
|
||||||
|
return return_results[min(len(calls) - 1, len(return_results) - 1)]
|
||||||
|
return {"rtn_code": 0}
|
||||||
|
|
||||||
|
with patch.object(timer, "get_db") as get_db, \
|
||||||
|
patch.object(timer, "request_with_user_auth", side_effect=fake_upstream), \
|
||||||
|
patch.object(timer, "_park_areas_for_user", return_value=PARK_AREAS), \
|
||||||
|
patch.object(timer, "_mark_returned"), \
|
||||||
|
patch.object(timer, "mark_return_tokens_used"), \
|
||||||
|
patch.object(timer, "_cancel_rental_timers"), \
|
||||||
|
patch.object(timer, "_maybe_renew_after_return",
|
||||||
|
return_value={"renewed": False}), \
|
||||||
|
patch.object(timer, "_time") as fake_time:
|
||||||
|
fake_time.sleep = lambda *_: None
|
||||||
|
get_db.return_value.cursor.return_value.fetchone.return_value = dict(self.RENTAL_ROW)
|
||||||
|
result = timer._auto_return_bike(1, 7, allow_renewal=False)
|
||||||
|
return result, calls
|
||||||
|
|
||||||
|
def test_return_goes_to_park_area_on_the_first_try(self):
|
||||||
|
"""车停在区外:发还车之前就对齐,不该让三次重试打同一个错坐标。"""
|
||||||
|
result, calls = self._run(36.5250, 116.7700, [{"rtn_code": 0, "message": "ok"}])
|
||||||
|
self.assertTrue(result["success"])
|
||||||
|
self.assertEqual(1, len(calls))
|
||||||
|
self.assertNotEqual(116.7700, calls[0]["longitude"])
|
||||||
|
self.assertTrue(campus.point_in_polygon(
|
||||||
|
calls[0]["latitude"], calls[0]["longitude"], PARK_SQUARE))
|
||||||
|
|
||||||
|
def test_inside_point_is_sent_as_is_and_transient_failure_retries(self):
|
||||||
|
"""车已在区内:坐标原样发;上游抖动一次后重试成功。"""
|
||||||
|
result, calls = self._run(36.5318, 116.7802, [
|
||||||
|
{"rtn_code": 500, "message": "busy"},
|
||||||
|
{"rtn_code": 0, "message": "ok"},
|
||||||
|
])
|
||||||
|
self.assertTrue(result["success"])
|
||||||
|
self.assertEqual(2, len(calls))
|
||||||
|
for call in calls:
|
||||||
|
self.assertAlmostEqual(116.7802, call["longitude"], places=6)
|
||||||
|
self.assertAlmostEqual(36.5318, call["latitude"], places=6)
|
||||||
|
|
||||||
|
def test_failure_after_inside_point_really_fails_and_keeps_order_open(self):
|
||||||
|
result, calls = self._run(36.5318, 116.7802, [
|
||||||
|
{"rtn_code": 400, "message": "请到指定停车点还车"},
|
||||||
|
])
|
||||||
|
self.assertFalse(result["success"])
|
||||||
|
self.assertEqual(3, len(calls))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""用户口令哈希:pbkdf2 + 旧 sha256 兼容与升级。"""
|
||||||
|
import hashlib
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from routes import auth as auth_routes
|
||||||
|
|
||||||
|
|
||||||
|
class PasswordHashTests(unittest.TestCase):
|
||||||
|
def test_new_hash_is_pbkdf2_and_verifies(self):
|
||||||
|
stored = auth_routes.hash_password("070517zhan")
|
||||||
|
self.assertTrue(stored.startswith("pbkdf2:"))
|
||||||
|
self.assertTrue(auth_routes.verify_password(stored, "070517zhan"))
|
||||||
|
self.assertFalse(auth_routes.verify_password(stored, "070517"))
|
||||||
|
self.assertFalse(auth_routes.password_needs_upgrade(stored))
|
||||||
|
|
||||||
|
def test_legacy_sha256_still_verifies_and_is_marked_for_upgrade(self):
|
||||||
|
legacy = hashlib.sha256("070517zhan".encode()).hexdigest()
|
||||||
|
self.assertTrue(auth_routes.verify_password(legacy, "070517zhan"))
|
||||||
|
self.assertFalse(auth_routes.verify_password(legacy, "wrong"))
|
||||||
|
self.assertTrue(auth_routes.password_needs_upgrade(legacy))
|
||||||
|
|
||||||
|
def test_empty_hash_never_verifies(self):
|
||||||
|
self.assertFalse(auth_routes.verify_password("", "x"))
|
||||||
|
self.assertFalse(auth_routes.verify_password(None, "x"))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -201,7 +201,8 @@ class OrderEndpointsTests(unittest.TestCase):
|
|||||||
self.assertEqual(4, response.get_json()["data"]["total_rounds"])
|
self.assertEqual(4, response.get_json()["data"]["total_rounds"])
|
||||||
# 本轮到期时间与剩余时长保持不变
|
# 本轮到期时间与剩余时长保持不变
|
||||||
self.assertEqual(before["end_time"], after["end_time"])
|
self.assertEqual(before["end_time"], after["end_time"])
|
||||||
self.assertEqual(before["remaining_seconds"], after["remaining_seconds"])
|
# 两次请求之间可能跨秒:剩余秒数允许 2 秒误差(end_time 必须完全相同)
|
||||||
|
self.assertLessEqual(abs(before["remaining_seconds"] - after["remaining_seconds"]), 2)
|
||||||
# 预计还车时间随轮数增加而后移
|
# 预计还车时间随轮数增加而后移
|
||||||
self.assertEqual(4, after["total_rounds"])
|
self.assertEqual(4, after["total_rounds"])
|
||||||
self.assertGreater(after["final_end_time"], before["final_end_time"])
|
self.assertGreater(after["final_end_time"], before["final_end_time"])
|
||||||
|
|||||||
@@ -0,0 +1,186 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""订阅调度与自动开锁的关键回归。
|
||||||
|
|
||||||
|
覆盖两件事:
|
||||||
|
1) 整分钟漏触发后当天要能补(`minute_of_day <= 当前分钟`);
|
||||||
|
2) 开锁失败时必须撤销刚下的半成品订单,避免重试叠加。
|
||||||
|
"""
|
||||||
|
import datetime as dt
|
||||||
|
import sqlite3
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import subscribe
|
||||||
|
|
||||||
|
|
||||||
|
SCHEMA = """
|
||||||
|
CREATE TABLE subscribe_rules (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
user_id INTEGER NOT NULL,
|
||||||
|
location_id INTEGER,
|
||||||
|
weekday INTEGER DEFAULT 0,
|
||||||
|
minute_of_day INTEGER NOT NULL,
|
||||||
|
enabled INTEGER DEFAULT 1,
|
||||||
|
notify_enabled INTEGER DEFAULT 1,
|
||||||
|
auto_unlock INTEGER DEFAULT 0,
|
||||||
|
last_fired_on TEXT DEFAULT '',
|
||||||
|
kinds TEXT DEFAULT 'small,big,red',
|
||||||
|
min_electric INTEGER DEFAULT 0,
|
||||||
|
max_electric INTEGER DEFAULT 100,
|
||||||
|
sort_by TEXT DEFAULT 'electric_desc',
|
||||||
|
retry_times INTEGER DEFAULT 3
|
||||||
|
);
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class ImmediateThread:
|
||||||
|
def __init__(self, target=None, args=(), kwargs=None, **rest):
|
||||||
|
self.target = target
|
||||||
|
self.args = args
|
||||||
|
self.kwargs = kwargs or {}
|
||||||
|
|
||||||
|
def start(self):
|
||||||
|
if self.target:
|
||||||
|
self.target(*self.args, **self.kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
class SubscribeFlowTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.tmp = tempfile.TemporaryDirectory()
|
||||||
|
self.db_path = Path(self.tmp.name) / "sub.db"
|
||||||
|
conn = sqlite3.connect(self.db_path)
|
||||||
|
conn.executescript(SCHEMA)
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
self.tmp.cleanup()
|
||||||
|
|
||||||
|
def _get_db(self):
|
||||||
|
conn = sqlite3.connect(self.db_path)
|
||||||
|
conn.row_factory = sqlite3.Row
|
||||||
|
return conn
|
||||||
|
|
||||||
|
def test_missed_minute_is_caught_up_later_same_day(self):
|
||||||
|
"""7:50 的规则,8:10 才跑到,仍然要发,且当天只发一次。"""
|
||||||
|
now = dt.datetime.now(dt.timezone(dt.timedelta(hours=8)))
|
||||||
|
conn = self._get_db()
|
||||||
|
past_minute = max(0, now.hour * 60 + now.minute - 5)
|
||||||
|
conn.execute("""
|
||||||
|
INSERT INTO subscribe_rules (user_id, location_id, weekday, minute_of_day,
|
||||||
|
enabled, notify_enabled, last_fired_on)
|
||||||
|
VALUES (7, 1, 0, ?, 1, 1, '')
|
||||||
|
""", (past_minute,))
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
fired = []
|
||||||
|
with patch.object(subscribe, "get_db", self._get_db), \
|
||||||
|
patch.object(subscribe.threading, "Thread", ImmediateThread), \
|
||||||
|
patch.object(subscribe, "fire_rule", side_effect=lambda r: fired.append(r["id"]) or True):
|
||||||
|
subscribe._tick()
|
||||||
|
|
||||||
|
self.assertEqual(1, len(fired), "过点的规则应该补发一次")
|
||||||
|
|
||||||
|
# 同一天再扫一遍不应重复触发
|
||||||
|
with patch.object(subscribe, "get_db", self._get_db), \
|
||||||
|
patch.object(subscribe.threading, "Thread", ImmediateThread), \
|
||||||
|
patch.object(subscribe, "fire_rule", side_effect=lambda r: fired.append(r["id"]) or True):
|
||||||
|
subscribe._tick()
|
||||||
|
self.assertEqual(1, len(fired), "当天已经发过就不该再发")
|
||||||
|
|
||||||
|
def test_future_minute_is_not_fired_early(self):
|
||||||
|
now = dt.datetime.now(dt.timezone(dt.timedelta(hours=8)))
|
||||||
|
conn = self._get_db()
|
||||||
|
future_minute = min(23 * 60 + 59, now.hour * 60 + now.minute + 30)
|
||||||
|
conn.execute("""
|
||||||
|
INSERT INTO subscribe_rules (user_id, location_id, weekday, minute_of_day,
|
||||||
|
enabled, notify_enabled, last_fired_on)
|
||||||
|
VALUES (7, 1, 0, ?, 1, 1, '')
|
||||||
|
""", (future_minute,))
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
fired = []
|
||||||
|
with patch.object(subscribe, "get_db", self._get_db), \
|
||||||
|
patch.object(subscribe.threading, "Thread", ImmediateThread), \
|
||||||
|
patch.object(subscribe, "fire_rule", side_effect=lambda r: fired.append(r["id"]) or True):
|
||||||
|
subscribe._tick()
|
||||||
|
self.assertEqual([], fired)
|
||||||
|
|
||||||
|
def test_failed_unlock_discards_the_pending_order(self):
|
||||||
|
"""下单成功但开锁失败:必须撤销那张单,否则重试会再叠一张。"""
|
||||||
|
responses = {
|
||||||
|
"/project/bicycle": {"rtn_code": 0, "data": {"status": 0, "code": "50001",
|
||||||
|
"latitude": 36.53, "longitude": 116.78}},
|
||||||
|
"/record/order": {"rtn_code": 0, "data": {"order_id": "777"}},
|
||||||
|
"/record/qrOrder": {"rtn_code": 500, "message": "open failed"},
|
||||||
|
"/record/return": {"rtn_code": 0, "message": "closed"},
|
||||||
|
}
|
||||||
|
|
||||||
|
def fake_auth(user_id, method, path, **kwargs):
|
||||||
|
return responses.get(path, {"rtn_code": 0, "data": {}})
|
||||||
|
|
||||||
|
with patch.object(subscribe, "_live_coord", return_value=(36.53, 116.78)), \
|
||||||
|
patch.object(subscribe, "AUTO_UNLOCK_ENABLED", True), \
|
||||||
|
patch("wechat.request_with_user_auth", side_effect=fake_auth), \
|
||||||
|
patch.object(subscribe, "_discard_pending_order", return_value=True) as discard:
|
||||||
|
result = subscribe._try_auto_unlock(7, "50001")
|
||||||
|
|
||||||
|
self.assertFalse(result["success"])
|
||||||
|
discard.assert_called_once()
|
||||||
|
self.assertEqual("777", str(discard.call_args.args[1]))
|
||||||
|
self.assertIn("已撤销本次下单", result["message"])
|
||||||
|
|
||||||
|
def test_realtime_points_use_electric_quantity_and_only_electric_bikes(self):
|
||||||
|
"""上游字段是 electric_quantity;写成 electric 会让电量筛选全部落空。
|
||||||
|
并且只取 type=3(电动车),别把共享单车混进候选。"""
|
||||||
|
payload = {"rtn_code": 0, "data": {"bicycleStation": [
|
||||||
|
{"code": "51287", "latitude": 36.53, "longitude": 116.78,
|
||||||
|
"electric_quantity": 66, "state": 1, "status": 0},
|
||||||
|
]}}
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def fake_api(method, path, params=None, data=None):
|
||||||
|
calls.append(params)
|
||||||
|
return payload
|
||||||
|
|
||||||
|
with patch("wechat.request_api", side_effect=fake_api):
|
||||||
|
rows = subscribe.refresh_bike_points(7)
|
||||||
|
|
||||||
|
self.assertEqual(1, len(rows))
|
||||||
|
self.assertEqual(66, rows[0]["electric"])
|
||||||
|
self.assertEqual("51287", rows[0]["bike_code"])
|
||||||
|
self.assertEqual("3", rows[0]["bike_type"])
|
||||||
|
self.assertEqual(["3"], [c["type"] for c in calls])
|
||||||
|
|
||||||
|
def test_missed_minute_beyond_window_is_skipped_without_email(self):
|
||||||
|
"""超过补发窗口(默认 5 分钟)的规则:只记今天已处理,不发信。"""
|
||||||
|
now = dt.datetime.now(dt.timezone(dt.timedelta(hours=8)))
|
||||||
|
conn = self._get_db()
|
||||||
|
old_minute = max(0, now.hour * 60 + now.minute - 30)
|
||||||
|
conn.execute("""
|
||||||
|
INSERT INTO subscribe_rules (user_id, location_id, weekday, minute_of_day,
|
||||||
|
enabled, notify_enabled, last_fired_on)
|
||||||
|
VALUES (7, 1, 0, ?, 1, 1, '')
|
||||||
|
""", (old_minute,))
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
fired = []
|
||||||
|
with patch.object(subscribe, "get_db", self._get_db), \
|
||||||
|
patch.object(subscribe.threading, "Thread", ImmediateThread), \
|
||||||
|
patch.object(subscribe, "fire_rule", side_effect=lambda r: fired.append(r["id"]) or True):
|
||||||
|
subscribe._tick()
|
||||||
|
|
||||||
|
self.assertEqual([], fired, "过窗口太久的规则不该补发")
|
||||||
|
conn = self._get_db()
|
||||||
|
row = conn.execute("SELECT last_fired_on FROM subscribe_rules").fetchone()
|
||||||
|
conn.close()
|
||||||
|
self.assertEqual(now.strftime("%Y-%m-%d"), row["last_fired_on"])
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""步行路线:百度轻量级路线规划 + 缓存 + 估算兜底。"""
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import Mock, patch
|
||||||
|
|
||||||
|
import walk_route
|
||||||
|
|
||||||
|
ORIGIN = (36.529440, 116.783740)
|
||||||
|
DEST = (36.534240, 116.787190)
|
||||||
|
|
||||||
|
|
||||||
|
class EstimateTests(unittest.TestCase):
|
||||||
|
def test_straight_line_is_expanded_by_detour_factor(self):
|
||||||
|
got = walk_route.estimate(*ORIGIN, *DEST)
|
||||||
|
self.assertEqual("estimate", got["source"])
|
||||||
|
# 直线约 615 米 -> 乘 1.3 绕行系数
|
||||||
|
self.assertGreater(got["straight"], 550)
|
||||||
|
self.assertLess(got["straight"], 700)
|
||||||
|
self.assertAlmostEqual(got["distance"], got["straight"] * 1.3, delta=2)
|
||||||
|
# 75 米/分钟
|
||||||
|
self.assertAlmostEqual(got["duration"], got["distance"] / 75 * 60, delta=2)
|
||||||
|
|
||||||
|
def test_bad_input_never_raises(self):
|
||||||
|
for args in ((None, None, None, None), ("a", "b", "c", "d")):
|
||||||
|
self.assertEqual("none", walk_route.estimate(*args)["source"])
|
||||||
|
|
||||||
|
|
||||||
|
class QueryAndSnTests(unittest.TestCase):
|
||||||
|
PARAMS = {"ak": "X", "origin": "36.5,116.7", "destination": "36.4,116.6",
|
||||||
|
"coord_type": "gcj02"}
|
||||||
|
|
||||||
|
def test_without_sk_no_sn(self):
|
||||||
|
q = walk_route.build_query(self.PARAMS, "")
|
||||||
|
self.assertNotIn("sn=", q)
|
||||||
|
self.assertIn("coord_type=gcj02", q)
|
||||||
|
|
||||||
|
def test_two_sn_modes_differ_and_are_deterministic(self):
|
||||||
|
a1 = walk_route.build_query(self.PARAMS, "SK", "official")
|
||||||
|
a2 = walk_route.build_query(self.PARAMS, "SK", "official")
|
||||||
|
b = walk_route.build_query(self.PARAMS, "SK", "simple")
|
||||||
|
self.assertEqual(a1, a2)
|
||||||
|
self.assertIn("sn=", a1)
|
||||||
|
self.assertIn("sn=", b)
|
||||||
|
self.assertNotEqual(a1.split("sn=")[1], b.split("sn=")[1])
|
||||||
|
|
||||||
|
def test_params_are_key_sorted(self):
|
||||||
|
q = walk_route.build_query(self.PARAMS, "")
|
||||||
|
keys = [part.split("=")[0] for part in q.split("&")]
|
||||||
|
self.assertEqual(sorted(keys), keys)
|
||||||
|
|
||||||
|
|
||||||
|
class GetWalkRouteTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.tmp = tempfile.TemporaryDirectory()
|
||||||
|
self.addCleanup(self.tmp.cleanup)
|
||||||
|
self.path = Path(self.tmp.name) / "walk_cache.db"
|
||||||
|
self.patches = [
|
||||||
|
patch.object(walk_route, "CACHE_PATH", self.path),
|
||||||
|
patch.object(walk_route, "_cache_ready", [False]),
|
||||||
|
patch.object(walk_route, "_last_call_at", [0.0]),
|
||||||
|
patch.object(walk_route, "MIN_INTERVAL_SECONDS", 0.0),
|
||||||
|
]
|
||||||
|
for p in self.patches:
|
||||||
|
p.start()
|
||||||
|
self.addCleanup(p.stop)
|
||||||
|
|
||||||
|
def _ok(self):
|
||||||
|
resp = Mock()
|
||||||
|
resp.raise_for_status = Mock()
|
||||||
|
resp.json = Mock(return_value={"status": 0, "result": {"routes": [
|
||||||
|
{"distance": 820, "duration": 640}]}})
|
||||||
|
return resp
|
||||||
|
|
||||||
|
def test_without_ak_returns_estimate_and_never_calls_bbox(self):
|
||||||
|
with patch.object(walk_route, "get_ak", return_value=""), \
|
||||||
|
patch("walk_route.requests.get") as http:
|
||||||
|
got = walk_route.get_walk_route(*ORIGIN, *DEST)
|
||||||
|
self.assertEqual("estimate", got["source"])
|
||||||
|
http.assert_not_called()
|
||||||
|
|
||||||
|
def test_baidu_success_then_served_from_cache(self):
|
||||||
|
with patch.object(walk_route, "get_ak", return_value="AK"), \
|
||||||
|
patch.object(walk_route, "get_sk", return_value=""), \
|
||||||
|
patch("walk_route.requests.get", return_value=self._ok()) as http:
|
||||||
|
first = walk_route.get_walk_route(*ORIGIN, *DEST)
|
||||||
|
second = walk_route.get_walk_route(*ORIGIN, *DEST)
|
||||||
|
self.assertEqual("baidu", first["source"])
|
||||||
|
self.assertEqual(820, first["distance"])
|
||||||
|
self.assertEqual(640, first["duration"])
|
||||||
|
self.assertEqual("cache", second["source"])
|
||||||
|
self.assertEqual(1, http.call_count) # 第二次没再打百度
|
||||||
|
|
||||||
|
def test_coord_type_is_gcj02(self):
|
||||||
|
with patch.object(walk_route, "get_ak", return_value="AK"), \
|
||||||
|
patch.object(walk_route, "get_sk", return_value=""), \
|
||||||
|
patch("walk_route.requests.get", return_value=self._ok()) as http:
|
||||||
|
walk_route.get_walk_route(*ORIGIN, *DEST)
|
||||||
|
url = http.call_args[0][0]
|
||||||
|
self.assertIn("coord_type=gcj02", url)
|
||||||
|
self.assertIn("directionlite/v1/walking", url)
|
||||||
|
|
||||||
|
def test_sn_failure_retries_the_other_mode(self):
|
||||||
|
bad = Mock()
|
||||||
|
bad.raise_for_status = Mock()
|
||||||
|
bad.json = Mock(return_value={"status": 211, "message": "APP SN校验失败"})
|
||||||
|
with patch.object(walk_route, "get_ak", return_value="AK"), \
|
||||||
|
patch.object(walk_route, "get_sk", return_value="SK"), \
|
||||||
|
patch.object(walk_route, "_SN_MODE", [None]), \
|
||||||
|
patch("walk_route.requests.get", side_effect=[bad, self._ok()]) as http:
|
||||||
|
got = walk_route.get_walk_route(*ORIGIN, *DEST)
|
||||||
|
self.assertEqual("baidu", got["source"])
|
||||||
|
self.assertEqual(2, http.call_count) # 官方算法失败后换了另一种
|
||||||
|
|
||||||
|
def test_app_disabled_falls_back_without_retry(self):
|
||||||
|
bad = Mock()
|
||||||
|
bad.raise_for_status = Mock()
|
||||||
|
bad.json = Mock(return_value={"status": 240, "message": "APP 服务被禁用"})
|
||||||
|
with patch.object(walk_route, "get_ak", return_value="AK"), \
|
||||||
|
patch.object(walk_route, "get_sk", return_value="SK"), \
|
||||||
|
patch("walk_route.requests.get", return_value=bad) as http:
|
||||||
|
got = walk_route.get_walk_route(*ORIGIN, *DEST)
|
||||||
|
self.assertEqual("estimate", got["source"])
|
||||||
|
self.assertEqual(1, http.call_count) # 240 不是 SN 问题,不重试
|
||||||
|
|
||||||
|
def test_network_error_falls_back(self):
|
||||||
|
with patch.object(walk_route, "get_ak", return_value="AK"), \
|
||||||
|
patch.object(walk_route, "get_sk", return_value=""), \
|
||||||
|
patch("walk_route.requests.get", side_effect=TimeoutError("boom")):
|
||||||
|
got = walk_route.get_walk_route(*ORIGIN, *DEST)
|
||||||
|
self.assertEqual("estimate", got["source"])
|
||||||
|
self.assertGreater(got["distance"], 0)
|
||||||
|
|
||||||
|
|
||||||
|
class CredentialStorageTests(unittest.TestCase):
|
||||||
|
"""管理端回显:SK 不能明文吐给前端。"""
|
||||||
|
|
||||||
|
def test_masked_hides_sk(self):
|
||||||
|
with patch.object(walk_route, "get_ak", return_value="AK123"), \
|
||||||
|
patch.object(walk_route, "get_sk", return_value="SK-abcdef1234"):
|
||||||
|
got = walk_route.masked_credentials()
|
||||||
|
self.assertEqual("AK123", got["ak"])
|
||||||
|
self.assertTrue(got["sk_set"])
|
||||||
|
self.assertEqual("1234", got["sk_tail"])
|
||||||
|
self.assertNotIn("SK-abcdef", str(got))
|
||||||
|
|
||||||
|
def test_masked_when_empty(self):
|
||||||
|
with patch.object(walk_route, "get_ak", return_value=""), \
|
||||||
|
patch.object(walk_route, "get_sk", return_value=""):
|
||||||
|
got = walk_route.masked_credentials()
|
||||||
|
self.assertFalse(got["enabled"])
|
||||||
|
self.assertFalse(got["sk_set"])
|
||||||
|
|
||||||
|
|
||||||
|
class DoublePrecisionCacheKeyTests(unittest.TestCase):
|
||||||
|
def test_nearby_points_share_a_cache_key(self):
|
||||||
|
a = walk_route._cache_key(36.529441, 116.783741, 36.534239, 116.787191)
|
||||||
|
b = walk_route._cache_key(36.529444, 116.783744, 36.534241, 116.787194)
|
||||||
|
self.assertEqual(a, b) # 10 米内视作同一对起终点
|
||||||
|
|
||||||
|
def test_far_points_differ(self):
|
||||||
|
a = walk_route._cache_key(36.5294, 116.7837, 36.5342, 116.7872)
|
||||||
|
b = walk_route._cache_key(36.5394, 116.7937, 36.5342, 116.7872)
|
||||||
|
self.assertNotEqual(a, b)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -13,6 +13,7 @@ from rental_mail import mark_return_tokens_used, send_rental_notification
|
|||||||
# ========== 计时器系统 ==========
|
# ========== 计时器系统 ==========
|
||||||
TIMER_CHECK_INTERVAL = 30
|
TIMER_CHECK_INTERVAL = 30
|
||||||
_active_timers: dict = {}
|
_active_timers: dict = {}
|
||||||
|
_timers_lock = threading.Lock() # 保护 _active_timers(多线程增删)
|
||||||
_renewal_locks: dict = {}
|
_renewal_locks: dict = {}
|
||||||
_renewal_locks_guard = threading.Lock()
|
_renewal_locks_guard = threading.Lock()
|
||||||
|
|
||||||
@@ -24,6 +25,10 @@ _checker_lock = threading.Lock()
|
|||||||
# 10 分钟轮询会让 5/3/2/1/0 分钟提醒继续发送,改为每分钟核对一次。
|
# 10 分钟轮询会让 5/3/2/1/0 分钟提醒继续发送,改为每分钟核对一次。
|
||||||
ORDER_CHECK_INTERVAL = 60
|
ORDER_CHECK_INTERVAL = 60
|
||||||
|
|
||||||
|
# 自动还车用的停车区缓存:{user_id: (ts, parkeArea)},避免续租链反复拉地图
|
||||||
|
_PARK_AREA_CACHE: dict = {}
|
||||||
|
_PARK_AREA_TTL = 60
|
||||||
|
|
||||||
|
|
||||||
def _get_remaining_seconds(rental: dict) -> int:
|
def _get_remaining_seconds(rental: dict) -> int:
|
||||||
"""计算距离过期的秒数"""
|
"""计算距离过期的秒数"""
|
||||||
@@ -34,6 +39,19 @@ def _get_remaining_seconds(rental: dict) -> int:
|
|||||||
return max(0, remaining)
|
return max(0, remaining)
|
||||||
|
|
||||||
|
|
||||||
|
def _rental_end_time_passed(rental: dict) -> bool:
|
||||||
|
"""end_time 是否已经过去(重启补还车 / 巡检补还车共用)。"""
|
||||||
|
end_time = (rental or {}).get("end_time")
|
||||||
|
if not end_time:
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
end = dt.datetime.strptime(end_time, "%Y-%m-%d %H:%M:%S")
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return False
|
||||||
|
tz = dt.timezone(dt.timedelta(hours=8))
|
||||||
|
return end.replace(tzinfo=tz) <= dt.datetime.now(tz)
|
||||||
|
|
||||||
|
|
||||||
def _extract_pay_methods(methods_result: dict):
|
def _extract_pay_methods(methods_result: dict):
|
||||||
data = methods_result.get("data", {}) if isinstance(methods_result, dict) else {}
|
data = methods_result.get("data", {}) if isinstance(methods_result, dict) else {}
|
||||||
if not isinstance(data, (list, dict)):
|
if not isinstance(data, (list, dict)):
|
||||||
@@ -223,26 +241,30 @@ def _mark_returned(rental_id: int, latitude=None, longitude=None):
|
|||||||
label = None
|
label = None
|
||||||
conn = get_db()
|
conn = get_db()
|
||||||
try:
|
try:
|
||||||
conn.execute("""
|
try:
|
||||||
UPDATE rentals SET expired = 1, returned_at = datetime('now', '+8 hours'),
|
conn.execute("""
|
||||||
end_latitude = ?, end_longitude = ?, end_label = ?
|
UPDATE rentals SET expired = 1, returned_at = datetime('now', '+8 hours'),
|
||||||
WHERE id = ?
|
end_latitude = ?, end_longitude = ?, end_label = ?
|
||||||
""", (latitude, longitude, label, rental_id))
|
WHERE id = ?
|
||||||
except sqlite3.OperationalError:
|
""", (latitude, longitude, label, rental_id))
|
||||||
# 轻量兜底:旧库/极简 schema 缺列时补齐再重试一次
|
except sqlite3.OperationalError:
|
||||||
for col_def in [("returned_at", "TIMESTAMP"), ("end_latitude", "REAL"),
|
# 轻量兜底:旧库/极简 schema 缺列时补齐再重试一次
|
||||||
("end_longitude", "REAL"), ("end_label", "TEXT")]:
|
for col_def in [("returned_at", "TIMESTAMP"), ("end_latitude", "REAL"),
|
||||||
try:
|
("end_longitude", "REAL"), ("end_label", "TEXT")]:
|
||||||
conn.execute(f"ALTER TABLE rentals ADD COLUMN {col_def[0]} {col_def[1]}")
|
try:
|
||||||
except sqlite3.OperationalError:
|
conn.execute(f"ALTER TABLE rentals ADD COLUMN {col_def[0]} {col_def[1]}")
|
||||||
pass
|
except sqlite3.OperationalError:
|
||||||
conn.execute("""
|
pass
|
||||||
UPDATE rentals SET expired = 1, returned_at = datetime('now', '+8 hours'),
|
conn.execute("""
|
||||||
end_latitude = ?, end_longitude = ?, end_label = ?
|
UPDATE rentals SET expired = 1, returned_at = datetime('now', '+8 hours'),
|
||||||
WHERE id = ?
|
end_latitude = ?, end_longitude = ?, end_label = ?
|
||||||
""", (latitude, longitude, label, rental_id))
|
WHERE id = ?
|
||||||
conn.commit()
|
""", (latitude, longitude, label, rental_id))
|
||||||
conn.close()
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
# 写失败也要关连接:以前这里异常会泄漏连接(fd 累积),
|
||||||
|
# 而且调用方拿不到「状态没落库」的信号
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
def _reopen_same_bike(user_id: int, bike_code: str) -> dict:
|
def _reopen_same_bike(user_id: int, bike_code: str) -> dict:
|
||||||
@@ -370,18 +392,71 @@ def _renewal_lock(rental_id: int):
|
|||||||
return _renewal_locks.setdefault(rental_id, threading.Lock())
|
return _renewal_locks.setdefault(rental_id, threading.Lock())
|
||||||
|
|
||||||
|
|
||||||
|
def _park_areas_for_user(user_id: int) -> list:
|
||||||
|
"""用用户凭据取上游停车区多边形(GCJ02)。结果短缓存,避免续租链反复拉地图。"""
|
||||||
|
import park_area
|
||||||
|
cached = _PARK_AREA_CACHE.get(user_id)
|
||||||
|
now = _time.time()
|
||||||
|
if cached and now - cached[0] < _PARK_AREA_TTL:
|
||||||
|
return cached[1]
|
||||||
|
try:
|
||||||
|
result = request_with_user_auth(
|
||||||
|
user_id, "GET", "/project/map", params={"type": "1"}, _silent=True
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[自动还车] 读取停车区失败: {exc}")
|
||||||
|
return []
|
||||||
|
if not isinstance(result, dict) or result.get("rtn_code") not in (None, 0):
|
||||||
|
return []
|
||||||
|
areas = park_area.parse_park_areas(result.get("data") or {})
|
||||||
|
if areas:
|
||||||
|
_PARK_AREA_CACHE[user_id] = (now, areas)
|
||||||
|
return areas
|
||||||
|
|
||||||
|
|
||||||
|
def _align_to_park_area(user_id: int, latitude, longitude):
|
||||||
|
"""把自动还车的坐标对齐到停车区(入参/返回都是 GCJ02)。
|
||||||
|
|
||||||
|
返回 (lat, lng, moved, distance)。拿不到 parkeArea 时原样返回。
|
||||||
|
自动还车前**先**对齐一次,绝大多数情况一次就还成功,不必靠重试撞。
|
||||||
|
"""
|
||||||
|
import park_area
|
||||||
|
areas = _park_areas_for_user(user_id)
|
||||||
|
if not areas:
|
||||||
|
return latitude, longitude, False, 0.0
|
||||||
|
try:
|
||||||
|
resolved = park_area.resolve_return_coord(latitude, longitude, areas)
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[自动还车] 停车区判定异常: {exc}")
|
||||||
|
return latitude, longitude, False, 0.0
|
||||||
|
if resolved and resolved.get("moved"):
|
||||||
|
return (resolved["latitude"], resolved["longitude"], True,
|
||||||
|
float(resolved.get("distance") or 0.0))
|
||||||
|
return latitude, longitude, False, 0.0
|
||||||
|
|
||||||
|
|
||||||
def _auto_return_bike(rental_id: int, user_id: int, allow_renewal: bool = True):
|
def _auto_return_bike(rental_id: int, user_id: int, allow_renewal: bool = True):
|
||||||
"""自动还车(含重试:最多3次),返回明确的成败结果。"""
|
"""自动还车(含重试:最多3次),返回明确的成败结果。
|
||||||
|
|
||||||
|
坐标链路(与手动还车同一套停车区规则):
|
||||||
|
1. 取车辆坐标(`/project/bicycle`,上游 = GCJ02,不要再转);
|
||||||
|
2. **发还车前**先用本地 parkeArea 多边形判定一次,不在停车区就先吸附到
|
||||||
|
最近的合法点 —— 原来直接发原始坐标,parkNoShow 时三次重试注定全失败;
|
||||||
|
3. 万一对齐后仍失败,第 2 次重试前再吸附一次(应对上游边界与本地不一致)。
|
||||||
|
"""
|
||||||
conn = get_db()
|
conn = get_db()
|
||||||
cursor = conn.cursor()
|
try:
|
||||||
cursor.execute("SELECT * FROM rentals WHERE id = ?", (rental_id,))
|
cursor = conn.cursor()
|
||||||
rental = cursor.fetchone()
|
cursor.execute("SELECT * FROM rentals WHERE id = ?", (rental_id,))
|
||||||
if not rental:
|
rental = cursor.fetchone()
|
||||||
|
finally:
|
||||||
|
# 这个连接只用来读这一行,读完立刻关:以前一直挂到函数末尾,
|
||||||
|
# 中间任何异常(上游超时、写库失败)都会把连接漏掉。
|
||||||
conn.close()
|
conn.close()
|
||||||
|
if not rental:
|
||||||
print(f"[自动还车] 记录不存在: rental_id={rental_id}")
|
print(f"[自动还车] 记录不存在: rental_id={rental_id}")
|
||||||
return {"success": False, "rtn_code": 404, "message": "本地租车记录不存在"}
|
return {"success": False, "rtn_code": 404, "message": "本地租车记录不存在"}
|
||||||
if rental["expired"]:
|
if rental["expired"]:
|
||||||
conn.close()
|
|
||||||
return {"success": True, "rtn_code": 0, "message": "订单已结束"}
|
return {"success": True, "rtn_code": 0, "message": "订单已结束"}
|
||||||
|
|
||||||
bike_code = rental["bike_code"]
|
bike_code = rental["bike_code"]
|
||||||
@@ -393,8 +468,18 @@ def _auto_return_bike(rental_id: int, user_id: int, allow_renewal: bool = True):
|
|||||||
# 上游要求真实订单号;老记录可能只有本地自增 id,则兜底用它
|
# 上游要求真实订单号;老记录可能只有本地自增 id,则兜底用它
|
||||||
upstream_order_id = rental["order_id"] if rental["order_id"] else str(rental_id)
|
upstream_order_id = rental["order_id"] if rental["order_id"] else str(rental_id)
|
||||||
|
|
||||||
|
# 发还车前先对齐停车区:车辆坐标不在 parkeArea 内时直接换成最近的合法点,
|
||||||
|
# 否则 parkNoShow 会让三次重试全都打在同一个错坐标上。
|
||||||
|
latitude, longitude, aligned, aligned_m = _align_to_park_area(
|
||||||
|
user_id, latitude, longitude
|
||||||
|
)
|
||||||
|
if aligned:
|
||||||
|
print(f"[自动还车] 车辆坐标不在停车区,已对齐到最近停车区 "
|
||||||
|
f"({latitude:.6f}, {longitude:.6f}) [{aligned_m:.0f}m]")
|
||||||
|
|
||||||
return_result = None
|
return_result = None
|
||||||
last_error = None
|
last_error = None
|
||||||
|
snap_attempted = aligned # 已经对齐过的话,重试前不必再对齐一次
|
||||||
for attempt in range(1, 4):
|
for attempt in range(1, 4):
|
||||||
try:
|
try:
|
||||||
return_result = request_with_user_auth(
|
return_result = request_with_user_auth(
|
||||||
@@ -411,6 +496,16 @@ def _auto_return_bike(rental_id: int, user_id: int, allow_renewal: bool = True):
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
last_error = str(e)
|
last_error = str(e)
|
||||||
print(f"[自动还车] 第{attempt}次异常: {last_error}")
|
print(f"[自动还车] 第{attempt}次异常: {last_error}")
|
||||||
|
# 首次失败:再对齐一次停车区(应对上游边界与本地多边形不一致)
|
||||||
|
if not snap_attempted and attempt < 3:
|
||||||
|
snap_attempted = True
|
||||||
|
new_lat, new_lng, moved, moved_m = _align_to_park_area(
|
||||||
|
user_id, latitude, longitude
|
||||||
|
)
|
||||||
|
if moved:
|
||||||
|
latitude, longitude = new_lat, new_lng
|
||||||
|
print(f"[自动还车] 已吸附到最近停车区 "
|
||||||
|
f"({latitude:.6f}, {longitude:.6f}) [{moved_m:.0f}m],准备重试")
|
||||||
if attempt < 3:
|
if attempt < 3:
|
||||||
_time.sleep(5)
|
_time.sleep(5)
|
||||||
|
|
||||||
@@ -430,7 +525,14 @@ def _auto_return_bike(rental_id: int, user_id: int, allow_renewal: bool = True):
|
|||||||
# 让邮件按钮可重试,后台对账也能继续跟踪真实状态。
|
# 让邮件按钮可重试,后台对账也能继续跟踪真实状态。
|
||||||
if success:
|
if success:
|
||||||
_mark_returned(rental_id, latitude, longitude)
|
_mark_returned(rental_id, latitude, longitude)
|
||||||
conn.close()
|
# 续租会换新的 order_id;不清掉 60 秒的 /user/info 缓存的话,
|
||||||
|
# 前端在缓存窗口内点还车会拿到旧 order_id、被判「已结束」返回 rtn 0,
|
||||||
|
# 而车其实已经在第 2 轮计费。
|
||||||
|
try:
|
||||||
|
from routes.rental import _user_info_cache
|
||||||
|
_user_info_cache.pop(user_id, None)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
renewal_result = {"renewed": False}
|
renewal_result = {"renewed": False}
|
||||||
if success:
|
if success:
|
||||||
_cancel_rental_timers(rental_id)
|
_cancel_rental_timers(rental_id)
|
||||||
@@ -470,11 +572,288 @@ def auto_return_bike(rental_id: int, user_id: int, allow_renewal: bool = True):
|
|||||||
|
|
||||||
|
|
||||||
def _cancel_rental_timers(rental_id: int):
|
def _cancel_rental_timers(rental_id: int):
|
||||||
"""取消某次租车的所有计时器"""
|
"""取消某次租车的所有计时器。
|
||||||
if rental_id in _active_timers:
|
|
||||||
for t in _active_timers[rental_id]:
|
用 pop 一次取出再取消:原来是 `in` 判断 + 取列表 + `del`,
|
||||||
|
中间被别的线程删掉会抛 KeyError;`del` 之后另一线程刚 append 的 timer
|
||||||
|
也会随之消失(脱管的计时器永远取消不掉,导致重复提醒/重复还车)。
|
||||||
|
"""
|
||||||
|
with _timers_lock:
|
||||||
|
timers = _active_timers.pop(rental_id, [])
|
||||||
|
for t in timers:
|
||||||
|
try:
|
||||||
t.cancel()
|
t.cancel()
|
||||||
del _active_timers[rental_id]
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
# 只有这些来源才代表「真的有上游骑行订单」,才能走自动还车。
|
||||||
|
# reminder 是前端自己开的计时提醒,没有上游订单;把本地自增 id 当订单号发出去
|
||||||
|
# 必然 204010,白打三次上游还要 sleep 15 秒。
|
||||||
|
AUTO_RETURN_SOURCES = ("unlock", "sync", "shared", "subscribe")
|
||||||
|
|
||||||
|
|
||||||
|
# 巡检补还车的节流:彻底失败的单不能每分钟重打上游
|
||||||
|
_recover_last_at: dict = {}
|
||||||
|
RECOVER_INTERVAL_SECONDS = 300 # 5 分钟
|
||||||
|
|
||||||
|
|
||||||
|
def _recover_throttled(rental_id: int) -> bool:
|
||||||
|
"""5 分钟内已经补过就不再补,返回 True 表示这次要跳过。"""
|
||||||
|
now = _time.time()
|
||||||
|
last = _recover_last_at.get(rental_id, 0)
|
||||||
|
if now - last < RECOVER_INTERVAL_SECONDS:
|
||||||
|
return True
|
||||||
|
_recover_last_at[rental_id] = now
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _upstream_ride_active(user_id: int, order_id):
|
||||||
|
"""上游这张单还在骑吗?True=在骑 / False=已结束 / None=查不到(别下结论)。
|
||||||
|
|
||||||
|
用户很可能直接在小程序里点了还车 —— 那种情况下本地还挂着 expired=0,
|
||||||
|
但我们**不能**再发一次 /record/return(上游会报订单不存在,白白制造错误)。
|
||||||
|
所以补还车前先看上游状态,上游说结束了就只做本地收尾。
|
||||||
|
"""
|
||||||
|
if not user_id or not order_id:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
info = request_with_user_auth(user_id, "GET", "/user/info", _silent=True)
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[自动还车] 查询上游订单状态失败: {exc}")
|
||||||
|
return None
|
||||||
|
if not isinstance(info, dict) or info.get("rtn_code") != 0:
|
||||||
|
return None
|
||||||
|
non_deal = (info.get("data") or {}).get("nonDealOrder") or {}
|
||||||
|
if not non_deal or not non_deal.get("order_id"):
|
||||||
|
return False # 上游没有未完成订单 → 已经结束了
|
||||||
|
if str(non_deal.get("order_id")) != str(order_id):
|
||||||
|
return False # 上游挂的是另一张单 → 这张已经结束
|
||||||
|
return str(non_deal.get("status")) == "2" # 2=骑行中
|
||||||
|
|
||||||
|
|
||||||
|
def _run_recovery(rental_id: int, user_id: int, order_id=None):
|
||||||
|
"""巡检/重启的补还车入口:成功后清掉节流记录,别让进程里留失败痕迹。
|
||||||
|
|
||||||
|
先问上游状态:上游说这单已结束(用户在小程序里还了),就只做本地收尾,
|
||||||
|
不再打 /record/return。
|
||||||
|
"""
|
||||||
|
# 跨进程独占:多 worker 下同一单只让一个进程去还,避免两次 /record/return +
|
||||||
|
# 两次月卡提交(_renewal_lock 只是进程内的 threading.Lock)
|
||||||
|
try:
|
||||||
|
from db import acquire_lease
|
||||||
|
if acquire_lease(f"rental-return:{rental_id}", 300) is False:
|
||||||
|
return {"success": False, "skipped": True,
|
||||||
|
"message": "另一个进程正在处理这一单"}
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[自动还车] 租约获取失败(按单进程处理): {exc}")
|
||||||
|
|
||||||
|
active = _upstream_ride_active(user_id, order_id) if order_id else None
|
||||||
|
if active is False:
|
||||||
|
_close_rental_locally(rental_id, "上游订单已结束(用户已在小程序还车)")
|
||||||
|
_recover_last_at.pop(rental_id, None)
|
||||||
|
return {"success": True, "skipped": True,
|
||||||
|
"message": "上游订单已结束,仅做本地收尾"}
|
||||||
|
try:
|
||||||
|
result = auto_return_bike(rental_id, user_id) or {}
|
||||||
|
if result.get("success"):
|
||||||
|
_recover_last_at.pop(rental_id, None)
|
||||||
|
return result
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[自动还车] 补还车异常 rental_id={rental_id}: {exc}")
|
||||||
|
return {"success": False, "message": str(exc)}
|
||||||
|
|
||||||
|
|
||||||
|
# 全局兜底扫描的节流(进程内一次/10 分钟,避免每个用户的巡检都全表扫)
|
||||||
|
_sweep_last_at = [0.0]
|
||||||
|
SWEEP_INTERVAL_SECONDS = 600
|
||||||
|
|
||||||
|
|
||||||
|
def sweep_overdue_rentals(force: bool = False) -> int:
|
||||||
|
"""兜底:捞「expired=0 且 end_time 已过」的单补还车,返回排队数量。
|
||||||
|
|
||||||
|
以前这件事只在 `restore_active_timers()` 里做一次;启动方式一变
|
||||||
|
(WSGI / `flask run` / 直接 import),这些僵尸单就永远挂着,
|
||||||
|
用户页面横幅一直显示「用车中」。现在巡检也会定期顺手扫一遍。
|
||||||
|
"""
|
||||||
|
now = _time.time()
|
||||||
|
if not force and now - _sweep_last_at[0] < SWEEP_INTERVAL_SECONDS:
|
||||||
|
return 0
|
||||||
|
_sweep_last_at[0] = now
|
||||||
|
|
||||||
|
tz = dt.timezone(dt.timedelta(hours=8))
|
||||||
|
now_str = dt.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
|
||||||
|
conn = get_db()
|
||||||
|
try:
|
||||||
|
rows = [dict(r) for r in conn.execute(
|
||||||
|
"SELECT * FROM rentals WHERE expired = 0 AND end_time < ?", (now_str,)
|
||||||
|
).fetchall()]
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[计时系统] 扫描超期订单失败: {exc}")
|
||||||
|
return 0
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
started = 0
|
||||||
|
closed_local = 0
|
||||||
|
for rental in rows:
|
||||||
|
if not _should_auto_return(rental):
|
||||||
|
# reminder 是纯本地计时提醒,没有上游订单:上游还不了,但也不能
|
||||||
|
# 一直挂着 expired=0,否则用户页面横幅永远显示「用车中」。
|
||||||
|
if str(rental.get("source") or "") == "reminder":
|
||||||
|
_close_rental_locally(rental["id"], "本地提醒单到期")
|
||||||
|
closed_local += 1
|
||||||
|
continue
|
||||||
|
if _recover_throttled(rental["id"]):
|
||||||
|
continue
|
||||||
|
threading.Thread(target=_run_recovery,
|
||||||
|
args=(rental["id"], rental.get("user_id"), rental.get("order_id")),
|
||||||
|
daemon=True).start()
|
||||||
|
started += 1
|
||||||
|
if started:
|
||||||
|
print(f"[计时系统] 巡检兜底:{started} 单超期未还,已排队补还车")
|
||||||
|
if closed_local:
|
||||||
|
print(f"[计时系统] 巡检兜底:{closed_local} 条本地提醒单超期,已就地关闭")
|
||||||
|
return started
|
||||||
|
|
||||||
|
|
||||||
|
def _close_rental_locally(rental_id: int, reason: str = ""):
|
||||||
|
"""只做本地收尾:标记结束 + 实际还车时间 + 取消计时器,**不碰上游**。
|
||||||
|
|
||||||
|
适用于两种情况:
|
||||||
|
1. reminder 单(本来就没有上游订单);
|
||||||
|
2. 用户已经在小程序里还车了(上游查不到这张单,再发 /record/return 只会 204010)。
|
||||||
|
"""
|
||||||
|
tz = dt.timezone(dt.timedelta(hours=8))
|
||||||
|
now_str = dt.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
|
||||||
|
conn = get_db()
|
||||||
|
try:
|
||||||
|
try:
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE rentals SET expired = 1, returned_at = COALESCE(returned_at, ?) "
|
||||||
|
"WHERE id = ? AND expired = 0", (now_str, rental_id))
|
||||||
|
except Exception as exc:
|
||||||
|
if "no such column" not in str(exc).lower():
|
||||||
|
raise
|
||||||
|
# 极简/旧 schema 没有 returned_at:只置 expired 也要把它关掉
|
||||||
|
conn.execute("UPDATE rentals SET expired = 1 WHERE id = ? AND expired = 0",
|
||||||
|
(rental_id,))
|
||||||
|
conn.commit()
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[计时系统] 本地收尾 rental_id={rental_id} 失败: {exc}")
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
try:
|
||||||
|
_cancel_rental_timers(rental_id)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
print(f"[计时系统] 本地收尾 rental_id={rental_id}"
|
||||||
|
+ (f":{reason}" if reason else ""))
|
||||||
|
|
||||||
|
|
||||||
|
def _should_auto_return(rental) -> bool:
|
||||||
|
"""这张单能不能走上游自动还车(restore / 巡检共用同一判断)。"""
|
||||||
|
if not rental:
|
||||||
|
return False
|
||||||
|
if str(rental.get("source") or "") not in AUTO_RETURN_SOURCES:
|
||||||
|
return False
|
||||||
|
return bool(rental.get("order_id"))
|
||||||
|
|
||||||
|
|
||||||
|
def _mark_notified(rental_id: int, reminder_type: str, conn=None, cursor=None):
|
||||||
|
"""把 notified_X 置位(缺列就跳过)。
|
||||||
|
|
||||||
|
调用方已经拿着连接/游标时直接复用,不再为一次 UPDATE 新开连接。
|
||||||
|
"""
|
||||||
|
col = f"notified_{reminder_type}"
|
||||||
|
if cursor is not None and conn is not None:
|
||||||
|
try:
|
||||||
|
cols = [d[0] for d in cursor.description]
|
||||||
|
if col in cols:
|
||||||
|
conn.execute(f"UPDATE rentals SET {col} = 1 WHERE id = ?", (rental_id,))
|
||||||
|
conn.commit()
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[提醒] 置位 {col} 失败: {exc}")
|
||||||
|
return
|
||||||
|
|
||||||
|
own_conn = get_db()
|
||||||
|
try:
|
||||||
|
cur = own_conn.execute("SELECT * FROM rentals WHERE id = ?", (rental_id,))
|
||||||
|
if col in [d[0] for d in cur.description]:
|
||||||
|
own_conn.execute(f"UPDATE rentals SET {col} = 1 WHERE id = ?", (rental_id,))
|
||||||
|
own_conn.commit()
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[提醒] 置位 {col} 失败: {exc}")
|
||||||
|
finally:
|
||||||
|
own_conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
# 0 分钟自动还车失败后的重试计数(进程内即可:重启后 restore/巡检会自动补还)
|
||||||
|
_auto_return_retries: dict = {}
|
||||||
|
AUTO_RETURN_RETRY_DELAY = 30 # 秒
|
||||||
|
AUTO_RETURN_MAX_RETRIES = 6
|
||||||
|
|
||||||
|
|
||||||
|
def _notify_auto_return_recovered(rental_id: int):
|
||||||
|
"""重试若干次后终于还车成功:再发一封「已还上」,别让用户去点邮件里的旧按钮。"""
|
||||||
|
try:
|
||||||
|
from email_utils import send_email
|
||||||
|
conn = get_db()
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT bike_code, email FROM rentals WHERE id = ?", (rental_id,)).fetchone()
|
||||||
|
conn.close()
|
||||||
|
if not row:
|
||||||
|
return
|
||||||
|
to_email = (row["email"] or "").strip()
|
||||||
|
if not to_email:
|
||||||
|
return
|
||||||
|
titled = f"自动还车已成功(#{row['bike_code']})"
|
||||||
|
body = (f"上次自动还车失败后系统已重试并成功,车辆 #{row['bike_code']} 已还车,"
|
||||||
|
f"这单不会再计费。\n\n如果你刚才点了邮件里的「还车」按钮,"
|
||||||
|
f"看到「订单已结束」是正常的 —— 不用再操作。")
|
||||||
|
send_email(to_email, f"【小白超人】{titled}", body,
|
||||||
|
f"<p>{body.replace(chr(10), '<br/>')}</p>")
|
||||||
|
print(f"[自动还车] rental_id={rental_id} 重试成功,已发最终成功通知")
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[自动还车] 重试成功通知发送失败: {exc}")
|
||||||
|
|
||||||
|
|
||||||
|
def _alert_auto_return_exhausted(rental_id: int, bike_code: str, message: str = ""):
|
||||||
|
"""重试耗尽仍失败:给管理员发告警邮件,不能只留一行 print。"""
|
||||||
|
try:
|
||||||
|
from alerts import get_alert_emails
|
||||||
|
from email_utils import send_email
|
||||||
|
recipients = get_alert_emails()
|
||||||
|
if not recipients:
|
||||||
|
print(f"[自动还车] rental_id={rental_id} 重试耗尽且没有配置告警邮箱")
|
||||||
|
return
|
||||||
|
title = f"自动还车失败需人工处理(#{bike_code})"
|
||||||
|
body = (f"rental_id={rental_id} 车辆 #{bike_code} 自动还车已重试 "
|
||||||
|
f"{AUTO_RETURN_MAX_RETRIES} 次仍失败。\n"
|
||||||
|
f"最后一次错误:{message or '(无)'}\n\n"
|
||||||
|
f"这单还在上游计费,请到管理后台「代还车」处理。")
|
||||||
|
for to in recipients:
|
||||||
|
send_email(to, f"【小白超人·告警】{title}", body,
|
||||||
|
f"<p>{body.replace(chr(10), '<br/>')}</p>")
|
||||||
|
print(f"[自动还车] rental_id={rental_id} 重试耗尽,已发告警给 {len(recipients)} 个邮箱")
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[自动还车] 重试耗尽告警发送失败: {exc}")
|
||||||
|
|
||||||
|
|
||||||
|
def _schedule_auto_return_retry(rental_id: int, email: str, bike_code: str, user_id,
|
||||||
|
message: str = ""):
|
||||||
|
"""自动还车失败:30 秒后再试,最多 6 次。notified_0 保持 0,让各处调度还能再次触发。"""
|
||||||
|
n = _auto_return_retries.get(rental_id, 0)
|
||||||
|
if n >= AUTO_RETURN_MAX_RETRIES:
|
||||||
|
print(f"[自动还车] rental_id={rental_id} 已重试 {n} 次仍失败,转人工")
|
||||||
|
_alert_auto_return_exhausted(rental_id, bike_code, message)
|
||||||
|
return
|
||||||
|
_auto_return_retries[rental_id] = n + 1
|
||||||
|
print(f"[自动还车] rental_id={rental_id} 第 {n+1} 次重试将在 "
|
||||||
|
f"{AUTO_RETURN_RETRY_DELAY}s 后执行")
|
||||||
|
_schedule_reminder(rental_id, AUTO_RETURN_RETRY_DELAY, "0", email, bike_code,
|
||||||
|
user_id, send_notification=False,
|
||||||
|
auto_return_enabled=True, auto_return_configured=True)
|
||||||
|
|
||||||
|
|
||||||
def _schedule_reminder(rental_id: int, delay_seconds: int, reminder_type: str,
|
def _schedule_reminder(rental_id: int, delay_seconds: int, reminder_type: str,
|
||||||
@@ -492,34 +871,60 @@ def _schedule_reminder(rental_id: int, delay_seconds: int, reminder_type: str,
|
|||||||
conn.close()
|
conn.close()
|
||||||
return
|
return
|
||||||
col = f"notified_{reminder_type}"
|
col = f"notified_{reminder_type}"
|
||||||
if col in [d[0] for d in cursor.description] and rental[col] == 0:
|
has_col = col in [d[0] for d in cursor.description]
|
||||||
cursor.execute(f"UPDATE rentals SET {col} = 1 WHERE id = ?", (rental_id,))
|
if not (has_col and rental[col] == 0):
|
||||||
conn.commit()
|
conn.close()
|
||||||
|
return
|
||||||
|
|
||||||
|
# 5/3/2/1 分钟这类纯提醒:先置位再发,发失败也不重发
|
||||||
|
if reminder_type != "0":
|
||||||
|
_mark_notified(rental_id, reminder_type, conn=conn, cursor=cursor)
|
||||||
conn.close()
|
conn.close()
|
||||||
return_result = None
|
|
||||||
if reminder_type == "0":
|
|
||||||
if auto_return_enabled and user_id:
|
|
||||||
try:
|
|
||||||
return_result = auto_return_bike(rental_id, user_id)
|
|
||||||
except Exception as e:
|
|
||||||
print(f"[自动还车] 失败: {e}")
|
|
||||||
return_result = {"attempted": True, "success": False, "message": str(e)}
|
|
||||||
elif not auto_return_configured:
|
|
||||||
return_result = {"attempted": False, "success": False,
|
|
||||||
"message": "用户未开启自动还车"}
|
|
||||||
else:
|
|
||||||
return_result = {"attempted": False, "success": False,
|
|
||||||
"message": "该提醒未绑定微信订单,无法自动还车"}
|
|
||||||
if send_notification:
|
if send_notification:
|
||||||
send_rental_notification(rental_id, reminder_type, return_result)
|
send_rental_notification(rental_id, reminder_type, None)
|
||||||
|
return
|
||||||
|
|
||||||
|
# 0 分钟:先把车还了,成功了才置位。
|
||||||
|
# 原来先置位再还车,上游三次重试一失败就再也不会重试,订单在上游继续计费。
|
||||||
|
conn.close()
|
||||||
|
return_result = None
|
||||||
|
if auto_return_enabled and user_id:
|
||||||
|
try:
|
||||||
|
return_result = auto_return_bike(rental_id, user_id)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"[自动还车] 失败: {e}")
|
||||||
|
return_result = {"attempted": True, "success": False, "message": str(e)}
|
||||||
|
elif not auto_return_configured:
|
||||||
|
return_result = {"attempted": False, "success": False,
|
||||||
|
"message": "用户未开启自动还车"}
|
||||||
else:
|
else:
|
||||||
conn.close()
|
return_result = {"attempted": False, "success": False,
|
||||||
|
"message": "该提醒未绑定微信订单,无法自动还车"}
|
||||||
|
|
||||||
|
success = bool(return_result and return_result.get("success"))
|
||||||
|
had_retries = _auto_return_retries.get(rental_id, 0)
|
||||||
|
if success:
|
||||||
|
_auto_return_retries.pop(rental_id, None)
|
||||||
|
_mark_notified(rental_id, "0")
|
||||||
|
if had_retries:
|
||||||
|
# 之前发过「自动还车失败」,这次终于还上了,必须再发一封收尾,
|
||||||
|
# 否则用户会去点旧邮件里的还车按钮(那时订单已结束)
|
||||||
|
_notify_auto_return_recovered(rental_id)
|
||||||
|
elif auto_return_enabled and user_id:
|
||||||
|
# 失败:不置位,短周期重试;页面横幅会提示「自动还车失败,点我重试」
|
||||||
|
_schedule_auto_return_retry(
|
||||||
|
rental_id, email, bike_code, user_id,
|
||||||
|
str((return_result or {}).get("message") or ""))
|
||||||
|
else:
|
||||||
|
_mark_notified(rental_id, "0") # 未绑定/未开启:一次性事件,直接置位
|
||||||
|
|
||||||
|
if send_notification:
|
||||||
|
send_rental_notification(rental_id, reminder_type, return_result)
|
||||||
|
|
||||||
timer = threading.Timer(delay_seconds, fire)
|
timer = threading.Timer(delay_seconds, fire)
|
||||||
timer.daemon = True
|
timer.daemon = True
|
||||||
if rental_id not in _active_timers:
|
with _timers_lock:
|
||||||
_active_timers[rental_id] = []
|
_active_timers.setdefault(rental_id, []).append(timer)
|
||||||
_active_timers[rental_id].append(timer)
|
|
||||||
# 先登记再启动,避免 0 秒任务先完成/取消后又被追加回活动列表。
|
# 先登记再启动,避免 0 秒任务先完成/取消后又被追加回活动列表。
|
||||||
timer.start()
|
timer.start()
|
||||||
return timer
|
return timer
|
||||||
@@ -613,22 +1018,61 @@ def reschedule_user_rental_timers(user_id: int, apply_duration: bool = False):
|
|||||||
|
|
||||||
|
|
||||||
def restore_active_timers():
|
def restore_active_timers():
|
||||||
"""启动时恢复所有未过期的计时器"""
|
"""启动时恢复计时器;**重启前就已越过到期时间**的单子立刻补一次自动还车。
|
||||||
|
|
||||||
|
以前这里只捞 `end_time > now`,服务重启时刚好跨过 19 分钟的那一单
|
||||||
|
既不会恢复计时器、也不会补还车,于是永久失去「自动还车」,
|
||||||
|
月卡还会按超时继续扣钱。现在把「已过期但没有 expired」的行单独捡出来补还。
|
||||||
|
"""
|
||||||
conn = get_db()
|
conn = get_db()
|
||||||
cursor = conn.cursor()
|
cursor = conn.cursor()
|
||||||
tz = dt.timezone(dt.timedelta(hours=8))
|
cursor.execute("SELECT * FROM rentals WHERE expired = 0")
|
||||||
now_beijing = dt.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
|
active_rows = [dict(r) for r in cursor.fetchall()]
|
||||||
cursor.execute("""
|
conn.close()
|
||||||
SELECT * FROM rentals
|
|
||||||
WHERE expired = 0 AND end_time > ?
|
restored = 0
|
||||||
""", (now_beijing,))
|
overdue = []
|
||||||
for rental in cursor.fetchall():
|
skipped = 0
|
||||||
remaining = _get_remaining_seconds(dict(rental))
|
for rental in active_rows:
|
||||||
|
remaining = _get_remaining_seconds(rental)
|
||||||
if remaining > 0:
|
if remaining > 0:
|
||||||
start_rental_timer(rental["id"], rental["email"], rental["bike_code"],
|
start_rental_timer(rental["id"], rental["email"], rental["bike_code"],
|
||||||
remaining / 60, rental["user_id"])
|
remaining / 60, rental["user_id"])
|
||||||
conn.close()
|
restored += 1
|
||||||
print(f"[计时系统] 已恢复 {len(_active_timers)} 个活跃计时器")
|
elif _should_auto_return(rental):
|
||||||
|
overdue.append(rental)
|
||||||
|
else:
|
||||||
|
# reminder 之类没有真实上游订单的单子:不要拿本地 id 去猜订单号
|
||||||
|
skipped += 1
|
||||||
|
|
||||||
|
print(f"[计时系统] 已恢复 {restored} 个活跃计时器")
|
||||||
|
if skipped:
|
||||||
|
print(f"[计时系统] {skipped} 个过期单没有上游订单(reminder 等),跳过补还车")
|
||||||
|
|
||||||
|
# 补还车放到后台线程,别把启动流程卡住
|
||||||
|
for rental in overdue:
|
||||||
|
print(f"[计时系统] rental_id={rental['id']} 在重启前已过期,补一次自动还车")
|
||||||
|
threading.Thread(target=_recover_overdue_rental, args=(rental,),
|
||||||
|
daemon=True).start()
|
||||||
|
|
||||||
|
|
||||||
|
def _recover_overdue_rental(rental: dict):
|
||||||
|
"""重启补还车:失败就交给巡检线程与告警,不在这里死磕。"""
|
||||||
|
rental_id = rental.get("id")
|
||||||
|
user_id = rental.get("user_id")
|
||||||
|
if not _should_auto_return(rental):
|
||||||
|
# 没有真实上游订单(reminder / 老记录),补还车必然 204010,别白打三次上游
|
||||||
|
print(f"[计时系统] rental_id={rental_id} 没有上游订单号,跳过补还车")
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
_time.sleep(3) # 等调度线程和上游会话就绪
|
||||||
|
if not user_id:
|
||||||
|
print(f"[计时系统] rental_id={rental_id} 没有 user_id,跳过补还车")
|
||||||
|
return
|
||||||
|
result = _run_recovery(rental_id, user_id, rental.get("order_id"))
|
||||||
|
print(f"[计时系统] 补还车结果 rental_id={rental_id}: {result.get('message')}")
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[计时系统] 补还车异常 rental_id={rental_id}: {exc}")
|
||||||
|
|
||||||
|
|
||||||
# ========== 用户订单检测系统 ==========
|
# ========== 用户订单检测系统 ==========
|
||||||
@@ -664,6 +1108,13 @@ def stop_user_order_checker(user_id: int):
|
|||||||
def _user_order_checker_loop(user_id: int, stop_event: threading.Event):
|
def _user_order_checker_loop(user_id: int, stop_event: threading.Event):
|
||||||
"""用户订单检测线程主循环"""
|
"""用户订单检测线程主循环"""
|
||||||
while not stop_event.is_set():
|
while not stop_event.is_set():
|
||||||
|
# 兜底扫一遍超期未还的单(内部 10 分钟节流,不会每轮都全表扫)。
|
||||||
|
# 放在循环里而不是 _check_user_order 里:启动路径一变 restore 不跑时,
|
||||||
|
# 这些僵尸单就靠这里清;同时保持单测里的 _check_user_order 纯净。
|
||||||
|
try:
|
||||||
|
sweep_overdue_rentals()
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[订单检测] 超期订单兜底扫描失败: {exc}")
|
||||||
try:
|
try:
|
||||||
_check_user_order(user_id)
|
_check_user_order(user_id)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -695,7 +1146,7 @@ def _check_user_order(user_id: int):
|
|||||||
info = request_with_user_auth(user_id, "GET", "/user/info", _silent=True)
|
info = request_with_user_auth(user_id, "GET", "/user/info", _silent=True)
|
||||||
if info.get("rtn_code") != 0:
|
if info.get("rtn_code") != 0:
|
||||||
if info.get("rtn_code") == 102001 or info.get("token_invalid"):
|
if info.get("rtn_code") == 102001 or info.get("token_invalid"):
|
||||||
# token_id 已被上游判定失效(通常是小程序重新登录踢掉了旧会话):
|
# token_id 已被上游判定失效(凭据过期/被上游拒绝):
|
||||||
# 停止轮询避免无效请求;用户在个人中心/管理端更新凭据时会自动重启线程
|
# 停止轮询避免无效请求;用户在个人中心/管理端更新凭据时会自动重启线程
|
||||||
print(f"[订单检测] 用户 {user_id} 凭据已失效,停止检测线程,等待更新凭据")
|
print(f"[订单检测] 用户 {user_id} 凭据已失效,停止检测线程,等待更新凭据")
|
||||||
stop_user_order_checker(user_id)
|
stop_user_order_checker(user_id)
|
||||||
@@ -722,12 +1173,31 @@ def _check_user_order(user_id: int):
|
|||||||
conn = get_db()
|
conn = get_db()
|
||||||
cursor = conn.cursor()
|
cursor = conn.cursor()
|
||||||
cursor.execute(
|
cursor.execute(
|
||||||
"SELECT id, source, expired, end_time FROM rentals WHERE order_id = ? AND user_id = ?",
|
"SELECT id, order_id, source, expired, end_time FROM rentals "
|
||||||
|
"WHERE order_id = ? AND user_id = ?",
|
||||||
(order_id, user_id)
|
(order_id, user_id)
|
||||||
)
|
)
|
||||||
existing = cursor.fetchone()
|
existing = cursor.fetchone()
|
||||||
|
|
||||||
if existing and existing["source"] in ("unlock", "sync", "shared") and existing["expired"] == 0:
|
if existing and existing["expired"] == 0:
|
||||||
|
rental = dict(existing)
|
||||||
|
# 到期时间已经过了却还挂着(重启丢了计时器、或 0 点那次失败):
|
||||||
|
# 巡检必须补一次自动还车,不能再无脑 return,否则这一单永远还不掉。
|
||||||
|
# 只有「真的有上游订单」的来源才补(reminder 之类拿本地 id 当订单号必然失败)。
|
||||||
|
if _should_auto_return(rental) and _rental_end_time_passed(rental):
|
||||||
|
conn.close()
|
||||||
|
if _recover_throttled(rental["id"]):
|
||||||
|
# 彻底还不上(车被锁死/订单状态怪)时不能每分钟重打:
|
||||||
|
# 5 分钟一次,避免每分钟 3~4 个上游请求 + 线程睡 15 秒的死循环
|
||||||
|
return {"ok": True, "active": True, "order_id": order_id,
|
||||||
|
"recovering": True}
|
||||||
|
print(f"[订单检测] rental_id={rental['id']} 已过到期时间,补一次自动还车")
|
||||||
|
threading.Thread(
|
||||||
|
target=lambda: _run_recovery(rental["id"], user_id, order_id),
|
||||||
|
daemon=True
|
||||||
|
).start()
|
||||||
|
return {"ok": True, "active": True, "order_id": order_id,
|
||||||
|
"recovered": True}
|
||||||
conn.close()
|
conn.close()
|
||||||
return {"ok": True, "active": True, "order_id": order_id}
|
return {"ok": True, "active": True, "order_id": order_id}
|
||||||
|
|
||||||
@@ -755,10 +1225,23 @@ def _check_user_order(user_id: int):
|
|||||||
|
|
||||||
if existing:
|
if existing:
|
||||||
rental_id = existing["id"]
|
rental_id = existing["id"]
|
||||||
cursor.execute("""
|
# 复活这张单时把 notified_* 一起复位:本地可能刚被 _close_rental_locally /
|
||||||
UPDATE rentals SET expired = 0, source = 'sync',
|
# _finish_active_wechat_rentals 置过 expired=1,那些提醒位还留着 1,
|
||||||
start_time = ?, end_time = ?, duration = ?, email = ? WHERE id = ?
|
# 复活的单就再也收不到 5/3/2/1 提醒和 0 分钟自动还车了。
|
||||||
""", (start_str, end_str, duration, email, rental_id))
|
try:
|
||||||
|
cursor.execute("""
|
||||||
|
UPDATE rentals SET expired = 0, source = 'sync',
|
||||||
|
start_time = ?, end_time = ?, duration = ?, email = ?,
|
||||||
|
notified_10 = 0, notified_5 = 0, notified_3 = 0,
|
||||||
|
notified_2 = 0, notified_1 = 0, notified_0 = 0
|
||||||
|
WHERE id = ?
|
||||||
|
""", (start_str, end_str, duration, email, rental_id))
|
||||||
|
except sqlite3.OperationalError:
|
||||||
|
# 极简 schema 没有这些列:退回原来的更新
|
||||||
|
cursor.execute("""
|
||||||
|
UPDATE rentals SET expired = 0, source = 'sync',
|
||||||
|
start_time = ?, end_time = ?, duration = ?, email = ? WHERE id = ?
|
||||||
|
""", (start_str, end_str, duration, email, rental_id))
|
||||||
old_source = existing["source"]
|
old_source = existing["source"]
|
||||||
print(f"[订单检测] 升级租车记录: rental_id={rental_id}, order_id={order_id}, "
|
print(f"[订单检测] 升级租车记录: rental_id={rental_id}, order_id={order_id}, "
|
||||||
f"source={old_source}→sync, 剩余={remaining}分钟")
|
f"source={old_source}→sync, 剩余={remaining}分钟")
|
||||||
@@ -809,26 +1292,6 @@ def _finish_active_wechat_rentals(user_id: int, reason: str):
|
|||||||
f"order_id={row['order_id']}, source={row['source']}, reason={reason}")
|
f"order_id={row['order_id']}, source={row['source']}, reason={reason}")
|
||||||
|
|
||||||
|
|
||||||
def _cleanup_stale_rentals(user_id: int):
|
|
||||||
"""用户无活跃订单时,清理本地残留的 active 记录"""
|
|
||||||
import datetime as dt
|
|
||||||
tz = dt.timezone(dt.timedelta(hours=8))
|
|
||||||
now_str = dt.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
|
|
||||||
conn = get_db()
|
|
||||||
cursor = conn.cursor()
|
|
||||||
cursor.execute("""
|
|
||||||
SELECT id, order_id, source FROM rentals
|
|
||||||
WHERE user_id = ? AND expired = 0 AND end_time < ?
|
|
||||||
""", (user_id, now_str))
|
|
||||||
for row in cursor.fetchall():
|
|
||||||
rental_id = row["id"]
|
|
||||||
_cancel_rental_timers(rental_id)
|
|
||||||
_mark_returned(rental_id)
|
|
||||||
print(f"[订单检测] 清理过期记录: rental_id={rental_id}, order_id={row['order_id']}, source={row['source']}")
|
|
||||||
conn.commit()
|
|
||||||
conn.close()
|
|
||||||
|
|
||||||
|
|
||||||
def start_all_order_checkers():
|
def start_all_order_checkers():
|
||||||
"""启动所有有凭据用户的订单检测线程。
|
"""启动所有有凭据用户的订单检测线程。
|
||||||
错峰启动:每个线程间隔 5 秒,避免启动瞬间并发请求上游被限流。"""
|
错峰启动:每个线程间隔 5 秒,避免启动瞬间并发请求上游被限流。"""
|
||||||
|
|||||||
@@ -1,5 +0,0 @@
|
|||||||
# 全局微信凭据
|
|
||||||
# token_id: 登录后服务端下发的会话标识(重新登录小程序会失效,单会话策略)
|
|
||||||
# access_token: 登录响应中的 accessToken(JWT,30天有效),用于实时计算签名;留空则发占位签名
|
|
||||||
token_id=1672159
|
|
||||||
access_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjFhNWVlMjI5ODJlNWI2ZDM1ZDA5Y2M0NzVkMDVkZjljZTc0OTg5ZGY4OGRiNjUxYjAxZTM1NDYwNjU5NGUwNmVlOGU2OTRlOGVlNjQ4NWZjIn0.eyJhdWQiOiIzIiwianRpIjoiMWE1ZWUyMjk4MmU1YjZkMzVkMDljYzQ3NWQwNWRmOWNlNzQ5ODlkZjg4ZGI2NTFiMDFlMzU0NjA2NTk0ZTA2ZWU4ZTY5NGU4ZWU2NDg1ZmMiLCJpYXQiOjE3OTMxMDA2NzcsIm5iZiI6MTc5MzEwMDY3NywiZXhwIjoxNzk1NjkyNjc3LCJzdWIiOiIyMzEwNDUiLCJzY29wZXMiOltdfQ.ild0ckS6fWSHEaftw5R3_K-4-T4KhNGu1mjZKjUTBdd60HA4elyKvMfZqsZO4vnDXlZHKRODiDFypCg9B1fUEVD02HlXwYvWZM_6sZNak56LqHLE_AsCBFWHOuojzV207qt5Is-qp7eKMEu9YLIc5meOlsUGZ9ydQqP80bPOoUi-B05NwWCR7zGwIvT3S00EoMxJdAb3y-UHqr6IPkdQkMHIIxTxac5_ejz7NEtOZCFGsb_lfCfEnXaOYmm4Uo7abDWCDTWThHIrDni-JRy9lfQmvmPysswDI0n_wc4PbydvJMrYCXwYYPGEoOzNYiooVojwHOzojnTp0F__Sdirk0D80jxos2l3OWMl5Cn4kOiGd5PAvaSv7xvfiHZ8RCDt-jFEM4QKeNKoEUqvLJq3iENnjTwcrsFDHvKTMF0Vw5gDRACSPvLBGtE-l2B9-QwZrVp_xY3IbSH5Nk_wzvVzhlAWZI_nKOFfJvVEzUAszAprXFqkueQerITbkjLLCSd-8njiSBbFipjaMrqVCdQ43dx70zfxtOkuEfCneIv7GAZcCSzQFO9mJLZ0ek6mmf-XdLWW_8xsR3aRfX7vzv_MD6E6UiRrRb27a5v9SqbcDWXTUTj9inC_qyaSmOf5OFgwQeNmFoeToc3MlfSIJqe4t7h5d9RWzS2kXoCeMoPCwQ0
|
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2019",
|
||||||
|
"module": "ESNext",
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"lib": ["ES2019", "DOM", "DOM.Iterable"],
|
||||||
|
|
||||||
|
"strict": false,
|
||||||
|
"noImplicitAny": false,
|
||||||
|
"strictNullChecks": false,
|
||||||
|
"useUnknownInCatchVariables": false,
|
||||||
|
|
||||||
|
"noEmit": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"allowJs": false,
|
||||||
|
"checkJs": false,
|
||||||
|
"isolatedModules": false,
|
||||||
|
"forceConsistentCasingInFileNames": true,
|
||||||
|
"resolveJsonModule": false,
|
||||||
|
"types": []
|
||||||
|
},
|
||||||
|
"include": ["src-ts/**/*.ts", "src-ts/**/*.d.ts"],
|
||||||
|
"exclude": ["node_modules", "static", "src-ts/tools"]
|
||||||
|
}
|
||||||
+419
@@ -0,0 +1,419 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""百度「步行路线规划(轻量)」:真实道路距离 + 步行耗时。
|
||||||
|
|
||||||
|
为什么要它:卡片原来只会拿直线距离 ÷ 80 米/分钟估时间,绕楼绕围墙时明显偏乐观。
|
||||||
|
百度轻量级路线规划接口(directionlite)直接给 `distance`(米)和 `duration`(秒),
|
||||||
|
且支持 `coord_type=gcj02` —— 正好和上游车辆坐标同一套,不用转换。
|
||||||
|
|
||||||
|
配额与限流(2026-11 实测控制台:0.5 万次/天,3 QPS):
|
||||||
|
- 结果按「起点+终点」四舍五入到 4 位小数(约 10 米)入库缓存 7 天;
|
||||||
|
- 进程内做 3 QPS 节流(保守取 350ms 间隔);
|
||||||
|
- 任何失败(没配 AK / 240 APP 服务被禁用 / 超时 / 配额耗尽)都退回本地估算,
|
||||||
|
绝不让卡片空着。
|
||||||
|
|
||||||
|
配置(缺一即走估算):
|
||||||
|
- 环境变量 BAIDU_ROUTE_AK / BAIDU_ROUTE_SK
|
||||||
|
- 或 server_config.json 里的 "baidu_route_ak" / "baidu_route_sk"
|
||||||
|
注意:
|
||||||
|
- 必须用**服务端**类型的 AK,且开通「步行路线规划(轻量)」;
|
||||||
|
- 页面里那个浏览器端 AK 调这个接口会返回 {"status":240,"message":"APP 服务被禁用"}(已实测);
|
||||||
|
- 若该 AK 在控制台开了「SN 校验」,请求必须带 sn(否则 211),所以需要配套的 SK,
|
||||||
|
见 `_build_query()`。
|
||||||
|
"""
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import math
|
||||||
|
import os
|
||||||
|
import sqlite3
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
from urllib.parse import quote, quote_plus, urlencode
|
||||||
|
|
||||||
|
import requests
|
||||||
|
|
||||||
|
HOST = "https://api.map.baidu.com"
|
||||||
|
PATH = "/directionlite/v1/walking"
|
||||||
|
BASE_URL = HOST + PATH
|
||||||
|
CACHE_PATH = Path(__file__).parent / "walk_cache.db"
|
||||||
|
CACHE_TTL_SECONDS = 7 * 24 * 3600
|
||||||
|
# 坐标精度:4 位小数 ≈ 11 米,够用且能显著提高缓存命中率
|
||||||
|
COORD_PRECISION = 4
|
||||||
|
# 3 QPS 配额,保守按 350ms 一次
|
||||||
|
MIN_INTERVAL_SECONDS = 0.35
|
||||||
|
REQUEST_TIMEOUT = 6
|
||||||
|
|
||||||
|
# 本地估算参数(百度不可用时兜底)
|
||||||
|
DETOUR_FACTOR = 1.3 # 直线 -> 道路的经验绕行系数
|
||||||
|
WALK_METERS_PER_MIN = 75.0 # 4.5 km/h
|
||||||
|
|
||||||
|
_lock = threading.Lock()
|
||||||
|
_last_call_at = [0.0]
|
||||||
|
_cache_ready = [False]
|
||||||
|
|
||||||
|
|
||||||
|
# ========== 配置 ==========
|
||||||
|
|
||||||
|
def _server_config() -> dict:
|
||||||
|
try:
|
||||||
|
path = Path(__file__).parent / "server_config.json"
|
||||||
|
if path.exists():
|
||||||
|
return json.loads(path.read_text("utf-8"))
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return {}
|
||||||
|
|
||||||
|
|
||||||
|
def get_ak() -> str:
|
||||||
|
"""服务端 AK:环境变量优先,其次 server_config.json 的 baidu_route_ak。"""
|
||||||
|
env = (os.environ.get("BAIDU_ROUTE_AK") or "").strip()
|
||||||
|
if env:
|
||||||
|
return env
|
||||||
|
return str(_server_config().get("baidu_route_ak") or "").strip()
|
||||||
|
|
||||||
|
|
||||||
|
def get_sk() -> str:
|
||||||
|
"""SN 校验用的 SK(私钥)。AK 未开 SN 校验时可以留空。"""
|
||||||
|
env = (os.environ.get("BAIDU_ROUTE_SK") or "").strip()
|
||||||
|
if env:
|
||||||
|
return env
|
||||||
|
return str(_server_config().get("baidu_route_sk") or "").strip()
|
||||||
|
|
||||||
|
|
||||||
|
def is_enabled() -> bool:
|
||||||
|
return bool(get_ak())
|
||||||
|
|
||||||
|
|
||||||
|
def save_credentials(ak: str, sk: str = None) -> bool:
|
||||||
|
"""把 AK/SK 写进 server_config.json(管理端弹窗用)。
|
||||||
|
|
||||||
|
sk 传 None 表示保持原值不动;传 "" 表示清空。
|
||||||
|
"""
|
||||||
|
path = Path(__file__).parent / "server_config.json"
|
||||||
|
try:
|
||||||
|
cfg = {}
|
||||||
|
if path.exists():
|
||||||
|
cfg = json.loads(path.read_text("utf-8")) or {}
|
||||||
|
cfg["baidu_route_ak"] = (ak or "").strip()
|
||||||
|
if sk is not None:
|
||||||
|
cfg["baidu_route_sk"] = (sk or "").strip()
|
||||||
|
path.write_text(json.dumps(cfg, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||||
|
return True
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[步行路线] 保存 AK/SK 失败: {exc}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def masked_credentials() -> dict:
|
||||||
|
"""给管理端回显用:AK 全量(管理员要看),SK 只回显尾 4 位。"""
|
||||||
|
ak = get_ak()
|
||||||
|
sk = get_sk()
|
||||||
|
return {"ak": ak, "sk_set": bool(sk),
|
||||||
|
"sk_tail": sk[-4:] if sk else "", "enabled": bool(ak)}
|
||||||
|
|
||||||
|
|
||||||
|
def build_query(params: dict, sk: str = "", mode: str = "official",
|
||||||
|
path: str = None) -> str:
|
||||||
|
"""按百度 SN 规则拼查询串。
|
||||||
|
|
||||||
|
百度官方样例(geocoder/v2 那份)与社区常见写法算出的 sn 不一致,
|
||||||
|
没有 SK 无法判定哪个对,所以两种都实现,由上层自动试:
|
||||||
|
- official:quote("path?query", safe=...) -> 追加 SK -> quote_plus -> md5
|
||||||
|
- simple :urlencode(按 key 升序, safe="") -> md5("path?query" + SK)
|
||||||
|
"""
|
||||||
|
api_path = path or PATH # SN 是绑路径的,换接口必须换路径
|
||||||
|
items = sorted((k, v) for k, v in params.items() if k != "sn")
|
||||||
|
if mode == "simple":
|
||||||
|
query = urlencode(items, encoding="utf-8", safe="")
|
||||||
|
if not sk:
|
||||||
|
return query
|
||||||
|
digest = hashlib.md5((api_path + "?" + query + sk).encode("utf-8")).hexdigest()
|
||||||
|
return query + "&sn=" + digest
|
||||||
|
|
||||||
|
raw_query = "&".join(f"{k}={v}" for k, v in items)
|
||||||
|
encoded = quote(api_path + "?" + raw_query, safe="/:=&?#+!$,;'@()*[]")
|
||||||
|
query = encoded[len(api_path) + 1:]
|
||||||
|
if not sk:
|
||||||
|
return query
|
||||||
|
digest = hashlib.md5(quote_plus(encoded + sk).encode("utf-8")).hexdigest()
|
||||||
|
return query + "&sn=" + digest
|
||||||
|
|
||||||
|
|
||||||
|
# 记住哪种 SN 算法能通,避免每次先撞一次 211
|
||||||
|
_SN_MODE = [None]
|
||||||
|
|
||||||
|
|
||||||
|
def _sn_modes():
|
||||||
|
if _SN_MODE[0]:
|
||||||
|
other = "simple" if _SN_MODE[0] != "simple" else "official"
|
||||||
|
return [_SN_MODE[0], other]
|
||||||
|
return ["official", "simple"]
|
||||||
|
|
||||||
|
|
||||||
|
# ========== 缓存 ==========
|
||||||
|
|
||||||
|
def _conn():
|
||||||
|
conn = sqlite3.connect(CACHE_PATH, timeout=5)
|
||||||
|
if not _cache_ready[0]:
|
||||||
|
conn.execute("""
|
||||||
|
CREATE TABLE IF NOT EXISTS walk_cache (
|
||||||
|
key TEXT PRIMARY KEY,
|
||||||
|
distance_m INTEGER NOT NULL,
|
||||||
|
duration_s INTEGER NOT NULL,
|
||||||
|
created_at REAL NOT NULL
|
||||||
|
)
|
||||||
|
""")
|
||||||
|
conn.commit()
|
||||||
|
_cache_ready[0] = True
|
||||||
|
return conn
|
||||||
|
|
||||||
|
|
||||||
|
def _cache_key(o_lat, o_lng, d_lat, d_lng) -> str:
|
||||||
|
p = COORD_PRECISION
|
||||||
|
return "%.*f,%.*f|%.*f,%.*f" % (p, o_lat, p, o_lng, p, d_lat, p, d_lng)
|
||||||
|
|
||||||
|
|
||||||
|
def _cache_get(key):
|
||||||
|
try:
|
||||||
|
conn = _conn()
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT distance_m, duration_s, created_at FROM walk_cache WHERE key = ?",
|
||||||
|
(key,)).fetchone()
|
||||||
|
conn.close()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
if time.time() - float(row[2]) > CACHE_TTL_SECONDS:
|
||||||
|
return None
|
||||||
|
return {"distance": int(row[0]), "duration": int(row[1])}
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[步行路线] 读缓存失败: {exc}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _cache_put(key, distance_m, duration_s):
|
||||||
|
try:
|
||||||
|
conn = _conn()
|
||||||
|
conn.execute(
|
||||||
|
"INSERT OR REPLACE INTO walk_cache (key, distance_m, duration_s, created_at) "
|
||||||
|
"VALUES (?, ?, ?, ?)", (key, int(distance_m), int(duration_s), time.time()))
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[步行路线] 写缓存失败: {exc}")
|
||||||
|
|
||||||
|
|
||||||
|
# ========== 节流 ==========
|
||||||
|
|
||||||
|
def _throttle():
|
||||||
|
"""全局 3 QPS 上限(百度给的并发就是 3)。"""
|
||||||
|
with _lock:
|
||||||
|
wait = _last_call_at[0] + MIN_INTERVAL_SECONDS - time.time()
|
||||||
|
if wait > 0:
|
||||||
|
time.sleep(wait)
|
||||||
|
_last_call_at[0] = time.time()
|
||||||
|
|
||||||
|
|
||||||
|
# ========== 估算兜底 ==========
|
||||||
|
|
||||||
|
# 百度各出行方式的距离上限(公里)。步行超 200km 会直接报
|
||||||
|
# "the distance of path must less then 200Km",先自己挡掉。
|
||||||
|
_MAX_ROUTE_KM = {"walking": 200, "riding": 200, "driving": 500}
|
||||||
|
|
||||||
|
|
||||||
|
def _haversine_m(lat1, lng1, lat2, lng2) -> float:
|
||||||
|
"""两点球面距离(米)。"""
|
||||||
|
r = 6371000.0
|
||||||
|
p1, p2 = math.radians(lat1), math.radians(lat2)
|
||||||
|
dphi = p2 - p1
|
||||||
|
dlmb = math.radians(lng2 - lng1)
|
||||||
|
a = math.sin(dphi / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dlmb / 2) ** 2
|
||||||
|
return 2 * r * math.asin(math.sqrt(a))
|
||||||
|
|
||||||
|
|
||||||
|
def estimate(origin_lat, origin_lng, dest_lat, dest_lng) -> dict:
|
||||||
|
"""直线 → 道路经验估算。永远有返回值。"""
|
||||||
|
try:
|
||||||
|
lat1, lng1, lat2, lng2 = map(float, (origin_lat, origin_lng, dest_lat, dest_lng))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return {"distance": 0, "duration": 0, "source": "none"}
|
||||||
|
r = 6371000.0
|
||||||
|
p1, p2 = math.radians(lat1), math.radians(lat2)
|
||||||
|
dphi = p2 - p1
|
||||||
|
dlmb = math.radians(lng2 - lng1)
|
||||||
|
a = math.sin(dphi / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dlmb / 2) ** 2
|
||||||
|
straight = 2 * r * math.asin(math.sqrt(a))
|
||||||
|
distance = int(round(straight * DETOUR_FACTOR))
|
||||||
|
duration = int(round(max(distance, 1) / WALK_METERS_PER_MIN * 60))
|
||||||
|
return {"distance": distance, "duration": duration, "straight": int(round(straight)),
|
||||||
|
"source": "estimate"}
|
||||||
|
|
||||||
|
|
||||||
|
# ========== 百度接口 ==========
|
||||||
|
|
||||||
|
def _call_baidu(ak, sk, origin_lat, origin_lng, dest_lat, dest_lng,
|
||||||
|
mode="official", api="walking", with_steps=False) -> dict:
|
||||||
|
_throttle()
|
||||||
|
params = {
|
||||||
|
"ak": ak,
|
||||||
|
"origin": f"{origin_lat:.6f},{origin_lng:.6f}",
|
||||||
|
"destination": f"{dest_lat:.6f},{dest_lng:.6f}",
|
||||||
|
"coord_type": "gcj02", # 入参坐标系:上游车辆坐标就是 GCJ02
|
||||||
|
# 关键:coord_type 只管"输入",折线默认按 BD09 返回(ret_coordtype 默认 bd09ll)。
|
||||||
|
# 不显式指定的话,前端再把 BD09 当 GCJ02 转一次,整体会偏 500~900 米。
|
||||||
|
"ret_coordtype": "gcj02",
|
||||||
|
}
|
||||||
|
if sk:
|
||||||
|
# 开了 SN 校验就必须带 timestamp(否则 status=2 timestamp is required when sn isset)
|
||||||
|
params["timestamp"] = int(time.time())
|
||||||
|
api_path = "/directionlite/v1/" + api
|
||||||
|
url = HOST + api_path + "?" + build_query(params, sk, mode, api_path)
|
||||||
|
resp = requests.get(url, timeout=REQUEST_TIMEOUT)
|
||||||
|
resp.raise_for_status()
|
||||||
|
data = resp.json()
|
||||||
|
status = data.get("status")
|
||||||
|
if status != 0:
|
||||||
|
raise RuntimeError(f"status={status} message={data.get('message')}")
|
||||||
|
result = data.get("result") or {}
|
||||||
|
# directionlite 正常返回 result.routes[0].{distance,duration};
|
||||||
|
# 少数版本把 distance/duration 直接挂在 result 上,一并兜住。
|
||||||
|
route = (result.get("routes") or [{}])[0]
|
||||||
|
distance = route.get("distance", result.get("distance"))
|
||||||
|
duration = route.get("duration", result.get("duration"))
|
||||||
|
if distance is None or duration is None:
|
||||||
|
raise RuntimeError(f"返回缺字段: {str(data)[:200]}")
|
||||||
|
out = {"distance": int(distance), "duration": int(duration)}
|
||||||
|
if with_steps:
|
||||||
|
out["steps"] = _parse_steps(route.get("steps") or [])
|
||||||
|
out["points"] = _merge_path(out["steps"])
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_steps(raw_steps) -> list:
|
||||||
|
"""把 steps[] 抽成前端要的最小集合(含折线)。"""
|
||||||
|
steps = []
|
||||||
|
for st in raw_steps:
|
||||||
|
if not isinstance(st, dict):
|
||||||
|
continue
|
||||||
|
points = []
|
||||||
|
for pair in str(st.get("path") or "").split(";"):
|
||||||
|
if not pair:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
lng_s, lat_s = pair.split(",")
|
||||||
|
points.append([float(lng_s), float(lat_s)])
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
steps.append({
|
||||||
|
"instruction": str(st.get("instruction") or ""),
|
||||||
|
"distance": int(st.get("distance") or 0),
|
||||||
|
"duration": int(st.get("duration") or 0),
|
||||||
|
"turn_type": str(st.get("turn_type") or ""),
|
||||||
|
"turn_type_id": st.get("turn_type_id"),
|
||||||
|
"points": points,
|
||||||
|
})
|
||||||
|
return steps
|
||||||
|
|
||||||
|
|
||||||
|
def _merge_path(steps, max_points=1500) -> list:
|
||||||
|
"""把所有分段的折线接成一条,超长时按等间隔抽稀。"""
|
||||||
|
points = []
|
||||||
|
for st in steps:
|
||||||
|
pts = st.get("points") or []
|
||||||
|
if points and pts and points[-1] == pts[0]:
|
||||||
|
pts = pts[1:]
|
||||||
|
points.extend(pts)
|
||||||
|
if len(points) > max_points:
|
||||||
|
stride = max(1, len(points) // max_points)
|
||||||
|
sampled = points[::stride]
|
||||||
|
if sampled[-1] != points[-1]:
|
||||||
|
sampled.append(points[-1])
|
||||||
|
return sampled
|
||||||
|
return points
|
||||||
|
|
||||||
|
|
||||||
|
def get_nav_route(origin_lat, origin_lng, dest_lat, dest_lng, api="walking") -> dict:
|
||||||
|
"""导航用:一次拿齐距离/耗时/分段指引/整条折线。失败返回 error。"""
|
||||||
|
try:
|
||||||
|
o_lat, o_lng = float(origin_lat), float(origin_lng)
|
||||||
|
d_lat, d_lng = float(dest_lat), float(dest_lng)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return {"error": "坐标非法"}
|
||||||
|
|
||||||
|
# 百度步行/骑行路线对距离有上限(超过会返回 status=2 的英文报错),
|
||||||
|
# 先自己算直线距离挡掉,别把 "the distance of path must less then 200Km" 抛给用户。
|
||||||
|
max_km = _MAX_ROUTE_KM.get(api, 200)
|
||||||
|
if max_km:
|
||||||
|
straight_km = _haversine_m(o_lat, o_lng, d_lat, d_lng) / 1000.0
|
||||||
|
if straight_km > max_km:
|
||||||
|
return {"error": f"距离太远(约 {straight_km:.0f} 公里),不提供{api}导航",
|
||||||
|
"error_kind": "too_far"}
|
||||||
|
|
||||||
|
ak = get_ak()
|
||||||
|
if not ak:
|
||||||
|
return {"error": "未配置百度 AK"}
|
||||||
|
|
||||||
|
sk = get_sk()
|
||||||
|
last_error = None
|
||||||
|
for mode in _sn_modes():
|
||||||
|
try:
|
||||||
|
got = _call_baidu(ak, sk, o_lat, o_lng, d_lat, d_lng, mode,
|
||||||
|
api=api, with_steps=True)
|
||||||
|
_SN_MODE[0] = mode
|
||||||
|
return {**got, "api": api}
|
||||||
|
except Exception as exc:
|
||||||
|
last_error = exc
|
||||||
|
text = str(exc)
|
||||||
|
if "211" not in text and "SN" not in text.upper():
|
||||||
|
break
|
||||||
|
msg = str(last_error)
|
||||||
|
if "200Km" in msg or "too long" in msg.lower():
|
||||||
|
return {"error": "距离太远,无法规划路线", "error_kind": "too_far"}
|
||||||
|
return {"error": f"百度返回失败: {last_error}"}
|
||||||
|
|
||||||
|
|
||||||
|
def get_walk_route(origin_lat, origin_lng, dest_lat, dest_lng, use_cache=True) -> dict:
|
||||||
|
"""返回 {distance(米), duration(秒), source: baidu|cache|estimate}。
|
||||||
|
|
||||||
|
source=cache 也代表数据来自百度(命中缓存)。
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
o_lat, o_lng = float(origin_lat), float(origin_lng)
|
||||||
|
d_lat, d_lng = float(dest_lat), float(dest_lng)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return estimate(origin_lat, origin_lng, dest_lat, dest_lng)
|
||||||
|
|
||||||
|
if not (math.isfinite(o_lat) and math.isfinite(o_lng)
|
||||||
|
and math.isfinite(d_lat) and math.isfinite(d_lng)):
|
||||||
|
return estimate(o_lat, o_lng, d_lat, d_lng)
|
||||||
|
|
||||||
|
key = _cache_key(o_lat, o_lng, d_lat, d_lng)
|
||||||
|
if use_cache:
|
||||||
|
hit = _cache_get(key)
|
||||||
|
if hit:
|
||||||
|
return {**hit, "source": "cache"}
|
||||||
|
|
||||||
|
ak = get_ak()
|
||||||
|
if not ak:
|
||||||
|
return estimate(o_lat, o_lng, d_lat, d_lng)
|
||||||
|
|
||||||
|
sk = get_sk()
|
||||||
|
got = None
|
||||||
|
last_error = None
|
||||||
|
for mode in _sn_modes():
|
||||||
|
try:
|
||||||
|
got = _call_baidu(ak, sk, o_lat, o_lng, d_lat, d_lng, mode)
|
||||||
|
_SN_MODE[0] = mode # 记住能通的算法
|
||||||
|
break
|
||||||
|
except Exception as exc:
|
||||||
|
last_error = exc
|
||||||
|
text = str(exc)
|
||||||
|
# 只有 SN 相关错误才值得换算法重试,其余(配额/超时)直接退回估算
|
||||||
|
if "211" not in text and "SN" not in text.upper():
|
||||||
|
break
|
||||||
|
if got is None:
|
||||||
|
print(f"[步行路线] 百度调用失败,退回估算: {last_error}")
|
||||||
|
return estimate(o_lat, o_lng, d_lat, d_lng)
|
||||||
|
|
||||||
|
_cache_put(key, got["distance"], got["duration"])
|
||||||
|
return {**got, "source": "baidu"}
|
||||||
@@ -3,10 +3,11 @@
|
|||||||
"""微信API通信模块
|
"""微信API通信模块
|
||||||
|
|
||||||
凭据模型(对照 98/ 反编译小程序与实机抓包还原):
|
凭据模型(对照 98/ 反编译小程序与实机抓包还原):
|
||||||
- token_id:登录后服务端下发的会话标识(单会话:小程序重新登录即失效)。
|
- token_id:登录后服务端下发的会话标识。上游目前唯一强校验的头,必填。
|
||||||
上游目前唯一强校验的头,必填。
|
- access_token:登录响应里的 JWT,有效期 30 天。小程序用它在本地实时计算签名:
|
||||||
- access_token:登录响应里的 JWT(30 天有效)。小程序用它在本地实时计算签名:
|
|
||||||
hsf-x-signature = sha1(access_token + base64(签名串))。选填。
|
hsf-x-signature = sha1(access_token + base64(签名串))。选填。
|
||||||
|
- 有效期到之前系统会发提醒邮件(1 天 / 1 小时 / 已过期),到期后到个人中心更新凭据即可。
|
||||||
|
不要再写「打开小程序就会让网页凭据失效」这类说法——它不是事实,只会让用户不敢用官方小程序。
|
||||||
|
|
||||||
签名策略(双模式 + 强验证开关):
|
签名策略(双模式 + 强验证开关):
|
||||||
- 常规模式:有真实 access_token 就实时计算签名;否则生成形似合法的
|
- 常规模式:有真实 access_token 就实时计算签名;否则生成形似合法的
|
||||||
@@ -265,7 +266,8 @@ def _normalize_token_invalid(result: dict, scope: str):
|
|||||||
if isinstance(result, dict) and result.get("rtn_code") == 102001:
|
if isinstance(result, dict) and result.get("rtn_code") == 102001:
|
||||||
result["token_invalid"] = True
|
result["token_invalid"] = True
|
||||||
if scope == "user":
|
if scope == "user":
|
||||||
result["message"] = "Token失效,微信凭据已过期,请在个人中心重新配置"
|
result["message"] = ("微信凭据需要更新(上游判定已失效/已过期),"
|
||||||
|
"请到个人中心重新获取并保存凭据")
|
||||||
else:
|
else:
|
||||||
result["message"] = "地图数据暂不可用:服务器全局凭据已失效,请联系管理员更新"
|
result["message"] = "地图数据暂不可用:服务器全局凭据已失效,请联系管理员更新"
|
||||||
return result
|
return result
|
||||||
@@ -406,7 +408,7 @@ _UPSTREAM_MESSAGE_MAP = (
|
|||||||
# 车辆状态
|
# 车辆状态
|
||||||
(("使用中", "骑行中"), "这辆车正在被别人骑行,换一辆试试", "occupied"),
|
(("使用中", "骑行中"), "这辆车正在被别人骑行,换一辆试试", "occupied"),
|
||||||
(("占用",), "这辆车当前被占用,换一辆试试", "occupied"),
|
(("占用",), "这辆车当前被占用,换一辆试试", "occupied"),
|
||||||
(("已被", "锁定"), "这辆车已被锁定或预约,换一辆试试", "occupied"),
|
(("已被", "锁定"), "这辆车已损坏或被锁定,换一辆试试", "occupied"),
|
||||||
# 订单/支付
|
# 订单/支付
|
||||||
(("未支付", "待支付"), "你有一笔未支付的订单,请先支付后再用车", "unpaid"),
|
(("未支付", "待支付"), "你有一笔未支付的订单,请先支付后再用车", "unpaid"),
|
||||||
(("余额", "欠费"), "账户余额不足,请先充值", "unpaid"),
|
(("余额", "欠费"), "账户余额不足,请先充值", "unpaid"),
|
||||||
|
|||||||
Reference in New Issue
Block a user