fix: 补全普通和共享订单横幅的时间轮次信息并适配窄屏

This commit is contained in:
zzy
2026-11-03 09:51:28 +08:00
parent d4adad620d
commit f986c8deae
8 changed files with 135 additions and 17 deletions
+2
View File
@@ -592,6 +592,7 @@ def share_active():
return jsonify({"rtn_code": 401, "message": "请先登录"}) return jsonify({"rtn_code": 401, "message": "请先登录"})
me = user["id"] me = user["id"]
from timer import _get_remaining_seconds from timer import _get_remaining_seconds
from routes.rental import _rounds_summary
now_bj = _beijing_now().strftime("%Y-%m-%d %H:%M:%S") now_bj = _beijing_now().strftime("%Y-%m-%d %H:%M:%S")
conn = get_db() conn = get_db()
cur = conn.cursor() cur = conn.cursor()
@@ -649,6 +650,7 @@ def share_active():
"remark": remark, "remark": remark,
"remaining_seconds": remain, "remaining_seconds": remain,
"end_time": r["end_time"], "end_time": r["end_time"],
**_rounds_summary(r, r.get("rider_user_id") or r["user_id"]),
}) })
return jsonify({"rtn_code": 0, "data": result}) return jsonify({"rtn_code": 0, "data": result})
+19
View File
@@ -1,4 +1,23 @@
#baidu_map canvas { filter: var(--basemap-filter, none); } #baidu_map canvas { filter: var(--basemap-filter, none); }
.order-banner-copy, .share-banner-copy { flex: 1; min-width: 0; }
#order-banner .order-banner-left { align-items: flex-start; overflow: visible; }
#order-banner #order-banner-text { display: block; }
#order-banner .banner-progress, .share-banner .banner-progress {
display: flex; flex-wrap: wrap; gap: 2px 10px; margin-top: 4px;
font-size: 12px; line-height: 1.55; opacity: .92; white-space: normal;
}
#order-banner #order-final-time, #order-banner #order-countdown {
white-space: normal; overflow: visible; text-overflow: clip;
}
#order-banner .order-banner-right { gap: 6px; margin-left: 10px; }
#order-banner .order-banner-btn { margin-right: 0 !important; }
.share-banner { gap: 10px; }
.share-banner-title { display: flex; flex-wrap: wrap; align-items: center; }
.share-banner .banner-progress > span { display: block; }
@media (max-width: 640px) {
#order-banner-detail-btn { display: none; }
#order-banner .banner-progress { flex-direction: column; gap: 0; }
}
.settings-page[hidden], .settings-view[hidden], #settings-page-home[hidden] { display: none !important; } .settings-page[hidden], .settings-view[hidden], #settings-page-home[hidden] { display: none !important; }
.settings-page { .settings-page {
position: fixed; inset: 0; z-index: 3500; display: flex; flex-direction: column; position: fixed; inset: 0; z-index: 3500; display: flex; flex-direction: column;
+1 -1
View File
@@ -2085,7 +2085,7 @@
.order-banner-right, .rental-bar > div:last-child { flex: 0 0 auto; white-space: nowrap; } .order-banner-right, .rental-bar > div:last-child { flex: 0 0 auto; white-space: nowrap; }
.order-banner-btn, .rental-bar-btn { white-space: nowrap; flex: 0 0 auto; } .order-banner-btn, .rental-bar-btn { white-space: nowrap; flex: 0 0 auto; }
#order-final-time, #order-countdown, #rental-final-time, #rental-time, #rental-bike-code, .rental-bar-info { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } #order-final-time, #order-countdown, #rental-final-time, #rental-time, #rental-bike-code, .rental-bar-info { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
@media (max-width: 430px) { #order-final-time { display: none !important; } .order-banner { padding: 9px 10px !important; font-size: 13px !important; } .order-banner-btn, .rental-bar-btn { padding: 5px 9px !important; font-size: 12px !important; } } @media (max-width: 430px) { .order-banner { padding: 9px 10px !important; font-size: 13px !important; } .order-banner-btn, .rental-bar-btn { padding: 5px 9px !important; font-size: 12px !important; } }
.order-banner.show { .order-banner.show {
display: flex; display: flex;
} }
+53 -11
View File
@@ -1740,6 +1740,9 @@
text.textContent = `待支付订单 #${order.code || order.order_id.slice(-6)}`; text.textContent = `待支付订单 #${order.code || order.order_id.slice(-6)}`;
btn.textContent = "去支付"; btn.textContent = "去支付";
hideOrderCountdown(); hideOrderCountdown();
const progress = document.getElementById("order-final-time");
progress.textContent = "待支付 · 骑行已结束";
progress.style.display = "inline";
} else if (Number(order.status) === 2) { } else if (Number(order.status) === 2) {
// 进行中 - 获取倒计时 // 进行中 - 获取倒计时
banner.classList.add("riding"); banner.classList.add("riding");
@@ -1751,6 +1754,12 @@
text.textContent = `进行中 #${order.code || order.order_id.slice(-6)}`; text.textContent = `进行中 #${order.code || order.order_id.slice(-6)}`;
} }
btn.textContent = "还车"; btn.textContent = "还车";
if (String(orderCountdownOrderId) !== String(order.order_id)) {
hideOrderCountdown();
const progress = document.getElementById("order-final-time");
progress.textContent = "骑行中 · 正在同步计时";
progress.style.display = "inline";
}
// 从后端获取剩余时间并启动倒计时 // 从后端获取剩余时间并启动倒计时
fetchOrderCountdown(order.order_id); fetchOrderCountdown(order.order_id);
} }
@@ -1760,6 +1769,21 @@
let orderCountdownTimer = null; let orderCountdownTimer = null;
let orderCountdownSeconds = 0; let orderCountdownSeconds = 0;
let orderCountdownDeadline = null;
let orderCountdownOrderId = null;
function rideProgressText(summary) {
const current = Math.max(1, Number(summary.current_round) || 1);
const total = Math.max(current, Number(summary.total_rounds) || current);
const end = String(summary.final_end_time || summary.end_time || "").match(/(?:T|\s)(\d{2}:\d{2})/);
const phase = summary.auto_return ? "自动还车已开启" : "手动还车";
return `第 ${current}/${total} 轮 · ${phase}` + (end ? ` · 预计 ${end[1]} 结束` : "");
}
function remainingTimeText(seconds) {
const remaining = Math.max(0, Math.ceil(Number(seconds) || 0));
return `${Math.floor(remaining / 60)}:${String(remaining % 60).padStart(2, "0")}`;
}
function fetchOrderCountdown(orderId) { function fetchOrderCountdown(orderId) {
if (!authToken || !orderId) return; if (!authToken || !orderId) return;
@@ -1769,19 +1793,17 @@
}) })
.then(r => r.json()) .then(r => r.json())
.then(data => { .then(data => {
if (!currentOrder || String(currentOrder.order_id) !== String(orderId) || Number(currentOrder.status) !== 2) return;
if (data.rtn_code === 0 && data.data && data.data.active) { if (data.rtn_code === 0 && data.data && data.data.active) {
orderCountdownSeconds = data.data.remaining_seconds; orderCountdownSeconds = Math.max(0, Number(data.data.remaining_seconds) || 0);
orderCountdownDeadline = performance.now() + orderCountdownSeconds * 1000;
orderCountdownOrderId = orderId;
// 多轮适配:展示计划总轮数与最终预计还车时间 // 多轮适配:展示计划总轮数与最终预计还车时间
const finalEl = document.getElementById("order-final-time"); const finalEl = document.getElementById("order-final-time");
const addBtn = document.getElementById("order-banner-add-round-btn"); const addBtn = document.getElementById("order-banner-add-round-btn");
if (finalEl) { if (finalEl) {
if (data.data.final_end_time && data.data.total_rounds > data.data.current_round) { finalEl.textContent = rideProgressText(data.data);
const hhmm = String(data.data.final_end_time).slice(11, 16);
finalEl.textContent = `共${data.data.total_rounds}轮 · 预计${hhmm}还车`;
finalEl.style.display = "inline"; finalEl.style.display = "inline";
} else {
finalEl.style.display = "none";
}
} }
if (addBtn) { if (addBtn) {
// 真实订单才可加轮; reminder 计时不显示 // 真实订单才可加轮; reminder 计时不显示
@@ -1790,6 +1812,11 @@
} }
showOrderCountdown(); showOrderCountdown();
startOrderCountdown(); startOrderCountdown();
} else if (data.rtn_code === 0) {
hideOrderCountdown();
const progress = document.getElementById("order-final-time");
progress.textContent = "骑行中 · 计时同步中";
progress.style.display = "inline";
} }
}) })
.catch(err => console.error("获取倒计时失败:", err)); .catch(err => console.error("获取倒计时失败:", err));
@@ -1802,6 +1829,10 @@
} }
function hideOrderCountdown() { function hideOrderCountdown() {
orderCountdownDeadline = null;
orderCountdownOrderId = null;
document.getElementById("order-banner-add-round-btn").style.display = "none";
document.getElementById("order-final-time").style.display = "none";
const el = document.getElementById("order-countdown"); const el = document.getElementById("order-countdown");
el.style.display = "none"; el.style.display = "none";
if (orderCountdownTimer) { if (orderCountdownTimer) {
@@ -1815,7 +1846,7 @@
const remaining = Math.max(0, orderCountdownSeconds); const remaining = Math.max(0, orderCountdownSeconds);
const mins = Math.floor(remaining / 60); const mins = Math.floor(remaining / 60);
const secs = remaining % 60; const secs = remaining % 60;
el.textContent = `${mins}:${secs.toString().padStart(2, "0")}`; el.textContent = remaining > 0 ? `本轮剩余 ${mins}:${secs.toString().padStart(2, "0")}` : "本轮到期 · 同步状态中";
// 变色提示 // 变色提示
if (remaining <= 60) { if (remaining <= 60) {
@@ -1830,7 +1861,7 @@
function startOrderCountdown() { function startOrderCountdown() {
if (orderCountdownTimer) clearInterval(orderCountdownTimer); if (orderCountdownTimer) clearInterval(orderCountdownTimer);
orderCountdownTimer = setInterval(() => { orderCountdownTimer = setInterval(() => {
orderCountdownSeconds--; orderCountdownSeconds = Math.max(0, Math.ceil((orderCountdownDeadline - performance.now()) / 1000));
updateOrderCountdownText(); updateOrderCountdownText();
if (orderCountdownSeconds <= 0) { if (orderCountdownSeconds <= 0) {
clearInterval(orderCountdownTimer); clearInterval(orderCountdownTimer);
@@ -5218,9 +5249,9 @@
const data = await shareApi("/api/share/active"); const data = await shareApi("/api/share/active");
if (data.rtn_code !== 0) return; if (data.rtn_code !== 0) return;
shareActiveList = data.data || []; shareActiveList = data.data || [];
shareActiveList.forEach(it => { it._countdownDeadline = performance.now() + Math.max(0, Number(it.remaining_seconds) || 0) * 1000; });
let html = ""; let html = "";
shareActiveList.forEach((it, idx) => { shareActiveList.forEach((it, idx) => {
const mins = Math.max(1, Math.ceil((it.remaining_seconds || 0) / 60));
const isOwner = it.role === "owner"; const isOwner = it.role === "owner";
const label = partnerLabel(it.partner_name, it.partner_email, it.remark); const label = partnerLabel(it.partner_name, it.partner_email, it.remark);
const esc = escHtml(label); const esc = escHtml(label);
@@ -5232,7 +5263,9 @@
text = '<span>使用 ' + esc + ' 的车中</span><b style="margin:0 4px;">#' + bike + '</b>'; text = '<span>使用 ' + esc + ' 的车中</span><b style="margin:0 4px;">#' + bike + '</b>';
} }
html += '<div class="share-banner show ' + (isOwner ? "" : "rider") + '">' html += '<div class="share-banner show ' + (isOwner ? "" : "rider") + '">'
+ '<div style="display:flex;align-items:center;gap:4px;min-width:0;overflow:hidden;white-space:nowrap;">' + text + '<span style="opacity:.8;font-size:12px;margin-left:6px;">剩' + mins + '分</span></div>' + '<div class="share-banner-copy"><div class="share-banner-title">' + text + '</div>'
+ '<div class="banner-progress"><span id="share-countdown-' + idx + '">本轮剩余 ' + remainingTimeText(it.remaining_seconds) + '</span>'
+ '<span>' + escHtml(rideProgressText(it)) + '</span></div></div>'
+ '<button class="share-banner-btn" onclick="openShareReturnByIdx(' + idx + ')">还车</button>' + '<button class="share-banner-btn" onclick="openShareReturnByIdx(' + idx + ')">还车</button>'
+ '</div>'; + '</div>';
}); });
@@ -5253,6 +5286,15 @@
: ('你正在使用 <b>' + esc + '</b> 的车 <b>#' + bike + '</b>,确认还车?'); : ('你正在使用 <b>' + esc + '</b> 的车 <b>#' + bike + '</b>,确认还车?');
document.getElementById("share-return-modal").classList.add("show"); document.getElementById("share-return-modal").classList.add("show");
} }
function updateShareCountdowns() {
shareActiveList.forEach((it, idx) => {
const el = document.getElementById('share-countdown-' + idx);
if (!el) return;
const seconds = Math.max(0, Math.ceil((it._countdownDeadline - performance.now()) / 1000));
el.textContent = seconds > 0 ? '本轮剩余 ' + remainingTimeText(seconds) : '本轮到期 · 同步状态中';
});
}
setInterval(updateShareCountdowns, 1000);
// HTML 的 ✕ / 取消 / 遮罩都调用它(此前漏了定义 → 点击直接 ReferenceError,弹窗关不掉) // HTML 的 ✕ / 取消 / 遮罩都调用它(此前漏了定义 → 点击直接 ReferenceError,弹窗关不掉)
function closeShareReturnModal() { function closeShareReturnModal() {
const modal = document.getElementById("share-return-modal"); const modal = document.getElementById("share-return-modal");
+6 -2
View File
@@ -57,11 +57,15 @@
<div class="order-banner" id="order-banner" onclick="handleOrderBannerSurfaceClick(event)"> <div class="order-banner" id="order-banner" onclick="handleOrderBannerSurfaceClick(event)">
<div class="order-banner-left"> <div class="order-banner-left">
<span id="order-banner-icon">⏳</span> <span id="order-banner-icon">⏳</span>
<div class="order-banner-copy">
<span id="order-banner-text">检测中...</span> <span id="order-banner-text">检测中...</span>
<div class="banner-progress" aria-live="off">
<span id="order-countdown" style="display:none"></span>
<span id="order-final-time" style="display:none"></span>
</div>
</div>
</div> </div>
<div class="order-banner-right"> <div class="order-banner-right">
<span id="order-final-time" style="display:none;font-size:12px;opacity:.85;margin-right:8px;"></span>
<span id="order-countdown" style="display:none;font-weight:bold;margin-right:8px;"></span>
<button class="order-banner-btn" id="order-banner-add-round-btn" onclick="event.stopPropagation(); addRoundFromBanner()" style="display:none;margin-right:8px;">+1轮</button> <button class="order-banner-btn" id="order-banner-add-round-btn" onclick="event.stopPropagation(); addRoundFromBanner()" style="display:none;margin-right:8px;">+1轮</button>
<button class="order-banner-btn" id="order-banner-detail-btn" onclick="viewBikeDetailFromOrder()" style="margin-right:8px;">查看详情</button> <button class="order-banner-btn" id="order-banner-detail-btn" onclick="viewBikeDetailFromOrder()" style="margin-right:8px;">查看详情</button>
<button class="order-banner-btn" id="order-banner-btn" onclick="handleOrderBannerClick()">处理</button> <button class="order-banner-btn" id="order-banner-btn" onclick="handleOrderBannerClick()">处理</button>
+36
View File
@@ -126,3 +126,39 @@ test('async SDK initialization waits for the Map constructor and runs only once'
e.context.initMap(); e.context.initMap();
assert.equal(initialized, 1); assert.equal(initialized, 1);
}); });
test('single and multiple rounds show progress and end time without promising automatic return when disabled', async () => {
const e = await environment();
assert.equal(e.context.rideProgressText({ current_round: 2, total_rounds: 3, auto_return: true, final_end_time: '2026-11-03 12:30:00' }),
'第 2/3 轮 · 自动还车已开启 · 预计 12:30 结束');
assert.equal(e.context.rideProgressText({ current_round: 1, total_rounds: 1, auto_return: false, end_time: '2026-11-03T12:10:00' }),
'第 1/1 轮 · 手动还车 · 预计 12:10 结束');
});
test('delayed countdown response cannot overwrite a newer pending-payment banner', async () => {
const e = await environment();
let respond;
e.context.fetch = () => new Promise(resolve => { respond = resolve; });
e.setOrder({ order_id: '9001', status: 2 });
e.context.fetchOrderCountdown('9001');
e.setOrder({ order_id: '9001', status: 1 });
respond({ json: async () => ({ rtn_code: 0, data: { active: true, remaining_seconds: 600 } }) });
await new Promise(resolve => setImmediate(resolve));
assert.equal(e.element('order-final-time').textContent, '');
});
test('countdown accounts for background throttling instead of decrementing only one second per callback', async () => {
const e = await environment();
let now = 0, tick;
e.context.performance.now = () => now;
e.context.setInterval = callback => { tick = callback; return 1; };
e.context.fetch = async () => ({ json: async () => ({ rtn_code: 0, data: {
active: true, order_id: '9001', remaining_seconds: 600, current_round: 1, total_rounds: 1, auto_return: false
} }) });
e.setOrder({ order_id: '9001', status: 2 });
e.context.fetchOrderCountdown('9001');
await new Promise(resolve => setImmediate(resolve));
now = 5000; tick();
assert.equal(e.element('order-countdown').textContent, '本轮剩余 9:55');
assert.match(e.element('order-final-time').textContent, /第 1\/1 轮/);
});
+2 -1
View File
@@ -270,7 +270,8 @@ class OrderSyncTests(unittest.TestCase):
def test_only_five_three_and_zero_minute_reminders_are_scheduled(self): def test_only_five_three_and_zero_minute_reminders_are_scheduled(self):
settings = {"reminder_enabled": True, "reminder_minutes": [5, 3, 0], settings = {"reminder_enabled": True, "reminder_minutes": [5, 3, 0],
"rental_duration_minutes": 19, "auto_return_enabled": True} "rental_duration_minutes": 19, "auto_return_enabled": True}
with patch.object(timer, "_cancel_rental_timers"), \ with patch.object(timer, "get_db", self._get_db), \
patch.object(timer, "_cancel_rental_timers"), \
patch.object(timer, "get_user_rental_settings", return_value=settings), \ patch.object(timer, "get_user_rental_settings", return_value=settings), \
patch.object(timer, "_schedule_reminder") as schedule: patch.object(timer, "_schedule_reminder") as schedule:
timer.start_rental_timer(101, "rider@example.test", "50001", 19, 7) timer.start_rental_timer(101, "rider@example.test", "50001", 19, 7)
+14
View File
@@ -12,6 +12,16 @@ from routes import rental
class SharedReturnTests(unittest.TestCase): class SharedReturnTests(unittest.TestCase):
def setUp(self): def setUp(self):
policy = patch.object(rental, "get_user_rental_settings", return_value={
"rental_duration_minutes": 19, "auto_return_enabled": True, "rental_rounds": 3})
policy.start()
self.addCleanup(policy.stop)
credentials = patch.object(rental, "get_user_auth", return_value=("fixture-token", "fixture-access"))
credentials.start()
self.addCleanup(credentials.stop)
email = patch("rental_mail.send_share_returned_email")
email.start()
self.addCleanup(email.stop)
handle = tempfile.NamedTemporaryFile(suffix=".db", delete=False) handle = tempfile.NamedTemporaryFile(suffix=".db", delete=False)
handle.close() handle.close()
self.db_path = Path(handle.name) self.db_path = Path(handle.name)
@@ -175,6 +185,10 @@ class SharedReturnTests(unittest.TestCase):
self.assertEqual(0, data["rtn_code"]) self.assertEqual(0, data["rtn_code"])
self.assertEqual(1, len(data["data"])) self.assertEqual(1, len(data["data"]))
self.assertEqual("9001", data["data"][0]["order_id"]) self.assertEqual("9001", data["data"][0]["order_id"])
self.assertEqual(1, data["data"][0]["current_round"])
self.assertEqual(3, data["data"][0]["total_rounds"])
self.assertTrue(data["data"][0]["auto_return"])
self.assertIn("final_end_time", data["data"][0])
def test_owner_order_status_reliably_marks_shared_order(self): def test_owner_order_status_reliably_marks_shared_order(self):
app = Flask(__name__) app = Flask(__name__)