fix: 共享单按骑行人设置,手动还车不续租,支持上游 A→B 切换
共享策略 - 预览:车主出卡,骑行人决定时长、轮次、提醒与保护卡策略 - 后端拦截共享车主的加轮、临时锁/开车与支付,普通订单不变 - 前端共享车主只保留还车按钮,不显示权限提示;骑行人沿用现有设置页 还车与续租 - auto_return_bike 默认 allow_renewal=False;仅 0 点定时器与过期巡检显式开启 - 页面按钮、邮件链接、共享还车均清理自动重试状态,剩余/临时加轮不再触发续租 - 官方小程序还车(上游订单消失)只做本地收尾,不重新开锁 - 续租拿不到原车位置时仍直接尝试下单开锁,失败再明确提示 上游 A→B - 网站开 A,官方小程序还 A 后又开 B:巡检保留 B,A 按已还车本地收尾 - 同一订单号不误关、不重复建单;无订单号记录保守跳过 测试:266 pytest + 45 node 全绿;tsc 与生产 bundle 检查通过
This commit is contained in:
+51
-6
@@ -89,6 +89,31 @@ def _serialize_order_return(func):
|
|||||||
return wrapped
|
return wrapped
|
||||||
|
|
||||||
|
|
||||||
|
def _shared_owner_action_guard(order_id, user):
|
||||||
|
"""共享单车主除还车外的操作统一拦截;普通订单与其它身份不受影响。"""
|
||||||
|
if not order_id:
|
||||||
|
return None
|
||||||
|
conn = get_db()
|
||||||
|
try:
|
||||||
|
row = conn.execute("""
|
||||||
|
SELECT user_id, rider_user_id FROM rentals
|
||||||
|
WHERE order_id = ? OR id = ?
|
||||||
|
ORDER BY expired ASC, id DESC LIMIT 1
|
||||||
|
""", (str(order_id), str(order_id))).fetchone()
|
||||||
|
except sqlite3.OperationalError:
|
||||||
|
return None # 老库没有 rider_user_id 时不影响普通订单
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
owner_id = row["user_id"]
|
||||||
|
rider_id = row["rider_user_id"]
|
||||||
|
if rider_id is not None and owner_id == user["id"] and rider_id != owner_id:
|
||||||
|
return jsonify({"rtn_code": 403,
|
||||||
|
"message": "共享订单仅骑行人可执行此操作,车主只能还车"})
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def _upstream_order_finished(user_id: int, order_id, bike_code=None) -> bool:
|
def _upstream_order_finished(user_id: int, order_id, bike_code=None) -> bool:
|
||||||
"""还车响应不明确时,确认指定订单是否已经不再骑行。
|
"""还车响应不明确时,确认指定订单是否已经不再骑行。
|
||||||
|
|
||||||
@@ -900,6 +925,9 @@ def order_temp_unlock():
|
|||||||
order_id = data.get("order_id")
|
order_id = data.get("order_id")
|
||||||
if not order_id:
|
if not order_id:
|
||||||
return jsonify({"rtn_code": 400, "message": "缺少订单ID"})
|
return jsonify({"rtn_code": 400, "message": "缺少订单ID"})
|
||||||
|
denied = _shared_owner_action_guard(order_id, user)
|
||||||
|
if denied:
|
||||||
|
return denied
|
||||||
|
|
||||||
result = request_with_user_auth(
|
result = request_with_user_auth(
|
||||||
user["id"], "POST", "/record/open", data={"order_id": order_id}
|
user["id"], "POST", "/record/open", data={"order_id": order_id}
|
||||||
@@ -931,6 +959,9 @@ def order_temp_lock():
|
|||||||
return jsonify({"rtn_code": 400, "message": "缺少车辆编码"})
|
return jsonify({"rtn_code": 400, "message": "缺少车辆编码"})
|
||||||
if latitude is None or longitude is None:
|
if latitude is None or longitude is None:
|
||||||
return jsonify({"rtn_code": 400, "message": "缺少位置信息"})
|
return jsonify({"rtn_code": 400, "message": "缺少位置信息"})
|
||||||
|
denied = _shared_owner_action_guard(order_id, user)
|
||||||
|
if denied:
|
||||||
|
return denied
|
||||||
|
|
||||||
try:
|
try:
|
||||||
latitude = float(latitude)
|
latitude = float(latitude)
|
||||||
@@ -1061,6 +1092,9 @@ def order_return():
|
|||||||
local_sync_warning = "本地记录稍后同步"
|
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)
|
||||||
|
# 页面按钮手动还车:剩余轮次(含临时加轮)一律作废,不进入续租。
|
||||||
|
from timer import _clear_auto_return_state
|
||||||
|
_clear_auto_return_state(rental_id)
|
||||||
_user_info_cache.pop(user["id"], None)
|
_user_info_cache.pop(user["id"], None)
|
||||||
|
|
||||||
# 还车已成功。自动尝试月卡/周卡支付仅作为附加操作,任何异常都不应让已成功的还车被前端判为失败。
|
# 还车已成功。自动尝试月卡/周卡支付仅作为附加操作,任何异常都不应让已成功的还车被前端判为失败。
|
||||||
@@ -1223,6 +1257,9 @@ def order_pay_with_card():
|
|||||||
package_id = data.get("package_id")
|
package_id = data.get("package_id")
|
||||||
if not order_id or not code or not package_id:
|
if not order_id or not code or not package_id:
|
||||||
return jsonify({"rtn_code": 400, "message": "缺少参数"})
|
return jsonify({"rtn_code": 400, "message": "缺少参数"})
|
||||||
|
denied = _shared_owner_action_guard(order_id, user)
|
||||||
|
if denied:
|
||||||
|
return denied
|
||||||
|
|
||||||
card_name = "月卡" if pay_type == "3" else "周卡"
|
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}")
|
print(f"[pay_with_card] user={user.get('email')}, order_id={order_id}, type={card_name}, package_id={package_id}")
|
||||||
@@ -1751,7 +1788,7 @@ def _card_preview(user_id: int, code: str):
|
|||||||
@bp.route("/api/order/preview")
|
@bp.route("/api/order/preview")
|
||||||
def order_preview():
|
def order_preview():
|
||||||
"""开锁前预览:月卡余量 + 按轮次设置预估的还车时间。code 必填;
|
"""开锁前预览:月卡余量 + 按轮次设置预估的还车时间。code 必填;
|
||||||
owner_user_id 传了走共享预览(用车主的卡与车主设置的轮次)。"""
|
owner_user_id 传了走共享预览:卡查车主,时长与轮次读当前骑行人。"""
|
||||||
user = get_current_user()
|
user = get_current_user()
|
||||||
if not user:
|
if not user:
|
||||||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||||||
@@ -1768,11 +1805,13 @@ def order_preview():
|
|||||||
from routes.share import _find_share
|
from routes.share import _find_share
|
||||||
if not _find_share(owner_user_id, user["id"]):
|
if not _find_share(owner_user_id, user["id"]):
|
||||||
return jsonify({"rtn_code": 400, "message": "共享关系不存在或已解绑"})
|
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)
|
settings_user_id = user["id"]
|
||||||
|
card_user_id = owner_user_id if shared else user["id"]
|
||||||
|
settings = get_user_rental_settings(settings_user_id)
|
||||||
duration = int(settings["rental_duration_minutes"])
|
duration = int(settings["rental_duration_minutes"])
|
||||||
rounds = int(settings["rental_rounds"])
|
rounds = int(settings["rental_rounds"])
|
||||||
cards = _card_preview(policy_user_id, code)
|
cards = _card_preview(card_user_id, code)
|
||||||
has_card = bool(cards)
|
has_card = bool(cards)
|
||||||
# 优先保护月卡:卡余量可识别时,预估轮次不超过卡余量(每轮还车+支付消耗一次)
|
# 优先保护月卡:卡余量可识别时,预估轮次不超过卡余量(每轮还车+支付消耗一次)
|
||||||
est_rounds = rounds
|
est_rounds = rounds
|
||||||
@@ -1794,7 +1833,7 @@ def order_preview():
|
|||||||
est_end = (dt.datetime.now(tz) + dt.timedelta(minutes=total_minutes)).strftime("%H:%M")
|
est_end = (dt.datetime.now(tz) + dt.timedelta(minutes=total_minutes)).strftime("%H:%M")
|
||||||
return jsonify({"rtn_code": 0, "data": {
|
return jsonify({"rtn_code": 0, "data": {
|
||||||
"shared": shared,
|
"shared": shared,
|
||||||
"policy_user": "车主" if shared else "本人",
|
"policy_user": "骑行人" if shared else "本人",
|
||||||
"duration_minutes": duration,
|
"duration_minutes": duration,
|
||||||
"rounds_setting": rounds,
|
"rounds_setting": rounds,
|
||||||
"rounds_planned": est_rounds if auto_on else 1,
|
"rounds_planned": est_rounds if auto_on else 1,
|
||||||
@@ -1816,7 +1855,7 @@ def order_preview():
|
|||||||
@bp.route("/api/order/add_round", methods=["POST"])
|
@bp.route("/api/order/add_round", methods=["POST"])
|
||||||
def order_add_round():
|
def order_add_round():
|
||||||
"""给进行中的订单追加一轮计划:只提高轮次上限,不改变本轮到期时间。
|
"""给进行中的订单追加一轮计划:只提高轮次上限,不改变本轮到期时间。
|
||||||
真实订单(unlock/sync/shared)可用;车主与骑行者均可操作。"""
|
真实订单(unlock/sync/shared)可用;共享单只能由骑行人操作,车主仅可还车。"""
|
||||||
user = get_current_user()
|
user = get_current_user()
|
||||||
if not user:
|
if not user:
|
||||||
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
return jsonify({"rtn_code": 401, "message": "请先登录"})
|
||||||
@@ -1837,6 +1876,12 @@ def order_add_round():
|
|||||||
if user["id"] not in (rental.get("user_id"), rental.get("rider_user_id")):
|
if user["id"] not in (rental.get("user_id"), rental.get("rider_user_id")):
|
||||||
conn.close()
|
conn.close()
|
||||||
return jsonify({"rtn_code": 403, "message": "无权操作"})
|
return jsonify({"rtn_code": 403, "message": "无权操作"})
|
||||||
|
if (rental.get("rider_user_id") is not None
|
||||||
|
and rental.get("rider_user_id") != user["id"]
|
||||||
|
and rental.get("user_id") == user["id"]):
|
||||||
|
conn.close()
|
||||||
|
return jsonify({"rtn_code": 403,
|
||||||
|
"message": "共享订单仅骑行人可加轮,车主只能还车"})
|
||||||
if not rental.get("order_id") or rental.get("source") == "reminder":
|
if not rental.get("order_id") or rental.get("source") == "reminder":
|
||||||
conn.close()
|
conn.close()
|
||||||
return jsonify({"rtn_code": 400, "message": "本地计时提醒不支持加轮,请用真实订单还车"})
|
return jsonify({"rtn_code": 400, "message": "本地计时提醒不支持加轮,请用真实订单还车"})
|
||||||
|
|||||||
@@ -1018,6 +1018,9 @@ def share_return():
|
|||||||
conn.close()
|
conn.close()
|
||||||
for rental_id in finished_rental_ids:
|
for rental_id in finished_rental_ids:
|
||||||
_cancel_rental_timers(int(rental_id))
|
_cancel_rental_timers(int(rental_id))
|
||||||
|
# 共享单由车主或骑行人手动还车,同样不触发剩余轮次续租。
|
||||||
|
from timer import _clear_auto_return_state
|
||||||
|
_clear_auto_return_state(int(rental_id))
|
||||||
|
|
||||||
# 还车后清除订单状态短缓存,避免前端短时间继续显示旧横幅。
|
# 还车后清除订单状态短缓存,避免前端短时间继续显示旧横幅。
|
||||||
from routes.rental import _user_info_cache
|
from routes.rental import _user_info_cache
|
||||||
|
|||||||
+18
-1
@@ -707,6 +707,10 @@ let orderTempActionLoading: any = false;
|
|||||||
// static/js/map.js:2213-2260
|
// static/js/map.js:2213-2260
|
||||||
export async function tempLockCurrentOrder() {
|
export async function tempLockCurrentOrder() {
|
||||||
if (orderTempActionLoading || !isOrderActionEligible(S.currentOrder) || Number(S.currentOrder.status) !== 2) return;
|
if (orderTempActionLoading || !isOrderActionEligible(S.currentOrder) || Number(S.currentOrder.status) !== 2) return;
|
||||||
|
if (S.currentOrder.shared) {
|
||||||
|
showToast("共享订单仅骑行人可临时锁车,车主只能还车");
|
||||||
|
return;
|
||||||
|
}
|
||||||
// 先快照:等定位(最长 5 秒)期间 20 秒轮询可能把 currentOrder 置空,
|
// 先快照:等定位(最长 5 秒)期间 20 秒轮询可能把 currentOrder 置空,
|
||||||
// 之后再读 currentOrder.order_id 会抛 TypeError 并被吞成「临时锁车失败」。
|
// 之后再读 currentOrder.order_id 会抛 TypeError 并被吞成「临时锁车失败」。
|
||||||
const order = S.currentOrder;
|
const order = S.currentOrder;
|
||||||
@@ -762,6 +766,10 @@ export async function tempLockCurrentOrder() {
|
|||||||
// static/js/map.js:2262-2300
|
// static/js/map.js:2262-2300
|
||||||
export async function tempUnlockCurrentOrder() {
|
export async function tempUnlockCurrentOrder() {
|
||||||
if (orderTempActionLoading || !isOrderActionEligible(S.currentOrder) || Number(S.currentOrder.status) !== 2) return;
|
if (orderTempActionLoading || !isOrderActionEligible(S.currentOrder) || Number(S.currentOrder.status) !== 2) return;
|
||||||
|
if (S.currentOrder.shared) {
|
||||||
|
showToast("共享订单仅骑行人可临时开车,车主只能还车");
|
||||||
|
return;
|
||||||
|
}
|
||||||
const button = document.getElementById("order-action-unlock");
|
const button = document.getElementById("order-action-unlock");
|
||||||
orderTempActionLoading = true;
|
orderTempActionLoading = true;
|
||||||
if (button) {
|
if (button) {
|
||||||
@@ -1368,12 +1376,20 @@ export async function confirmAddRound() {
|
|||||||
// static/js/map.js:2946-2949
|
// static/js/map.js:2946-2949
|
||||||
export function addRoundForCurrent() {
|
export function addRoundForCurrent() {
|
||||||
if (!S.activeRental || !S.authToken) { showToast("当前没有进行中的订单"); return; }
|
if (!S.activeRental || !S.authToken) { showToast("当前没有进行中的订单"); return; }
|
||||||
|
if (S.currentOrder && S.currentOrder.shared) {
|
||||||
|
showToast("共享订单仅骑行人可加轮,车主只能还车");
|
||||||
|
return;
|
||||||
|
}
|
||||||
showAddRoundConfirm({ kind: "rental", value: S.activeRental.rental_id });
|
showAddRoundConfirm({ kind: "rental", value: S.activeRental.rental_id });
|
||||||
}
|
}
|
||||||
|
|
||||||
// static/js/map.js:2950-2954
|
// static/js/map.js:2950-2954
|
||||||
export function addRoundFromBanner() {
|
export function addRoundFromBanner() {
|
||||||
if (!S.currentOrder || !S.currentOrder.order_id) { showToast("当前没有进行中的订单"); return; }
|
if (!S.currentOrder || !S.currentOrder.order_id) { showToast("当前没有进行中的订单"); return; }
|
||||||
|
if (S.currentOrder.shared) {
|
||||||
|
showToast("共享订单仅骑行人可加轮,车主只能还车");
|
||||||
|
return;
|
||||||
|
}
|
||||||
showAddRoundConfirm({ kind: "order", value: S.currentOrder.order_id });
|
showAddRoundConfirm({ kind: "order", value: S.currentOrder.order_id });
|
||||||
}
|
}
|
||||||
// 页面加载时检查订单状态和租车状态
|
// 页面加载时检查订单状态和租车状态
|
||||||
@@ -1853,7 +1869,8 @@ export function showRentalBar() {
|
|||||||
if (addBtn) {
|
if (addBtn) {
|
||||||
const realOrder = S.activeRental.source ? S.activeRental.source !== "reminder"
|
const realOrder = S.activeRental.source ? S.activeRental.source !== "reminder"
|
||||||
: !!S.activeRental.order_id;
|
: !!S.activeRental.order_id;
|
||||||
addBtn.style.display = realOrder ? "inline-flex" : "none";
|
const ownerShared = !!(S.currentOrder && S.currentOrder.shared);
|
||||||
|
addBtn.style.display = (realOrder && !ownerShared) ? "inline-flex" : "none";
|
||||||
}
|
}
|
||||||
updateRentalFinalTime();
|
updateRentalFinalTime();
|
||||||
updateRentalCountdown();
|
updateRentalCountdown();
|
||||||
|
|||||||
+32
-9
@@ -53,6 +53,7 @@ export function showOrderBanner(order) {
|
|||||||
const icon = document.getElementById("order-banner-icon");
|
const icon = document.getElementById("order-banner-icon");
|
||||||
const text = document.getElementById("order-banner-text");
|
const text = document.getElementById("order-banner-text");
|
||||||
const btn = document.getElementById("order-banner-btn");
|
const btn = document.getElementById("order-banner-btn");
|
||||||
|
btn.onclick = handleOrderBannerClick;
|
||||||
|
|
||||||
banner.classList.remove("warning", "riding");
|
banner.classList.remove("warning", "riding");
|
||||||
|
|
||||||
@@ -61,7 +62,9 @@ export function showOrderBanner(order) {
|
|||||||
banner.classList.add("warning");
|
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>';
|
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)}`;
|
text.textContent = `待支付订单 #${order.code || order.order_id.slice(-6)}`;
|
||||||
btn.textContent = "去支付";
|
// 共享单的支付、时长与轮次由骑行人处理,车主只能还车。
|
||||||
|
btn.textContent = order.shared ? "查看" : "去支付";
|
||||||
|
if (order.shared) btn.onclick = showOrderActionsModal;
|
||||||
hideOrderCountdown();
|
hideOrderCountdown();
|
||||||
const progress = document.getElementById("order-final-time");
|
const progress = document.getElementById("order-final-time");
|
||||||
progress.textContent = "待支付 · 骑行已结束";
|
progress.textContent = "待支付 · 骑行已结束";
|
||||||
@@ -125,7 +128,8 @@ export function fetchOrderCountdown(orderId) {
|
|||||||
}
|
}
|
||||||
if (addBtn) {
|
if (addBtn) {
|
||||||
// 真实订单才可加轮; reminder 计时不显示
|
// 真实订单才可加轮; reminder 计时不显示
|
||||||
const eligible = data.data.order_id && String(data.data.source) !== "reminder";
|
const eligible = data.data.order_id && String(data.data.source) !== "reminder"
|
||||||
|
&& !(S.currentOrder && S.currentOrder.shared);
|
||||||
addBtn.style.display = eligible ? "inline-block" : "none";
|
addBtn.style.display = eligible ? "inline-block" : "none";
|
||||||
}
|
}
|
||||||
showOrderCountdown();
|
showOrderCountdown();
|
||||||
@@ -260,23 +264,29 @@ export function showOrderActionsModal() {
|
|||||||
const hint = document.getElementById("order-actions-hint");
|
const hint = document.getElementById("order-actions-hint");
|
||||||
const code = S.currentOrder.code || S.currentOrder.order_id || "未知";
|
const code = S.currentOrder.code || S.currentOrder.order_id || "未知";
|
||||||
const pending = Number(S.currentOrder.status) === 1;
|
const pending = Number(S.currentOrder.status) === 1;
|
||||||
|
// order_status 只有当前登录车主会带 shared,因此这里可可靠地区分车主与骑行人。
|
||||||
|
const ownerShared = !!S.currentOrder.shared;
|
||||||
|
|
||||||
meta.textContent = `车辆 #${code}`;
|
meta.textContent = `车辆 #${code}`;
|
||||||
status.textContent = pending ? "待支付订单" : "订单进行中";
|
status.textContent = ownerShared ? "" : (pending ? "待支付订单" : "订单进行中");
|
||||||
status.classList.toggle("warning", pending);
|
status.style.display = ownerShared ? "none" : "";
|
||||||
|
status.classList.toggle("warning", pending && !ownerShared);
|
||||||
status.classList.toggle("riding", !pending);
|
status.classList.toggle("riding", !pending);
|
||||||
hint.textContent = pending
|
hint.textContent = ownerShared ? "" : (pending
|
||||||
? "当前订单尚未支付,请先完成支付后再使用车辆操作。"
|
? "当前订单尚未支付,请先完成支付后再使用车辆操作。"
|
||||||
: "临时锁车不会结束订单,确认车辆停放安全后再操作。";
|
: "临时锁车不会结束订单,确认车辆停放安全后再操作。");
|
||||||
|
hint.style.display = ownerShared ? "none" : "";
|
||||||
|
|
||||||
// 待支付订单明确不展示临时锁车/临时开车。
|
// 待支付订单不展示临时锁/开车;共享车主连寻车、支付也一并隐藏。
|
||||||
["order-action-lock", "order-action-unlock"].forEach(id => {
|
["order-action-lock", "order-action-unlock"].forEach(id => {
|
||||||
const button = document.getElementById(id);
|
const button = document.getElementById(id);
|
||||||
if (button) button.style.display = pending ? "none" : "flex";
|
if (button) button.style.display = (pending || ownerShared) ? "none" : "flex";
|
||||||
});
|
});
|
||||||
|
const find = document.getElementById("order-action-find");
|
||||||
const pay = document.getElementById("order-action-pay");
|
const pay = document.getElementById("order-action-pay");
|
||||||
const ret = document.getElementById("order-action-return");
|
const ret = document.getElementById("order-action-return");
|
||||||
if (pay) pay.style.display = pending ? "flex" : "none";
|
if (find) find.style.display = ownerShared ? "none" : "flex";
|
||||||
|
if (pay) pay.style.display = (pending && !ownerShared) ? "flex" : "none";
|
||||||
if (ret) ret.style.display = pending ? "none" : "flex";
|
if (ret) ret.style.display = pending ? "none" : "flex";
|
||||||
|
|
||||||
modal.classList.add("show");
|
modal.classList.add("show");
|
||||||
@@ -297,6 +307,10 @@ export function closeOrderActionsModal() {
|
|||||||
// static/js/map.js:1943-1973
|
// static/js/map.js:1943-1973
|
||||||
export async function findCurrentOrderBike() {
|
export async function findCurrentOrderBike() {
|
||||||
if (!isOrderActionEligible(S.currentOrder)) return;
|
if (!isOrderActionEligible(S.currentOrder)) return;
|
||||||
|
if (S.currentOrder.shared) {
|
||||||
|
showToast("共享订单仅骑行人可寻车,车主只能还车");
|
||||||
|
return;
|
||||||
|
}
|
||||||
const code = (S.currentOrder.code || "").toString().trim();
|
const code = (S.currentOrder.code || "").toString().trim();
|
||||||
if (!code) {
|
if (!code) {
|
||||||
showToast("该订单没有车牌信息");
|
showToast("该订单没有车牌信息");
|
||||||
@@ -329,6 +343,10 @@ export async function findCurrentOrderBike() {
|
|||||||
|
|
||||||
// static/js/map.js:1975-1978
|
// static/js/map.js:1975-1978
|
||||||
export function payCurrentOrderFromModal() {
|
export function payCurrentOrderFromModal() {
|
||||||
|
if (S.currentOrder && S.currentOrder.shared) {
|
||||||
|
showToast("共享订单由骑行人处理支付,车主只能还车");
|
||||||
|
return;
|
||||||
|
}
|
||||||
closeOrderActionsModal();
|
closeOrderActionsModal();
|
||||||
tryCardPayOrRedirect();
|
tryCardPayOrRedirect();
|
||||||
}
|
}
|
||||||
@@ -348,6 +366,11 @@ export function handleOrderBannerClick() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (Number(S.currentOrder.status) === 1) {
|
if (Number(S.currentOrder.status) === 1) {
|
||||||
|
// 共享单待支付也只能由骑行人处理,车主没有支付入口。
|
||||||
|
if (S.currentOrder.shared) {
|
||||||
|
showOrderActionsModal();
|
||||||
|
return;
|
||||||
|
}
|
||||||
// 待支付 - 先检查是否有月卡/周卡
|
// 待支付 - 先检查是否有月卡/周卡
|
||||||
tryCardPayOrRedirect();
|
tryCardPayOrRedirect();
|
||||||
} else if (Number(S.currentOrder.status) === 2) {
|
} else if (Number(S.currentOrder.status) === 2) {
|
||||||
|
|||||||
Vendored
+44
-8
@@ -829,12 +829,14 @@
|
|||||||
const icon = document.getElementById("order-banner-icon");
|
const icon = document.getElementById("order-banner-icon");
|
||||||
const text = document.getElementById("order-banner-text");
|
const text = document.getElementById("order-banner-text");
|
||||||
const btn = document.getElementById("order-banner-btn");
|
const btn = document.getElementById("order-banner-btn");
|
||||||
|
btn.onclick = handleOrderBannerClick;
|
||||||
banner.classList.remove("warning", "riding");
|
banner.classList.remove("warning", "riding");
|
||||||
if (Number(order.status) === 1) {
|
if (Number(order.status) === 1) {
|
||||||
banner.classList.add("warning");
|
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>';
|
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)}`;
|
text.textContent = `待支付订单 #${order.code || order.order_id.slice(-6)}`;
|
||||||
btn.textContent = "去支付";
|
btn.textContent = order.shared ? "查看" : "去支付";
|
||||||
|
if (order.shared) btn.onclick = showOrderActionsModal;
|
||||||
hideOrderCountdown();
|
hideOrderCountdown();
|
||||||
const progress = document.getElementById("order-final-time");
|
const progress = document.getElementById("order-final-time");
|
||||||
progress.textContent = "待支付 · 骑行已结束";
|
progress.textContent = "待支付 · 骑行已结束";
|
||||||
@@ -880,7 +882,7 @@
|
|||||||
finalEl.style.display = "inline";
|
finalEl.style.display = "inline";
|
||||||
}
|
}
|
||||||
if (addBtn) {
|
if (addBtn) {
|
||||||
const eligible = data.data.order_id && String(data.data.source) !== "reminder";
|
const eligible = data.data.order_id && String(data.data.source) !== "reminder" && !(S.currentOrder && S.currentOrder.shared);
|
||||||
addBtn.style.display = eligible ? "inline-block" : "none";
|
addBtn.style.display = eligible ? "inline-block" : "none";
|
||||||
}
|
}
|
||||||
showOrderCountdown();
|
showOrderCountdown();
|
||||||
@@ -984,18 +986,23 @@
|
|||||||
const hint = document.getElementById("order-actions-hint");
|
const hint = document.getElementById("order-actions-hint");
|
||||||
const code = S.currentOrder.code || S.currentOrder.order_id || "未知";
|
const code = S.currentOrder.code || S.currentOrder.order_id || "未知";
|
||||||
const pending = Number(S.currentOrder.status) === 1;
|
const pending = Number(S.currentOrder.status) === 1;
|
||||||
|
const ownerShared = !!S.currentOrder.shared;
|
||||||
meta.textContent = `车辆 #${code}`;
|
meta.textContent = `车辆 #${code}`;
|
||||||
status.textContent = pending ? "待支付订单" : "订单进行中";
|
status.textContent = ownerShared ? "" : pending ? "待支付订单" : "订单进行中";
|
||||||
status.classList.toggle("warning", pending);
|
status.style.display = ownerShared ? "none" : "";
|
||||||
|
status.classList.toggle("warning", pending && !ownerShared);
|
||||||
status.classList.toggle("riding", !pending);
|
status.classList.toggle("riding", !pending);
|
||||||
hint.textContent = pending ? "当前订单尚未支付,请先完成支付后再使用车辆操作。" : "临时锁车不会结束订单,确认车辆停放安全后再操作。";
|
hint.textContent = ownerShared ? "" : pending ? "当前订单尚未支付,请先完成支付后再使用车辆操作。" : "临时锁车不会结束订单,确认车辆停放安全后再操作。";
|
||||||
|
hint.style.display = ownerShared ? "none" : "";
|
||||||
["order-action-lock", "order-action-unlock"].forEach((id) => {
|
["order-action-lock", "order-action-unlock"].forEach((id) => {
|
||||||
const button = document.getElementById(id);
|
const button = document.getElementById(id);
|
||||||
if (button) button.style.display = pending ? "none" : "flex";
|
if (button) button.style.display = pending || ownerShared ? "none" : "flex";
|
||||||
});
|
});
|
||||||
|
const find = document.getElementById("order-action-find");
|
||||||
const pay = document.getElementById("order-action-pay");
|
const pay = document.getElementById("order-action-pay");
|
||||||
const ret = document.getElementById("order-action-return");
|
const ret = document.getElementById("order-action-return");
|
||||||
if (pay) pay.style.display = pending ? "flex" : "none";
|
if (find) find.style.display = ownerShared ? "none" : "flex";
|
||||||
|
if (pay) pay.style.display = pending && !ownerShared ? "flex" : "none";
|
||||||
if (ret) ret.style.display = pending ? "none" : "flex";
|
if (ret) ret.style.display = pending ? "none" : "flex";
|
||||||
modal.classList.add("show");
|
modal.classList.add("show");
|
||||||
modal.setAttribute("aria-hidden", "false");
|
modal.setAttribute("aria-hidden", "false");
|
||||||
@@ -1014,6 +1021,10 @@
|
|||||||
}
|
}
|
||||||
async function findCurrentOrderBike() {
|
async function findCurrentOrderBike() {
|
||||||
if (!isOrderActionEligible(S.currentOrder)) return;
|
if (!isOrderActionEligible(S.currentOrder)) return;
|
||||||
|
if (S.currentOrder.shared) {
|
||||||
|
showToast("共享订单仅骑行人可寻车,车主只能还车");
|
||||||
|
return;
|
||||||
|
}
|
||||||
const code = (S.currentOrder.code || "").toString().trim();
|
const code = (S.currentOrder.code || "").toString().trim();
|
||||||
if (!code) {
|
if (!code) {
|
||||||
showToast("该订单没有车牌信息");
|
showToast("该订单没有车牌信息");
|
||||||
@@ -1042,6 +1053,10 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
function payCurrentOrderFromModal() {
|
function payCurrentOrderFromModal() {
|
||||||
|
if (S.currentOrder && S.currentOrder.shared) {
|
||||||
|
showToast("共享订单由骑行人处理支付,车主只能还车");
|
||||||
|
return;
|
||||||
|
}
|
||||||
closeOrderActionsModal();
|
closeOrderActionsModal();
|
||||||
tryCardPayOrRedirect();
|
tryCardPayOrRedirect();
|
||||||
}
|
}
|
||||||
@@ -1056,6 +1071,10 @@
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (Number(S.currentOrder.status) === 1) {
|
if (Number(S.currentOrder.status) === 1) {
|
||||||
|
if (S.currentOrder.shared) {
|
||||||
|
showOrderActionsModal();
|
||||||
|
return;
|
||||||
|
}
|
||||||
tryCardPayOrRedirect();
|
tryCardPayOrRedirect();
|
||||||
} else if (Number(S.currentOrder.status) === 2) {
|
} else if (Number(S.currentOrder.status) === 2) {
|
||||||
showReturnConfirm();
|
showReturnConfirm();
|
||||||
@@ -2512,6 +2531,10 @@
|
|||||||
var orderTempActionLoading = false;
|
var orderTempActionLoading = false;
|
||||||
async function tempLockCurrentOrder() {
|
async function tempLockCurrentOrder() {
|
||||||
if (orderTempActionLoading || !isOrderActionEligible(S.currentOrder) || Number(S.currentOrder.status) !== 2) return;
|
if (orderTempActionLoading || !isOrderActionEligible(S.currentOrder) || Number(S.currentOrder.status) !== 2) return;
|
||||||
|
if (S.currentOrder.shared) {
|
||||||
|
showToast("共享订单仅骑行人可临时锁车,车主只能还车");
|
||||||
|
return;
|
||||||
|
}
|
||||||
const order = S.currentOrder;
|
const order = S.currentOrder;
|
||||||
const button = document.getElementById("order-action-lock");
|
const button = document.getElementById("order-action-lock");
|
||||||
orderTempActionLoading = true;
|
orderTempActionLoading = true;
|
||||||
@@ -2559,6 +2582,10 @@
|
|||||||
}
|
}
|
||||||
async function tempUnlockCurrentOrder() {
|
async function tempUnlockCurrentOrder() {
|
||||||
if (orderTempActionLoading || !isOrderActionEligible(S.currentOrder) || Number(S.currentOrder.status) !== 2) return;
|
if (orderTempActionLoading || !isOrderActionEligible(S.currentOrder) || Number(S.currentOrder.status) !== 2) return;
|
||||||
|
if (S.currentOrder.shared) {
|
||||||
|
showToast("共享订单仅骑行人可临时开车,车主只能还车");
|
||||||
|
return;
|
||||||
|
}
|
||||||
const button = document.getElementById("order-action-unlock");
|
const button = document.getElementById("order-action-unlock");
|
||||||
orderTempActionLoading = true;
|
orderTempActionLoading = true;
|
||||||
if (button) {
|
if (button) {
|
||||||
@@ -3068,6 +3095,10 @@
|
|||||||
showToast("当前没有进行中的订单");
|
showToast("当前没有进行中的订单");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (S.currentOrder && S.currentOrder.shared) {
|
||||||
|
showToast("共享订单仅骑行人可加轮,车主只能还车");
|
||||||
|
return;
|
||||||
|
}
|
||||||
showAddRoundConfirm({ kind: "rental", value: S.activeRental.rental_id });
|
showAddRoundConfirm({ kind: "rental", value: S.activeRental.rental_id });
|
||||||
}
|
}
|
||||||
function addRoundFromBanner() {
|
function addRoundFromBanner() {
|
||||||
@@ -3075,6 +3106,10 @@
|
|||||||
showToast("当前没有进行中的订单");
|
showToast("当前没有进行中的订单");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (S.currentOrder.shared) {
|
||||||
|
showToast("共享订单仅骑行人可加轮,车主只能还车");
|
||||||
|
return;
|
||||||
|
}
|
||||||
showAddRoundConfirm({ kind: "order", value: S.currentOrder.order_id });
|
showAddRoundConfirm({ kind: "order", value: S.currentOrder.order_id });
|
||||||
}
|
}
|
||||||
function scanCode() {
|
function scanCode() {
|
||||||
@@ -3429,7 +3464,8 @@
|
|||||||
const addBtn = document.getElementById("rental-add-round-btn");
|
const addBtn = document.getElementById("rental-add-round-btn");
|
||||||
if (addBtn) {
|
if (addBtn) {
|
||||||
const realOrder = S.activeRental.source ? S.activeRental.source !== "reminder" : !!S.activeRental.order_id;
|
const realOrder = S.activeRental.source ? S.activeRental.source !== "reminder" : !!S.activeRental.order_id;
|
||||||
addBtn.style.display = realOrder ? "inline-flex" : "none";
|
const ownerShared = !!(S.currentOrder && S.currentOrder.shared);
|
||||||
|
addBtn.style.display = realOrder && !ownerShared ? "inline-flex" : "none";
|
||||||
}
|
}
|
||||||
updateRentalFinalTime();
|
updateRentalFinalTime();
|
||||||
updateRentalCountdown();
|
updateRentalCountdown();
|
||||||
|
|||||||
@@ -0,0 +1,153 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""手动还车永不续租;只有自动到点还车才允许进入下一轮。"""
|
||||||
|
import os
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from flask import Flask
|
||||||
|
|
||||||
|
import db
|
||||||
|
import timer
|
||||||
|
from routes import rental as rental_routes
|
||||||
|
from routes import share as share_routes
|
||||||
|
|
||||||
|
|
||||||
|
class ManualReturnNoRenewalTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
os.environ["XBCR_DISABLE_BACKGROUND"] = "1"
|
||||||
|
os.environ["XBCR_DISABLE_LEASES"] = "1"
|
||||||
|
self.tmp = tempfile.TemporaryDirectory()
|
||||||
|
self._old_db = db.DB_PATH
|
||||||
|
db.DB_PATH = Path(self.tmp.name) / "manual-return.db"
|
||||||
|
db.init_db()
|
||||||
|
conn = db.get_db()
|
||||||
|
conn.execute("INSERT INTO users (id, email, password_hash, rental_rounds) VALUES (7, 'owner@example.test', 'x', 3)")
|
||||||
|
conn.execute("INSERT INTO users (id, email, password_hash, rental_rounds) VALUES (8, 'rider@example.test', 'x', 3)")
|
||||||
|
conn.execute("""
|
||||||
|
INSERT INTO rentals (id, order_id, bike_code, email, user_id, rider_user_id,
|
||||||
|
start_time, end_time, duration, expired, source,
|
||||||
|
renewal_round, rounds_override)
|
||||||
|
VALUES (9001, '9001', '51287', 'rider@example.test', 7, 8,
|
||||||
|
'2099-01-01 09:00:00', '2099-01-01 09:19:00', 19, 0, 'shared', 1, 5)
|
||||||
|
""")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
for table in (timer._auto_return_retries, timer._auto_return_backoff_until,
|
||||||
|
timer._auto_return_first_fail_at, timer._recover_last_at):
|
||||||
|
table[9001] = 1
|
||||||
|
self.user = {"id": 8, "email": "rider@example.test"}
|
||||||
|
root = Path(__file__).resolve().parents[1]
|
||||||
|
self.app = Flask(__name__, template_folder=str(root / "templates"))
|
||||||
|
self.app.register_blueprint(rental_routes.bp)
|
||||||
|
self.app.register_blueprint(share_routes.bp)
|
||||||
|
self.client = self.app.test_client()
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
db.DB_PATH = self._old_db
|
||||||
|
for table in (timer._auto_return_retries, timer._auto_return_backoff_until,
|
||||||
|
timer._auto_return_first_fail_at, timer._recover_last_at):
|
||||||
|
table.pop(9001, None)
|
||||||
|
self.tmp.cleanup()
|
||||||
|
|
||||||
|
def assert_stopped(self, reopen):
|
||||||
|
reopen.assert_not_called()
|
||||||
|
self.assertNotIn(9001, timer._auto_return_retries)
|
||||||
|
self.assertNotIn(9001, timer._auto_return_backoff_until)
|
||||||
|
self.assertNotIn(9001, timer._auto_return_first_fail_at)
|
||||||
|
self.assertNotIn(9001, timer._recover_last_at)
|
||||||
|
|
||||||
|
def test_generic_manual_return_defaults_to_no_renewal(self):
|
||||||
|
responses = [
|
||||||
|
{"rtn_code": 0, "data": {"latitude": 36.6, "longitude": 116.9}},
|
||||||
|
{"rtn_code": 0, "message": "ok"},
|
||||||
|
]
|
||||||
|
with patch.object(timer, "_park_areas_for_user", return_value=[]), \
|
||||||
|
patch.object(timer, "request_with_user_auth", side_effect=responses), \
|
||||||
|
patch.object(timer, "_try_card_pay_auto", return_value={"success": True}), \
|
||||||
|
patch.object(timer, "_reopen_same_bike") as reopen:
|
||||||
|
result = timer.auto_return_bike(9001, 7) # 不传 allow_renewal = 手动语义
|
||||||
|
|
||||||
|
self.assertTrue(result["success"])
|
||||||
|
self.assertFalse(result["renewal"]["renewed"])
|
||||||
|
self.assert_stopped(reopen)
|
||||||
|
|
||||||
|
def test_page_button_return_never_reopens(self):
|
||||||
|
owner = {"id": 7, "email": "owner@example.test"}
|
||||||
|
with patch.object(rental_routes, "get_current_user", return_value=owner), \
|
||||||
|
patch.object(rental_routes, "get_user_display_name", return_value="骑行人"), \
|
||||||
|
patch.object(rental_routes, "_try_return_candidates",
|
||||||
|
return_value=({"rtn_code": 0}, (36.6, 116.9), ["上报位置"])), \
|
||||||
|
patch.object(rental_routes, "_try_card_pay_auto", return_value={}), \
|
||||||
|
patch.object(timer, "_reopen_same_bike") as reopen:
|
||||||
|
body = self.client.post("/api/order/return", json={
|
||||||
|
"order_id": "9001", "code": "51287",
|
||||||
|
"latitude": 36.6, "longitude": 116.9,
|
||||||
|
}).get_json()
|
||||||
|
self.assertEqual(0, body["rtn_code"], body)
|
||||||
|
self.assert_stopped(reopen)
|
||||||
|
|
||||||
|
def test_email_link_explicitly_disables_renewal(self):
|
||||||
|
row = {"id": 9001, "user_id": 7, "order_id": "9001",
|
||||||
|
"source": "shared", "bike_code": "51287"}
|
||||||
|
with patch.object(rental_routes, "resolve_return_token", return_value=("valid", row)), \
|
||||||
|
patch.object(rental_routes, "auto_return_bike",
|
||||||
|
return_value={"success": True}) as auto_return, \
|
||||||
|
patch.object(timer, "_reopen_same_bike") as reopen:
|
||||||
|
response = self.client.post("/rental/email-return", data={"token": "one-time"})
|
||||||
|
self.assertEqual(200, response.status_code)
|
||||||
|
auto_return.assert_called_once_with(9001, 7, allow_renewal=False)
|
||||||
|
reopen.assert_not_called()
|
||||||
|
|
||||||
|
def test_shared_return_never_reopens(self):
|
||||||
|
def fake_auth(user_id, method, path, **kwargs):
|
||||||
|
if path == "/record/checkLocation":
|
||||||
|
return {"rtn_code": 0, "parkNoShow": False}
|
||||||
|
if path == "/record/return":
|
||||||
|
return {"rtn_code": 0}
|
||||||
|
raise AssertionError(path)
|
||||||
|
|
||||||
|
with patch.object(share_routes, "get_current_user", return_value=self.user), \
|
||||||
|
patch.object(share_routes, "request_with_user_auth", side_effect=fake_auth), \
|
||||||
|
patch.object(rental_routes, "_try_card_pay_auto", return_value={}), \
|
||||||
|
patch("rental_mail.send_share_returned_email", return_value=None), \
|
||||||
|
patch.object(timer, "_reopen_same_bike") as reopen:
|
||||||
|
body = self.client.post("/api/share/return", json={
|
||||||
|
"order_id": "9001", "latitude": 36.6, "longitude": 116.9,
|
||||||
|
}).get_json()
|
||||||
|
self.assertEqual(0, body["rtn_code"], body)
|
||||||
|
self.assert_stopped(reopen)
|
||||||
|
|
||||||
|
def test_official_miniprogram_return_only_closes_locally(self):
|
||||||
|
with patch.object(timer, "_bike_pos_from_history", return_value=None), \
|
||||||
|
patch.object(timer, "_reopen_same_bike") as reopen:
|
||||||
|
timer._finish_active_wechat_rentals(7, "官方小程序内手动还车")
|
||||||
|
conn = db.get_db()
|
||||||
|
expired = conn.execute("SELECT expired FROM rentals WHERE id=9001").fetchone()[0]
|
||||||
|
conn.close()
|
||||||
|
self.assertEqual(1, expired)
|
||||||
|
self.assert_stopped(reopen)
|
||||||
|
|
||||||
|
def test_automatic_recovery_is_the_explicit_renewal_exception(self):
|
||||||
|
"""自动路径必须显式声明续租,不能靠默认值。"""
|
||||||
|
responses = [
|
||||||
|
{"rtn_code": 0, "data": {"latitude": 36.6, "longitude": 116.9}},
|
||||||
|
{"rtn_code": 0, "message": "ok"},
|
||||||
|
]
|
||||||
|
settings = {"rental_duration_minutes": 19, "rental_rounds": 3,
|
||||||
|
"auto_return_enabled": True, "protect_card": False}
|
||||||
|
with patch.object(timer, "_park_areas_for_user", return_value=[]), \
|
||||||
|
patch.object(timer, "request_with_user_auth", side_effect=responses), \
|
||||||
|
patch.object(timer, "get_user_rental_settings", return_value=settings), \
|
||||||
|
patch.object(timer, "_try_card_pay_auto", return_value={"success": True}), \
|
||||||
|
patch.object(timer, "_has_available_card", return_value=True), \
|
||||||
|
patch.object(timer, "_reopen_same_bike",
|
||||||
|
return_value={"success": True, "order_id": "NEXT-9001"}), \
|
||||||
|
patch.object(timer, "start_rental_timer"):
|
||||||
|
result = timer.auto_return_bike(9001, 7, allow_renewal=True)
|
||||||
|
self.assertTrue(result["renewal"]["renewed"])
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -233,7 +233,7 @@ class OrderSyncTests(unittest.TestCase):
|
|||||||
patch.object(timer, "start_rental_timer"), \
|
patch.object(timer, "start_rental_timer"), \
|
||||||
patch.object(timer, "_cancel_rental_timers"), \
|
patch.object(timer, "_cancel_rental_timers"), \
|
||||||
patch.object(timer, "mark_return_tokens_used"):
|
patch.object(timer, "mark_return_tokens_used"):
|
||||||
result = timer.auto_return_bike(101, 7)
|
result = timer.auto_return_bike(101, 7, allow_renewal=True)
|
||||||
|
|
||||||
self.assertTrue(result["success"])
|
self.assertTrue(result["success"])
|
||||||
self.assertTrue(result["renewal"]["renewed"])
|
self.assertTrue(result["renewal"]["renewed"])
|
||||||
@@ -267,7 +267,7 @@ class OrderSyncTests(unittest.TestCase):
|
|||||||
patch.object(timer, "_reopen_same_bike") as reopen, \
|
patch.object(timer, "_reopen_same_bike") as reopen, \
|
||||||
patch.object(timer, "_cancel_rental_timers"), \
|
patch.object(timer, "_cancel_rental_timers"), \
|
||||||
patch.object(timer, "mark_return_tokens_used"):
|
patch.object(timer, "mark_return_tokens_used"):
|
||||||
result = timer.auto_return_bike(101, 7)
|
result = timer.auto_return_bike(101, 7, allow_renewal=True)
|
||||||
|
|
||||||
self.assertTrue(result["success"])
|
self.assertTrue(result["success"])
|
||||||
self.assertTrue(result["renewal"]["blocked"])
|
self.assertTrue(result["renewal"]["blocked"])
|
||||||
@@ -547,7 +547,7 @@ class OrderSyncTests(unittest.TestCase):
|
|||||||
send_notification=False, auto_return_enabled=True,
|
send_notification=False, auto_return_enabled=True,
|
||||||
auto_return_configured=True,
|
auto_return_configured=True,
|
||||||
)
|
)
|
||||||
auto_return.assert_called_once_with(101, 7)
|
auto_return.assert_called_once_with(101, 7, allow_renewal=True)
|
||||||
notify.assert_not_called()
|
notify.assert_not_called()
|
||||||
|
|
||||||
def test_sync_rental_backfills_start_from_bike_history(self):
|
def test_sync_rental_backfills_start_from_bike_history(self):
|
||||||
@@ -907,7 +907,7 @@ class OrderSyncTests(unittest.TestCase):
|
|||||||
}) as auto_return:
|
}) as auto_return:
|
||||||
result = timer._run_recovery(121, 7, "9021")
|
result = timer._run_recovery(121, 7, "9021")
|
||||||
|
|
||||||
auto_return.assert_called_once_with(121, 7)
|
auto_return.assert_called_once_with(121, 7, allow_renewal=True)
|
||||||
self.assertTrue(result.get("success"))
|
self.assertTrue(result.get("success"))
|
||||||
|
|
||||||
def test_sweep_queues_overdue_rentals_and_is_throttled(self):
|
def test_sweep_queues_overdue_rentals_and_is_throttled(self):
|
||||||
|
|||||||
@@ -0,0 +1,171 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""共享单策略:设置属于骑行人,车主只能还车;续租无坐标也先尝试下单。"""
|
||||||
|
import os
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from flask import Flask
|
||||||
|
|
||||||
|
import db
|
||||||
|
import timer
|
||||||
|
from routes import rental
|
||||||
|
|
||||||
|
|
||||||
|
class SharedRiderPolicyTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
os.environ["XBCR_DISABLE_BACKGROUND"] = "1"
|
||||||
|
os.environ["XBCR_DISABLE_LEASES"] = "1"
|
||||||
|
self.tmp = tempfile.TemporaryDirectory()
|
||||||
|
self._old_db = db.DB_PATH
|
||||||
|
db.DB_PATH = Path(self.tmp.name) / "shared.db"
|
||||||
|
db.init_db()
|
||||||
|
conn = db.get_db()
|
||||||
|
conn.execute("INSERT INTO users (id, email, password_hash, rental_duration_minutes, rental_rounds, protect_card) VALUES (7, 'owner@example.test', 'x', 19, 2, 1)")
|
||||||
|
conn.execute("INSERT INTO users (id, email, password_hash, rental_duration_minutes, rental_rounds, protect_card) VALUES (8, 'rider@example.test', 'x', 27, 4, 0)")
|
||||||
|
conn.execute("INSERT INTO shares (owner_user_id, rider_user_id, status) VALUES (7, 8, 'active')")
|
||||||
|
conn.execute("""
|
||||||
|
INSERT INTO rentals (id, order_id, bike_code, email, user_id, rider_user_id,
|
||||||
|
start_time, end_time, duration, expired, source, renewal_round)
|
||||||
|
VALUES (9001, 'ORD-SHARED', '51287', 'rider@example.test', 7, 8,
|
||||||
|
'2099-01-01 09:00:00', '2099-01-01 09:19:00', 19, 0, 'shared', 1)
|
||||||
|
""")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
self.app = Flask(__name__)
|
||||||
|
self.app.register_blueprint(rental.bp)
|
||||||
|
self.client = self.app.test_client()
|
||||||
|
self.owner = {"id": 7, "email": "owner@example.test"}
|
||||||
|
self.rider = {"id": 8, "email": "rider@example.test"}
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
db.DB_PATH = self._old_db
|
||||||
|
self.tmp.cleanup()
|
||||||
|
|
||||||
|
def test_preview_uses_rider_settings_and_owner_card(self):
|
||||||
|
"""预览:车主出卡,骑行人决定 27 分钟 / 4 轮 / 不保护卡。"""
|
||||||
|
seen_users = []
|
||||||
|
|
||||||
|
def fake_auth(user_id, method, path, **kwargs):
|
||||||
|
seen_users.append((user_id, path))
|
||||||
|
return {"rtn_code": 0, "data": {"bike_packages": [
|
||||||
|
{"name": "月卡", "remainTimes": 9, "type": "3"}
|
||||||
|
]}}
|
||||||
|
|
||||||
|
with patch.object(rental, "get_current_user", return_value=self.rider), \
|
||||||
|
patch.object(rental, "request_with_user_auth", side_effect=fake_auth):
|
||||||
|
body = self.client.get(
|
||||||
|
"/api/order/preview?code=51287&owner_user_id=7"
|
||||||
|
).get_json()["data"]
|
||||||
|
|
||||||
|
self.assertEqual(27, body["duration_minutes"])
|
||||||
|
self.assertEqual(4, body["rounds_planned"])
|
||||||
|
self.assertFalse(body["protect_card"])
|
||||||
|
self.assertTrue(body["has_card"])
|
||||||
|
self.assertIn((7, "/user/packages"), seen_users)
|
||||||
|
self.assertNotIn((8, "/user/packages"), seen_users)
|
||||||
|
|
||||||
|
def test_shared_owner_cannot_add_round_but_rider_can(self):
|
||||||
|
with patch.object(rental, "get_current_user", return_value=self.owner):
|
||||||
|
body = self.client.post(
|
||||||
|
"/api/order/add_round", json={"order_id": "ORD-SHARED"}
|
||||||
|
).get_json()
|
||||||
|
self.assertEqual(403, body["rtn_code"])
|
||||||
|
self.assertIn("车主只能还车", body["message"])
|
||||||
|
|
||||||
|
with patch.object(rental, "get_current_user", return_value=self.rider):
|
||||||
|
body = self.client.post(
|
||||||
|
"/api/order/add_round", json={"order_id": "ORD-SHARED"}
|
||||||
|
).get_json()
|
||||||
|
self.assertEqual(0, body["rtn_code"], body)
|
||||||
|
self.assertEqual(5, body["data"]["total_rounds"], body)
|
||||||
|
|
||||||
|
conn = db.get_db()
|
||||||
|
value = conn.execute("SELECT rounds_override FROM rentals WHERE id=9001").fetchone()[0]
|
||||||
|
conn.close()
|
||||||
|
self.assertEqual(5, value)
|
||||||
|
|
||||||
|
def test_shared_owner_cannot_temp_lock_or_unlock(self):
|
||||||
|
with patch.object(rental, "get_current_user", return_value=self.owner), \
|
||||||
|
patch.object(rental, "request_with_user_auth") as upstream:
|
||||||
|
unlock = self.client.post(
|
||||||
|
"/api/order/temp_unlock", json={"order_id": "ORD-SHARED"}
|
||||||
|
).get_json()
|
||||||
|
lock = self.client.post("/api/order/temp_lock", json={
|
||||||
|
"order_id": "ORD-SHARED", "code": "51287",
|
||||||
|
"latitude": 36.5318, "longitude": 116.7802,
|
||||||
|
}).get_json()
|
||||||
|
self.assertEqual(403, unlock["rtn_code"])
|
||||||
|
self.assertEqual(403, lock["rtn_code"])
|
||||||
|
upstream.assert_not_called()
|
||||||
|
|
||||||
|
def test_shared_rider_can_still_temp_lock_and_unlock(self):
|
||||||
|
def success(*args, **kwargs):
|
||||||
|
return {"rtn_code": 0, "data": {}}
|
||||||
|
|
||||||
|
with patch.object(rental, "get_current_user", return_value=self.rider), \
|
||||||
|
patch.object(rental, "get_user_display_name", return_value="骑行人"), \
|
||||||
|
patch.object(rental, "_resolve_order_location",
|
||||||
|
return_value=(36.5318, 116.7802, False)), \
|
||||||
|
patch.object(rental, "request_with_user_auth", side_effect=success):
|
||||||
|
unlock = self.client.post(
|
||||||
|
"/api/order/temp_unlock", json={"order_id": "ORD-SHARED"}
|
||||||
|
).get_json()
|
||||||
|
lock = self.client.post("/api/order/temp_lock", json={
|
||||||
|
"order_id": "ORD-SHARED", "code": "51287",
|
||||||
|
"latitude": 36.5318, "longitude": 116.7802,
|
||||||
|
}).get_json()
|
||||||
|
self.assertEqual(0, unlock["rtn_code"], unlock)
|
||||||
|
self.assertEqual(0, lock["rtn_code"], lock)
|
||||||
|
|
||||||
|
def test_shared_owner_cannot_pay_with_card(self):
|
||||||
|
with patch.object(rental, "get_current_user", return_value=self.owner), \
|
||||||
|
patch.object(rental, "request_with_user_auth") as upstream:
|
||||||
|
body = self.client.post("/api/order/pay_with_card", json={
|
||||||
|
"order_id": "ORD-SHARED", "code": "51287",
|
||||||
|
"package_id": 1, "pay_type": "3",
|
||||||
|
}).get_json()
|
||||||
|
self.assertEqual(403, body["rtn_code"])
|
||||||
|
upstream.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
class RenewalCoordinateFallbackTests(unittest.TestCase):
|
||||||
|
def _run(self, record_order_response):
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def fake_auth(user_id, method, path, **kwargs):
|
||||||
|
calls.append((path, kwargs.get("data") or {}))
|
||||||
|
if path == "/project/bicycle":
|
||||||
|
return {"rtn_code": 0, "data": {}}
|
||||||
|
if path == "/project/map":
|
||||||
|
return {"rtn_code": 0, "data": {"bicycleStation": []}}
|
||||||
|
if path == "/record/order":
|
||||||
|
return record_order_response
|
||||||
|
if path == "/record/qrOrder":
|
||||||
|
return {"rtn_code": 0}
|
||||||
|
raise AssertionError(path)
|
||||||
|
|
||||||
|
with patch.object(timer, "request_with_user_auth", side_effect=fake_auth):
|
||||||
|
result = timer._reopen_same_bike(8, "51287")
|
||||||
|
return result, calls
|
||||||
|
|
||||||
|
def test_no_position_still_tries_order_and_unlock(self):
|
||||||
|
result, calls = self._run({"rtn_code": 0, "data": {"order_id": "NEXT-1"}})
|
||||||
|
self.assertTrue(result["success"], result)
|
||||||
|
self.assertEqual("NEXT-1", result["order_id"])
|
||||||
|
order_data = next(data for path, data in calls if path == "/record/order")
|
||||||
|
self.assertNotIn("start_latitude", order_data)
|
||||||
|
self.assertNotIn("start_longitude", order_data)
|
||||||
|
self.assertTrue(any(path == "/record/qrOrder" for path, _ in calls))
|
||||||
|
|
||||||
|
def test_no_position_reports_actual_order_failure(self):
|
||||||
|
result, calls = self._run({"rtn_code": 500, "message": "车辆状态异常"})
|
||||||
|
self.assertFalse(result["success"])
|
||||||
|
self.assertIn("车辆状态异常", result["message"])
|
||||||
|
self.assertIn("已直接尝试下单", result["message"])
|
||||||
|
self.assertFalse(any(path == "/record/qrOrder" for path, _ in calls))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""上游从 A 切换到 B:A 按小程序还车收尾,B 接续,不保留双骑行单。"""
|
||||||
|
import os
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import db
|
||||||
|
import timer
|
||||||
|
|
||||||
|
|
||||||
|
class UpstreamOrderSwitchTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
os.environ["XBCR_DISABLE_BACKGROUND"] = "1"
|
||||||
|
os.environ["XBCR_DISABLE_LEASES"] = "1"
|
||||||
|
self.tmp = tempfile.TemporaryDirectory()
|
||||||
|
self._old_db = db.DB_PATH
|
||||||
|
db.DB_PATH = Path(self.tmp.name) / "switch.db"
|
||||||
|
db.init_db()
|
||||||
|
conn = db.get_db()
|
||||||
|
conn.execute("INSERT INTO users (id, email, password_hash) VALUES (7, 'rider@example.test', 'x')")
|
||||||
|
conn.execute("""
|
||||||
|
INSERT INTO rentals (id, order_id, bike_code, email, user_id,
|
||||||
|
start_time, end_time, duration, expired, source)
|
||||||
|
VALUES (100, 'ORDER-A', 'BIKE-A', 'rider@example.test', 7,
|
||||||
|
'2099-01-01 09:00:00', '2099-01-01 09:19:00', 19, 0, 'unlock')
|
||||||
|
""")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
timer._auto_return_retries[100] = 2
|
||||||
|
timer._auto_return_backoff_until[100] = 9999999999
|
||||||
|
timer._auto_return_first_fail_at[100] = 1
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
db.DB_PATH = self._old_db
|
||||||
|
for table in (timer._auto_return_retries, timer._auto_return_backoff_until,
|
||||||
|
timer._auto_return_first_fail_at):
|
||||||
|
table.pop(100, None)
|
||||||
|
self.tmp.cleanup()
|
||||||
|
|
||||||
|
def _check(self, upstream_order="ORDER-B", bike="BIKE-B"):
|
||||||
|
def fake_auth(user_id, method, path, **kwargs):
|
||||||
|
if path == "/user/info":
|
||||||
|
return {"rtn_code": 0, "data": {"nonDealOrder": {
|
||||||
|
"order_id": upstream_order, "status": 2, "code": bike}}}
|
||||||
|
if path == "/record/detail":
|
||||||
|
return {"rtn_code": 0, "data": {"minutes": 2, "code": bike}}
|
||||||
|
raise AssertionError(path)
|
||||||
|
|
||||||
|
with patch.object(timer, "get_user_auth", return_value=("token", "access")), \
|
||||||
|
patch.object(timer, "request_with_user_auth", side_effect=fake_auth), \
|
||||||
|
patch.object(timer, "get_user_rental_settings", return_value={
|
||||||
|
"rental_duration_minutes": 19, "rental_rounds": 2,
|
||||||
|
"auto_return_enabled": True, "reminder_enabled": False,
|
||||||
|
"reminder_minutes": [], "protect_card": False}), \
|
||||||
|
patch.object(timer, "_fill_missing_start", return_value=True), \
|
||||||
|
patch.object(timer, "start_rental_timer") as start_timer, \
|
||||||
|
patch.object(timer, "_reopen_same_bike") as reopen:
|
||||||
|
result = timer._check_user_order(7)
|
||||||
|
return result, start_timer, reopen
|
||||||
|
|
||||||
|
def test_switch_closes_a_and_starts_b_without_renewal(self):
|
||||||
|
result, start_timer, reopen = self._check()
|
||||||
|
self.assertTrue(result["active"])
|
||||||
|
self.assertEqual("ORDER-B", result["order_id"])
|
||||||
|
|
||||||
|
conn = db.get_db()
|
||||||
|
a = conn.execute("SELECT expired, returned_at FROM rentals WHERE id=100").fetchone()
|
||||||
|
b = conn.execute("SELECT id, bike_code, expired FROM rentals WHERE order_id='ORDER-B'").fetchone()
|
||||||
|
conn.close()
|
||||||
|
self.assertEqual(1, a["expired"], "A 必须按小程序还车收尾")
|
||||||
|
self.assertIsNotNone(a["returned_at"])
|
||||||
|
self.assertIsNotNone(b)
|
||||||
|
self.assertEqual("BIKE-B", b["bike_code"])
|
||||||
|
self.assertEqual(0, b["expired"])
|
||||||
|
start_timer.assert_called_once()
|
||||||
|
self.assertEqual(b["id"], start_timer.call_args.args[0])
|
||||||
|
reopen.assert_not_called()
|
||||||
|
self.assertNotIn(100, timer._auto_return_retries)
|
||||||
|
self.assertNotIn(100, timer._auto_return_backoff_until)
|
||||||
|
self.assertNotIn(100, timer._auto_return_first_fail_at)
|
||||||
|
|
||||||
|
def test_same_order_does_not_close_or_duplicate_it(self):
|
||||||
|
result, start_timer, reopen = self._check(upstream_order="ORDER-A", bike="BIKE-A")
|
||||||
|
self.assertTrue(result["active"])
|
||||||
|
conn = db.get_db()
|
||||||
|
rows = conn.execute("SELECT expired FROM rentals WHERE order_id='ORDER-A'").fetchall()
|
||||||
|
conn.close()
|
||||||
|
self.assertEqual(1, len(rows))
|
||||||
|
self.assertEqual(0, rows[0]["expired"])
|
||||||
|
start_timer.assert_not_called()
|
||||||
|
reopen.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -27,6 +27,7 @@ function bundleSource() {
|
|||||||
stdin: {
|
stdin: {
|
||||||
contents: [
|
contents: [
|
||||||
'export * from "./src-ts/order/actions";',
|
'export * from "./src-ts/order/actions";',
|
||||||
|
'export * from "./src-ts/order/status";',
|
||||||
'export { S } from "./src-ts/core/state";',
|
'export { S } from "./src-ts/core/state";',
|
||||||
].join('\n'),
|
].join('\n'),
|
||||||
resolveDir: ROOT,
|
resolveDir: ROOT,
|
||||||
@@ -52,7 +53,9 @@ const BASE_IDS = [
|
|||||||
'return-confirm-modal', 'return-confirm-text', 'return-confirm-btn',
|
'return-confirm-modal', 'return-confirm-text', 'return-confirm-btn',
|
||||||
'order-banner', 'order-banner-icon', 'order-banner-text', 'order-countdown', 'order-final-time',
|
'order-banner', 'order-banner-icon', 'order-banner-text', 'order-countdown', 'order-final-time',
|
||||||
'order-banner-add-round-btn', 'order-banner-detail-btn', 'order-banner-btn',
|
'order-banner-add-round-btn', 'order-banner-detail-btn', 'order-banner-btn',
|
||||||
'order-actions-status', 'order-action-lock', 'order-action-unlock',
|
'order-actions-modal', 'order-actions-meta', 'order-actions-status', 'order-actions-hint',
|
||||||
|
'order-action-lock', 'order-action-unlock', 'order-action-find',
|
||||||
|
'order-action-pay', 'order-action-return',
|
||||||
'login-gate', 'share-banners', 'settings-page',
|
'login-gate', 'share-banners', 'settings-page',
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -419,3 +422,42 @@ test('开锁坐标链:车坐标缺失→地图中心;三处都拿不到→
|
|||||||
assert.equal(hasPath(env2.requests, '/api/share/sources'), false, '拿不到坐标就不该进入开锁流程');
|
assert.equal(hasPath(env2.requests, '/api/share/sources'), false, '拿不到坐标就不该进入开锁流程');
|
||||||
assert.match(env2.el('toast').textContent, /拿不到车辆坐标/, '要明确告诉用户为什么开不了锁');
|
assert.match(env2.el('toast').textContent, /拿不到车辆坐标/, '要明确告诉用户为什么开不了锁');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('共享车主只保留还车按钮,不加轮、不寻车、不临时锁开、不支付,也无权限提示', () => {
|
||||||
|
const env = makeEnv();
|
||||||
|
const S = env.context.XB.S;
|
||||||
|
S.currentOrder = { order_id: 'SHARED-1', code: '51287', status: 2,
|
||||||
|
shared: { role: 'owner', partner: 'rider@example.test' } };
|
||||||
|
|
||||||
|
env.XB.showOrderActionsModal();
|
||||||
|
|
||||||
|
assert.equal(env.el('order-actions-modal').classList.contains('show'), true);
|
||||||
|
for (const id of ['order-action-lock', 'order-action-unlock', 'order-action-find', 'order-action-pay']) {
|
||||||
|
assert.equal(env.el(id).style.display, 'none', `${id} 对车主必须隐藏`);
|
||||||
|
}
|
||||||
|
assert.equal(env.el('order-action-return').style.display, 'flex', '车主保留还车');
|
||||||
|
assert.equal(env.el('order-actions-status').style.display, 'none', '车主不需要状态提示');
|
||||||
|
assert.equal(env.el('order-actions-hint').style.display, 'none', '车主不需要权限提示');
|
||||||
|
|
||||||
|
env.XB.addRoundFromBanner();
|
||||||
|
assert.equal(env.el('add-round-modal').classList.contains('show'), false, '车主不能打开加轮弹窗');
|
||||||
|
assert.match(env.el('toast').textContent, /车主只能还车/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('普通订单仍保留原有操作按钮,不被共享权限规则误伤', () => {
|
||||||
|
const env = makeEnv({ ids: [...BASE_IDS, 'add-round-modal', 'add-round-desc',
|
||||||
|
'add-round-confirm-btn', 'add-round-current-desc'] });
|
||||||
|
const S = env.context.XB.S;
|
||||||
|
S.currentOrder = { order_id: 'OWN-1', code: '51287', status: 2, shared: null };
|
||||||
|
|
||||||
|
env.XB.showOrderActionsModal();
|
||||||
|
|
||||||
|
for (const id of ['order-action-lock', 'order-action-unlock', 'order-action-find', 'order-action-return']) {
|
||||||
|
assert.equal(env.el(id).style.display, 'flex', `${id} 普通订单应保留`);
|
||||||
|
}
|
||||||
|
assert.notEqual(env.el('order-actions-status').style.display, 'none');
|
||||||
|
assert.notEqual(env.el('order-actions-hint').style.display, 'none');
|
||||||
|
|
||||||
|
env.XB.addRoundFromBanner();
|
||||||
|
assert.equal(env.el('add-round-modal').classList.contains('show'), true, '普通订单可以加轮');
|
||||||
|
});
|
||||||
|
|||||||
@@ -357,20 +357,24 @@ def _reopen_same_bike(user_id: int, bike_code: str) -> dict:
|
|||||||
return {"success": False, "message": bike_result.get("message", "获取车辆信息失败")}
|
return {"success": False, "message": bike_result.get("message", "获取车辆信息失败")}
|
||||||
|
|
||||||
bike_data = bike_result.get("data") or {}
|
bike_data = bike_result.get("data") or {}
|
||||||
# 续租是"用真实起点再开一单":拿不到实时坐标就不要开,绝不用假坐标下单
|
# 优先用实时位置开单;取不到原车位置时也不提前中止,按上游允许的方式
|
||||||
|
# 直接尝试下单开锁(不填起点坐标),确实失败再把原因明确告诉用户。
|
||||||
position = _live_bike_position(user_id, bike_code, first_payload=bike_data)
|
position = _live_bike_position(user_id, bike_code, first_payload=bike_data)
|
||||||
if not position:
|
order_data = {"code": bike_code}
|
||||||
return {"success": False,
|
if position:
|
||||||
"message": "拿不到车辆实时位置,已停止续租(避免用假坐标开单)"}
|
latitude, longitude = position
|
||||||
latitude, longitude = position
|
order_data.update({"start_longitude": longitude, "start_latitude": latitude})
|
||||||
|
else:
|
||||||
|
print(f"[续租] 未获取到 {bike_code} 的实时位置,仍直接尝试下单开锁")
|
||||||
order_result = request_with_user_auth(
|
order_result = request_with_user_auth(
|
||||||
user_id, "POST", "/record/order",
|
user_id, "POST", "/record/order", data=order_data
|
||||||
data={"code": bike_code, "start_longitude": longitude,
|
|
||||||
"start_latitude": latitude}
|
|
||||||
)
|
)
|
||||||
order_data = order_result.get("data") or {}
|
order_data = order_result.get("data") or {}
|
||||||
if order_result.get("rtn_code") != 0 or not order_data.get("order_id"):
|
if order_result.get("rtn_code") != 0 or not order_data.get("order_id"):
|
||||||
return {"success": False, "message": order_result.get("message", "创建下一轮订单失败")}
|
reason = order_result.get("message", "创建下一轮订单失败")
|
||||||
|
if not position:
|
||||||
|
reason += "(未获取到原车位置,已直接尝试下单)"
|
||||||
|
return {"success": False, "message": reason}
|
||||||
|
|
||||||
order_id = order_data["order_id"]
|
order_id = order_data["order_id"]
|
||||||
open_result = request_with_user_auth(
|
open_result = request_with_user_auth(
|
||||||
@@ -553,7 +557,7 @@ def _align_to_park_area(user_id: int, latitude, longitude):
|
|||||||
return latitude, longitude, False, 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 = False):
|
||||||
"""自动还车(含重试:最多3次),返回明确的成败结果。
|
"""自动还车(含重试:最多3次),返回明确的成败结果。
|
||||||
|
|
||||||
坐标链路(与手动还车同一套停车区规则):
|
坐标链路(与手动还车同一套停车区规则):
|
||||||
@@ -655,6 +659,9 @@ def _auto_return_bike(rental_id: int, user_id: int, allow_renewal: bool = True):
|
|||||||
if success:
|
if success:
|
||||||
_cancel_rental_timers(rental_id)
|
_cancel_rental_timers(rental_id)
|
||||||
mark_return_tokens_used(rental_id)
|
mark_return_tokens_used(rental_id)
|
||||||
|
if not allow_renewal:
|
||||||
|
# 邮件链接等手动还车:清掉后续自动重试状态,绝不能因为剩余轮次再开锁。
|
||||||
|
_clear_auto_return_state(rental_id)
|
||||||
try:
|
try:
|
||||||
renewal_result = _maybe_renew_after_return(
|
renewal_result = _maybe_renew_after_return(
|
||||||
dict(rental), user_id, pay_result, allow_renewal
|
dict(rental), user_id, pay_result, allow_renewal
|
||||||
@@ -683,8 +690,9 @@ 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):
|
def auto_return_bike(rental_id: int, user_id: int, allow_renewal: bool = False):
|
||||||
"""串行执行还车,避免定时器和手动入口同时触发重复续租。"""
|
"""串行执行还车。默认按用户手动还车处理,不续租;
|
||||||
|
只有 0 点定时器与过期巡检显式传 allow_renewal=True 才允许进入下一轮。"""
|
||||||
with _renewal_lock(rental_id):
|
with _renewal_lock(rental_id):
|
||||||
return _auto_return_bike(rental_id, user_id, allow_renewal)
|
return _auto_return_bike(rental_id, user_id, allow_renewal)
|
||||||
|
|
||||||
@@ -854,7 +862,7 @@ def _run_recovery_locked(rental_id: int, user_id: int, order_id=None):
|
|||||||
return {"success": True, "skipped": True,
|
return {"success": True, "skipped": True,
|
||||||
"message": "上游订单已结束,仅做本地收尾"}
|
"message": "上游订单已结束,仅做本地收尾"}
|
||||||
try:
|
try:
|
||||||
result = auto_return_bike(rental_id, user_id) or {}
|
result = auto_return_bike(rental_id, user_id, allow_renewal=True) or {}
|
||||||
if result.get("success"):
|
if result.get("success"):
|
||||||
_clear_auto_return_state(rental_id)
|
_clear_auto_return_state(rental_id)
|
||||||
elif not result.get("skipped"):
|
elif not result.get("skipped"):
|
||||||
@@ -1281,7 +1289,7 @@ def _schedule_reminder(rental_id: int, delay_seconds: int, reminder_type: str,
|
|||||||
return
|
return
|
||||||
if auto_return_enabled and user_id:
|
if auto_return_enabled and user_id:
|
||||||
try:
|
try:
|
||||||
return_result = auto_return_bike(rental_id, user_id)
|
return_result = auto_return_bike(rental_id, user_id, allow_renewal=True)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"[自动还车] 失败: {e}")
|
print(f"[自动还车] 失败: {e}")
|
||||||
return_result = {"attempted": True, "success": False, "message": str(e)}
|
return_result = {"attempted": True, "success": False, "message": str(e)}
|
||||||
@@ -1573,6 +1581,14 @@ def _check_user_order(user_id: int):
|
|||||||
|
|
||||||
order_id = str(non_deal.get("order_id"))
|
order_id = str(non_deal.get("order_id"))
|
||||||
order_status = non_deal.get("status") # 1=未支付, 2=进行中
|
order_status = non_deal.get("status") # 1=未支付, 2=进行中
|
||||||
|
if str(order_status) == "2":
|
||||||
|
# 用户可能先在官方小程序还了 A,又在同步间隙从官方小程序开了 B。
|
||||||
|
# 上游只保留当前进行中的 B:其它本地活跃单必须按「A 已在小程序还车」
|
||||||
|
# 收尾,绝不能留两条骑行计时,也不能因为 A 的剩余轮次再自动开锁。
|
||||||
|
_finish_active_wechat_rentals(
|
||||||
|
user_id, f"上游已切换到订单 {order_id},其它订单已在小程序结束",
|
||||||
|
keep_order_id=order_id,
|
||||||
|
)
|
||||||
if str(order_status) != "2":
|
if str(order_status) != "2":
|
||||||
# 微信端还车后,nonDealOrder 可能仍保留但状态变为 1(待支付)。
|
# 微信端还车后,nonDealOrder 可能仍保留但状态变为 1(待支付)。
|
||||||
# 订单横幅仍由 /api/order/status 展示,但本地骑行计时和邮件必须立即停止。
|
# 订单横幅仍由 /api/order/status 展示,但本地骑行计时和邮件必须立即停止。
|
||||||
@@ -1785,12 +1801,14 @@ def _fill_missing_start(rental_id: int, bike_code: str, start_str: str):
|
|||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
def _finish_active_wechat_rentals(user_id: int, reason: str):
|
def _finish_active_wechat_rentals(user_id: int, reason: str, keep_order_id=None):
|
||||||
"""微信已确认没有进行中骑行时,结束本地镜像记录并取消邮件计时器。
|
"""结束本地镜像记录并取消邮件计时器。
|
||||||
|
|
||||||
只处理由微信订单产生的 unlock/sync/shared 记录,不影响用户
|
只处理由微信订单产生的 unlock/sync/shared/subscribe 记录,不影响用户
|
||||||
单独创建的 reminder 计时。该函数只能在上游请求成功后调用,
|
单独创建的 reminder 计时。该函数只能在上游请求成功后调用,
|
||||||
避免把网络或凭据故障误判为已还车。
|
避免把网络或凭据故障误判为已还车。
|
||||||
|
keep_order_id 用于「A 已在小程序还车、马上又开了 B」:保留当前上游 B,
|
||||||
|
只收尾其它本地活跃单;没有订单号的记录无法确认身份,不会误关。
|
||||||
"""
|
"""
|
||||||
conn = get_db()
|
conn = get_db()
|
||||||
cursor = conn.cursor()
|
cursor = conn.cursor()
|
||||||
@@ -1803,6 +1821,10 @@ def _finish_active_wechat_rentals(user_id: int, reason: str):
|
|||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
for row in active_rows:
|
for row in active_rows:
|
||||||
|
if keep_order_id is not None:
|
||||||
|
# 无订单号的记录无法判断是否就是 B,保守跳过,避免误关真实骑行。
|
||||||
|
if not row["order_id"] or str(row["order_id"]) == str(keep_order_id):
|
||||||
|
continue
|
||||||
# 微信端自行还车:上游只告诉我们"订单没了",没有坐标;
|
# 微信端自行还车:上游只告诉我们"订单没了",没有坐标;
|
||||||
# 用这辆车最新的采集点当作终点,避免后台显示「终点未知」
|
# 用这辆车最新的采集点当作终点,避免后台显示「终点未知」
|
||||||
pos = _bike_pos_from_history(row["bike_code"])
|
pos = _bike_pos_from_history(row["bike_code"])
|
||||||
@@ -1811,6 +1833,9 @@ def _finish_active_wechat_rentals(user_id: int, reason: str):
|
|||||||
else:
|
else:
|
||||||
_mark_returned(row["id"])
|
_mark_returned(row["id"])
|
||||||
_cancel_rental_timers(row["id"])
|
_cancel_rental_timers(row["id"])
|
||||||
|
# 官方小程序手动还车:这里只做本地收尾,清掉后续自动还车/续租状态,
|
||||||
|
# 即使本轮之后还有剩余轮次,也不能再把车开起来。
|
||||||
|
_clear_auto_return_state(row["id"])
|
||||||
print(f"[订单检测] 结束本地骑行记录: rental_id={row['id']}, "
|
print(f"[订单检测] 结束本地骑行记录: rental_id={row['id']}, "
|
||||||
f"order_id={row['order_id']}, source={row['source']}, reason={reason}")
|
f"order_id={row['order_id']}, source={row['source']}, reason={reason}")
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user