created device config, created new UI elements in device dashboard
This commit is contained in:
@@ -1,15 +1,10 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardFooter,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Button } from "@/components/ui/button";
|
||||
Card, CardContent, CardFooter, CardHeader, CardTitle,
|
||||
} from '@/components/ui/card'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
NumberField,
|
||||
NumberFieldContent,
|
||||
@@ -17,121 +12,278 @@ import {
|
||||
NumberFieldIncrement,
|
||||
NumberFieldInput,
|
||||
} from '@/components/ui/number-field'
|
||||
import AssignDevice from "./AssignDevice.vue";
|
||||
import { ref, type PropType } from "vue";
|
||||
import Separator from "@/components/ui/separator/Separator.vue";
|
||||
import DataRangePicker from "./DataRangePicker.vue";
|
||||
import { api } from "@/lib/api";
|
||||
import type { Task } from "@/lib/interfaces";
|
||||
const selectedUserIds = ref<string[]>([])
|
||||
const usrIDs = selectedUserIds.value
|
||||
|
||||
import { h, ref, watch, computed, type PropType } from 'vue'
|
||||
import { api } from '@/lib/api'
|
||||
|
||||
// Table bits for tasks
|
||||
import type { Task, TaskDto, TaskListResp } from '@/lib/interfaces'
|
||||
import type { ColumnDef } from '@tanstack/vue-table'
|
||||
import DataTableNoCheckboxScroll from './DataTableNoCheckboxScroll.vue'
|
||||
|
||||
const props = defineProps({
|
||||
guid: { type: String as PropType<string>, required: true },
|
||||
})
|
||||
|
||||
/** -------------------- Config (left card) -------------------- **/
|
||||
type DeviceConfigDto = {
|
||||
m_guid: string
|
||||
m_recordingDuration: number
|
||||
m_baseUrl: string
|
||||
m_polling: number
|
||||
m_jitter: number
|
||||
}
|
||||
|
||||
const cfgLoading = ref(false)
|
||||
const cfgError = ref<string | null>(null)
|
||||
const savingCfg = ref(false)
|
||||
|
||||
const baseUrl = ref<string>('')
|
||||
const duration = ref<number>(240)
|
||||
const polling = ref<number>(60)
|
||||
const jitter = ref<number>(10)
|
||||
|
||||
async function loadConfig() {
|
||||
if (!props.guid) return
|
||||
cfgLoading.value = true
|
||||
cfgError.value = null
|
||||
try {
|
||||
const { data } = await api.get<DeviceConfigDto>(`/device/${encodeURIComponent(props.guid)}/config`)
|
||||
// map DTO → UI state
|
||||
baseUrl.value = data.m_baseUrl ?? ''
|
||||
duration.value = Number.isFinite(data.m_recordingDuration) ? data.m_recordingDuration : 240
|
||||
polling.value = Number.isFinite(data.m_polling) ? data.m_polling : 60
|
||||
jitter.value = Number.isFinite(data.m_jitter) ? data.m_jitter : 10
|
||||
} catch (e: any) {
|
||||
console.error(e)
|
||||
cfgError.value = e?.message ?? 'Failed to load config'
|
||||
} finally {
|
||||
cfgLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function saveUpdateConfigTask() {
|
||||
if (!props.guid) return
|
||||
savingCfg.value = true
|
||||
cfgError.value = null
|
||||
|
||||
// Build config DTO exactly as backend expects
|
||||
const cfgBody = {
|
||||
m_recordingDuration: Number(duration.value),
|
||||
m_baseUrl: String(baseUrl.value || ''),
|
||||
m_polling: Number(polling.value), // <-- FIXED (was duration)
|
||||
m_jitter: Number(jitter.value),
|
||||
}
|
||||
|
||||
try {
|
||||
// 1) Update DB config first (send as object; Axios sets JSON header)
|
||||
await api.put(`/device/${encodeURIComponent(props.guid)}/config`, cfgBody)
|
||||
|
||||
// 2) Push live config to device via task (matches C++ handler: duration/sleep/jitter/endpoint)
|
||||
const taskPayload = {
|
||||
duration: Number(duration.value),
|
||||
sleep: Number(polling.value),
|
||||
jitter: Number(jitter.value),
|
||||
endpoint: String(baseUrl.value || ''),
|
||||
}
|
||||
|
||||
const dto: Task = {
|
||||
type: 'update_config',
|
||||
payload: JSON.stringify(taskPayload),
|
||||
}
|
||||
|
||||
await api.post(`/device/${encodeURIComponent(props.guid)}/task`, dto)
|
||||
|
||||
// 3) Re-load from server to reflect DB state
|
||||
await loadConfig()
|
||||
} catch (e: any) {
|
||||
console.error(e)
|
||||
cfgError.value = e?.response?.data?.message ?? 'Failed to update config'
|
||||
} finally {
|
||||
savingCfg.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** Optional quick actions */
|
||||
const sending = ref(false)
|
||||
async function startRecording() {
|
||||
const dto: Task = {
|
||||
type: 'start_recording',
|
||||
payload: '' // empty as requested
|
||||
}
|
||||
// debug
|
||||
console.log('CreateTaskDto →', dto)
|
||||
|
||||
if (!props.guid) return
|
||||
const dto: Task = { type: 'start_recording', payload: '' }
|
||||
try {
|
||||
sending.value = true
|
||||
await api.post(`/device/${encodeURIComponent(props.guid)}/task`, dto)
|
||||
} catch (e) {
|
||||
console.error('Failed to create task:', e)
|
||||
} finally {
|
||||
sending.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function stopRecording() {
|
||||
const dto: Task = {
|
||||
type: 'stop_recording',
|
||||
payload: '' // empty as requested
|
||||
}
|
||||
// debug
|
||||
console.log('CreateTaskDto →', dto)
|
||||
|
||||
if (!props.guid) return
|
||||
const dto: Task = { type: 'stop_recording', payload: '' }
|
||||
try {
|
||||
sending.value = true
|
||||
await api.post(`/device/${encodeURIComponent(props.guid)}/task`, dto)
|
||||
} catch (e) {
|
||||
console.error('Failed to create task:', e)
|
||||
} finally {
|
||||
sending.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** -------------------- Tasks (right card) -------------------- **/
|
||||
const tasks = ref<TaskDto[]>([])
|
||||
const tasksLoading = ref(false)
|
||||
const tasksError = ref<string | null>(null)
|
||||
|
||||
async function fetchTasks() {
|
||||
if (!props.guid) return
|
||||
tasksLoading.value = true
|
||||
tasksError.value = null
|
||||
try {
|
||||
const { data } = await api.get<TaskListResp>(`/device/${encodeURIComponent(props.guid)}/tasks`)
|
||||
tasks.value = Array.isArray(data?.tasks) ? data.tasks : []
|
||||
} catch (e: any) {
|
||||
console.error(e)
|
||||
tasksError.value = e?.message ?? 'Failed to load tasks'
|
||||
tasks.value = []
|
||||
} finally {
|
||||
tasksLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function fmt(ts?: string | null) {
|
||||
if (!ts) return ''
|
||||
try { return new Date(ts).toLocaleString() } catch { return ts ?? '' }
|
||||
}
|
||||
|
||||
const task_columns: ColumnDef<TaskDto, any>[] = [
|
||||
{ accessorKey: 'id', header: 'ID' },
|
||||
{ accessorKey: 'type', header: 'Task' },
|
||||
{
|
||||
accessorKey: 'status',
|
||||
header: 'Status',
|
||||
cell: ({ row }) => {
|
||||
const s = row.original.status
|
||||
const cls =
|
||||
s === 'finished' ? 'px-2 py-0.5 rounded text-xs text-green-700 bg-green-100'
|
||||
: s === 'running' ? 'px-2 py-0.5 rounded text-xs text-blue-700 bg-blue-100'
|
||||
: s === 'error' ? 'px-2 py-0.5 rounded text-xs text-red-700 bg-red-100'
|
||||
: 'px-2 py-0.5 rounded text-xs text-amber-700 bg-amber-100'
|
||||
return h('span', { class: cls }, s)
|
||||
},
|
||||
},
|
||||
{ accessorKey: 'createdAt', header: 'Created', cell: ({ row }) => fmt(row.original.createdAt) },
|
||||
{ accessorKey: 'startedAt', header: 'Started', cell: ({ row }) => fmt(row.original.startedAt) },
|
||||
{ accessorKey: 'finishedAt', header: 'Finished', cell: ({ row }) => fmt(row.original.finishedAt) },
|
||||
]
|
||||
|
||||
/** -------------------- lifecycle -------------------- **/
|
||||
watch(() => props.guid, (g) => {
|
||||
if (g) {
|
||||
loadConfig()
|
||||
fetchTasks()
|
||||
}
|
||||
}, { immediate: true })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Card class="flex w-full max-w-4xl mx-auto">
|
||||
<CardHeader class="pb-4">
|
||||
<CardTitle>
|
||||
Dashboard
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="flex-1 grid gap-4 py-4">
|
||||
<div class="grid gap-5">
|
||||
<div class="grid space-y-2 grid-cols-4 items-center">
|
||||
<Label for="users">Allowed users</Label>
|
||||
<AssignDevice v-model="usrIDs" class="col-span-3 w-full"></AssignDevice>
|
||||
<!-- Two columns, full available height -->
|
||||
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6 h-[calc(100vh-6rem)]">
|
||||
<!-- LEFT: Config card -->
|
||||
<Card class="h-full flex flex-col">
|
||||
<CardHeader>
|
||||
<div class="flex items-center justify-between">
|
||||
<CardTitle>Device {{ props.guid }}</CardTitle>
|
||||
<div class="flex gap-2">
|
||||
<Button variant="outline" :disabled="cfgLoading" @click="loadConfig">
|
||||
{{ cfgLoading ? 'Loading…' : 'Refresh config' }}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
<div class="flex space-x-4 pt-2 gap-4">
|
||||
<Button :disabled="sending" @click="startRecording">
|
||||
{{ sending ? 'Starting…' : 'Start recording' }}
|
||||
</Button>
|
||||
<Button :disabled="sending" @click="stopRecording">
|
||||
{{ sending ? 'Stopping…' : 'Stop recording' }}
|
||||
</Button>
|
||||
</div>
|
||||
<div class="space-y-2 gap-4">
|
||||
<NumberField id="duration" :default-value="120" :min="30">
|
||||
<Label for="duration"> Record duration in seconds</Label>
|
||||
<NumberFieldContent>
|
||||
<NumberFieldDecrement></NumberFieldDecrement>
|
||||
<NumberFieldInput></NumberFieldInput>
|
||||
<NumberFieldIncrement></NumberFieldIncrement>
|
||||
</NumberFieldContent>
|
||||
</NumberField>
|
||||
</div>
|
||||
<CardContent class="flex-1 grid gap-5">
|
||||
<div class="flex gap-2">
|
||||
<Button :disabled="sending" @click="startRecording">
|
||||
{{ sending ? 'Starting…' : 'Start recording' }}
|
||||
</Button>
|
||||
<Button :disabled="sending" @click="stopRecording">
|
||||
{{ sending ? 'Stopping…' : 'Stop recording' }}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Separator class="my-6">Communication settings</Separator>
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<div v-if="cfgError" class="text-sm text-red-600">{{ cfgError }}</div>
|
||||
|
||||
<!-- Base URL -->
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="baseurl" class="text-right">Base URL</Label>
|
||||
<Input id="baseurl" class="col-span-3 w-full" placeholder="https://host" v-model="baseUrl"
|
||||
:disabled="cfgLoading || savingCfg" />
|
||||
</div>
|
||||
|
||||
<!-- Row 1: duration (full width) -->
|
||||
<div class="space-y-2">
|
||||
<NumberField id="polling" :default-value="60" :min="30">
|
||||
<Label for="polling"> Timeout interwal in seconds </Label>
|
||||
<NumberField id="duration" v-model="duration" :min="30" :step="1">
|
||||
<Label for="duration">Record duration (sec)</Label>
|
||||
<NumberFieldContent>
|
||||
<NumberFieldDecrement></NumberFieldDecrement>
|
||||
<NumberFieldInput></NumberFieldInput>
|
||||
<NumberFieldIncrement></NumberFieldIncrement>
|
||||
<NumberFieldDecrement />
|
||||
<NumberFieldInput />
|
||||
<NumberFieldIncrement />
|
||||
</NumberFieldContent>
|
||||
</NumberField>
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
|
||||
<NumberField id="jitter" :default-value="10" :min="5">
|
||||
<Label for="jitter"> Jitter in seconds </Label>
|
||||
<NumberFieldContent>
|
||||
<NumberFieldDecrement></NumberFieldDecrement>
|
||||
<NumberFieldInput></NumberFieldInput>
|
||||
<NumberFieldIncrement></NumberFieldIncrement>
|
||||
</NumberFieldContent>
|
||||
</NumberField>
|
||||
<!-- Row 2: polling + jitter (two columns) -->
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div class="space-y-2">
|
||||
<NumberField id="polling" v-model="polling" :min="30" :step="1">
|
||||
<Label for="polling">Timeout interval (sec)</Label>
|
||||
<NumberFieldContent>
|
||||
<NumberFieldDecrement />
|
||||
<NumberFieldInput />
|
||||
<NumberFieldIncrement />
|
||||
</NumberFieldContent>
|
||||
</NumberField>
|
||||
</div>
|
||||
|
||||
<div class="space-y-2">
|
||||
<NumberField id="jitter" v-model="jitter" :min="5" :step="1">
|
||||
<Label for="jitter">Jitter (sec)</Label>
|
||||
<NumberFieldContent>
|
||||
<NumberFieldDecrement />
|
||||
<NumberFieldInput />
|
||||
<NumberFieldIncrement />
|
||||
</NumberFieldContent>
|
||||
</NumberField>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<Separator></Separator>
|
||||
<div class="space-y-2 gap-4">
|
||||
<Label for="sleepdate">Date/time to sleep</Label>
|
||||
<DataRangePicker id="sleepdate"></DataRangePicker>
|
||||
</div>
|
||||
</CardContent>
|
||||
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
<CardFooter class="flex gap-2">
|
||||
<Button :disabled="savingCfg || cfgLoading" @click="saveUpdateConfigTask">
|
||||
{{ savingCfg ? 'Saving…' : 'Update config (task)' }}
|
||||
</Button>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
|
||||
<!-- RIGHT: Tasks card -->
|
||||
<Card class="h-full flex flex-col">
|
||||
<CardHeader class="pb-0">
|
||||
<div class="flex items-center justify-between">
|
||||
<CardTitle>Tasks</CardTitle>
|
||||
<Button variant="outline" :disabled="tasksLoading || !props.guid" @click="fetchTasks">
|
||||
{{ tasksLoading ? 'Loading…' : 'Refresh' }}
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent class="flex-1 pt-4">
|
||||
<div v-if="tasksError" class="text-sm text-red-600 mb-3">{{ tasksError }}</div>
|
||||
|
||||
<div v-if="tasksLoading" class="text-sm text-muted-foreground py-8 text-center">
|
||||
Loading tasks…
|
||||
</div>
|
||||
<div v-else class="h-full">
|
||||
<DataTableNoCheckboxScroll :columns="task_columns" :data="tasks" minTableWidth="min-w-[800px]" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -5,47 +5,61 @@ import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import AssignDevice from '@/customcompometns/AssignDevice.vue'
|
||||
import Navbar from '@/customcompometns/Navbar.vue'
|
||||
import { useColorMode } from '@vueuse/core'
|
||||
import Navbar from '@/customcompometns/Navbar.vue';
|
||||
import type { PropType } from 'vue';
|
||||
import { defineProps, defineEmits, reactive, watch, ref, computed } from 'vue';
|
||||
import { defineProps, reactive, watch, ref, computed, type PropType } from 'vue'
|
||||
import { v4 as uuidv4 } from 'uuid'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { api } from '@/lib/api'
|
||||
|
||||
// shadcn-vue number field parts
|
||||
import {
|
||||
NumberField,
|
||||
NumberFieldContent,
|
||||
NumberFieldDecrement,
|
||||
NumberFieldIncrement,
|
||||
NumberFieldInput,
|
||||
} from '@/components/ui/number-field'
|
||||
|
||||
const mode = useColorMode()
|
||||
const router = useRouter()
|
||||
|
||||
type CreateDevicePayload = {
|
||||
guid: string
|
||||
name: string
|
||||
userIds: number[]
|
||||
}
|
||||
|
||||
type CreateUserPayload = {
|
||||
username: string
|
||||
password: string
|
||||
role: string // 'admin' | 'user'
|
||||
}
|
||||
|
||||
type CreateTrackerPayload = {
|
||||
guid: string
|
||||
name: string
|
||||
userIds: number[]
|
||||
type CreateDeviceConfigDto = {
|
||||
m_recordingDuration: number
|
||||
m_baseUrl: string
|
||||
m_polling: number
|
||||
m_jitter: number
|
||||
}
|
||||
|
||||
const router = useRouter()
|
||||
type CreateTrackerConfigDto = {
|
||||
m_baseUrl: string
|
||||
m_polling: number
|
||||
m_jitter: number
|
||||
}
|
||||
|
||||
const props = defineProps({
|
||||
modelValue: {
|
||||
type: Boolean as PropType<boolean>,
|
||||
required: true,
|
||||
},
|
||||
modelValue: { type: Boolean as PropType<boolean>, required: true },
|
||||
})
|
||||
|
||||
// local form state
|
||||
// ------------------------ Local form state ------------------------
|
||||
const device_form = reactive({
|
||||
guid: uuidv4(), // default fresh UUID
|
||||
guid: uuidv4(),
|
||||
name: '',
|
||||
// config fields
|
||||
baseUrl: '',
|
||||
duration: 240,
|
||||
polling: 60,
|
||||
jitter: 10,
|
||||
})
|
||||
|
||||
const user_form = reactive({
|
||||
@@ -57,31 +71,50 @@ const user_form = reactive({
|
||||
const tracker_form = reactive({
|
||||
guid: uuidv4(),
|
||||
name: '',
|
||||
// config fields
|
||||
baseUrl: '',
|
||||
polling: 60,
|
||||
jitter: 10,
|
||||
})
|
||||
|
||||
// userIds from AssignDevice (expects v-model of string[] ids)
|
||||
// Selected user IDs for both forms (split if you want separate sets)
|
||||
const selectedUserIds = ref<string[]>([])
|
||||
|
||||
watch(
|
||||
() => props.modelValue,
|
||||
(val) => {
|
||||
if (val) {
|
||||
// reset device
|
||||
device_form.guid = uuidv4()
|
||||
device_form.name = ''
|
||||
device_form.baseUrl = ''
|
||||
device_form.duration = 240
|
||||
device_form.polling = 60
|
||||
device_form.jitter = 10
|
||||
|
||||
// reset tracker
|
||||
tracker_form.guid = uuidv4()
|
||||
tracker_form.name = ''
|
||||
tracker_form.baseUrl = ''
|
||||
tracker_form.polling = 60
|
||||
tracker_form.jitter = 10
|
||||
|
||||
// reset users + user form
|
||||
selectedUserIds.value = []
|
||||
user_form.username = ''
|
||||
user_form.password = ''
|
||||
user_form.isAdmin = false
|
||||
|
||||
userError.value = null
|
||||
userSubmitting.value = false
|
||||
userSuccess.value = null
|
||||
// tracker_form.guid = uuidv4()
|
||||
// tracker_form.name = ''
|
||||
errorMsg.value = null
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
// simple UUIDv4 check (best-effort)
|
||||
// ------------------------ Validation / helpers ------------------------
|
||||
const uuidV4Re = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
|
||||
const submitting = ref(false)
|
||||
const errorMsg = ref<string | null>(null)
|
||||
@@ -91,19 +124,58 @@ const userError = ref<string | null>(null)
|
||||
const userSuccess = ref<string | null>(null)
|
||||
const userRole = computed<string>(() => (user_form.isAdmin ? 'admin' : 'user'))
|
||||
|
||||
const canSubmit = computed(() => {
|
||||
return (
|
||||
!!device_form.guid &&
|
||||
uuidV4Re.test(device_form.guid) &&
|
||||
!!device_form.name.trim() &&
|
||||
!submitting.value
|
||||
)
|
||||
})
|
||||
const canSubmitDevice = computed(() =>
|
||||
!!device_form.guid &&
|
||||
uuidV4Re.test(device_form.guid) &&
|
||||
!!device_form.name.trim() &&
|
||||
!!device_form.baseUrl.trim() &&
|
||||
Number.isFinite(device_form.duration) &&
|
||||
Number.isFinite(device_form.polling) &&
|
||||
Number.isFinite(device_form.jitter) &&
|
||||
!submitting.value
|
||||
)
|
||||
|
||||
const canSubmitTracker = computed(() =>
|
||||
!!tracker_form.guid &&
|
||||
uuidV4Re.test(tracker_form.guid) &&
|
||||
!!tracker_form.name.trim() &&
|
||||
!!tracker_form.baseUrl.trim() &&
|
||||
Number.isFinite(tracker_form.polling) &&
|
||||
Number.isFinite(tracker_form.jitter) &&
|
||||
!submitting.value
|
||||
)
|
||||
|
||||
const canSubmitUser = computed(() =>
|
||||
user_form.username.trim().length >= 3 &&
|
||||
user_form.password.length >= 8 &&
|
||||
!userSubmitting.value
|
||||
)
|
||||
|
||||
const canDownloadDeviceConfig = computed(() =>
|
||||
!!device_form.guid && uuidV4Re.test(device_form.guid) && !!device_form.baseUrl.trim()
|
||||
)
|
||||
const canDownloadTrackerConfig = computed(() =>
|
||||
!!tracker_form.guid && uuidV4Re.test(tracker_form.guid) && !!tracker_form.baseUrl.trim()
|
||||
)
|
||||
|
||||
// Save a config.json file to the browser
|
||||
function downloadConfig(filename: string, data: unknown) {
|
||||
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
|
||||
const url = URL.createObjectURL(blob)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = filename
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
a.remove()
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
|
||||
// ------------------------ Submit handlers ------------------------
|
||||
async function submitDevice() {
|
||||
errorMsg.value = null
|
||||
if (!canSubmit.value) {
|
||||
errorMsg.value = 'Please provide a valid GUID and name.'
|
||||
if (!canSubmitDevice.value) {
|
||||
errorMsg.value = 'Please provide a valid GUID, name and config fields.'
|
||||
return
|
||||
}
|
||||
|
||||
@@ -117,25 +189,90 @@ async function submitDevice() {
|
||||
userIds,
|
||||
}
|
||||
|
||||
const config: CreateDeviceConfigDto = {
|
||||
m_recordingDuration: Number(device_form.duration),
|
||||
m_baseUrl: device_form.baseUrl.trim(),
|
||||
m_polling: Number(device_form.polling),
|
||||
m_jitter: Number(device_form.jitter),
|
||||
}
|
||||
|
||||
submitting.value = true
|
||||
try {
|
||||
// 1) create device
|
||||
await api.post('/devices/create', payload)
|
||||
|
||||
// 2) send config to device
|
||||
await api.post(`/device/${encodeURIComponent(device_form.guid)}/config`, config)
|
||||
|
||||
// 3) download config.json example
|
||||
// downloadConfig(
|
||||
// 'config.json',
|
||||
// {
|
||||
// m_guid: device_form.guid,
|
||||
// m_recordingDuration: config.m_recordingDuration,
|
||||
// m_baseUrl: config.m_baseUrl,
|
||||
// m_polling: config.m_polling,
|
||||
// m_jitter: config.m_jitter,
|
||||
// }
|
||||
// )
|
||||
|
||||
router.replace('/admin')
|
||||
} catch (e: any) {
|
||||
// keep client error generic
|
||||
errorMsg.value = e?.response?.status === 403 ? 'Access denied.' : 'Failed to create device.'
|
||||
errorMsg.value = e?.response?.status === 403 ? 'Access denied.' : 'Failed to create device or send config.'
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const canSubmitUser = computed(() => {
|
||||
return (
|
||||
user_form.username.trim().length >= 3 &&
|
||||
user_form.password.length >= 8 && // basic client-side check; real policy enforced server-side
|
||||
!userSubmitting.value
|
||||
)
|
||||
})
|
||||
async function submitTracker() {
|
||||
errorMsg.value = null
|
||||
if (!canSubmitTracker.value) {
|
||||
errorMsg.value = 'Please provide a valid GUID, name and config fields.'
|
||||
return
|
||||
}
|
||||
|
||||
const userIds: number[] = selectedUserIds.value
|
||||
.map((s) => Number(s))
|
||||
.filter((n) => Number.isFinite(n) && n >= 0)
|
||||
|
||||
const payload: CreateDevicePayload = {
|
||||
guid: tracker_form.guid,
|
||||
name: tracker_form.name.trim(),
|
||||
userIds,
|
||||
}
|
||||
|
||||
const config: CreateTrackerConfigDto = {
|
||||
m_baseUrl: tracker_form.baseUrl.trim(),
|
||||
m_polling: Number(tracker_form.polling),
|
||||
m_jitter: Number(tracker_form.jitter),
|
||||
}
|
||||
|
||||
submitting.value = true
|
||||
try {
|
||||
// 1) create tracker (your API already uses /trackers/create)
|
||||
await api.post('/trackers/create', payload)
|
||||
|
||||
// 2) send config; assuming symmetrical tracker endpoint:
|
||||
// await api.post(`/trackers/${encodeURIComponent(tracker_form.guid)}/config`, config)
|
||||
|
||||
// 3) download config.json
|
||||
// downloadConfig(
|
||||
// 'config.json',
|
||||
// {
|
||||
// m_guid: tracker_form.guid,
|
||||
// m_baseUrl: config.m_baseUrl,
|
||||
// m_polling: config.m_polling,
|
||||
// m_jitter: config.m_jitter,
|
||||
// }
|
||||
// )
|
||||
|
||||
router.replace('/admin')
|
||||
} catch (e: any) {
|
||||
errorMsg.value = e?.response?.status === 403 ? 'Access denied.' : 'Failed to create tracker or send config.'
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function submitUser() {
|
||||
userError.value = null
|
||||
@@ -148,7 +285,7 @@ async function submitUser() {
|
||||
|
||||
const payload: CreateUserPayload = {
|
||||
username: user_form.username.trim(),
|
||||
password: user_form.password, // do not trim passwords
|
||||
password: user_form.password,
|
||||
role: userRole.value,
|
||||
}
|
||||
|
||||
@@ -164,33 +301,25 @@ async function submitUser() {
|
||||
}
|
||||
}
|
||||
|
||||
async function submitTracker() {
|
||||
errorMsg.value = null
|
||||
if (!canSubmit.value) {
|
||||
errorMsg.value = 'Please provide a valid GUID and name.'
|
||||
return
|
||||
function downloadDeviceConfig() {
|
||||
const payload = {
|
||||
m_guid: device_form.guid,
|
||||
m_recordingDuration: Number(device_form.duration),
|
||||
m_baseUrl: device_form.baseUrl.trim(),
|
||||
m_polling: Number(device_form.polling),
|
||||
m_jitter: Number(device_form.jitter),
|
||||
}
|
||||
downloadConfig(`config-${device_form.guid}.json`, payload)
|
||||
}
|
||||
|
||||
const userIds: number[] = selectedUserIds.value
|
||||
.map((s) => Number(s))
|
||||
.filter((n) => Number.isFinite(n) && n >= 0)
|
||||
|
||||
const payload: CreateDevicePayload = {
|
||||
guid: device_form.guid,
|
||||
name: device_form.name.trim(),
|
||||
userIds,
|
||||
}
|
||||
|
||||
submitting.value = true
|
||||
try {
|
||||
await api.post('/trackers/create', payload)
|
||||
router.replace('/admin')
|
||||
} catch (e: any) {
|
||||
// keep client error generic
|
||||
errorMsg.value = e?.response?.status === 403 ? 'Access denied.' : 'Failed to create device.'
|
||||
} finally {
|
||||
submitting.value = false
|
||||
function downloadTrackerConfig() {
|
||||
const payload = {
|
||||
m_guid: tracker_form.guid,
|
||||
m_baseUrl: tracker_form.baseUrl.trim(),
|
||||
m_polling: Number(tracker_form.polling),
|
||||
m_jitter: Number(tracker_form.jitter),
|
||||
}
|
||||
downloadConfig(`config-${tracker_form.guid}.json`, payload)
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -198,40 +327,75 @@ async function submitTracker() {
|
||||
<Navbar>
|
||||
<div class="w-full py-8">
|
||||
<div class="mx-auto">
|
||||
<!-- Horizontal cards with gap -->
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-6 items-stretch">
|
||||
|
||||
<!-- Create device -->
|
||||
<Card class="h-full flex flex-col">
|
||||
<CardHeader>
|
||||
<CardTitle>Create device</CardTitle>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent class="flex-1">
|
||||
<!-- add vertical spacing between rows -->
|
||||
<div class="grid gap-5">
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="guid" class="text-right">GUID</Label>
|
||||
<Input id="guid" class="col-span-3 w-full" v-model="device_form.guid" />
|
||||
<Label for="d-guid" class="text-right">GUID</Label>
|
||||
<Input id="d-guid" class="col-span-3 w-full" v-model="device_form.guid" />
|
||||
</div>
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="d-name" class="text-right">Name</Label>
|
||||
<Input id="d-name" class="col-span-3 w-full" v-model="device_form.name" />
|
||||
</div>
|
||||
|
||||
<!-- Config -->
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="name" class="text-right">Name</Label>
|
||||
<Input id="name" class="col-span-3 w-full" v-model="device_form.name" />
|
||||
<Label for="d-baseurl" class="text-right">Base URL</Label>
|
||||
<Input id="d-baseurl" class="col-span-3 w-full" placeholder="https://host"
|
||||
v-model="device_form.baseUrl" />
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="users" class="text-right">Allowed users</Label>
|
||||
<!-- make the component span and fill -->
|
||||
<AssignDevice id="users" class="col-span-3 w-full" v-model="selectedUserIds" />
|
||||
<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<NumberField id="d-duration" v-model="device_form.duration" :min="30" :step="1">
|
||||
<Label for="d-duration">Record duration (sec)</Label>
|
||||
<NumberFieldContent>
|
||||
<NumberFieldDecrement />
|
||||
<NumberFieldInput />
|
||||
<NumberFieldIncrement />
|
||||
</NumberFieldContent>
|
||||
</NumberField>
|
||||
|
||||
<NumberField id="d-polling" v-model="device_form.polling" :min="30" :step="1">
|
||||
<Label for="d-polling">Timeout interval (sec)</Label>
|
||||
<NumberFieldContent>
|
||||
<NumberFieldDecrement />
|
||||
<NumberFieldInput />
|
||||
<NumberFieldIncrement />
|
||||
</NumberFieldContent>
|
||||
</NumberField>
|
||||
|
||||
<NumberField id="d-jitter" v-model="device_form.jitter" :min="5" :step="1">
|
||||
<Label for="d-jitter">Jitter (sec)</Label>
|
||||
<NumberFieldContent>
|
||||
<NumberFieldDecrement />
|
||||
<NumberFieldInput />
|
||||
<NumberFieldIncrement />
|
||||
</NumberFieldContent>
|
||||
</NumberField>
|
||||
</div>
|
||||
<p v-if="errorMsg" class="text-sm text-red-600" aria-live="assertive">
|
||||
{{ errorMsg }}
|
||||
</p>
|
||||
|
||||
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="d-users" class="text-right">Allowed users</Label>
|
||||
<AssignDevice id="d-users" class="col-span-3 w-full" v-model="selectedUserIds" />
|
||||
</div>
|
||||
|
||||
<p v-if="errorMsg" class="text-sm text-red-600">{{ errorMsg }}</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
|
||||
<CardFooter>
|
||||
<Button :disabled="!canSubmit" @click="submitDevice">
|
||||
<CardFooter class="flex gap-2">
|
||||
<Button variant="outline" @click="downloadDeviceConfig"
|
||||
:disabled="!canDownloadDeviceConfig">
|
||||
Download config
|
||||
</Button>
|
||||
<Button :disabled="!canSubmitDevice" @click="submitDevice">
|
||||
{{ submitting ? 'Saving…' : 'Save' }}
|
||||
</Button>
|
||||
</CardFooter>
|
||||
@@ -242,76 +406,97 @@ async function submitTracker() {
|
||||
<CardHeader>
|
||||
<CardTitle>Create user</CardTitle>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent class="flex-1">
|
||||
<div class="grid gap-5">
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="username" class="text-right">Username</Label>
|
||||
<Input id="username" class="col-span-3 w-full" v-model="user_form.username" />
|
||||
<Label for="u-user" class="text-right">Username</Label>
|
||||
<Input id="u-user" class="col-span-3 w-full" v-model="user_form.username" />
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="password" class="text-right">Password</Label>
|
||||
<Input id="password" type="password" class="col-span-3 w-full"
|
||||
<Label for="u-pass" class="text-right">Password</Label>
|
||||
<Input id="u-pass" type="password" class="col-span-3 w-full"
|
||||
v-model="user_form.password" />
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="isAdmin" class="text-right">Make admin</Label>
|
||||
<Label for="u-admin" class="text-right">Make admin</Label>
|
||||
<div class="col-span-3">
|
||||
<Switch id="isAdmin" v-model:checked="user_form.isAdmin"
|
||||
v-model="user_form.isAdmin"
|
||||
<Switch id="u-admin" v-model:checked="user_form.isAdmin"
|
||||
v-model="user_form.isAdmin"
|
||||
@update:checked="(v: any) => user_form.isAdmin = !!v"
|
||||
@update:modelValue="(v: any) => user_form.isAdmin = !!v"/>
|
||||
</div>
|
||||
</div>
|
||||
<p v-if="userError" class="text-sm text-red-600" aria-live="assertive">
|
||||
{{ userError }}
|
||||
</p>
|
||||
<p v-if="userSuccess" class="text-sm text-green-600" aria-live="polite">
|
||||
{{ userSuccess }}
|
||||
</p>
|
||||
<p v-if="userError" class="text-sm text-red-600">{{ userError }}</p>
|
||||
<p v-if="userSuccess" class="text-sm text-green-600">{{ userSuccess }}</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
|
||||
<CardFooter>
|
||||
<Button :disabled="!canSubmitUser" @click="submitUser">
|
||||
{{ userSubmitting ? 'Saving…' : 'Save changes' }}
|
||||
</Button>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
|
||||
|
||||
<!-- Create tracker -->
|
||||
<Card class="h-full flex flex-col">
|
||||
<CardHeader>
|
||||
<CardTitle>Create tracker</CardTitle>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent class="flex-1">
|
||||
<!-- add vertical spacing between rows -->
|
||||
<div class="grid gap-5">
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="guid" class="text-right">GUID</Label>
|
||||
<Input id="guid" class="col-span-3 w-full" v-model="device_form.guid" />
|
||||
<Label for="t-guid" class="text-right">GUID</Label>
|
||||
<Input id="t-guid" class="col-span-3 w-full" v-model="tracker_form.guid" />
|
||||
</div>
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="t-name" class="text-right">Name</Label>
|
||||
<Input id="t-name" class="col-span-3 w-full" v-model="tracker_form.name" />
|
||||
</div>
|
||||
|
||||
<!-- Config -->
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="t-baseurl" class="text-right">Base URL</Label>
|
||||
<Input id="t-baseurl" class="col-span-3 w-full" placeholder="https://host"
|
||||
v-model="tracker_form.baseUrl" />
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<div class="space-y-2">
|
||||
<NumberField id="t-polling" v-model="tracker_form.polling" :min="30">
|
||||
<Label for="t-polling">Timeout interval (sec)</Label>
|
||||
<NumberFieldContent>
|
||||
<NumberFieldDecrement />
|
||||
<NumberFieldInput />
|
||||
<NumberFieldIncrement />
|
||||
</NumberFieldContent>
|
||||
</NumberField>
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<NumberField id="t-jitter" v-model="tracker_form.jitter" :min="5">
|
||||
<Label for="t-jitter">Jitter (sec)</Label>
|
||||
<NumberFieldContent>
|
||||
<NumberFieldDecrement />
|
||||
<NumberFieldInput />
|
||||
<NumberFieldIncrement />
|
||||
</NumberFieldContent>
|
||||
</NumberField>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="name" class="text-right">Name</Label>
|
||||
<Input id="name" class="col-span-3 w-full" v-model="device_form.name" />
|
||||
<Label for="t-users" class="text-right">Allowed users</Label>
|
||||
<AssignDevice id="t-users" class="col-span-3 w-full" v-model="selectedUserIds" />
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-4 items-center gap-4">
|
||||
<Label for="users" class="text-right">Allowed users</Label>
|
||||
<!-- make the component span and fill -->
|
||||
<AssignDevice id="users" class="col-span-3 w-full" v-model="selectedUserIds" />
|
||||
</div>
|
||||
<p v-if="errorMsg" class="text-sm text-red-600" aria-live="assertive">
|
||||
{{ errorMsg }}
|
||||
</p>
|
||||
<p v-if="errorMsg" class="text-sm text-red-600">{{ errorMsg }}</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
|
||||
<CardFooter>
|
||||
<Button :disabled="!canSubmit" @click="submitTracker">
|
||||
<CardFooter class="flex gap-2">
|
||||
<Button variant="outline" @click="downloadTrackerConfig"
|
||||
:disabled="!canDownloadTrackerConfig">
|
||||
Download config
|
||||
</Button>
|
||||
<Button :disabled="!canSubmitTracker" @click="submitTracker">
|
||||
{{ submitting ? 'Saving…' : 'Save' }}
|
||||
</Button>
|
||||
</CardFooter>
|
||||
@@ -321,4 +506,4 @@ async function submitTracker() {
|
||||
</div>
|
||||
</div>
|
||||
</Navbar>
|
||||
</template>
|
||||
</template>
|
||||
|
||||
@@ -22,5 +22,6 @@ func AutoMigrate(db *gorm.DB) error {
|
||||
&models.DEviceTask{},
|
||||
&models.DeviceCertificate{},
|
||||
&models.RevokedSerial{},
|
||||
&models.DeviceConfig{},
|
||||
)
|
||||
}
|
||||
|
||||
36
server/internal/dto/cert.go
Normal file
36
server/internal/dto/cert.go
Normal file
@@ -0,0 +1,36 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"smoop-api/internal/models"
|
||||
"time"
|
||||
)
|
||||
|
||||
type DeviceCertDto struct {
|
||||
ID uint `json:"id"`
|
||||
DeviceGUID string `json:"deviceGuid"`
|
||||
SerialHex string `json:"serialHex"`
|
||||
IssuerCN string `json:"issuerCN"`
|
||||
SubjectDN string `json:"subjectDN"`
|
||||
NotBefore time.Time `json:"notBefore"`
|
||||
NotAfter time.Time `json:"notAfter"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
// PemCert is sensitive/noisy; expose only if you really need it:
|
||||
// PemCert string `json:"pemCert,omitempty"`
|
||||
}
|
||||
|
||||
type DeviceCertListDto struct {
|
||||
Certs []DeviceCertDto `json:"certs"`
|
||||
}
|
||||
|
||||
func MapDeviceCert(c models.DeviceCertificate) DeviceCertDto {
|
||||
return DeviceCertDto{
|
||||
ID: c.ID,
|
||||
DeviceGUID: c.DeviceGUID,
|
||||
SerialHex: c.SerialHex,
|
||||
IssuerCN: c.IssuerCN,
|
||||
SubjectDN: c.SubjectDN,
|
||||
NotBefore: c.NotBefore,
|
||||
NotAfter: c.NotAfter,
|
||||
CreatedAt: c.CreatedAt,
|
||||
}
|
||||
}
|
||||
35
server/internal/dto/device_config.go
Normal file
35
server/internal/dto/device_config.go
Normal file
@@ -0,0 +1,35 @@
|
||||
package dto
|
||||
|
||||
import "smoop-api/internal/models"
|
||||
|
||||
type DeviceConfigDto struct {
|
||||
MGuid string `json:"m_guid"`
|
||||
MRecordingDuration int `json:"m_recordingDuration"`
|
||||
MBaseURL string `json:"m_baseUrl"`
|
||||
MPolling int `json:"m_polling"`
|
||||
MJitter int `json:"m_jitter"`
|
||||
}
|
||||
|
||||
type CreateDeviceConfigDto struct {
|
||||
MRecordingDuration int `json:"m_recordingDuration" binding:"required"`
|
||||
MBaseURL string `json:"m_baseUrl" binding:"required"`
|
||||
MPolling int `json:"m_polling" binding:"required"`
|
||||
MJitter int `json:"m_jitter" binding:"required"`
|
||||
}
|
||||
|
||||
type UpdateDeviceConfigDto struct {
|
||||
MRecordingDuration *int `json:"m_recordingDuration,omitempty"`
|
||||
MBaseURL *string `json:"m_baseUrl,omitempty"`
|
||||
MPolling *int `json:"m_polling,omitempty"`
|
||||
MJitter *int `json:"m_jitter,omitempty"`
|
||||
}
|
||||
|
||||
func MapDeviceConfig(cfg models.DeviceConfig) DeviceConfigDto {
|
||||
return DeviceConfigDto{
|
||||
MGuid: cfg.MGuid,
|
||||
MRecordingDuration: cfg.MRecordingDuration,
|
||||
MBaseURL: cfg.MBaseURL,
|
||||
MPolling: cfg.MPolling,
|
||||
MJitter: cfg.MJitter,
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
@@ -302,5 +303,147 @@ func (h *DevicesHandler) ListCertsByDevice(c *gin.Context) {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "query failed"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"certs": list})
|
||||
out := make([]dto.DeviceCertDto, 0, len(list))
|
||||
for _, it := range list {
|
||||
out = append(out, dto.MapDeviceCert(it))
|
||||
}
|
||||
c.JSON(http.StatusOK, dto.DeviceCertListDto{Certs: out})
|
||||
}
|
||||
|
||||
// GET /device/:guid/config (admin or assigned user — choose policy; here adminOnly for symmetry with certs)
|
||||
func (h *DevicesHandler) GetDeviceConfig(c *gin.Context) {
|
||||
guid := c.Param("guid")
|
||||
|
||||
// Ensure device exists
|
||||
var d models.Device
|
||||
if err := h.db.Where("guid = ?", guid).First(&d).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "device not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var cfg models.DeviceConfig
|
||||
if err := h.db.Where("device_guid = ?", guid).First(&cfg).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "config not found"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "query failed"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, dto.MapDeviceConfig(cfg))
|
||||
}
|
||||
|
||||
// POST /device/:guid/config (create)
|
||||
func (h *DevicesHandler) CreateDeviceConfig(c *gin.Context) {
|
||||
guid := c.Param("guid")
|
||||
|
||||
var d models.Device
|
||||
if err := h.db.Where("guid = ?", guid).First(&d).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "device not found"})
|
||||
return
|
||||
}
|
||||
|
||||
// Ensure not exists
|
||||
var exists int64
|
||||
_ = h.db.Model(&models.DeviceConfig{}).Where("device_guid = ?", guid).Count(&exists).Error
|
||||
if exists > 0 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "config already exists"})
|
||||
return
|
||||
}
|
||||
|
||||
var req dto.CreateDeviceConfigDto
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
cfg := models.DeviceConfig{
|
||||
DeviceGUID: guid,
|
||||
MGuid: guid,
|
||||
MRecordingDuration: req.MRecordingDuration,
|
||||
MBaseURL: req.MBaseURL,
|
||||
MPolling: req.MPolling,
|
||||
MJitter: req.MJitter,
|
||||
}
|
||||
if err := h.db.Create(&cfg).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "create failed"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, dto.MapDeviceConfig(cfg))
|
||||
}
|
||||
|
||||
// PUT /device/:guid/config (partial update)
|
||||
func (h *DevicesHandler) UpdateDeviceConfig(c *gin.Context) {
|
||||
guid := c.Param("guid")
|
||||
|
||||
var req dto.UpdateDeviceConfigDto
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
var cfg models.DeviceConfig
|
||||
err := h.db.Where("device_guid = ?", guid).First(&cfg).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
// Create-on-update behavior
|
||||
// m_baseUrl is required to create (NOT NULL constraint in model)
|
||||
if req.MBaseURL == nil || strings.TrimSpace(*req.MBaseURL) == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "m_baseUrl is required to create config"})
|
||||
return
|
||||
}
|
||||
|
||||
// Defaults
|
||||
recDur := 240
|
||||
if req.MRecordingDuration != nil {
|
||||
recDur = *req.MRecordingDuration
|
||||
}
|
||||
poll := 30
|
||||
if req.MPolling != nil {
|
||||
poll = *req.MPolling
|
||||
}
|
||||
jitter := 10
|
||||
if req.MJitter != nil {
|
||||
jitter = *req.MJitter
|
||||
}
|
||||
|
||||
cfg = models.DeviceConfig{
|
||||
DeviceGUID: guid,
|
||||
MGuid: guid,
|
||||
MRecordingDuration: recDur,
|
||||
MBaseURL: strings.TrimSpace(*req.MBaseURL),
|
||||
MPolling: poll,
|
||||
MJitter: jitter,
|
||||
}
|
||||
if err := h.db.Create(&cfg).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "create failed"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, dto.MapDeviceConfig(cfg))
|
||||
return
|
||||
}
|
||||
// Other DB error
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "query failed"})
|
||||
return
|
||||
}
|
||||
|
||||
// Patch only provided fields
|
||||
if req.MRecordingDuration != nil {
|
||||
cfg.MRecordingDuration = *req.MRecordingDuration
|
||||
}
|
||||
if req.MBaseURL != nil {
|
||||
cfg.MBaseURL = strings.TrimSpace(*req.MBaseURL)
|
||||
}
|
||||
if req.MPolling != nil {
|
||||
cfg.MPolling = *req.MPolling
|
||||
}
|
||||
if req.MJitter != nil {
|
||||
cfg.MJitter = *req.MJitter
|
||||
}
|
||||
|
||||
if err := h.db.Save(&cfg).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "save failed"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, dto.MapDeviceConfig(cfg))
|
||||
}
|
||||
|
||||
@@ -11,4 +11,6 @@ type Device struct {
|
||||
Certs []DeviceCertificate `gorm:"foreignKey:DeviceGUID;references:GUID;constraint:OnDelete:CASCADE"`
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
|
||||
Config *DeviceConfig `gorm:"foreignKey:DeviceGUID;references:GUID;constraint:OnDelete:CASCADE"`
|
||||
}
|
||||
|
||||
19
server/internal/models/device_config.go
Normal file
19
server/internal/models/device_config.go
Normal file
@@ -0,0 +1,19 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
// One-to-one config bound to a device GUID.
|
||||
type DeviceConfig struct {
|
||||
DeviceGUID string `gorm:"primaryKey;size:64"` // 1:1 with Device.GUID
|
||||
// Fields reflect your device JSON keys (m_*)
|
||||
MGuid string `gorm:"size:64;not null"` // duplicate for device FW convenience
|
||||
MRecordingDuration int `gorm:"not null;default:240"`
|
||||
MBaseURL string `gorm:"size:512;not null"`
|
||||
MPolling int `gorm:"not null;default:30"`
|
||||
MJitter int `gorm:"not null;default:10"`
|
||||
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
|
||||
Device Device `gorm:"constraint:OnDelete:CASCADE;foreignKey:DeviceGUID;references:GUID"`
|
||||
}
|
||||
@@ -62,6 +62,9 @@ func Build(db *gorm.DB, minio *minio.Client, cfg *config.Config) *gin.Engine {
|
||||
r.GET("/device/:guid/tasks", authMW, middleware.DeviceAccessFilter(), tasksH.ListDeviceTasks)
|
||||
r.GET("/device/:guid/certs", authMW, adminOnly, devH.ListCertsByDevice)
|
||||
r.POST("/certs/revoke", authMW, adminOnly, certsAdminH.Revoke)
|
||||
r.GET("/device/:guid/config", authMW, middleware.DeviceAccessFilter(), devH.GetDeviceConfig)
|
||||
r.POST("/device/:guid/config", authMW, adminOnly, devH.CreateDeviceConfig)
|
||||
r.PUT("/device/:guid/config", authMW, middleware.DeviceAccessFilter(), devH.UpdateDeviceConfig)
|
||||
|
||||
r.POST("/records/upload", middleware.MTLSGuardUpload(db), recH.Upload)
|
||||
r.GET("/records", authMW, recH.List)
|
||||
|
||||
Reference in New Issue
Block a user