Skip to content

Commit c101566

Browse files
committed
fix(trading): show recoverable ownership snapshot errors on mobile
Signed-off-by: TIANHE <[email protected]>
1 parent ad0e066 commit c101566

3 files changed

Lines changed: 82 additions & 8 deletions

File tree

‎src/api/index.js‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -392,12 +392,10 @@ export const strategyApi = {
392392
},
393393
getPositionOwnership: async (id) => {
394394
const res = await http.get('/api/strategies/position-ownership', {
395-
params: { id }
395+
params: { id },
396+
suppressErrorToast: true
396397
})
397-
return {
398-
...res,
399-
data: res.data || { items: [], status: 'ok' }
400-
}
398+
return res
401399
},
402400
getGridRestingOrders: async (id, sync = false) => {
403401
const res = await http.get('/api/strategies/grid-resting-orders', {

‎src/views/trading/StrategyDetail.vue‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,7 @@
112112
<van-action-sheet v-model:show="showReviewHistory" :actions="reviewHistoryActions" :cancel-text="$t('common.cancel')" @select="selectReview" />
113113
<van-popup v-model:show="showOwnershipRepair" position="bottom" round teleport="body" class="ownership-sheet">
114114
<div class="sheet-head"><div><strong>{{ $t('trading.position_ownership_title') }}</strong><small>{{ $t('trading.position_ownership_risk_title') }}</small></div><button type="button" :aria-label="$t('common.close')" @click="showOwnershipRepair = false"><van-icon name="cross" /></button></div><div class="sheet-warning"><van-icon name="warning-o" /><span>{{ $t('trading.position_ownership_risk_desc') }}</span></div><van-loading v-if="ownershipLoading" class="section-loading" vertical>{{ $t('common.loading') }}</van-loading>
115+
<van-empty v-else-if="ownershipFailed" :description="$t('trading.position_ownership_load_failed')"><van-button type="primary" @click="loadOwnership()">{{ $t('common.retry') }}</van-button></van-empty>
115116
<div v-else-if="ownershipRows.length" class="record-list"><article v-for="row in ownershipRows" :key="`${row.symbol}:${row.side}`" class="ownership-card"><div class="record-head"><div><strong>{{ row.symbol }}</strong><small>{{ sideText(row.side) }}</small></div><em :class="{ danger: row.status === 'drift_blocked' }">{{ $t(row.status === 'drift_blocked' ? 'trading.position_ownership_blocked' : 'trading.position_ownership_normal') }}</em></div><dl><div><dt>{{ $t('trading.position_ownership_account') }}</dt><dd>{{ ownershipQty(row.account_qty) }}</dd></div><div><dt>{{ $t('trading.position_ownership_strategy') }}</dt><dd>{{ ownershipQty(row.strategy_qty) }}</dd></div><div><dt>{{ $t('trading.position_ownership_protected') }}</dt><dd>{{ ownershipQty(row.protected_qty) }}</dd></div><div><dt>{{ $t('trading.position_ownership_unknown') }}</dt><dd :class="{ loss: ownershipHasUnknown(row) }">{{ ownershipQty(row.unknown_qty) }}</dd></div></dl><div class="ownership-actions"><van-button v-if="ownership.advanced_coexistence_available && (row.coexistence_mode !== 'advanced' || ownershipHasUnknown(row))" size="small" type="warning" plain :loading="ownershipRepairKey === `${row.symbol}:${row.side}:protect_manual`" @click="repairOwnership(row, 'protect_manual')">{{ $t('trading.position_ownership_protect') }}</van-button><van-button v-else-if="row.coexistence_mode === 'advanced'" size="small" plain :loading="ownershipRepairKey === `${row.symbol}:${row.side}:strict_mode`" @click="repairOwnership(row, 'strict_mode')">{{ $t('trading.position_ownership_use_strict') }}</van-button><van-button size="small" type="primary" plain :loading="ownershipRepairKey === `${row.symbol}:${row.side}:recheck`" @click="repairOwnership(row, 'recheck')">{{ $t('trading.position_ownership_recheck') }}</van-button></div></article></div><van-empty v-else :description="$t('trading.no_positions')" />
116117
</van-popup>
117118
</div>
@@ -129,7 +130,7 @@ const EXIT_TYPES = ['close_long', 'close_short', 'reduce_long', 'reduce_short',
129130
130131
export default {
131132
name: 'StrategyDetail',
132-
data() { return { strategy: null, positions: [], trades: [], tradePage: 1, logs: [], logFilter: 'all', logPage: 1, pageSize: 10, equityCurve: [], performance: {}, costSummary: {}, aiDecisions: [], gridOrders: [], gridOrderSummary: {}, ownership: { items: [], status: 'ok', advanced_coexistence_available: false }, review: null, reviewHistory: [], selectedReviewId: null, activeTab: 'overview', loading: false, detailFailed: false, exposureReady: false, actionLoading: false, ownershipLoading: false, gridOrdersLoading: false, gridOrdersFailed: false, gridOrdersTimer: null, gridOrdersRequestId: 0, ownershipRepairKey: '', reviewLoading: false, reviewHistoryLoaded: false, showReviewHistory: false, showOwnershipRepair: false, stopCommandTrackers: new Set(), componentActive: true } },
133+
data() { return { strategy: null, positions: [], trades: [], tradePage: 1, logs: [], logFilter: 'all', logPage: 1, pageSize: 10, equityCurve: [], performance: {}, costSummary: {}, aiDecisions: [], gridOrders: [], gridOrderSummary: {}, ownership: { items: [], status: 'ok', advanced_coexistence_available: false }, review: null, reviewHistory: [], selectedReviewId: null, activeTab: 'overview', loading: false, detailFailed: false, exposureReady: false, actionLoading: false, ownershipLoading: false, ownershipFailed: false, gridOrdersLoading: false, gridOrdersFailed: false, gridOrdersTimer: null, gridOrdersRequestId: 0, ownershipRepairKey: '', reviewLoading: false, reviewHistoryLoaded: false, showReviewHistory: false, showOwnershipRepair: false, stopCommandTrackers: new Set(), componentActive: true } },
133134
computed: {
134135
gridAuditWarning() {
135136
if (this.gridOrderSummary.sync_error === 'grid_exchange_reconciliation_pending') return this.$t('gridAudit.reconciliationHint')
@@ -204,7 +205,22 @@ export default {
204205
beforeUnmount() { this.componentActive = false; this.stopGridOrderPolling(); document.removeEventListener('visibilitychange', this.syncGridOrderPolling); this.stopCommandTrackers.clear() },
205206
methods: {
206207
async load() { if (this.loading) return; this.loading = true; this.exposureReady = false; this.detailFailed = false; try { const [detail, positions, ledger, logs, performance, curve, decisions] = await Promise.allSettled([strategyApi.getDetail(this.strategyId), strategyApi.getPositions(this.strategyId), strategyApi.getTradeLedger(this.strategyId, 100, { group_by: 'order' }), strategyApi.getLogs(this.strategyId, 1000), strategyApi.getPerformance(this.strategyId), strategyApi.getEquityCurve(this.strategyId), strategyApi.getAiDecisions(this.strategyId)]); this.exposureReady = detail.status === 'fulfilled' && positions.status === 'fulfilled'; this.detailFailed = [detail, positions, ledger, logs, performance, curve].some(result => result.status === 'rejected'); if (detail.status === 'fulfilled') this.strategy = detail.value.data; this.positions = positions.status === 'fulfilled' ? positions.value.data || [] : []; const ledgerData = ledger.status === 'fulfilled' ? ledger.value.data || {} : {}; this.trades = ledgerData.items || []; this.tradePage = Math.min(this.tradePage, Math.max(1, Math.ceil(this.trades.length / this.pageSize))); this.costSummary = ledgerData.cost_summary || {}; this.logs = logs.status === 'fulfilled' ? logs.value.data || [] : []; this.logPage = Math.min(this.logPage, Math.max(1, Math.ceil(this.filteredLogs.length / this.pageSize))); this.performance = performance.status === 'fulfilled' ? performance.value.data || {} : {}; this.equityCurve = curve.status === 'fulfilled' ? curve.value.data || [] : []; this.aiDecisions = decisions.status === 'fulfilled' ? decisions.value.data || [] : []; if (this.isLiveStrategy) await this.loadOwnership(false); else this.ownership = { items: [], status: 'ok', advanced_coexistence_available: false }; if (this.isGridStrategy) await this.loadGridOrders(false); else { this.gridOrders = []; this.gridOrderSummary = {} } } finally { this.loading = false } },
207-
async loadOwnership(showFailure = true) { this.ownershipLoading = true; try { const response = await strategyApi.getPositionOwnership(this.strategyId); this.ownership = response?.data || { items: [], status: 'ok', advanced_coexistence_available: false } } catch { if (showFailure) showToast({ message: this.$t('trading.position_ownership_load_failed'), type: 'fail' }) } finally { this.ownershipLoading = false } },
208+
async loadOwnership(showFailure = true) {
209+
if (this.ownershipLoading) return
210+
this.ownershipLoading = true
211+
this.ownershipFailed = false
212+
try {
213+
const response = await strategyApi.getPositionOwnership(this.strategyId)
214+
if (!Array.isArray(response?.data?.items)) throw new Error('invalid_ownership_snapshot')
215+
this.ownership = response.data
216+
} catch {
217+
this.ownershipFailed = true
218+
this.ownership = { items: [], status: 'unavailable', advanced_coexistence_available: false }
219+
if (showFailure) showToast({ message: this.$t('trading.position_ownership_load_failed'), type: 'fail' })
220+
} finally {
221+
this.ownershipLoading = false
222+
}
223+
},
208224
canPollGridOrders() { return this.componentActive && this.isGridStrategy && this.activeTab === 'grid-orders' && !document.hidden },
209225
stopGridOrderPolling() {
210226
clearTimeout(this.gridOrdersTimer)
@@ -254,7 +270,7 @@ export default {
254270
async generateReview() { try { await showConfirmDialog({ title: this.$t('live_detail.reviewConfirmTitle'), message: this.$t('live_detail.reviewConfirmMessage') }) } catch { return } this.reviewLoading = true; try { const response = await strategyApi.generateReview(this.strategyId, { lookback_days: 30, include_ai: true, language: this.$i18n.locale }); this.review = response?.data || null; this.selectedReviewId = this.review?.history_id || null; await this.loadReviewHistory() } catch { showToast({ message: this.$t('live_detail.reviewFailed'), type: 'fail' }) } finally { this.reviewLoading = false } },
255271
async selectReview(action) { this.showReviewHistory = false; await this.loadReview(action.reportId) }, reviewHistoryLabel(item) { return this.time(item.created_at || item.generated_at) || `#${item.id}` }, async openOwnershipRepair() { this.showOwnershipRepair = true; await this.loadOwnership() },
256272
ownershipQty(value) { const amount = this.finite(value); return amount == null ? '-' : amount.toLocaleString(undefined, { maximumFractionDigits: 8 }) }, ownershipHasUnknown(row) { return Math.abs(Number(row?.unknown_qty || 0)) > Math.abs(Number(row?.tolerance || 0)) },
257-
async repairOwnership(row, action) { const key = `${row.symbol}:${row.side}:${action}`; if (this.ownershipRepairKey) return; if (action !== 'recheck') { try { const isProtect = action === 'protect_manual'; await showConfirmDialog({ title: this.$t(isProtect ? 'trading.position_ownership_protect_confirm_title' : 'trading.position_ownership_strict_confirm_title'), message: this.$t(isProtect ? 'trading.position_ownership_protect_confirm' : 'trading.position_ownership_strict_confirm') }) } catch { return } } this.ownershipRepairKey = key; try { await strategyApi.repairPositionOwnership({ id: this.strategyId, symbol: row.symbol, side: row.side, action }); showToast({ message: this.$t('trading.position_ownership_repair_success'), type: 'success' }); const [positions] = await Promise.all([strategyApi.getPositions(this.strategyId), this.loadOwnership(false)]); this.positions = positions?.data || [] } catch { showToast({ message: this.$t('trading.position_ownership_repair_failed'), type: 'fail' }) } finally { this.ownershipRepairKey = '' } },
273+
async repairOwnership(row, action) { const key = `${row.symbol}:${row.side}:${action}`; if (this.ownershipRepairKey || this.ownershipLoading || this.ownershipFailed) return; if (action !== 'recheck') { try { const isProtect = action === 'protect_manual'; await showConfirmDialog({ title: this.$t(isProtect ? 'trading.position_ownership_protect_confirm_title' : 'trading.position_ownership_strict_confirm_title'), message: this.$t(isProtect ? 'trading.position_ownership_protect_confirm' : 'trading.position_ownership_strict_confirm') }) } catch { return } } this.ownershipRepairKey = key; try { await strategyApi.repairPositionOwnership({ id: this.strategyId, symbol: row.symbol, side: row.side, action }); showToast({ message: this.$t('trading.position_ownership_repair_success'), type: 'success' }); const [positions] = await Promise.all([strategyApi.getPositions(this.strategyId), this.loadOwnership(false)]); this.positions = positions?.data || [] } catch { showToast({ message: this.$t('trading.position_ownership_repair_failed'), type: 'fail' }) } finally { this.ownershipRepairKey = '' } },
258274
finite(value) { if (value == null || value === '' || !Number.isFinite(Number(value))) return null; return Number(value) }, number(value, digits = 8) { const amount = this.finite(value); return amount == null ? '-' : amount.toLocaleString(undefined, { maximumFractionDigits: digits }) }, money(value) { const amount = this.finite(value); return amount == null ? '—' : amount.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }) }, signedMoney(value) { const amount = this.finite(value); return amount == null ? '—' : `${amount > 0 ? '+' : ''}${this.money(amount)}` }, expense(value) { const amount = this.finite(value); return amount == null ? '—' : this.signedMoney(-Math.abs(amount)) }, percent(value) { const amount = this.finite(value); return amount == null ? '—' : `${Math.abs(amount).toFixed(2)}%` }, signedPercent(value) { const amount = this.finite(value); return amount == null ? '—' : `${amount > 0 ? '+' : ''}${amount.toFixed(2)}%` }, pnlClass(value) { const amount = Number(value || 0); return amount > 0 ? 'profit' : amount < 0 ? 'loss' : '' },
259275
time(value) { if (!value) return ''; const numeric = /^\d+(?:\.\d+)?$/.test(String(value)) ? Number(value) : null; const date = new Date(numeric != null ? numeric * (numeric < 1e12 ? 1000 : 1) : value); return Number.isNaN(date.getTime()) ? String(value) : date.toLocaleString() }, shortTime(value) { if (!value) return ''; const numeric = /^\d+(?:\.\d+)?$/.test(String(value)) ? Number(value) : null; const date = new Date(numeric != null ? numeric * (numeric < 1e12 ? 1000 : 1) : value); return Number.isNaN(date.getTime()) ? '' : date.toLocaleString(undefined, { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' }) },
260276
positionLeverage(item) { const value = this.finite(item?.leverage); return value != null && value > 0 ? value : this.leverage }, positionCost(item) { return Math.abs((this.finite(item?.entry_price) || 0) * (this.finite(item?.quantity) || 0)) }, positionValue(item) { return Math.abs((this.finite(item?.current_price) || 0) * (this.finite(item?.quantity) || 0)) }, positionRoi(item) { const direct = this.finite(item?.profit_pct_on_margin ?? item?.roi ?? item?.unrealized_pnl_percentage); if (direct != null) return direct; const margin = this.positionCost(item) / this.positionLeverage(item); return margin ? Number(item?.unrealized_pnl || 0) / margin * 100 : 0 },
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import assert from 'node:assert/strict'
2+
import { readFile } from 'node:fs/promises'
3+
import test from 'node:test'
4+
5+
const source = await readFile(new URL('../../src/views/trading/StrategyDetail.vue', import.meta.url), 'utf8')
6+
const method = source.slice(source.indexOf(' async loadOwnership('), source.indexOf(' canPollGridOrders('))
7+
const buildLoader = new Function('strategyApi', 'showToast', `return ({${method}}).loadOwnership`)
8+
9+
function setup(fetch) {
10+
const notifications = []
11+
const state = {
12+
strategyId: 1,
13+
ownershipLoading: false,
14+
ownershipFailed: false,
15+
ownership: { items: [{ symbol: 'CPRT', account_qty: 52 }], status: 'ok' },
16+
$t: key => key
17+
}
18+
return { state, notifications, load: buildLoader({ getPositionOwnership: fetch }, value => notifications.push(value)).bind(state) }
19+
}
20+
21+
test('failed snapshot discards stale rows; retry can recover a valid empty account', async () => {
22+
let fail = true
23+
const { state, notifications, load } = setup(async () => {
24+
if (fail) throw new Error('snapshot_unavailable')
25+
return { data: { items: [], status: 'ok' } }
26+
})
27+
await load(false)
28+
assert.equal(state.ownershipFailed, true)
29+
assert.equal(state.ownership.status, 'unavailable')
30+
assert.deepEqual(state.ownership.items, [])
31+
assert.equal(state.ownershipLoading, false)
32+
assert.equal(notifications.length, 0)
33+
fail = false
34+
await load()
35+
assert.equal(state.ownershipFailed, false)
36+
assert.equal(state.ownership.status, 'ok')
37+
})
38+
39+
test('missing or malformed snapshot is not presented as an empty account', async () => {
40+
for (const response of [{}, { data: null }, { data: {} }, { data: { items: {} } }]) {
41+
const { state, notifications, load } = setup(async () => response)
42+
await load()
43+
assert.equal(state.ownershipFailed, true)
44+
assert.equal(notifications.length, 1)
45+
}
46+
})
47+
48+
test('repeated refresh cannot overwrite an in-flight snapshot', async () => {
49+
let resolve
50+
let requests = 0
51+
const { state, load } = setup(() => { requests++; return new Promise(done => { resolve = done }) })
52+
const first = load()
53+
await load()
54+
assert.equal(requests, 1)
55+
assert.equal(state.ownershipLoading, true)
56+
resolve({ data: { items: [{ symbol: 'CPRT', account_qty: 50 }], status: 'ok' } })
57+
await first
58+
assert.equal(state.ownership.items[0].account_qty, 50)
59+
assert.equal(state.ownershipLoading, false)
60+
})

0 commit comments

Comments
 (0)