From c1906b23dda91d184b536250f1cf3d6df1c69679 Mon Sep 17 00:00:00 2001 From: yibaiba <946100224@qq.com> Date: Fri, 14 Aug 2026 01:09:10 +0800 Subject: [PATCH] fix(balance): keep manual values directly addressable --- internal/api/balance_query.go | 16 +++++ internal/api/command_center.go | 1 + internal/api/command_center_test.go | 13 ++++ internal/api/openapi.vohive.yaml | 23 +++++++ internal/balance/manual.go | 15 +++++ internal/balance/service_test.go | 7 +++ .../components/commands/BalanceMessage.vue | 1 + .../components/commands/CommandTimeline.vue | 3 + web/src/services/commands.ts | 7 +++ web/src/views/Commands.vue | 60 ++++++++++++++++--- web/tests/manualBalance.test.ts | 11 ++++ 11 files changed, 150 insertions(+), 7 deletions(-) diff --git a/internal/api/balance_query.go b/internal/api/balance_query.go index 50a5670d..0102a610 100644 --- a/internal/api/balance_query.go +++ b/internal/api/balance_query.go @@ -84,6 +84,22 @@ func (s *Server) handleDeviceManualBalancePut(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"query": query}) } +func (s *Server) handleDeviceManualBalanceGet(c *gin.Context) { + if !s.requireBalance(c) { + return + } + query, found, err := s.balance.GetManualBalance(c.Request.Context(), c.Param("device_id")) + if err != nil { + writeManualBalanceError(c, err, "手动余额读取失败") + return + } + if !found { + c.JSON(http.StatusOK, gin.H{"query": nil}) + return + } + c.JSON(http.StatusOK, gin.H{"query": query}) +} + func (s *Server) handleDeviceManualBalanceDelete(c *gin.Context) { if !s.requireBalance(c) { return diff --git a/internal/api/command_center.go b/internal/api/command_center.go index b1ec2682..cb53893d 100644 --- a/internal/api/command_center.go +++ b/internal/api/command_center.go @@ -38,6 +38,7 @@ func (s *Server) registerApprovedCommandRoutes(api *gin.RouterGroup) { api.GET("/balances", s.handleBalanceQueryList) api.POST("/devices/:device_id/balance-queries", s.handleDeviceBalanceQueryStart) api.GET("/devices/:device_id/balance-queries", s.handleDeviceBalanceQueryList) + api.GET("/devices/:device_id/manual-balance", s.handleDeviceManualBalanceGet) api.PUT("/devices/:device_id/manual-balance", s.handleDeviceManualBalancePut) api.DELETE("/devices/:device_id/manual-balance", s.handleDeviceManualBalanceDelete) api.GET("/carrier-query-rules", s.handleBalanceRules) diff --git a/internal/api/command_center_test.go b/internal/api/command_center_test.go index 73c10b4d..76a8d6ea 100644 --- a/internal/api/command_center_test.go +++ b/internal/api/command_center_test.go @@ -130,6 +130,7 @@ func TestApprovedCommandCenterRoutesAreProtected(t *testing.T) { {method: http.MethodGet, path: "/api/balances"}, {method: http.MethodPost, path: "/api/devices/wwan0/balance-queries"}, {method: http.MethodGet, path: "/api/devices/wwan0/balance-queries"}, + {method: http.MethodGet, path: "/api/devices/wwan0/manual-balance"}, {method: http.MethodPut, path: "/api/devices/wwan0/manual-balance"}, {method: http.MethodDelete, path: "/api/devices/wwan0/manual-balance"}, {method: http.MethodGet, path: "/api/carrier-query-rules"}, @@ -162,6 +163,12 @@ func TestManualBalanceRoutesPersistUpdateAndDeleteWithoutSending(t *testing.T) { if updated.Code != http.StatusOK || !strings.Contains(updated.Body.String(), `"amount":"9.50"`) { t.Fatalf("update manual balance status=%d body=%s", updated.Code, updated.Body.String()) } + current := performAPIRequest(router, apiRequestOptions{ + method: http.MethodGet, path: "/api/devices/wwan0/manual-balance", token: token, + }) + if current.Code != http.StatusOK || !strings.Contains(current.Body.String(), `"amount":"9.50"`) { + t.Fatalf("get manual balance status=%d body=%s", current.Code, current.Body.String()) + } listed := performAPIRequest(router, apiRequestOptions{method: http.MethodGet, path: "/api/balances", token: token}) if listed.Code != http.StatusOK || strings.Count(listed.Body.String(), `"transport":"manual"`) != 1 { t.Fatalf("list manual balance status=%d body=%s", listed.Code, listed.Body.String()) @@ -179,6 +186,12 @@ func TestManualBalanceRoutesPersistUpdateAndDeleteWithoutSending(t *testing.T) { if strings.Contains(listed.Body.String(), `"transport":"manual"`) { t.Fatalf("manual balance remains after delete: %s", listed.Body.String()) } + current = performAPIRequest(router, apiRequestOptions{ + method: http.MethodGet, path: "/api/devices/wwan0/manual-balance", token: token, + }) + if current.Code != http.StatusOK || !strings.Contains(current.Body.String(), `"query":null`) { + t.Fatalf("get cleared manual balance status=%d body=%s", current.Code, current.Body.String()) + } } func TestManualBalanceRouteRejectsInvalidAmount(t *testing.T) { diff --git a/internal/api/openapi.vohive.yaml b/internal/api/openapi.vohive.yaml index 9fae2e01..587eca46 100644 --- a/internal/api/openapi.vohive.yaml +++ b/internal/api/openapi.vohive.yaml @@ -1958,6 +1958,29 @@ paths: $ref: '#/components/responses/Unauthorized' /devices/{device_id}/manual-balance: + get: + tags: [balance] + summary: 获取指定设备的当前手动余额 + description: 返回当前手动余额;尚未设置时 query 为 null。 + parameters: + - $ref: '#/components/parameters/DeviceIDPath' + responses: + '200': + description: 当前手动余额或空值 + content: + application/json: + schema: + type: object + required: [query] + properties: + query: + nullable: true + allOf: + - $ref: '#/components/schemas/BalanceQuery' + '400': + $ref: '#/components/responses/ErrorMessage' + '401': + $ref: '#/components/responses/Unauthorized' put: tags: [balance] summary: 保存或更新指定设备的手动余额 diff --git a/internal/balance/manual.go b/internal/balance/manual.go index 64b88028..9db3ab39 100644 --- a/internal/balance/manual.go +++ b/internal/balance/manual.go @@ -54,6 +54,21 @@ func (s *Service) ClearManualBalance(ctx context.Context, deviceID string) (bool return s.repo.DeleteManual(ctx, deviceID) } +func (s *Service) GetManualBalance(ctx context.Context, deviceID string) (Query, bool, error) { + deviceID = strings.TrimSpace(deviceID) + if deviceID == "" { + return Query{}, false, ErrDeviceNotFound + } + query, found, err := s.repo.Get(ctx, manualBalanceID(deviceID)) + if err != nil || !found { + return Query{}, found, err + } + if query.DeviceID != deviceID || query.Transport != TransportManual { + return Query{}, false, nil + } + return query, true, nil +} + func normalizeManualBalance(amount, currency string) (string, string, error) { amount = strings.TrimSpace(amount) if len(amount) == 0 || len(amount) > maxManualAmountLength || !manualAmountPattern.MatchString(amount) { diff --git a/internal/balance/service_test.go b/internal/balance/service_test.go index 248e4edc..7e4fba49 100644 --- a/internal/balance/service_test.go +++ b/internal/balance/service_test.go @@ -266,10 +266,17 @@ func TestManualBalanceUpsertsWithoutSendingAndCanBeCleared(t *testing.T) { if err != nil || len(queries) != 1 || queries[0].Amount != "9.5" { t.Fatalf("manual query list = %+v, err=%v", queries, err) } + current, found, err := service.GetManualBalance(context.Background(), "wwan0") + if err != nil || !found || current.ID != first.ID || current.Amount != "9.5" { + t.Fatalf("GetManualBalance() = %+v, %v, %v", current, found, err) + } cleared, err := service.ClearManualBalance(context.Background(), "wwan0") if err != nil || !cleared { t.Fatalf("ClearManualBalance() = %v, %v", cleared, err) } + if _, found, err := service.GetManualBalance(context.Background(), "wwan0"); err != nil || found { + t.Fatalf("GetManualBalance() after clear found=%v err=%v", found, err) + } } func TestManualBalanceRejectsInvalidAmountWithoutPersisting(t *testing.T) { diff --git a/web/src/components/commands/BalanceMessage.vue b/web/src/components/commands/BalanceMessage.vue index 7d004bd5..4efa65ed 100644 --- a/web/src/components/commands/BalanceMessage.vue +++ b/web/src/components/commands/BalanceMessage.vue @@ -31,6 +31,7 @@ defineProps<{ query: BalanceQuery }>() .balance-message p { margin: 0; color: var(--ui-danger); font-size: var(--ui-font-body-sm); overflow-wrap: anywhere; } .tone-waiting, .tone-running { color: var(--ui-warning); } .tone-parsed { color: var(--ui-info); } +.tone-manual { color: var(--ui-primary); } .tone-success { color: var(--ui-success); } .tone-danger { color: var(--ui-danger); } diff --git a/web/src/components/commands/CommandTimeline.vue b/web/src/components/commands/CommandTimeline.vue index 7c0b11ff..514a55fb 100644 --- a/web/src/components/commands/CommandTimeline.vue +++ b/web/src/components/commands/CommandTimeline.vue @@ -16,6 +16,7 @@ import { Chat24Regular, CheckmarkCircle24Regular, Clock24Regular, + Edit24Regular, ErrorCircle24Regular, Send24Regular } from '@vicons/fluent' @@ -187,6 +188,7 @@ function audioAttachments(event: CommandEvent) { + @@ -282,6 +284,7 @@ function audioAttachments(event: CommandEvent) { .tone-sent { color: var(--ui-communication); } .tone-running, .tone-waiting { color: var(--ui-warning); } .tone-parsed { color: var(--ui-info); } +.tone-manual { color: var(--ui-primary); } .tone-success { color: var(--ui-success); } .tone-danger { color: var(--ui-danger); } .empty-state, .empty-line { diff --git a/web/src/services/commands.ts b/web/src/services/commands.ts index c7f733af..79134a9b 100644 --- a/web/src/services/commands.ts +++ b/web/src/services/commands.ts @@ -62,6 +62,13 @@ export const commandService = { }) }, + manualBalance(deviceId: string) { + return callService(async () => { + const response = await api.get(`/devices/${encodeURIComponent(deviceId)}/manual-balance`) + return (response.data?.query || null) as BalanceQuery | null + }) + }, + setManualBalance(deviceId: string, input: ManualBalanceInput) { return callService(async () => { const response = await api.put(`/devices/${encodeURIComponent(deviceId)}/manual-balance`, input) diff --git a/web/src/views/Commands.vue b/web/src/views/Commands.vue index 9c588b5e..7ac39c90 100644 --- a/web/src/views/Commands.vue +++ b/web/src/views/Commands.vue @@ -9,7 +9,7 @@ import { useEventStream } from '../composables/useEventStream' import { useCommandRuntimeStatus } from '../composables/useCommandRuntimeStatus' import { commandService } from '../services/commands' import { devicesService } from '../services/devices' -import type { CarrierQueryRule, CommandDefinition, CommandEvent, ManualBalanceInput } from '../types/commands' +import type { BalanceQuery, CarrierQueryRule, CommandDefinition, CommandEvent, ManualBalanceInput } from '../types/commands' import { isCarrierRuleOperationBlocked } from '../utils/carrierRuleRuntime' import { buildDangerousCommand } from '../utils/commandInput' @@ -38,6 +38,8 @@ const deletingRuleID = ref('') const rulesLoading = ref(false) const rulesLoaded = ref(false) const rulesError = ref('') +const manualBalance = ref(null) +const manualBalanceError = ref('') const ruleOperationBlocked = computed(() => isCarrierRuleOperationBlocked({ loading: rulesLoading.value, saving: savingRule.value, @@ -47,6 +49,7 @@ const dangerousDefinition = ref(null) const dangerForm = reactive({ device: '', target: '', phone: '', duration: 15 }) let disposed = false let rulesRequestID = 0 +let manualBalanceRequestID = 0 const runtimeStatus = useCommandRuntimeStatus({ fetchDevices: () => devicesService.listManaged(), @@ -56,9 +59,17 @@ const runtimeStatus = useCommandRuntimeStatus({ const devices = runtimeStatus.devices const balances = runtimeStatus.balances const selectedDeviceModel = computed(() => devices.value.find((device) => device.id === selectedDevice.value)) -const selectedManualBalance = computed(() => balances.value.find((query) => ( - query.device_id === selectedDevice.value && query.transport === 'manual' -))) +const selectedManualBalance = computed(() => manualBalance.value?.device_id === selectedDevice.value + ? manualBalance.value + : undefined) +const displayedBalances = computed(() => { + const withoutSelectedManual = balances.value.filter((query) => ( + query.device_id !== selectedDevice.value || query.transport !== 'manual' + )) + return selectedManualBalance.value + ? [selectedManualBalance.value, ...withoutSelectedManual] + : withoutSelectedManual +}) const stream = useEventStream({ path: '/command-center/stream', @@ -70,7 +81,8 @@ const stream = useEventStream({ const streamConnected = stream.connected const syncWarning = computed(() => [ stream.lastError.value ? `实时事件:${stream.lastError.value}` : '', - runtimeStatus.syncWarning.value + runtimeStatus.syncWarning.value, + manualBalanceError.value ? `手动余额:${manualBalanceError.value}` : '' ].filter(Boolean).join(';')) watch(devices, (nextDevices) => { @@ -78,6 +90,15 @@ watch(devices, (nextDevices) => { selectedDevice.value = nextDevices[0]?.id || '' }, { flush: 'sync' }) +watch(selectedDevice, () => { + manualBalance.value = null + void loadManualBalance() +}, { flush: 'sync' }) + +watch(runtimeStatus.lastSyncedAt, () => { + void loadManualBalance() +}) + const dangerousTitle = computed(() => { if (dangerousDefinition.value?.name === 'switch') return '切换 eSIM' if (dangerousDefinition.value?.name === 'vocall') return 'VoWiFi 通话' @@ -196,11 +217,32 @@ async function refreshAll() { loadRules() ]) if (eventsLoaded) refreshVersion.value += 1 + await loadManualBalance(true) } finally { manualRefreshing.value = false } } +async function loadManualBalance(showError = false) { + const deviceID = selectedDevice.value + const requestID = ++manualBalanceRequestID + if (!deviceID) { + manualBalance.value = null + manualBalanceError.value = '' + return true + } + const result = await commandService.manualBalance(deviceID) + if (requestID !== manualBalanceRequestID || deviceID !== selectedDevice.value) return false + if (!result.ok) { + manualBalanceError.value = result.error.message || '手动余额读取失败' + if (showError) ElMessage.error(manualBalanceError.value) + return false + } + manualBalance.value = result.data + manualBalanceError.value = '' + return true +} + async function clearHistory() { const confirmed = await ElMessageBox.confirm('只清除已完成和失败的记录,进行中的命令会保留。', '清除命令历史', { confirmButtonText: '清除', cancelButtonText: '取消', type: 'warning' @@ -239,6 +281,8 @@ async function saveManualBalance(input: ManualBalanceInput) { return } balances.value = [result.data, ...balances.value.filter((item) => item.id !== result.data.id)] + manualBalance.value = result.data + manualBalanceError.value = '' manualBalanceOpen.value = false ElMessage.success('手动余额已保存') } @@ -259,6 +303,8 @@ async function clearManualBalance() { balances.value = balances.value.filter((item) => ( item.device_id !== selectedDevice.value || item.transport !== 'manual' )) + manualBalance.value = null + manualBalanceError.value = '' manualBalanceOpen.value = false ElMessage.success('手动余额已清除') } @@ -341,7 +387,7 @@ function updateRulesOpen(open: boolean) { { assert.deepEqual(prepareManualBalanceInput(' 12,89 ', ' gbp '), { amount: '12.89', currency: 'GBP' }) @@ -23,3 +25,12 @@ test('manual balance UI uses real save and clear endpoints and labels its source assert.match(dialog, /来源会明确显示为“手动录入”/) assert.match(dialog, /清除手动值/) }) + +test('manual balance remains independently addressable and visually distinct', () => { + assert.match(service, /api\.get\(`\/devices\/\$\{encodeURIComponent\(deviceId\)\}\/manual-balance`\)/) + assert.match(commands, /const displayedBalances = computed/) + assert.match(commands, /loadManualBalance\(true\)/) + assert.match(timeline, /tone === 'manual'/) + assert.match(timeline, /\.tone-manual \{ color: var\(--ui-primary\); \}/) + assert.match(balanceMessage, /\.tone-manual \{ color: var\(--ui-primary\); \}/) +})