mirror of
https://github.com/yibaiba/hideck.git
synced 2026-12-06 00:01:20 +00:00
fix(balance): keep manual values directly addressable
This commit is contained in:
1 parent
b74f076197
commit
c1906b23dd
11 files changed
+150
-7
No files matched your search
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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: 保存或更新指定设备的手动余额
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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); }
|
||||
</style>
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
Chat24Regular,
|
||||
CheckmarkCircle24Regular,
|
||||
Clock24Regular,
|
||||
Edit24Regular,
|
||||
ErrorCircle24Regular,
|
||||
Send24Regular
|
||||
} from '@vicons/fluent'
|
||||
@@ -187,6 +188,7 @@ function audioAttachments(event: CommandEvent) {
|
||||
<el-icon v-else-if="item.presentation.tone === 'running'"><Clock24Regular /></el-icon>
|
||||
<el-icon v-else-if="item.presentation.tone === 'waiting'"><Clock24Regular /></el-icon>
|
||||
<el-icon v-else-if="item.presentation.tone === 'parsed'"><Chat24Regular /></el-icon>
|
||||
<el-icon v-else-if="item.presentation.tone === 'manual'"><Edit24Regular /></el-icon>
|
||||
<el-icon v-else-if="item.presentation.tone === 'danger'"><ErrorCircle24Regular /></el-icon>
|
||||
<el-icon v-else><CheckmarkCircle24Regular /></el-icon>
|
||||
</span>
|
||||
@@ -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 {
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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<BalanceQuery | null>(null)
|
||||
const manualBalanceError = ref('')
|
||||
const ruleOperationBlocked = computed(() => isCarrierRuleOperationBlocked({
|
||||
loading: rulesLoading.value,
|
||||
saving: savingRule.value,
|
||||
@@ -47,6 +49,7 @@ const dangerousDefinition = ref<CommandDefinition | null>(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<CommandEvent>({
|
||||
path: '/command-center/stream',
|
||||
@@ -70,7 +81,8 @@ const stream = useEventStream<CommandEvent>({
|
||||
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) {
|
||||
<CommandChat
|
||||
v-model:selected-device="selectedDevice"
|
||||
:events="events"
|
||||
:balance-queries="balances"
|
||||
:balance-queries="displayedBalances"
|
||||
:definitions="definitions"
|
||||
:devices="devices"
|
||||
:loading="loading"
|
||||
@@ -365,7 +411,7 @@ function updateRulesOpen(open: boolean) {
|
||||
v-model="balanceOpen"
|
||||
v-model:selected-device="selectedDevice"
|
||||
:devices="devices"
|
||||
:queries="balances"
|
||||
:queries="displayedBalances"
|
||||
:built-in-rules="builtInRules"
|
||||
:custom-rules="customRules"
|
||||
:loading="loading"
|
||||
|
||||
@@ -7,6 +7,8 @@ const service = await readFile(new URL('../src/services/commands.ts', import.met
|
||||
const commands = await readFile(new URL('../src/views/Commands.vue', import.meta.url), 'utf8')
|
||||
const panel = await readFile(new URL('../src/components/commands/BalancePanel.vue', import.meta.url), 'utf8')
|
||||
const dialog = await readFile(new URL('../src/components/commands/ManualBalanceDialog.vue', import.meta.url), 'utf8')
|
||||
const timeline = await readFile(new URL('../src/components/commands/CommandTimeline.vue', import.meta.url), 'utf8')
|
||||
const balanceMessage = await readFile(new URL('../src/components/commands/BalanceMessage.vue', import.meta.url), 'utf8')
|
||||
|
||||
test('manual balance input normalizes amount and currency without inventing defaults', () => {
|
||||
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\); \}/)
|
||||
})
|
||||
Reference in new issue
Block a user