1494 lines
65 KiB
Python
1494 lines
65 KiB
Python
#!/usr/bin/env python3
|
||
# -*- coding: utf-8 -*-
|
||
"""租赁/订单路由 — 照搬 app.py.bak 原始逻辑"""
|
||
import json
|
||
import math
|
||
import random
|
||
import datetime as dt
|
||
import threading
|
||
import time
|
||
from functools import wraps
|
||
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 routes.auth import get_current_user
|
||
from wechat import request_api, request_with_user_auth
|
||
from timer import (start_rental_timer, _cancel_rental_timers, _get_remaining_seconds,
|
||
_check_user_order, auto_return_bike)
|
||
from rental_mail import get_rental_mail_context, resolve_return_token
|
||
|
||
bp = Blueprint("rental", __name__)
|
||
|
||
_email_return_locks = {}
|
||
_email_return_locks_guard = threading.Lock()
|
||
_order_return_locks = {}
|
||
_order_return_locks_guard = threading.Lock()
|
||
|
||
|
||
def _email_return_lock(rental_id: int):
|
||
with _email_return_locks_guard:
|
||
return _email_return_locks.setdefault(rental_id, threading.Lock())
|
||
|
||
|
||
def _serialize_order_return(func):
|
||
"""同一订单的重复还车请求串行执行,避免重复调用上游锁车接口。"""
|
||
@wraps(func)
|
||
def wrapped(*args, **kwargs):
|
||
data = request.get_json(silent=True) or {}
|
||
key = str(data.get("order_id") or "missing")
|
||
with _order_return_locks_guard:
|
||
lock = _order_return_locks.setdefault(key, threading.Lock())
|
||
with lock:
|
||
return func(*args, **kwargs)
|
||
return wrapped
|
||
|
||
|
||
def _upstream_order_finished(user_id: int, order_id) -> bool:
|
||
"""还车响应不明确时,确认指定订单是否已经不再骑行。"""
|
||
result = request_with_user_auth(user_id, "GET", "/user/info", _silent=True)
|
||
if result.get("rtn_code") != 0:
|
||
return False
|
||
non_deal = (result.get("data") or {}).get("nonDealOrder")
|
||
if not non_deal or not non_deal.get("order_id"):
|
||
return True
|
||
if str(non_deal.get("order_id")) != str(order_id):
|
||
return True
|
||
return str(non_deal.get("status")) != "2"
|
||
|
||
|
||
def _return_page(**context):
|
||
response = make_response(render_template("email_return.html", **context))
|
||
response.headers["Cache-Control"] = "no-store, max-age=0"
|
||
response.headers["Pragma"] = "no-cache"
|
||
response.headers["Referrer-Policy"] = "no-referrer"
|
||
response.headers["X-Frame-Options"] = "DENY"
|
||
return response
|
||
|
||
|
||
# ========== 工具函数 ==========
|
||
|
||
def _try_card_pay_auto(user_id: int, order_id: str, code: str) -> dict:
|
||
"""
|
||
自动尝试用月卡/周卡支付订单(从 app.py.bak 原样复制)
|
||
返回: {"success": True/False, "message": "xxx"}
|
||
"""
|
||
methods_result = request_with_user_auth(
|
||
user_id, "GET", "/pay/methods",
|
||
params={"code": code}
|
||
)
|
||
if methods_result.get("rtn_code") != 0:
|
||
return {"success": False, "message": "查询支付方式失败"}
|
||
|
||
data = methods_result.get("data", {})
|
||
methods = data if isinstance(data, list) else data.get("payMethods", data.get("methods", []))
|
||
card_methods = [m for m in methods if str(m.get("type")) in ("3", "4")]
|
||
|
||
if not card_methods:
|
||
return {"success": False, "message": "没有可用的月卡/周卡"}
|
||
|
||
preferred = card_methods[0]
|
||
for m in card_methods:
|
||
if m.get("get_type") == 2:
|
||
preferred = m
|
||
break
|
||
|
||
pay_type = str(preferred.get("type", "3"))
|
||
package_id = str(preferred.get("package_id", ""))
|
||
if not package_id:
|
||
return {"success": False, "message": "卡包ID为空"}
|
||
|
||
card_name = "月卡" if pay_type == "3" else "周卡"
|
||
print(f"[_try_card_pay_auto] 使用{card_name}支付: order_id={order_id}, code={code}, package_id={package_id}")
|
||
|
||
pay_result = request_with_user_auth(
|
||
user_id, "POST", "/pay/submit",
|
||
data={"platform": "1", "order_id": order_id, "code": code,
|
||
"type": pay_type, "package_id": package_id}
|
||
)
|
||
|
||
# 解析 /pay/submit 返回的支付状态:data 可能是 dict / 列表 / 空列表 / None,
|
||
# 需全部兜底,避免空列表 [0] 越界抛异常(否则还车成功但自动支付崩→整请求500被前端判失败)。
|
||
_pd = pay_result.get("data")
|
||
if isinstance(_pd, list):
|
||
pay_status = str(_pd[0].get("status", "")) if _pd and isinstance(_pd[0], dict) else ""
|
||
elif isinstance(_pd, dict):
|
||
pay_status = str(_pd.get("status", ""))
|
||
else:
|
||
pay_status = ""
|
||
if pay_status == "0":
|
||
return {"success": True, "message": f"{card_name}支付成功"}
|
||
elif pay_status == "1":
|
||
return {"success": False, "message": f"{card_name}余额不足,需要微信支付"}
|
||
else:
|
||
return {"success": False, "message": pay_result.get("message", "支付失败")}
|
||
|
||
|
||
def get_nearest_park_point(lat: float, lng: float) -> dict:
|
||
"""获取最近的停车点坐标(从 app.py.bak 原样复制)"""
|
||
result = request_api("GET", "/project/map", params={"type": "1"})
|
||
if result.get("rtn_code") != 0 or not result.get("data"):
|
||
return None
|
||
bike_stations = result["data"].get("bicycleStation", [])
|
||
if not bike_stations:
|
||
return None
|
||
nearest = None
|
||
min_dist = float('inf')
|
||
for station in bike_stations:
|
||
station_lat = station.get("latitude") or station.get("lat")
|
||
station_lng = station.get("longitude") or station.get("lng")
|
||
if not station_lat or not station_lng:
|
||
continue
|
||
dist = math.sqrt((station_lat - lat) ** 2 + (station_lng - lng) ** 2)
|
||
if dist < min_dist:
|
||
min_dist = dist
|
||
nearest = {"latitude": station_lat, "longitude": station_lng}
|
||
return nearest
|
||
|
||
|
||
def _near_coord(lat, lng, jitter=0.0001):
|
||
"""车辆坐标附近加随机抖动,模拟真实定位。返回 (lat, lng)"""
|
||
try:
|
||
lat = float(lat)
|
||
lng = float(lng)
|
||
except (TypeError, ValueError):
|
||
lat, lng = 36.67, 116.98
|
||
return lat + random.uniform(-jitter, jitter), lng + random.uniform(-jitter, jitter)
|
||
|
||
|
||
def _fetch_live_bike_coord(user_id: int, code: str, btype=None):
|
||
"""实时从 /project/map 抓取该车当前坐标(地图坐标空间,与网页一致)。
|
||
车会被骑走导致位置变化,故必须实时抓,而非用 /project/bicycle 的静止坐标。
|
||
返回 (latitude, longitude) 或 None"""
|
||
types = []
|
||
if btype:
|
||
types.append(str(btype))
|
||
for t in ["1", "3", "6"]:
|
||
if t not in types:
|
||
types.append(t)
|
||
for t in types:
|
||
try:
|
||
res = request_with_user_auth(user_id, "GET", "/project/map",
|
||
params={"type": t}, _silent=True)
|
||
except Exception:
|
||
continue
|
||
if res.get("rtn_code") != 0:
|
||
continue
|
||
stations = ((res.get("data") or {}).get("bicycleStation")) or []
|
||
for st in stations:
|
||
if str(st.get("code")) == str(code) and st.get("latitude") and st.get("longitude"):
|
||
return st["latitude"], st["longitude"]
|
||
return None
|
||
|
||
|
||
def _resolve_order_location(user_id: int, code: str, latitude, longitude):
|
||
"""按还车的同一套规则校验并解析订单操作位置。
|
||
|
||
临时锁车也需要把当前位置同步给车辆服务,因此不能复用一键开锁时
|
||
的车辆坐标或随机坐标。停车点校验失败时,沿用还车逻辑切到最近停车点。
|
||
"""
|
||
check_result = request_with_user_auth(
|
||
user_id, "POST", "/record/checkLocation",
|
||
data={"longitude": longitude, "latitude": latitude, "bicycleCode": code}
|
||
)
|
||
|
||
use_nearest = False
|
||
if check_result.get("rtn_code") != 0 or check_result.get("parkNoShow") is True:
|
||
nearest = get_nearest_park_point(latitude, longitude)
|
||
if nearest:
|
||
latitude = nearest.get("latitude") or nearest.get("lat")
|
||
longitude = nearest.get("longitude") or nearest.get("lng")
|
||
use_nearest = True
|
||
|
||
return latitude, longitude, use_nearest
|
||
|
||
|
||
def _location_label(latitude, longitude):
|
||
"""GCJ02 坐标 -> 「博学楼附近」标签(未配置校园地点时返回 None)。"""
|
||
try:
|
||
from campus import resolve_location_label
|
||
return resolve_location_label(latitude, longitude)
|
||
except Exception as e:
|
||
print(f"[地点解析] 失败: {e}")
|
||
return None
|
||
|
||
|
||
def _set_rental_start(conn, rental_id, latitude, longitude):
|
||
"""在给定连接上回填订单起点坐标与位置标签(GCJ02,与上游接口同一坐标系)。
|
||
旧库/极简 schema 缺列时自动补列重试一次。"""
|
||
try:
|
||
lat = float(latitude)
|
||
lng = float(longitude)
|
||
except (TypeError, ValueError):
|
||
return
|
||
label = _location_label(lat, lng)
|
||
sql = """
|
||
UPDATE rentals SET start_latitude = ?, start_longitude = ?, start_label = ?
|
||
WHERE id = ?
|
||
"""
|
||
params = (lat, lng, label, rental_id)
|
||
try:
|
||
conn.execute(sql, params)
|
||
except Exception as e:
|
||
if "no such column" not in str(e).lower():
|
||
raise
|
||
for col_def in [("start_latitude", "REAL"), ("start_longitude", "REAL"),
|
||
("start_label", "TEXT")]:
|
||
try:
|
||
conn.execute(f"ALTER TABLE rentals ADD COLUMN {col_def[0]} {col_def[1]}")
|
||
except Exception:
|
||
pass
|
||
conn.execute(sql, params)
|
||
|
||
|
||
def _record_rental_start(rental_id: int, latitude, longitude):
|
||
"""回填订单起点坐标与位置标签。"""
|
||
conn = get_db()
|
||
try:
|
||
_set_rental_start(conn, rental_id, latitude, longitude)
|
||
conn.commit()
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def _set_rental_finished(conn, where_sql, where_params, latitude, longitude):
|
||
"""在给定连接上结束订单并回填终点(供本模块与 share 模块复用,
|
||
连接由调用方提供 —— 各蓝图各自管理事务/测试替身)。
|
||
|
||
旧库/极简 schema 缺列时自动补列重试一次。
|
||
"""
|
||
end_lat = None
|
||
end_lng = None
|
||
try:
|
||
end_lat, end_lng = float(latitude), float(longitude)
|
||
except (TypeError, ValueError):
|
||
pass
|
||
label = _location_label(end_lat, end_lng) if end_lat is not None else None
|
||
tz = dt.timezone(dt.timedelta(hours=8))
|
||
now_str = dt.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
|
||
sql = f"""
|
||
UPDATE rentals SET expired = 1, returned_at = ?,
|
||
end_latitude = ?, end_longitude = ?, end_label = ?
|
||
{where_sql}
|
||
"""
|
||
params = (now_str, end_lat, end_lng, label, *where_params)
|
||
try:
|
||
conn.execute(sql, params)
|
||
except Exception as e:
|
||
if "no such column" not in str(e).lower():
|
||
raise
|
||
# 轻量兜底:缺列补齐后重试
|
||
for col_def in [("returned_at", "TIMESTAMP"), ("end_latitude", "REAL"),
|
||
("end_longitude", "REAL"), ("end_label", "TEXT")]:
|
||
try:
|
||
conn.execute(f"ALTER TABLE rentals ADD COLUMN {col_def[0]} {col_def[1]}")
|
||
except Exception:
|
||
pass
|
||
conn.execute(sql, params)
|
||
|
||
|
||
def _record_rental_end(order_id: str, user_id: int, latitude, longitude):
|
||
"""标记订单结束:实际还车时间 + 终点坐标与位置标签。"""
|
||
conn = get_db()
|
||
try:
|
||
_set_rental_finished(conn, "WHERE order_id = ? AND user_id = ? AND expired = 0",
|
||
(str(order_id), user_id), latitude, longitude)
|
||
conn.commit()
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
# ========== 订单路由(原样复制自 app.py.bak) ==========
|
||
|
||
@bp.route("/api/order/unlock", methods=["POST"])
|
||
def order_unlock():
|
||
"""一键开锁(使用用户凭据)。
|
||
说明:下单坐标以 /project/bicycle 返回的车辆真实坐标为准并加随机抖动,
|
||
不采用客户端(网页/App)上报的 GPS,避免真实GPS与车辆坐标相差数百米被判“远程扫码”。
|
||
"""
|
||
user = get_current_user()
|
||
if not user:
|
||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||
|
||
data = request.get_json() or {}
|
||
code = data.get("code", "")
|
||
|
||
if not code:
|
||
return jsonify({"rtn_code": 400, "message": "缺少车辆编码"})
|
||
|
||
# 扫码、下单、开锁三连统一使用同一用户 token(与小程序一致,避免后端判定"远程扫码")
|
||
bike_result = request_with_user_auth(
|
||
user["id"], "POST", "/project/bicycle", data={"code": code}
|
||
)
|
||
if bike_result.get("rtn_code") != 0:
|
||
return jsonify({"rtn_code": bike_result.get("rtn_code", 500),
|
||
"message": bike_result.get("message", "获取车辆信息失败")})
|
||
|
||
# 用实时地图坐标(+抖动)作为下单起点:优先 /project/map 抓该车当前坐标(车会被骑走、位置会变),
|
||
# 取不到再退回 /project/bicycle 的坐标。绕开"坐标空间/位置已变"导致的远程拦截。
|
||
bike_data = bike_result.get("data") or {}
|
||
live = _fetch_live_bike_coord(user["id"], code, bike_data.get("type"))
|
||
if live:
|
||
latitude, longitude = _near_coord(live[0], live[1])
|
||
else:
|
||
latitude, longitude = _near_coord(
|
||
bike_data.get("latitude", 36.67), bike_data.get("longitude", 116.98)
|
||
)
|
||
|
||
user_name = get_user_display_name(user["id"])
|
||
print(f"[操作日志] 一键开锁: code={code}, 使用实时地图坐标 lat={latitude:.6f}, lng={longitude:.6f}, user={user_name}")
|
||
|
||
order_result = request_with_user_auth(
|
||
user["id"], "POST", "/record/order",
|
||
data={"code": code, "start_longitude": longitude, "start_latitude": latitude}
|
||
)
|
||
|
||
if order_result.get("rtn_code") != 0 or not order_result.get("data", {}).get("order_id"):
|
||
order_msg = order_result.get("message", "创建订单失败")
|
||
if order_result.get("rtn_code") == 102001 or "token" in order_msg.lower():
|
||
return jsonify({"rtn_code": 102001, "message": "Token失效,微信凭据已过期,请在个人中心重新配置"})
|
||
if "未支付" in order_msg or "待支付" in order_msg or "non" in order_msg.lower():
|
||
print(f"[开锁] 检测到未支付订单,尝试自动月卡支付: code={code}")
|
||
info_result = request_with_user_auth(user["id"], "GET", "/user/info")
|
||
non_deal = info_result.get("data", {}).get("nonDealOrder")
|
||
if non_deal and non_deal.get("order_id"):
|
||
unpaid_order_id = non_deal["order_id"]
|
||
unpaid_code = non_deal.get("code", code)
|
||
pay_result = _try_card_pay_auto(user["id"], unpaid_order_id, unpaid_code)
|
||
if pay_result["success"]:
|
||
print(f"[开锁] 月卡支付成功,重新创建订单: {pay_result['message']}")
|
||
order_result = request_with_user_auth(
|
||
user["id"], "POST", "/record/order",
|
||
data={"code": code, "start_longitude": longitude, "start_latitude": latitude}
|
||
)
|
||
else:
|
||
return jsonify({"rtn_code": 400,
|
||
"message": f"未支付订单处理失败: {pay_result['message']}",
|
||
"need_pay": True, "unpaid_order_id": unpaid_order_id,
|
||
"unpaid_code": unpaid_code})
|
||
|
||
if order_result.get("rtn_code") != 0 or not order_result.get("data", {}).get("order_id"):
|
||
from wechat import friendly_upstream_message
|
||
final_msg = friendly_upstream_message(order_result.get("message", ""),
|
||
fallback="创建订单失败,请稍后重试")
|
||
if order_result.get("rtn_code") == 102001 or "token" in str(order_result.get("message", "")).lower():
|
||
final_msg = "Token失效,微信凭据已过期,请在个人中心重新配置"
|
||
return jsonify({"rtn_code": order_result.get("rtn_code", 500),
|
||
"message": final_msg})
|
||
|
||
order_id = order_result["data"]["order_id"]
|
||
|
||
open_result = request_with_user_auth(
|
||
user["id"], "POST", "/record/qrOrder",
|
||
data={"order_id": order_id}
|
||
)
|
||
|
||
if open_result.get("rtn_code") == 0:
|
||
tz = dt.timezone(dt.timedelta(hours=8))
|
||
now_beijing = dt.datetime.now(tz)
|
||
duration = get_user_rental_settings(user["id"])["rental_duration_minutes"]
|
||
end_time = now_beijing + dt.timedelta(minutes=duration)
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
cursor.execute("""
|
||
INSERT INTO rentals (id, order_id, bike_code, email, user_id, start_time, end_time,
|
||
duration, expired, source)
|
||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, 'unlock')
|
||
""", (int(order_id), 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))
|
||
conn.commit()
|
||
conn.close()
|
||
|
||
start_rental_timer(rental_id=int(order_id), email=user["email"],
|
||
bike_code=code, duration_minutes=duration, user_id=user["id"])
|
||
_record_rental_start(int(order_id), latitude, longitude)
|
||
# 带上轮次预估:前端租车条要显示「共N轮 · 预计HH:MM还车」
|
||
row = get_db().execute(
|
||
"SELECT renewal_round, rounds_override, end_time FROM rentals WHERE id = ?",
|
||
(int(order_id),)).fetchone()
|
||
summary = _rounds_summary(
|
||
dict(row) if row else {"order_id": str(order_id),
|
||
"end_time": end_time.strftime("%Y-%m-%d %H:%M:%S")},
|
||
user["id"])
|
||
return jsonify({"rtn_code": 0, "message": "开锁成功", "order_id": order_id,
|
||
"data": {**summary, "remaining": duration * 60}})
|
||
else:
|
||
from wechat import friendly_upstream_message
|
||
raw_open_msg = open_result.get("message", "")
|
||
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": open_result.get("rtn_code", 500),
|
||
"message": friendly_upstream_message(raw_open_msg, fallback="开锁失败,请稍后重试"),
|
||
"order_id": order_id})
|
||
|
||
|
||
@bp.route("/api/order/temp_unlock", methods=["POST"])
|
||
def order_temp_unlock():
|
||
"""进行中电动车订单临时开锁(不创建新订单、不改变订单状态)。"""
|
||
user = get_current_user()
|
||
if not user:
|
||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||
|
||
data = request.get_json() or {}
|
||
order_id = data.get("order_id")
|
||
if not order_id:
|
||
return jsonify({"rtn_code": 400, "message": "缺少订单ID"})
|
||
|
||
result = request_with_user_auth(
|
||
user["id"], "POST", "/record/open", data={"order_id": order_id}
|
||
)
|
||
if result.get("rtn_code") == 0:
|
||
return jsonify({"rtn_code": 0, "message": result.get("message", "临时开锁成功"),
|
||
"data": result.get("data")})
|
||
return jsonify({"rtn_code": result.get("rtn_code", 500),
|
||
"message": result.get("message", "临时开锁失败"),
|
||
"data": result.get("data")})
|
||
|
||
|
||
@bp.route("/api/order/temp_lock", methods=["POST"])
|
||
def order_temp_lock():
|
||
"""进行中电动车订单临时锁车,并按还车逻辑上报当前位置。"""
|
||
user = get_current_user()
|
||
if not user:
|
||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||
|
||
data = request.get_json() or {}
|
||
order_id = data.get("order_id")
|
||
code = str(data.get("code") or "").strip()
|
||
latitude = data.get("latitude")
|
||
longitude = data.get("longitude")
|
||
|
||
if not order_id:
|
||
return jsonify({"rtn_code": 400, "message": "缺少订单ID"})
|
||
if not code:
|
||
return jsonify({"rtn_code": 400, "message": "缺少车辆编码"})
|
||
if latitude is None or longitude is None:
|
||
return jsonify({"rtn_code": 400, "message": "缺少位置信息"})
|
||
|
||
try:
|
||
latitude = float(latitude)
|
||
longitude = float(longitude)
|
||
if not math.isfinite(latitude) or not math.isfinite(longitude):
|
||
raise ValueError
|
||
except (TypeError, ValueError):
|
||
return jsonify({"rtn_code": 400, "message": "位置信息无效"})
|
||
|
||
user_name = get_user_display_name(user["id"])
|
||
print(f"[操作日志] 临时锁车: order_id={order_id}, code={code}, "
|
||
f"lat={latitude}, lng={longitude}, user={user_name}")
|
||
|
||
latitude, longitude, use_nearest = _resolve_order_location(
|
||
user["id"], code, latitude, longitude
|
||
)
|
||
|
||
# 原电动车端的临时锁车顺序:先上报中控位置,再执行 record/close。
|
||
coordinate_result = request_with_user_auth(
|
||
user["id"], "POST", "/project/coordinate",
|
||
data={"order_id": order_id, "code": code}
|
||
)
|
||
coordinate_ok = coordinate_result.get("success")
|
||
if coordinate_ok is None:
|
||
coordinate_ok = coordinate_result.get("rtn_code") == 0
|
||
if not coordinate_ok:
|
||
return jsonify({"rtn_code": coordinate_result.get("rtn_code", 500),
|
||
"message": coordinate_result.get("message", "中控定位失败,请重试"),
|
||
"used_nearest": use_nearest})
|
||
|
||
lock_result = request_with_user_auth(
|
||
user["id"], "POST", "/record/close",
|
||
data={"order_id": order_id, "end_longitude": longitude,
|
||
"end_latitude": latitude}
|
||
)
|
||
if lock_result.get("rtn_code") == 0:
|
||
return jsonify({"rtn_code": 0,
|
||
"message": lock_result.get("message", "临时锁车成功"),
|
||
"data": lock_result.get("data"),
|
||
"used_nearest": use_nearest})
|
||
return jsonify({"rtn_code": lock_result.get("rtn_code", 500),
|
||
"message": lock_result.get("message", "临时锁车失败"),
|
||
"data": lock_result.get("data"),
|
||
"used_nearest": use_nearest})
|
||
|
||
|
||
@bp.route("/api/order/return", methods=["POST"])
|
||
@_serialize_order_return
|
||
def order_return():
|
||
"""还车(使用用户凭据,自动处理位置)"""
|
||
user = get_current_user()
|
||
if not user:
|
||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||
|
||
data = request.get_json() or {}
|
||
order_id = data.get("order_id")
|
||
latitude = data.get("latitude")
|
||
longitude = data.get("longitude")
|
||
|
||
if not order_id:
|
||
return jsonify({"rtn_code": 400, "message": "缺少订单ID"})
|
||
if not latitude or not longitude:
|
||
return jsonify({"rtn_code": 400, "message": "缺少位置信息"})
|
||
|
||
conn = get_db()
|
||
finished = conn.execute("""
|
||
SELECT 1 FROM rentals
|
||
WHERE order_id = ? AND user_id = ? AND expired = 1
|
||
LIMIT 1
|
||
""", (str(order_id), user["id"])).fetchone()
|
||
conn.close()
|
||
if finished:
|
||
return jsonify({"rtn_code": 0, "message": "订单已结束,无需重复还车"})
|
||
|
||
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}")
|
||
|
||
latitude, longitude, use_nearest = _resolve_order_location(
|
||
user["id"], data.get("code", ""), latitude, longitude
|
||
)
|
||
|
||
return_result = request_with_user_auth(
|
||
user["id"], "POST", "/record/return",
|
||
data={"order_id": order_id, "longitude": longitude, "latitude": latitude}
|
||
)
|
||
|
||
confirmed_by_status = False
|
||
if return_result.get("rtn_code") != 0:
|
||
for attempt in range(4):
|
||
if attempt:
|
||
time.sleep(1)
|
||
if _upstream_order_finished(user["id"], order_id):
|
||
confirmed_by_status = True
|
||
break
|
||
|
||
if return_result.get("rtn_code") == 0 or confirmed_by_status:
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
# unlock 记录的 id 通常等于 order_id,但 sync 记录使用自增 id。
|
||
# 必须按 order_id 查找真实 rental_id,否则网页还车后邮件计时器也会残留。
|
||
cursor.execute("""
|
||
SELECT id FROM rentals
|
||
WHERE order_id = ? AND user_id = ? AND expired = 0
|
||
""", (str(order_id), user["id"]))
|
||
rental_ids = [row["id"] for row in cursor.fetchall()]
|
||
conn.close()
|
||
# 统一回填:expired=1 + 实际还车时间 + 终点坐标/位置标签
|
||
_record_rental_end(order_id, user["id"], latitude, longitude)
|
||
for rental_id in rental_ids:
|
||
_cancel_rental_timers(rental_id)
|
||
_user_info_cache.pop(user["id"], None)
|
||
|
||
# 还车已成功。自动尝试月卡/周卡支付仅作为附加操作,任何异常都不应让已成功的还车被前端判为失败。
|
||
pay_result = {}
|
||
try:
|
||
pay_result = _try_card_pay_auto(user["id"], str(order_id), data.get("code", "")) or {}
|
||
except Exception as e:
|
||
print(f"[order_return] 自动卡支付异常(不影响还车结果): {e}")
|
||
pay_result = {}
|
||
pay_msg = pay_result.get("message", "")
|
||
pay_success = bool(pay_result.get("success"))
|
||
|
||
success_message = "还车成功"
|
||
if confirmed_by_status:
|
||
success_message += "(已通过订单状态确认)"
|
||
return jsonify({"rtn_code": 0,
|
||
"message": success_message + (f",{pay_msg}" if pay_success else ""),
|
||
"used_nearest": use_nearest, "card_pay": pay_result})
|
||
else:
|
||
return jsonify({"rtn_code": return_result.get("rtn_code", 500),
|
||
"message": return_result.get("message", "还车失败")})
|
||
|
||
|
||
# /user/info 结果的短缓存:前端每 20s 轮询订单状态,
|
||
# 不必每次都打上游。缓存 60s,订单变化最多延迟一分钟可见。
|
||
_user_info_cache: dict = {}
|
||
_USER_INFO_TTL = 60
|
||
|
||
|
||
def _get_user_info_cached(user_id: int) -> dict:
|
||
import time as _t
|
||
hit = _user_info_cache.get(user_id)
|
||
now = _t.time()
|
||
if hit and now - hit[0] < _USER_INFO_TTL:
|
||
return hit[1]
|
||
result = request_with_user_auth(user_id, "GET", "/user/info", _silent=True)
|
||
if result.get("rtn_code") == 0: # 失败不缓存,便于立即重试
|
||
_user_info_cache[user_id] = (now, result)
|
||
return result
|
||
|
||
|
||
@bp.route("/api/order/status")
|
||
def order_status():
|
||
"""获取用户订单状态(需要用户已配置凭据)"""
|
||
user = get_current_user()
|
||
if not user:
|
||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||
|
||
token_id, access_token = get_user_auth(user["id"])
|
||
if not token_id:
|
||
return jsonify({"rtn_code": 0, "has_credentials": False, "message": "用户未配置微信签名"})
|
||
|
||
result = _get_user_info_cached(user["id"])
|
||
if result.get("rtn_code") != 0:
|
||
return jsonify({"rtn_code": result.get("rtn_code", 500), "has_credentials": True,
|
||
"message": result.get("message", "获取失败")})
|
||
|
||
data = result.get("data", {})
|
||
non_deal_order = data.get("nonDealOrder")
|
||
|
||
if not non_deal_order or not non_deal_order.get("order_id"):
|
||
return jsonify({"rtn_code": 0, "has_credentials": True, "has_order": False, "order": None})
|
||
|
||
# 共享标记:该订单若是"我共享出去、别人正在用",返回 shared 信息供前端显示"共享中"
|
||
shared = None
|
||
try:
|
||
import datetime as _dt
|
||
_tz = _dt.timezone(_dt.timedelta(hours=8))
|
||
_now = _dt.datetime.now(_tz).strftime("%Y-%m-%d %H:%M:%S")
|
||
_conn = get_db()
|
||
_cur = _conn.cursor()
|
||
_cur.execute("""
|
||
SELECT r.*, rider.email AS rider_email FROM rentals r
|
||
LEFT JOIN users rider ON rider.id = r.rider_user_id
|
||
WHERE order_id = ? AND user_id = ? AND expired = 0 AND end_time > ?
|
||
AND rider_user_id IS NOT NULL AND rider_user_id != ?
|
||
LIMIT 1
|
||
""", (str(non_deal_order.get("order_id")), user["id"], _now, user["id"]))
|
||
_rental_row = _cur.fetchone()
|
||
_rental = dict(_rental_row) if _rental_row else None
|
||
# 车主(owner,即当前登录用户)给用车方(rider)起的私密备注,仅 owner 侧显示
|
||
_owner_remark = ""
|
||
if _rental:
|
||
_cur.execute("""
|
||
SELECT owner_remark FROM shares
|
||
WHERE owner_user_id = ? AND rider_user_id = ?
|
||
ORDER BY id DESC LIMIT 1
|
||
""", (user["id"], _rental["rider_user_id"]))
|
||
_shr = _cur.fetchone()
|
||
if _shr and _shr["owner_remark"]:
|
||
_owner_remark = _shr["owner_remark"]
|
||
_conn.close()
|
||
if _rental:
|
||
from db import get_user_display_name
|
||
shared = {
|
||
"rental_id": _rental["id"],
|
||
"rider_user_id": _rental["rider_user_id"],
|
||
"rider_email": _rental.get("rider_email"),
|
||
"rider_name": get_user_display_name(_rental["rider_user_id"]),
|
||
"remark": _owner_remark,
|
||
"bike_code": _rental["bike_code"],
|
||
}
|
||
if not shared["rider_email"]:
|
||
_conn2 = get_db()
|
||
_c2 = _conn2.cursor()
|
||
_c2.execute("SELECT email FROM users WHERE id = ?", (_rental["rider_user_id"],))
|
||
_r2 = _c2.fetchone()
|
||
_conn2.close()
|
||
if _r2:
|
||
shared["rider_email"] = _r2["email"]
|
||
except Exception as exc:
|
||
print(f"[订单状态] 识别共享订单失败: {exc}")
|
||
|
||
order_status_value = non_deal_order.get("status")
|
||
if str(order_status_value) in ("1", "2"):
|
||
order_status_value = int(order_status_value)
|
||
return jsonify({"rtn_code": 0, "has_credentials": True, "has_order": True,
|
||
"order": {"order_id": non_deal_order.get("order_id"),
|
||
"status": order_status_value, # 1=未支付, 2=进行中
|
||
"code": non_deal_order.get("code"),
|
||
"type": non_deal_order.get("type"),
|
||
"lock_protocol_id": non_deal_order.get("lock_protocol_id"),
|
||
"shared": shared}})
|
||
|
||
|
||
@bp.route("/api/order/pay_methods", methods=["GET"])
|
||
def order_pay_methods():
|
||
"""获取订单可用支付方式(代理 /pay/methods)"""
|
||
user = get_current_user()
|
||
if not user:
|
||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||
code = request.args.get("code", "").strip()
|
||
if not code:
|
||
return jsonify({"rtn_code": 400, "message": "缺少 code 参数"})
|
||
result = request_with_user_auth(user["id"], "GET", "/pay/methods", params={"code": code})
|
||
if result.get("rtn_code") != 0:
|
||
return jsonify({"rtn_code": result.get("rtn_code", 500),
|
||
"message": result.get("message", "获取支付方式失败"),
|
||
"data": {"methods": []}})
|
||
data = result.get("data", {})
|
||
methods = data if isinstance(data, list) else data.get("payMethods", data.get("methods", []))
|
||
card_methods = [m for m in methods if str(m.get("type")) in ("3", "4")]
|
||
return jsonify({"rtn_code": 0, "data": {"methods": methods, "has_card": len(card_methods) > 0,
|
||
"card_methods": card_methods}})
|
||
|
||
|
||
@bp.route("/api/order/pay_with_card", methods=["POST"])
|
||
def order_pay_with_card():
|
||
"""月卡/周卡自动支付订单(代理 POST /pay/submit)"""
|
||
user = get_current_user()
|
||
if not user:
|
||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||
data = request.get_json() or {}
|
||
order_id = data.get("order_id")
|
||
code = data.get("code")
|
||
pay_type = data.get("type", "3")
|
||
package_id = data.get("package_id")
|
||
if not order_id or not code or not package_id:
|
||
return jsonify({"rtn_code": 400, "message": "缺少参数"})
|
||
|
||
card_name = "月卡" if pay_type == "3" else "周卡"
|
||
print(f"[pay_with_card] user={user.get('email')}, order_id={order_id}, type={card_name}, package_id={package_id}")
|
||
|
||
result = request_with_user_auth(user["id"], "POST", "/pay/submit", data={
|
||
"platform": "1", "order_id": order_id, "code": code,
|
||
"type": pay_type, "package_id": package_id
|
||
})
|
||
|
||
# 解析 /pay/submit 返回的支付状态:data 可能是 dict / 列表 / 空列表 / None,需全部兜底
|
||
_pd = result.get("data")
|
||
if isinstance(_pd, list):
|
||
pay_status = str(_pd[0].get("status", "")) if _pd and isinstance(_pd[0], dict) else ""
|
||
elif isinstance(_pd, dict):
|
||
pay_status = str(_pd.get("status", ""))
|
||
else:
|
||
pay_status = ""
|
||
if pay_status == "0":
|
||
return jsonify({"rtn_code": 0, "success": True,
|
||
"message": f"{card_name}支付成功", "need_wechat_pay": False})
|
||
elif pay_status == "1":
|
||
return jsonify({"rtn_code": 0, "success": False,
|
||
"message": f"{card_name}余额不足,需要微信支付",
|
||
"need_wechat_pay": True})
|
||
else:
|
||
return jsonify({"rtn_code": result.get("rtn_code", 0),
|
||
"message": result.get("message", "支付结果未知"),
|
||
"data": result.get("data", {})})
|
||
|
||
|
||
# ========== 租赁计时路由(原样复制自 app.py.bak) ==========
|
||
|
||
@bp.route("/api/rental/start", methods=["POST"])
|
||
def rental_start():
|
||
"""开始用车计时"""
|
||
print(f"[rental/start] Headers: {dict(request.headers)}")
|
||
user = get_current_user()
|
||
print(f"[rental/start] User: {user}")
|
||
if not user:
|
||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||
|
||
data = request.get_json() or {}
|
||
bike_code = str(data.get("bike_code", "")).strip()
|
||
if not bike_code:
|
||
return jsonify({"rtn_code": 400, "message": "缺少 bike_code"})
|
||
|
||
tz = dt.timezone(dt.timedelta(hours=8))
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
|
||
now_beijing = dt.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
|
||
cursor.execute("SELECT * FROM rentals WHERE email = ? AND expired = 0 AND end_time > ?",
|
||
(user["email"], now_beijing))
|
||
existing = cursor.fetchone()
|
||
if existing:
|
||
conn.close()
|
||
return jsonify({"rtn_code": 400, "message": "您已有进行中的用车计时,请先还车"})
|
||
|
||
duration = get_user_rental_settings(user["id"])["rental_duration_minutes"]
|
||
now_beijing = dt.datetime.now(tz)
|
||
end_beijing = now_beijing + dt.timedelta(minutes=duration)
|
||
start_str = now_beijing.strftime("%Y-%m-%d %H:%M:%S")
|
||
end_str = end_beijing.strftime("%Y-%m-%d %H:%M:%S")
|
||
cursor.execute("""
|
||
INSERT INTO rentals (bike_code, email, user_id, start_time, end_time, duration, source)
|
||
VALUES (?, ?, ?, ?, ?, ?, 'reminder')
|
||
""", (bike_code, user["email"], user["id"], start_str, end_str, duration))
|
||
rental_id = cursor.lastrowid
|
||
conn.commit()
|
||
conn.close()
|
||
print(f"[rental/start] 创建租车: bike={bike_code}, email={user['email']}, rental_id={rental_id}")
|
||
|
||
start_rental_timer(rental_id, user["email"], bike_code, duration, user["id"])
|
||
|
||
return jsonify({"rtn_code": 0, "message": "计时开始",
|
||
"data": {"rental_id": rental_id, "bike_code": bike_code,
|
||
"duration": duration, "remaining_seconds": duration * 60}})
|
||
|
||
|
||
@bp.route("/api/rental/status", methods=["GET"])
|
||
def rental_status():
|
||
"""查询当前用户用车状态"""
|
||
user = get_current_user()
|
||
print(f"[rental/status] User: {user}")
|
||
if not user:
|
||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
tz = dt.timezone(dt.timedelta(hours=8))
|
||
now_beijing = dt.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
|
||
order_id = request.args.get("order_id")
|
||
|
||
# 轮次预估需要 user_id/rider_user_id/renewal_round/rounds_override:
|
||
# 这几个列必须一起 SELECT,否则 _rounds_summary 只能拿到默认设置(轮数恒为 1)。
|
||
_RENTAL_COLS = """id, order_id, bike_code, email, start_time, end_time, expired, source,
|
||
user_id, rider_user_id, renewal_round, rounds_override"""
|
||
if order_id:
|
||
# 只允许查询自己的订单,否则任意登录用户可用 order_id 探测他人订单
|
||
cursor.execute(f"""
|
||
SELECT {_RENTAL_COLS}
|
||
FROM rentals WHERE order_id = ? AND expired = 0 AND end_time > ?
|
||
AND (user_id = ? OR email = ?) LIMIT 1
|
||
""", (order_id, now_beijing, user["id"], user["email"]))
|
||
else:
|
||
cursor.execute(f"""
|
||
SELECT {_RENTAL_COLS}
|
||
FROM rentals WHERE email = ? AND expired = 0 AND end_time > ? AND source = 'reminder'
|
||
ORDER BY id DESC LIMIT 1
|
||
""", (user["email"], now_beijing))
|
||
|
||
rental = cursor.fetchone()
|
||
print(f"[rental/status] 查询结果: email={user['email']}, order_id={order_id}, rental={dict(rental) if rental else None}")
|
||
|
||
if not rental:
|
||
conn.close()
|
||
return jsonify({"rtn_code": 0, "data": {"active": False}})
|
||
|
||
r = dict(rental)
|
||
remaining = _get_remaining_seconds(r)
|
||
|
||
if remaining <= 0:
|
||
cursor.execute("UPDATE rentals SET expired = 1 WHERE id = ?", (r["id"],))
|
||
conn.commit()
|
||
conn.close()
|
||
return jsonify({"rtn_code": 0, "data": {"active": False}})
|
||
|
||
conn.close()
|
||
return jsonify({"rtn_code": 0, "data": {
|
||
"active": True, "rental_id": r["id"], "order_id": r.get("order_id"),
|
||
"bike_code": r["bike_code"], "email": r["email"],
|
||
"start_time": r["start_time"], "end_time": r["end_time"],
|
||
"remaining_seconds": remaining, "source": r.get("source"),
|
||
**_rounds_summary(r, r.get("rider_user_id") or r.get("user_id")),
|
||
}})
|
||
|
||
|
||
@bp.route("/api/rental/return", methods=["POST"])
|
||
def rental_return():
|
||
"""结束独立提醒计时;真实订单必须走实际还车接口。"""
|
||
user = get_current_user()
|
||
if not user:
|
||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||
data = request.get_json() or {}
|
||
rental_id = data.get("rental_id")
|
||
if not rental_id:
|
||
return jsonify({"rtn_code": 400, "message": "缺少 rental_id"})
|
||
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
cursor.execute("SELECT user_id, source, expired FROM rentals WHERE id = ?", (rental_id,))
|
||
rental = cursor.fetchone()
|
||
if not rental:
|
||
conn.close()
|
||
return jsonify({"rtn_code": 404, "message": "计时记录不存在"})
|
||
if rental["user_id"] != user["id"]:
|
||
conn.close()
|
||
return jsonify({"rtn_code": 403, "message": "无权操作"})
|
||
if rental["source"] != "reminder":
|
||
conn.close()
|
||
return jsonify({"rtn_code": 400, "message": "真实订单请使用订单还车功能"})
|
||
if rental["expired"]:
|
||
conn.close()
|
||
return jsonify({"rtn_code": 0, "message": "计时已经结束"})
|
||
cursor.execute("UPDATE rentals SET expired = 1 WHERE id = ? AND expired = 0", (rental_id,))
|
||
conn.commit()
|
||
conn.close()
|
||
_cancel_rental_timers(rental_id)
|
||
print(f"[操作日志] 手动还车(计时结束): rental_id={rental_id}")
|
||
return jsonify({"rtn_code": 0, "message": "已确认还车"})
|
||
|
||
|
||
# ========== 邮件能力链接还车(无需登录) ==========
|
||
|
||
@bp.route("/rental/email-return", methods=["GET"])
|
||
def email_return_page():
|
||
"""邮件按钮的确认页。token 放在 URL fragment,不会进入服务器访问日志。"""
|
||
return _return_page(mode="confirm")
|
||
|
||
|
||
@bp.route("/api/rental/email-return/inspect", methods=["POST"])
|
||
def email_return_inspect():
|
||
"""只读检查能力令牌,用于确认页展示车辆与共享关系。"""
|
||
data = request.get_json(silent=True) or {}
|
||
status, rental = resolve_return_token(str(data.get("token") or ""))
|
||
if status != "valid":
|
||
messages = {
|
||
"used": "该还车链接已使用",
|
||
"expired": "该还车链接已过期",
|
||
"finished": "该订单已结束",
|
||
"invalid": "还车链接无效",
|
||
}
|
||
return jsonify({"rtn_code": 400, "status": status,
|
||
"message": messages.get(status, "还车链接不可用")})
|
||
|
||
context = get_rental_mail_context(rental["id"]) or rental
|
||
owner_email = context.get("owner_email") or context.get("email") or ""
|
||
rider_email = context.get("rider_email") or ""
|
||
shared = bool(rider_email and context.get("rider_user_id") != context.get("user_id"))
|
||
can_return = bool(context.get("order_id") and context.get("source") != "reminder")
|
||
return jsonify({"rtn_code": 0, "data": {
|
||
"bike_code": context.get("bike_code"),
|
||
"order_id": context.get("order_id") or context.get("id"),
|
||
"shared": shared,
|
||
"owner": owner_email,
|
||
"rider": rider_email if shared else owner_email,
|
||
"can_return": can_return,
|
||
}})
|
||
|
||
|
||
@bp.route("/rental/email-return", methods=["POST"])
|
||
def email_return_execute():
|
||
"""以邮件中的短期单次 token 执行还车;不依赖登录会话。"""
|
||
token = str(request.form.get("token") or "")
|
||
status, rental = resolve_return_token(token)
|
||
if status in ("used", "finished"):
|
||
return _return_page(mode="success", title="订单已结束",
|
||
message="这辆车已经完成还车,无需重复操作。")
|
||
if status != "valid" or not rental:
|
||
message = "还车链接已过期" if status == "expired" else "还车链接无效"
|
||
return _return_page(mode="error", title="无法使用此链接", message=message), 400
|
||
|
||
rental_id = int(rental["id"])
|
||
with _email_return_lock(rental_id):
|
||
# 等待同一订单的其他请求后再校验一次,防止双击/双方同时还车。
|
||
status, rental = resolve_return_token(token)
|
||
if status in ("used", "finished"):
|
||
return _return_page(mode="success", title="订单已结束",
|
||
message="这辆车已经完成还车,无需重复操作。")
|
||
if status != "valid" or not rental:
|
||
return _return_page(mode="error", title="无法使用此链接",
|
||
message="链接已失效,请回到系统查看订单。"), 400
|
||
if not rental.get("user_id"):
|
||
return _return_page(mode="error", title="还车失败",
|
||
message="该记录未绑定微信用户,无法执行远程还车。"), 400
|
||
if not rental.get("order_id") or rental.get("source") == "reminder":
|
||
return _return_page(mode="error", title="无法远程还车",
|
||
message="这是未绑定微信订单的本地计时提醒,请在小白单车中手动还车。"), 400
|
||
# 邮件按钮是用户主动结束订单,不应因为自动续租设置又把车重新开起来。
|
||
result = auto_return_bike(rental_id, int(rental["user_id"]), allow_renewal=False)
|
||
|
||
if result.get("success"):
|
||
return _return_page(mode="success", title="还车成功",
|
||
message=f"车辆 #{rental['bike_code']} 已成功还车。")
|
||
return _return_page(mode="retry", title="还车失败",
|
||
message=result.get("message") or "上游还车服务暂未确认成功。",
|
||
token=token, bike_code=rental.get("bike_code")), 502
|
||
|
||
|
||
# ========== 新增:微信订单同步 ==========
|
||
|
||
@bp.route("/api/rental/sync", methods=["POST"])
|
||
def rental_sync():
|
||
"""立即同步微信订单状态到本地"""
|
||
user = get_current_user()
|
||
if not user:
|
||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||
sync_result = _check_user_order(user["id"])
|
||
# 强制同步已经读取了最新 /user/info,丢弃订单状态接口的旧缓存。
|
||
_user_info_cache.pop(user["id"], None)
|
||
if not sync_result or not sync_result.get("ok"):
|
||
return jsonify({
|
||
"rtn_code": (sync_result or {}).get("rtn_code", 502),
|
||
"message": (sync_result or {}).get("message", "同步微信订单状态失败"),
|
||
"data": {"active": None},
|
||
})
|
||
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
cursor.execute("""
|
||
SELECT id, order_id, bike_code, expired, end_time, source,
|
||
user_id, rider_user_id, renewal_round, rounds_override
|
||
FROM rentals
|
||
WHERE user_id = ? AND expired = 0 AND end_time > datetime('now', '+8 hours')
|
||
ORDER BY id DESC LIMIT 1
|
||
""", (user["id"],))
|
||
rental = cursor.fetchone()
|
||
conn.close()
|
||
|
||
if rental:
|
||
tz = dt.timezone(dt.timedelta(hours=8))
|
||
now = dt.datetime.now(tz)
|
||
end = dt.datetime.strptime(rental["end_time"], "%Y-%m-%d %H:%M:%S").replace(tzinfo=tz)
|
||
remaining = max(int((end - now).total_seconds()), 0)
|
||
return jsonify({"rtn_code": 0, "data": {
|
||
"active": True, "rental_id": rental["id"],
|
||
"bike_code": rental["bike_code"],
|
||
"remaining_seconds": remaining,
|
||
"end_time": rental["end_time"], "source": rental["source"],
|
||
**_rounds_summary(dict(rental), rental["user_id"]),
|
||
}})
|
||
return jsonify({"rtn_code": 0, "data": {"active": False}})
|
||
|
||
|
||
# ========== 订单历史(我的弹窗,双方可见共享明细) ==========
|
||
|
||
def _order_row_for(row: dict, viewer_id: int) -> dict:
|
||
"""把 rentals 行转成前端订单历史卡片。"""
|
||
tz = dt.timezone(dt.timedelta(hours=8))
|
||
start = row.get("start_time")
|
||
finished = bool(row.get("expired"))
|
||
# 实际结束时间优先 returned_at;未结束的用 end_time
|
||
end_effective = row.get("returned_at") or row.get("end_time")
|
||
duration_seconds = None
|
||
try:
|
||
s = dt.datetime.strptime(start, "%Y-%m-%d %H:%M:%S").replace(tzinfo=tz)
|
||
e = dt.datetime.strptime(end_effective, "%Y-%m-%d %H:%M:%S").replace(tzinfo=tz)
|
||
duration_seconds = max(int((e - s).total_seconds()), 0)
|
||
except (TypeError, ValueError):
|
||
pass
|
||
is_shared = bool(row.get("rider_user_id") and row["rider_user_id"] != row.get("user_id"))
|
||
role = None
|
||
partner_label = ""
|
||
if is_shared:
|
||
is_owner = row.get("user_id") == viewer_id
|
||
role = "owner" if is_owner else "rider"
|
||
# 双方可见:给对方起的私密备注 + 邮箱
|
||
if is_owner:
|
||
partner_label = (row.get("owner_remark") or row.get("rider_email")
|
||
or get_user_display_name(row["rider_user_id"]))
|
||
else:
|
||
partner_label = (row.get("rider_remark") or row.get("user_email")
|
||
or get_user_display_name(row["user_id"]))
|
||
return {
|
||
"id": row["id"],
|
||
"order_id": row.get("order_id") or str(row["id"]),
|
||
"bike_code": row["bike_code"],
|
||
"source": row.get("source") or "",
|
||
"start_time": start,
|
||
"end_time": end_effective,
|
||
"returned": finished,
|
||
"duration_seconds": duration_seconds,
|
||
"start_label": row.get("start_label"),
|
||
"end_label": row.get("end_label"),
|
||
"shared": is_shared,
|
||
"role": role,
|
||
"partner": partner_label if is_shared else "",
|
||
}
|
||
|
||
|
||
# 自动续租产生的多轮订单:同一辆车、轮次 +1、首尾时间相接(≤10 分钟)→ 合并成一条历史
|
||
CHAIN_GAP_SECONDS = 10 * 60
|
||
|
||
|
||
def _parse_dt(value):
|
||
if not value:
|
||
return None
|
||
try:
|
||
return dt.datetime.strptime(str(value), "%Y-%m-%d %H:%M:%S")
|
||
except (TypeError, ValueError):
|
||
return None
|
||
|
||
|
||
def _merge_rental_chains(rows):
|
||
"""把 rentals 行按「自动续租链」分组成 chain。
|
||
|
||
判定条件(全部满足才并入上一条):
|
||
1) 同一辆车
|
||
2) 同一车主 + 同一骑行人的组合
|
||
3) renewal_round 恰好 +1(手动重新开锁总是第 1 轮,不会被误并)
|
||
4) 本轮开始时间与上一轮结束时间相差 -1 ~ 10 分钟(续租是紧接着重开的)
|
||
"""
|
||
ordered = sorted(rows, key=lambda r: (r.get("start_time") or "", r["id"]))
|
||
chains = []
|
||
for row in ordered:
|
||
rnd = int(row.get("renewal_round") or 1)
|
||
merged = False
|
||
if chains:
|
||
last = chains[-1]["rows"][-1]
|
||
last_rnd = int(last.get("renewal_round") or 1)
|
||
same_bike = str(row.get("bike_code")) == str(last.get("bike_code"))
|
||
same_pair = (row.get("user_id") == last.get("user_id")
|
||
and row.get("rider_user_id") == last.get("rider_user_id"))
|
||
prev_end = _parse_dt(last.get("returned_at") or last.get("end_time"))
|
||
this_start = _parse_dt(row.get("start_time"))
|
||
gap_ok = False
|
||
if prev_end and this_start:
|
||
gap = (this_start - prev_end).total_seconds()
|
||
gap_ok = -60 <= gap <= CHAIN_GAP_SECONDS
|
||
if same_bike and same_pair and rnd == last_rnd + 1 and gap_ok:
|
||
chains[-1]["rows"].append(row)
|
||
merged = True
|
||
if not merged:
|
||
chains.append({"rows": [row]})
|
||
return chains
|
||
|
||
|
||
def _chain_order_dict(chain: dict, viewer_id: int) -> dict:
|
||
"""把一条续租链渲染成一张订单卡片:总时长 = 各轮实际用时之和。"""
|
||
rows = chain["rows"]
|
||
first, last = rows[0], rows[-1]
|
||
total_seconds = 0
|
||
for r in rows:
|
||
s = _parse_dt(r.get("start_time"))
|
||
e = _parse_dt(r.get("returned_at") or r.get("end_time"))
|
||
if s and e:
|
||
total_seconds += max(int((e - s).total_seconds()), 0)
|
||
base = _order_row_for(last, viewer_id)
|
||
base.update({
|
||
"id": last["id"],
|
||
"ids": [r["id"] for r in rows],
|
||
"rounds": len(rows),
|
||
"start_time": first.get("start_time"),
|
||
"end_time": last.get("returned_at") or last.get("end_time"),
|
||
"duration_seconds": total_seconds,
|
||
"start_label": first.get("start_label"),
|
||
"end_label": last.get("end_label"),
|
||
# 多轮里任一轮未结束,整条链就算「进行中」
|
||
"returned": all(bool(r.get("expired")) for r in rows),
|
||
"order_id": last.get("order_id") or str(last["id"]),
|
||
})
|
||
return base
|
||
|
||
|
||
@bp.route("/api/user/orders")
|
||
def user_orders():
|
||
"""订单历史:本人作为车主或骑行者的真实订单(不含本地计时 reminder)。
|
||
|
||
自动续租产生的多轮订单会合并成一条,显示总用时与整体起止时间。
|
||
"""
|
||
user = get_current_user()
|
||
if not user:
|
||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||
try:
|
||
limit = max(1, min(500, int(request.args.get("limit", 80))))
|
||
except (TypeError, ValueError):
|
||
limit = 80
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
cursor.execute("""
|
||
SELECT r.*, o.email AS user_email, ri.email AS rider_email,
|
||
s.owner_remark AS owner_remark, s.rider_remark AS rider_remark
|
||
FROM rentals r
|
||
LEFT JOIN users o ON o.id = r.user_id
|
||
LEFT JOIN users ri ON ri.id = r.rider_user_id
|
||
LEFT JOIN shares s
|
||
ON s.owner_user_id = r.user_id AND s.rider_user_id = r.rider_user_id
|
||
AND s.id = (SELECT MAX(id) FROM shares
|
||
WHERE owner_user_id = r.user_id AND rider_user_id = r.rider_user_id)
|
||
WHERE (r.user_id = ? OR r.rider_user_id = ?)
|
||
AND COALESCE(r.source, '') != 'reminder'
|
||
ORDER BY r.id DESC LIMIT ?
|
||
""", (user["id"], user["id"], limit))
|
||
rows = [dict(r) for r in cursor.fetchall()]
|
||
conn.close()
|
||
chains = _merge_rental_chains(rows)
|
||
# 最近的在最前
|
||
chains.sort(key=lambda c: (c["rows"][-1].get("start_time") or "", c["rows"][-1]["id"]),
|
||
reverse=True)
|
||
return jsonify({"rtn_code": 0,
|
||
"data": [_chain_order_dict(c, user["id"]) for c in chains]})
|
||
|
||
|
||
# ========== 开锁前预览(月卡余量 + 自动续租轮次预估) ==========
|
||
|
||
def _rounds_summary(rental: dict, policy_user_id: int) -> dict:
|
||
"""轮次预估:当前轮 / 计划总轮数 / 最终预计还车时间。
|
||
|
||
最终还车时间 = 本轮 end_time + 剩余轮数 × 单轮时长。
|
||
"""
|
||
settings = get_user_rental_settings(policy_user_id)
|
||
duration = int(settings.get("rental_duration_minutes", 19))
|
||
try:
|
||
current_round = max(1, int(rental.get("renewal_round") or 1))
|
||
except (TypeError, ValueError):
|
||
current_round = 1
|
||
override = rental.get("rounds_override")
|
||
try:
|
||
total_rounds = int(override) if override else int(settings.get("rental_rounds", 1))
|
||
except (TypeError, ValueError):
|
||
total_rounds = int(settings.get("rental_rounds", 1))
|
||
total_rounds = max(current_round, total_rounds)
|
||
# 只有真实订单(有 order_id)才可能自动续租;本地计时 reminder 不会重开
|
||
auto_on = bool(settings.get("auto_return_enabled")) and bool(rental.get("order_id"))
|
||
remaining_rounds = max(0, total_rounds - current_round) if auto_on else 0
|
||
final_end = rental.get("end_time")
|
||
try:
|
||
tz = dt.timezone(dt.timedelta(hours=8))
|
||
end = dt.datetime.strptime(rental["end_time"], "%Y-%m-%d %H:%M:%S").replace(tzinfo=tz)
|
||
final_end = (end + dt.timedelta(minutes=duration * remaining_rounds)).strftime(
|
||
"%Y-%m-%d %H:%M:%S")
|
||
except (KeyError, TypeError, ValueError):
|
||
pass
|
||
return {
|
||
"current_round": current_round,
|
||
"total_rounds": total_rounds if auto_on else current_round,
|
||
"auto_return": auto_on,
|
||
"duration_minutes": duration,
|
||
"final_end_time": final_end,
|
||
"rounds_override": int(override) if override else None,
|
||
}
|
||
|
||
|
||
def _card_preview(user_id: int, code: str):
|
||
"""读取优惠卡状态:[(card_name, remain or None=无限), ...](读取失败返回 None)。"""
|
||
try:
|
||
result = request_with_user_auth(user_id, "GET", "/user/packages", _silent=True)
|
||
except Exception:
|
||
return None
|
||
if not result or result.get("rtn_code") != 0:
|
||
return None
|
||
data = result.get("data") or {}
|
||
if not isinstance(data, dict):
|
||
return None
|
||
pkgs = data.get("bike_packages", data.get("packages", [])) or []
|
||
if not isinstance(pkgs, list):
|
||
return None
|
||
cards = []
|
||
for p in pkgs:
|
||
if not isinstance(p, dict):
|
||
continue
|
||
remain = p.get("remainTimes")
|
||
name = (p.get("name") or p.get("packageName")
|
||
or ("月卡" if str(p.get("type")) == "3" else "卡包"))
|
||
if remain is None or str(remain).strip().lower() in ("", "none", "null"):
|
||
cards.append({"name": name, "remain": None})
|
||
continue
|
||
try:
|
||
cards.append({"name": name, "remain": int(float(remain))})
|
||
except (TypeError, ValueError):
|
||
cards.append({"name": name, "remain": None})
|
||
return cards
|
||
|
||
|
||
@bp.route("/api/order/preview")
|
||
def order_preview():
|
||
"""开锁前预览:月卡余量 + 按轮次设置预估的还车时间。code 必填;
|
||
owner_user_id 传了走共享预览(用车主的卡与车主设置的轮次)。"""
|
||
user = get_current_user()
|
||
if not user:
|
||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||
code = (request.args.get("code") or "").strip()
|
||
if not code:
|
||
return jsonify({"rtn_code": 400, "message": "缺少 code"})
|
||
owner_user_id = request.args.get("owner_user_id")
|
||
shared = bool(owner_user_id)
|
||
if shared:
|
||
try:
|
||
owner_user_id = int(owner_user_id)
|
||
except (TypeError, ValueError):
|
||
return jsonify({"rtn_code": 400, "message": "共享者参数错误"})
|
||
from routes.share import _find_share
|
||
if not _find_share(owner_user_id, user["id"]):
|
||
return jsonify({"rtn_code": 400, "message": "共享关系不存在或已解绑"})
|
||
policy_user_id = owner_user_id if shared else user["id"]
|
||
settings = get_user_rental_settings(policy_user_id)
|
||
duration = int(settings["rental_duration_minutes"])
|
||
rounds = int(settings["rental_rounds"])
|
||
cards = _card_preview(policy_user_id, code)
|
||
has_card = bool(cards)
|
||
# 优先保护月卡:卡余量可识别时,预估轮次不超过卡余量(每轮还车+支付消耗一次)
|
||
est_rounds = rounds
|
||
card_note = ""
|
||
if settings.get("protect_card") and cards:
|
||
finite = [c["remain"] for c in cards if c["remain"] is not None]
|
||
if finite:
|
||
best = max(finite)
|
||
est_rounds = max(1, min(rounds, best))
|
||
card_note = f"卡余量 {best} 次" if best < rounds else ""
|
||
else:
|
||
card_note = "卡余量不限"
|
||
elif cards:
|
||
finite = [c["remain"] for c in cards if c["remain"] is not None]
|
||
card_note = f"卡余量 {max(finite)} 次" if finite else "卡余量不限"
|
||
auto_on = bool(settings.get("auto_return_enabled"))
|
||
total_minutes = duration * (est_rounds if auto_on else 1)
|
||
tz = dt.timezone(dt.timedelta(hours=8))
|
||
est_end = (dt.datetime.now(tz) + dt.timedelta(minutes=total_minutes)).strftime("%H:%M")
|
||
return jsonify({"rtn_code": 0, "data": {
|
||
"shared": shared,
|
||
"policy_user": "车主" if shared else "本人",
|
||
"duration_minutes": duration,
|
||
"rounds_setting": rounds,
|
||
"rounds_planned": est_rounds if auto_on else 1,
|
||
"auto_return": auto_on,
|
||
"total_minutes": total_minutes,
|
||
"est_end_time": est_end,
|
||
"has_card": has_card,
|
||
"cards": cards or [],
|
||
"card_note": card_note,
|
||
"protect_card": bool(settings.get("protect_card")),
|
||
}})
|
||
|
||
|
||
# ========== 手动 +1 轮 ==========
|
||
# 语义(与前端弹窗文案一致):只把「计划轮数」+1,**不延长当前这一轮**。
|
||
# 当前轮照常到点 → 自动还车 → 优惠卡支付 → 立刻重新开锁同一辆车进入下一轮。
|
||
# 提高 rounds_override 后,timer._planned_rounds 的续租上限随之提高。
|
||
|
||
@bp.route("/api/order/add_round", methods=["POST"])
|
||
def order_add_round():
|
||
"""给进行中的订单追加一轮计划:只提高轮次上限,不改变本轮到期时间。
|
||
真实订单(unlock/sync/shared)可用;车主与骑行者均可操作。"""
|
||
user = get_current_user()
|
||
if not user:
|
||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||
data = request.get_json(silent=True) or {}
|
||
order_id = data.get("order_id") or data.get("rental_id")
|
||
if not order_id:
|
||
return jsonify({"rtn_code": 400, "message": "缺少订单ID"})
|
||
conn = get_db()
|
||
row = conn.execute("""
|
||
SELECT * FROM rentals
|
||
WHERE (order_id = ? OR id = ?) AND expired = 0
|
||
ORDER BY id DESC LIMIT 1
|
||
""", (str(order_id), str(order_id))).fetchone()
|
||
if not row:
|
||
conn.close()
|
||
return jsonify({"rtn_code": 404, "message": "进行中的订单不存在"})
|
||
rental = dict(row)
|
||
if user["id"] not in (rental.get("user_id"), rental.get("rider_user_id")):
|
||
conn.close()
|
||
return jsonify({"rtn_code": 403, "message": "无权操作"})
|
||
if not rental.get("order_id") or rental.get("source") == "reminder":
|
||
conn.close()
|
||
return jsonify({"rtn_code": 400, "message": "本地计时提醒不支持加轮,请用真实订单还车"})
|
||
|
||
# 轮次策略跟随骑行者的设置(共享用车时骑行者决定时长/轮数)
|
||
policy_user_id = rental.get("rider_user_id") or rental.get("user_id")
|
||
settings = get_user_rental_settings(policy_user_id)
|
||
try:
|
||
current_round = max(1, int(rental.get("renewal_round") or 1))
|
||
except (TypeError, ValueError):
|
||
current_round = 1
|
||
override = rental.get("rounds_override")
|
||
try:
|
||
planned = int(override) if override else int(settings["rental_rounds"])
|
||
except (TypeError, ValueError):
|
||
planned = int(settings["rental_rounds"])
|
||
# 加轮的意义是「多骑一轮」:把计划提到 max(当前轮, 原计划)+1,最多 50 轮
|
||
new_total = min(50, max(current_round, planned) + 1)
|
||
if new_total <= current_round:
|
||
conn.close()
|
||
return jsonify({"rtn_code": 400, "message": "已达轮次上限"})
|
||
|
||
# 关键:只写 rounds_override,end_time / duration 保持不变 → 本轮时长绝不被延长
|
||
conn.execute("UPDATE rentals SET rounds_override = ? WHERE id = ?",
|
||
(new_total, rental["id"]))
|
||
conn.commit()
|
||
conn.close()
|
||
|
||
# 清除订单状态短缓存,让前端立刻读到新的轮数
|
||
_user_info_cache.pop(policy_user_id, None)
|
||
|
||
summary = _rounds_summary({**rental, "rounds_override": new_total}, policy_user_id)
|
||
print(f"[操作日志] 手动加轮: order_id={rental.get('order_id')}, "
|
||
f"new_total={new_total}, end_time 不变={rental.get('end_time')}, user={user['email']}")
|
||
return jsonify({"rtn_code": 0,
|
||
"message": f"已追加 1 轮(共 {new_total} 轮),本轮时长不变",
|
||
"data": {
|
||
"rental_id": rental["id"],
|
||
"end_time": rental.get("end_time"),
|
||
"remaining_seconds": _get_remaining_seconds(rental),
|
||
**summary,
|
||
}})
|
||
|
||
|
||
@bp.route("/api/user/orders/trajectory")
|
||
def user_order_trajectory():
|
||
"""订单骑行轨迹:传 rental_id 时按「整条续租链」取轨迹。
|
||
|
||
- 多轮订单(自动续租)合并:起点=第 1 轮开始,终点=最后一轮结束
|
||
- 坐标来源 bike_history(GCJ02,与上游车辆同坐标系)
|
||
- 同时返回起终点坐标兜底,便于采集缺口时也能画出示意线
|
||
"""
|
||
user = get_current_user()
|
||
if not user:
|
||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||
try:
|
||
rental_id = int(request.args.get("rental_id"))
|
||
except (TypeError, ValueError):
|
||
return jsonify({"rtn_code": 400, "message": "缺少 rental_id"})
|
||
|
||
conn = get_db()
|
||
row = conn.execute("""
|
||
SELECT r.*, o.email AS user_email, ri.email AS rider_email,
|
||
s.owner_remark AS owner_remark, s.rider_remark AS rider_remark
|
||
FROM rentals r
|
||
LEFT JOIN users o ON o.id = r.user_id
|
||
LEFT JOIN users ri ON ri.id = r.rider_user_id
|
||
LEFT JOIN shares s
|
||
ON s.owner_user_id = r.user_id AND s.rider_user_id = r.rider_user_id
|
||
AND s.id = (SELECT MAX(id) FROM shares
|
||
WHERE owner_user_id = r.user_id AND rider_user_id = r.rider_user_id)
|
||
WHERE r.id = ?
|
||
""", (rental_id,)).fetchone()
|
||
if not row:
|
||
conn.close()
|
||
return jsonify({"rtn_code": 404, "message": "订单不存在"})
|
||
rental = dict(row)
|
||
# 权限:只有该订单的车主或骑行者可看
|
||
if user["id"] not in (rental.get("user_id"), rental.get("rider_user_id")):
|
||
conn.close()
|
||
return jsonify({"rtn_code": 403, "message": "无权查看该订单轨迹"})
|
||
|
||
# 找出该订单所属的整条续租链(用同一套合并规则,保证与列表一致)
|
||
siblings = conn.execute("""
|
||
SELECT * FROM rentals
|
||
WHERE bike_code = ?
|
||
AND COALESCE(user_id, 0) = ?
|
||
AND COALESCE(rider_user_id, 0) = ?
|
||
AND COALESCE(source, '') != 'reminder'
|
||
ORDER BY id ASC
|
||
""", (rental.get("bike_code"),
|
||
rental.get("user_id") or 0,
|
||
rental.get("rider_user_id") or 0)).fetchall()
|
||
chains = _merge_rental_chains([dict(s) for s in siblings])
|
||
chain_rows = [rental]
|
||
for c in chains:
|
||
if any(r["id"] == rental_id for r in c["rows"]):
|
||
chain_rows = c["rows"]
|
||
break
|
||
|
||
first, last = chain_rows[0], chain_rows[-1]
|
||
code = rental.get("bike_code") or ""
|
||
start_time = first.get("start_time")
|
||
end_time = last.get("returned_at") or last.get("end_time")
|
||
points = []
|
||
if code and start_time and end_time:
|
||
# 采集点是 GCJ02;按订单窗口取点(前后各留 2 分钟容错)
|
||
rows = conn.execute("""
|
||
SELECT latitude, longitude, recorded_at
|
||
FROM bike_history
|
||
WHERE bike_code = ?
|
||
AND recorded_at >= datetime(?, '-2 minutes')
|
||
AND recorded_at <= datetime(?, '+2 minutes')
|
||
ORDER BY recorded_at ASC
|
||
LIMIT 3000
|
||
""", (str(code), start_time, end_time)).fetchall()
|
||
points = [{"lat": r["latitude"], "lng": r["longitude"],
|
||
"time": r["recorded_at"]} for r in rows
|
||
if r["latitude"] is not None and r["longitude"] is not None]
|
||
conn.close()
|
||
|
||
duration_seconds = None
|
||
s_dt, e_dt = _parse_dt(start_time), _parse_dt(end_time)
|
||
if s_dt and e_dt:
|
||
duration_seconds = max(int((e_dt - s_dt).total_seconds()), 0)
|
||
|
||
return jsonify({"rtn_code": 0, "data": {
|
||
"rental_id": rental_id,
|
||
"ids": [r["id"] for r in chain_rows],
|
||
"rounds": len(chain_rows),
|
||
"bike_code": code,
|
||
"start_time": start_time,
|
||
"end_time": end_time,
|
||
"duration_seconds": duration_seconds,
|
||
"returned": all(bool(r.get("expired")) for r in chain_rows),
|
||
"start_label": first.get("start_label"),
|
||
"end_label": last.get("end_label"),
|
||
"start_point": ({"lat": first.get("start_latitude"),
|
||
"lng": first.get("start_longitude")}
|
||
if first.get("start_latitude") is not None else None),
|
||
"end_point": ({"lat": last.get("end_latitude"),
|
||
"lng": last.get("end_longitude")}
|
||
if last.get("end_latitude") is not None else None),
|
||
"points": points,
|
||
}})
|