created device config, created new UI elements in device dashboard
This commit is contained in:
@@ -1,15 +1,10 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import {
|
import {
|
||||||
Card,
|
Card, CardContent, CardFooter, CardHeader, CardTitle,
|
||||||
CardContent,
|
} from '@/components/ui/card'
|
||||||
CardDescription,
|
import { Input } from '@/components/ui/input'
|
||||||
CardFooter,
|
import { Label } from '@/components/ui/label'
|
||||||
CardHeader,
|
import { Button } from '@/components/ui/button'
|
||||||
CardTitle,
|
|
||||||
} from "@/components/ui/card";
|
|
||||||
import { Input } from "@/components/ui/input";
|
|
||||||
import { Label } from "@/components/ui/label";
|
|
||||||
import { Button } from "@/components/ui/button";
|
|
||||||
import {
|
import {
|
||||||
NumberField,
|
NumberField,
|
||||||
NumberFieldContent,
|
NumberFieldContent,
|
||||||
@@ -17,73 +12,195 @@ import {
|
|||||||
NumberFieldIncrement,
|
NumberFieldIncrement,
|
||||||
NumberFieldInput,
|
NumberFieldInput,
|
||||||
} from '@/components/ui/number-field'
|
} from '@/components/ui/number-field'
|
||||||
import AssignDevice from "./AssignDevice.vue";
|
|
||||||
import { ref, type PropType } from "vue";
|
import { h, ref, watch, computed, type PropType } from 'vue'
|
||||||
import Separator from "@/components/ui/separator/Separator.vue";
|
import { api } from '@/lib/api'
|
||||||
import DataRangePicker from "./DataRangePicker.vue";
|
|
||||||
import { api } from "@/lib/api";
|
// Table bits for tasks
|
||||||
import type { Task } from "@/lib/interfaces";
|
import type { Task, TaskDto, TaskListResp } from '@/lib/interfaces'
|
||||||
const selectedUserIds = ref<string[]>([])
|
import type { ColumnDef } from '@tanstack/vue-table'
|
||||||
const usrIDs = selectedUserIds.value
|
import DataTableNoCheckboxScroll from './DataTableNoCheckboxScroll.vue'
|
||||||
|
|
||||||
const props = defineProps({
|
const props = defineProps({
|
||||||
guid: { type: String as PropType<string>, required: true },
|
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)
|
const sending = ref(false)
|
||||||
async function startRecording() {
|
async function startRecording() {
|
||||||
const dto: Task = {
|
if (!props.guid) return
|
||||||
type: 'start_recording',
|
const dto: Task = { type: 'start_recording', payload: '' }
|
||||||
payload: '' // empty as requested
|
|
||||||
}
|
|
||||||
// debug
|
|
||||||
console.log('CreateTaskDto →', dto)
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
sending.value = true
|
sending.value = true
|
||||||
await api.post(`/device/${encodeURIComponent(props.guid)}/task`, dto)
|
await api.post(`/device/${encodeURIComponent(props.guid)}/task`, dto)
|
||||||
} catch (e) {
|
|
||||||
console.error('Failed to create task:', e)
|
|
||||||
} finally {
|
} finally {
|
||||||
sending.value = false
|
sending.value = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function stopRecording() {
|
async function stopRecording() {
|
||||||
const dto: Task = {
|
if (!props.guid) return
|
||||||
type: 'stop_recording',
|
const dto: Task = { type: 'stop_recording', payload: '' }
|
||||||
payload: '' // empty as requested
|
|
||||||
}
|
|
||||||
// debug
|
|
||||||
console.log('CreateTaskDto →', dto)
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
sending.value = true
|
sending.value = true
|
||||||
await api.post(`/device/${encodeURIComponent(props.guid)}/task`, dto)
|
await api.post(`/device/${encodeURIComponent(props.guid)}/task`, dto)
|
||||||
} catch (e) {
|
|
||||||
console.error('Failed to create task:', e)
|
|
||||||
} finally {
|
} finally {
|
||||||
sending.value = false
|
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>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<Card class="flex w-full max-w-4xl mx-auto">
|
<!-- Two columns, full available height -->
|
||||||
<CardHeader class="pb-4">
|
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6 h-[calc(100vh-6rem)]">
|
||||||
<CardTitle>
|
<!-- LEFT: Config card -->
|
||||||
Dashboard
|
<Card class="h-full flex flex-col">
|
||||||
</CardTitle>
|
<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>
|
||||||
</CardHeader>
|
</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>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="flex space-x-4 pt-2 gap-4">
|
<CardContent class="flex-1 grid gap-5">
|
||||||
|
<div class="flex gap-2">
|
||||||
<Button :disabled="sending" @click="startRecording">
|
<Button :disabled="sending" @click="startRecording">
|
||||||
{{ sending ? 'Starting…' : 'Start recording' }}
|
{{ sending ? 'Starting…' : 'Start recording' }}
|
||||||
</Button>
|
</Button>
|
||||||
@@ -91,47 +208,82 @@ async function stopRecording() {
|
|||||||
{{ sending ? 'Stopping…' : 'Stop recording' }}
|
{{ sending ? 'Stopping…' : 'Stop recording' }}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
<div class="space-y-2 gap-4">
|
|
||||||
<NumberField id="duration" :default-value="120" :min="30">
|
<div v-if="cfgError" class="text-sm text-red-600">{{ cfgError }}</div>
|
||||||
<Label for="duration"> Record duration in seconds</Label>
|
|
||||||
<NumberFieldContent>
|
<!-- Base URL -->
|
||||||
<NumberFieldDecrement></NumberFieldDecrement>
|
<div class="grid grid-cols-4 items-center gap-4">
|
||||||
<NumberFieldInput></NumberFieldInput>
|
<Label for="baseurl" class="text-right">Base URL</Label>
|
||||||
<NumberFieldIncrement></NumberFieldIncrement>
|
<Input id="baseurl" class="col-span-3 w-full" placeholder="https://host" v-model="baseUrl"
|
||||||
</NumberFieldContent>
|
:disabled="cfgLoading || savingCfg" />
|
||||||
</NumberField>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Separator class="my-6">Communication settings</Separator>
|
<!-- Row 1: duration (full width) -->
|
||||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
|
|
||||||
<div class="space-y-2">
|
<div class="space-y-2">
|
||||||
<NumberField id="polling" :default-value="60" :min="30">
|
<NumberField id="duration" v-model="duration" :min="30" :step="1">
|
||||||
<Label for="polling"> Timeout interwal in seconds </Label>
|
<Label for="duration">Record duration (sec)</Label>
|
||||||
<NumberFieldContent>
|
<NumberFieldContent>
|
||||||
<NumberFieldDecrement></NumberFieldDecrement>
|
<NumberFieldDecrement />
|
||||||
<NumberFieldInput></NumberFieldInput>
|
<NumberFieldInput />
|
||||||
<NumberFieldIncrement></NumberFieldIncrement>
|
<NumberFieldIncrement />
|
||||||
</NumberFieldContent>
|
</NumberFieldContent>
|
||||||
</NumberField>
|
</NumberField>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Row 2: polling + jitter (two columns) -->
|
||||||
|
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||||
<div class="space-y-2">
|
<div class="space-y-2">
|
||||||
|
<NumberField id="polling" v-model="polling" :min="30" :step="1">
|
||||||
<NumberField id="jitter" :default-value="10" :min="5">
|
<Label for="polling">Timeout interval (sec)</Label>
|
||||||
<Label for="jitter"> Jitter in seconds </Label>
|
|
||||||
<NumberFieldContent>
|
<NumberFieldContent>
|
||||||
<NumberFieldDecrement></NumberFieldDecrement>
|
<NumberFieldDecrement />
|
||||||
<NumberFieldInput></NumberFieldInput>
|
<NumberFieldInput />
|
||||||
<NumberFieldIncrement></NumberFieldIncrement>
|
<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>
|
</NumberFieldContent>
|
||||||
</NumberField>
|
</NumberField>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<Separator></Separator>
|
</CardContent>
|
||||||
<div class="space-y-2 gap-4">
|
|
||||||
<Label for="sleepdate">Date/time to sleep</Label>
|
|
||||||
<DataRangePicker id="sleepdate"></DataRangePicker>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
|
<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>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
</div>
|
||||||
</template>
|
</template>
|
||||||
@@ -5,47 +5,61 @@ import { Input } from '@/components/ui/input'
|
|||||||
import { Label } from '@/components/ui/label'
|
import { Label } from '@/components/ui/label'
|
||||||
import { Switch } from '@/components/ui/switch'
|
import { Switch } from '@/components/ui/switch'
|
||||||
import AssignDevice from '@/customcompometns/AssignDevice.vue'
|
import AssignDevice from '@/customcompometns/AssignDevice.vue'
|
||||||
|
import Navbar from '@/customcompometns/Navbar.vue'
|
||||||
import { useColorMode } from '@vueuse/core'
|
import { useColorMode } from '@vueuse/core'
|
||||||
import Navbar from '@/customcompometns/Navbar.vue';
|
import { defineProps, reactive, watch, ref, computed, type PropType } from 'vue'
|
||||||
import type { PropType } from 'vue';
|
|
||||||
import { defineProps, defineEmits, reactive, watch, ref, computed } from 'vue';
|
|
||||||
import { v4 as uuidv4 } from 'uuid'
|
import { v4 as uuidv4 } from 'uuid'
|
||||||
import { useRouter } from 'vue-router'
|
import { useRouter } from 'vue-router'
|
||||||
import { api } from '@/lib/api'
|
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 mode = useColorMode()
|
||||||
|
const router = useRouter()
|
||||||
|
|
||||||
type CreateDevicePayload = {
|
type CreateDevicePayload = {
|
||||||
guid: string
|
guid: string
|
||||||
name: string
|
name: string
|
||||||
userIds: number[]
|
userIds: number[]
|
||||||
}
|
}
|
||||||
|
|
||||||
type CreateUserPayload = {
|
type CreateUserPayload = {
|
||||||
username: string
|
username: string
|
||||||
password: string
|
password: string
|
||||||
role: string // 'admin' | 'user'
|
role: string // 'admin' | 'user'
|
||||||
}
|
}
|
||||||
|
type CreateDeviceConfigDto = {
|
||||||
type CreateTrackerPayload = {
|
m_recordingDuration: number
|
||||||
guid: string
|
m_baseUrl: string
|
||||||
name: string
|
m_polling: number
|
||||||
userIds: number[]
|
m_jitter: number
|
||||||
}
|
}
|
||||||
|
|
||||||
const router = useRouter()
|
type CreateTrackerConfigDto = {
|
||||||
|
m_baseUrl: string
|
||||||
|
m_polling: number
|
||||||
|
m_jitter: number
|
||||||
|
}
|
||||||
|
|
||||||
const props = defineProps({
|
const props = defineProps({
|
||||||
modelValue: {
|
modelValue: { type: Boolean as PropType<boolean>, required: true },
|
||||||
type: Boolean as PropType<boolean>,
|
|
||||||
required: true,
|
|
||||||
},
|
|
||||||
})
|
})
|
||||||
|
|
||||||
// local form state
|
// ------------------------ Local form state ------------------------
|
||||||
const device_form = reactive({
|
const device_form = reactive({
|
||||||
guid: uuidv4(), // default fresh UUID
|
guid: uuidv4(),
|
||||||
name: '',
|
name: '',
|
||||||
|
// config fields
|
||||||
|
baseUrl: '',
|
||||||
|
duration: 240,
|
||||||
|
polling: 60,
|
||||||
|
jitter: 10,
|
||||||
})
|
})
|
||||||
|
|
||||||
const user_form = reactive({
|
const user_form = reactive({
|
||||||
@@ -57,31 +71,50 @@ const user_form = reactive({
|
|||||||
const tracker_form = reactive({
|
const tracker_form = reactive({
|
||||||
guid: uuidv4(),
|
guid: uuidv4(),
|
||||||
name: '',
|
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[]>([])
|
const selectedUserIds = ref<string[]>([])
|
||||||
|
|
||||||
watch(
|
watch(
|
||||||
() => props.modelValue,
|
() => props.modelValue,
|
||||||
(val) => {
|
(val) => {
|
||||||
if (val) {
|
if (val) {
|
||||||
|
// reset device
|
||||||
device_form.guid = uuidv4()
|
device_form.guid = uuidv4()
|
||||||
device_form.name = ''
|
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 = []
|
selectedUserIds.value = []
|
||||||
user_form.username = ''
|
user_form.username = ''
|
||||||
user_form.password = ''
|
user_form.password = ''
|
||||||
user_form.isAdmin = false
|
user_form.isAdmin = false
|
||||||
|
|
||||||
userError.value = null
|
userError.value = null
|
||||||
userSubmitting.value = false
|
userSubmitting.value = false
|
||||||
userSuccess.value = null
|
userSuccess.value = null
|
||||||
// tracker_form.guid = uuidv4()
|
errorMsg.value = null
|
||||||
// tracker_form.name = ''
|
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 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 submitting = ref(false)
|
||||||
const errorMsg = ref<string | null>(null)
|
const errorMsg = ref<string | null>(null)
|
||||||
@@ -91,19 +124,58 @@ const userError = ref<string | null>(null)
|
|||||||
const userSuccess = ref<string | null>(null)
|
const userSuccess = ref<string | null>(null)
|
||||||
const userRole = computed<string>(() => (user_form.isAdmin ? 'admin' : 'user'))
|
const userRole = computed<string>(() => (user_form.isAdmin ? 'admin' : 'user'))
|
||||||
|
|
||||||
const canSubmit = computed(() => {
|
const canSubmitDevice = computed(() =>
|
||||||
return (
|
|
||||||
!!device_form.guid &&
|
!!device_form.guid &&
|
||||||
uuidV4Re.test(device_form.guid) &&
|
uuidV4Re.test(device_form.guid) &&
|
||||||
!!device_form.name.trim() &&
|
!!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
|
!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() {
|
async function submitDevice() {
|
||||||
errorMsg.value = null
|
errorMsg.value = null
|
||||||
if (!canSubmit.value) {
|
if (!canSubmitDevice.value) {
|
||||||
errorMsg.value = 'Please provide a valid GUID and name.'
|
errorMsg.value = 'Please provide a valid GUID, name and config fields.'
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -117,25 +189,90 @@ async function submitDevice() {
|
|||||||
userIds,
|
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
|
submitting.value = true
|
||||||
try {
|
try {
|
||||||
|
// 1) create device
|
||||||
await api.post('/devices/create', payload)
|
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')
|
router.replace('/admin')
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
// keep client error generic
|
errorMsg.value = e?.response?.status === 403 ? 'Access denied.' : 'Failed to create device or send config.'
|
||||||
errorMsg.value = e?.response?.status === 403 ? 'Access denied.' : 'Failed to create device.'
|
|
||||||
} finally {
|
} finally {
|
||||||
submitting.value = false
|
submitting.value = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const canSubmitUser = computed(() => {
|
async function submitTracker() {
|
||||||
return (
|
errorMsg.value = null
|
||||||
user_form.username.trim().length >= 3 &&
|
if (!canSubmitTracker.value) {
|
||||||
user_form.password.length >= 8 && // basic client-side check; real policy enforced server-side
|
errorMsg.value = 'Please provide a valid GUID, name and config fields.'
|
||||||
!userSubmitting.value
|
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() {
|
async function submitUser() {
|
||||||
userError.value = null
|
userError.value = null
|
||||||
@@ -148,7 +285,7 @@ async function submitUser() {
|
|||||||
|
|
||||||
const payload: CreateUserPayload = {
|
const payload: CreateUserPayload = {
|
||||||
username: user_form.username.trim(),
|
username: user_form.username.trim(),
|
||||||
password: user_form.password, // do not trim passwords
|
password: user_form.password,
|
||||||
role: userRole.value,
|
role: userRole.value,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -164,33 +301,25 @@ async function submitUser() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function submitTracker() {
|
function downloadDeviceConfig() {
|
||||||
errorMsg.value = null
|
const payload = {
|
||||||
if (!canSubmit.value) {
|
m_guid: device_form.guid,
|
||||||
errorMsg.value = 'Please provide a valid GUID and name.'
|
m_recordingDuration: Number(device_form.duration),
|
||||||
return
|
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
|
function downloadTrackerConfig() {
|
||||||
.map((s) => Number(s))
|
const payload = {
|
||||||
.filter((n) => Number.isFinite(n) && n >= 0)
|
m_guid: tracker_form.guid,
|
||||||
|
m_baseUrl: tracker_form.baseUrl.trim(),
|
||||||
const payload: CreateDevicePayload = {
|
m_polling: Number(tracker_form.polling),
|
||||||
guid: device_form.guid,
|
m_jitter: Number(tracker_form.jitter),
|
||||||
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
|
|
||||||
}
|
}
|
||||||
|
downloadConfig(`config-${tracker_form.guid}.json`, payload)
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -198,40 +327,75 @@ async function submitTracker() {
|
|||||||
<Navbar>
|
<Navbar>
|
||||||
<div class="w-full py-8">
|
<div class="w-full py-8">
|
||||||
<div class="mx-auto">
|
<div class="mx-auto">
|
||||||
<!-- Horizontal cards with gap -->
|
|
||||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-6 items-stretch">
|
<div class="grid grid-cols-1 md:grid-cols-2 gap-6 items-stretch">
|
||||||
|
|
||||||
<!-- Create device -->
|
<!-- Create device -->
|
||||||
<Card class="h-full flex flex-col">
|
<Card class="h-full flex flex-col">
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>Create device</CardTitle>
|
<CardTitle>Create device</CardTitle>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
|
|
||||||
<CardContent class="flex-1">
|
<CardContent class="flex-1">
|
||||||
<!-- add vertical spacing between rows -->
|
|
||||||
<div class="grid gap-5">
|
<div class="grid gap-5">
|
||||||
<div class="grid grid-cols-4 items-center gap-4">
|
<div class="grid grid-cols-4 items-center gap-4">
|
||||||
<Label for="guid" class="text-right">GUID</Label>
|
<Label for="d-guid" class="text-right">GUID</Label>
|
||||||
<Input id="guid" class="col-span-3 w-full" v-model="device_form.guid" />
|
<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>
|
</div>
|
||||||
|
|
||||||
|
<!-- Config -->
|
||||||
<div class="grid grid-cols-4 items-center gap-4">
|
<div class="grid grid-cols-4 items-center gap-4">
|
||||||
<Label for="name" class="text-right">Name</Label>
|
<Label for="d-baseurl" class="text-right">Base URL</Label>
|
||||||
<Input id="name" class="col-span-3 w-full" v-model="device_form.name" />
|
<Input id="d-baseurl" class="col-span-3 w-full" placeholder="https://host"
|
||||||
|
v-model="device_form.baseUrl" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="grid grid-cols-4 items-center gap-4">
|
<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||||
<Label for="users" class="text-right">Allowed users</Label>
|
<NumberField id="d-duration" v-model="device_form.duration" :min="30" :step="1">
|
||||||
<!-- make the component span and fill -->
|
<Label for="d-duration">Record duration (sec)</Label>
|
||||||
<AssignDevice id="users" class="col-span-3 w-full" v-model="selectedUserIds" />
|
<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>
|
</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>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
|
<CardFooter class="flex gap-2">
|
||||||
<CardFooter>
|
<Button variant="outline" @click="downloadDeviceConfig"
|
||||||
<Button :disabled="!canSubmit" @click="submitDevice">
|
:disabled="!canDownloadDeviceConfig">
|
||||||
|
Download config
|
||||||
|
</Button>
|
||||||
|
<Button :disabled="!canSubmitDevice" @click="submitDevice">
|
||||||
{{ submitting ? 'Saving…' : 'Save' }}
|
{{ submitting ? 'Saving…' : 'Save' }}
|
||||||
</Button>
|
</Button>
|
||||||
</CardFooter>
|
</CardFooter>
|
||||||
@@ -242,38 +406,30 @@ async function submitTracker() {
|
|||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>Create user</CardTitle>
|
<CardTitle>Create user</CardTitle>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
|
|
||||||
<CardContent class="flex-1">
|
<CardContent class="flex-1">
|
||||||
<div class="grid gap-5">
|
<div class="grid gap-5">
|
||||||
<div class="grid grid-cols-4 items-center gap-4">
|
<div class="grid grid-cols-4 items-center gap-4">
|
||||||
<Label for="username" class="text-right">Username</Label>
|
<Label for="u-user" class="text-right">Username</Label>
|
||||||
<Input id="username" class="col-span-3 w-full" v-model="user_form.username" />
|
<Input id="u-user" class="col-span-3 w-full" v-model="user_form.username" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="grid grid-cols-4 items-center gap-4">
|
<div class="grid grid-cols-4 items-center gap-4">
|
||||||
<Label for="password" class="text-right">Password</Label>
|
<Label for="u-pass" class="text-right">Password</Label>
|
||||||
<Input id="password" type="password" class="col-span-3 w-full"
|
<Input id="u-pass" type="password" class="col-span-3 w-full"
|
||||||
v-model="user_form.password" />
|
v-model="user_form.password" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="grid grid-cols-4 items-center gap-4">
|
<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">
|
<div class="col-span-3">
|
||||||
<Switch id="isAdmin" v-model:checked="user_form.isAdmin"
|
<Switch id="u-admin" v-model:checked="user_form.isAdmin"
|
||||||
v-model="user_form.isAdmin"
|
v-model="user_form.isAdmin"
|
||||||
@update:checked="(v: any) => user_form.isAdmin = !!v"
|
@update:checked="(v: any) => user_form.isAdmin = !!v"
|
||||||
@update:modelValue="(v: any) => user_form.isAdmin = !!v"/>
|
@update:modelValue="(v: any) => user_form.isAdmin = !!v"/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<p v-if="userError" class="text-sm text-red-600" aria-live="assertive">
|
<p v-if="userError" class="text-sm text-red-600">{{ userError }}</p>
|
||||||
{{ userError }}
|
<p v-if="userSuccess" class="text-sm text-green-600">{{ userSuccess }}</p>
|
||||||
</p>
|
|
||||||
<p v-if="userSuccess" class="text-sm text-green-600" aria-live="polite">
|
|
||||||
{{ userSuccess }}
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
|
|
||||||
<CardFooter>
|
<CardFooter>
|
||||||
<Button :disabled="!canSubmitUser" @click="submitUser">
|
<Button :disabled="!canSubmitUser" @click="submitUser">
|
||||||
{{ userSubmitting ? 'Saving…' : 'Save changes' }}
|
{{ userSubmitting ? 'Saving…' : 'Save changes' }}
|
||||||
@@ -281,37 +437,66 @@ async function submitTracker() {
|
|||||||
</CardFooter>
|
</CardFooter>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
|
<!-- Create tracker -->
|
||||||
<Card class="h-full flex flex-col">
|
<Card class="h-full flex flex-col">
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>Create tracker</CardTitle>
|
<CardTitle>Create tracker</CardTitle>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
|
|
||||||
<CardContent class="flex-1">
|
<CardContent class="flex-1">
|
||||||
<!-- add vertical spacing between rows -->
|
|
||||||
<div class="grid gap-5">
|
<div class="grid gap-5">
|
||||||
<div class="grid grid-cols-4 items-center gap-4">
|
<div class="grid grid-cols-4 items-center gap-4">
|
||||||
<Label for="guid" class="text-right">GUID</Label>
|
<Label for="t-guid" class="text-right">GUID</Label>
|
||||||
<Input id="guid" class="col-span-3 w-full" v-model="device_form.guid" />
|
<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>
|
||||||
|
|
||||||
<div class="grid grid-cols-4 items-center gap-4">
|
<div class="grid grid-cols-4 items-center gap-4">
|
||||||
<Label for="name" class="text-right">Name</Label>
|
<Label for="t-users" class="text-right">Allowed users</Label>
|
||||||
<Input id="name" class="col-span-3 w-full" v-model="device_form.name" />
|
<AssignDevice id="t-users" class="col-span-3 w-full" v-model="selectedUserIds" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="grid grid-cols-4 items-center gap-4">
|
<p v-if="errorMsg" class="text-sm text-red-600">{{ errorMsg }}</p>
|
||||||
<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>
|
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
|
<CardFooter class="flex gap-2">
|
||||||
<CardFooter>
|
<Button variant="outline" @click="downloadTrackerConfig"
|
||||||
<Button :disabled="!canSubmit" @click="submitTracker">
|
:disabled="!canDownloadTrackerConfig">
|
||||||
|
Download config
|
||||||
|
</Button>
|
||||||
|
<Button :disabled="!canSubmitTracker" @click="submitTracker">
|
||||||
{{ submitting ? 'Saving…' : 'Save' }}
|
{{ submitting ? 'Saving…' : 'Save' }}
|
||||||
</Button>
|
</Button>
|
||||||
</CardFooter>
|
</CardFooter>
|
||||||
|
|||||||
@@ -22,5 +22,6 @@ func AutoMigrate(db *gorm.DB) error {
|
|||||||
&models.DEviceTask{},
|
&models.DEviceTask{},
|
||||||
&models.DeviceCertificate{},
|
&models.DeviceCertificate{},
|
||||||
&models.RevokedSerial{},
|
&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
|
package handlers
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
@@ -302,5 +303,147 @@ func (h *DevicesHandler) ListCertsByDevice(c *gin.Context) {
|
|||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "query failed"})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "query failed"})
|
||||||
return
|
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"`
|
Certs []DeviceCertificate `gorm:"foreignKey:DeviceGUID;references:GUID;constraint:OnDelete:CASCADE"`
|
||||||
CreatedAt time.Time
|
CreatedAt time.Time
|
||||||
UpdatedAt 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/tasks", authMW, middleware.DeviceAccessFilter(), tasksH.ListDeviceTasks)
|
||||||
r.GET("/device/:guid/certs", authMW, adminOnly, devH.ListCertsByDevice)
|
r.GET("/device/:guid/certs", authMW, adminOnly, devH.ListCertsByDevice)
|
||||||
r.POST("/certs/revoke", authMW, adminOnly, certsAdminH.Revoke)
|
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.POST("/records/upload", middleware.MTLSGuardUpload(db), recH.Upload)
|
||||||
r.GET("/records", authMW, recH.List)
|
r.GET("/records", authMW, recH.List)
|
||||||
|
|||||||
Reference in New Issue
Block a user