This commit is contained in:
commit
b1fef52688
|
|
@ -0,0 +1 @@
|
|||
NUXT_PUBLIC_API_BASE=http://localhost:10000/api/v1
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
# Nuxt
|
||||
.nuxt/
|
||||
.output/
|
||||
.data/
|
||||
.nitro/
|
||||
.cache/
|
||||
dist/
|
||||
|
||||
# Dependencies
|
||||
node_modules/
|
||||
|
||||
# Logs
|
||||
*.log
|
||||
|
||||
# Environment files
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
|
||||
# IDE and OS
|
||||
.idea/
|
||||
.vscode/
|
||||
.DS_Store
|
||||
|
||||
# Test output
|
||||
coverage/
|
||||
playwright-report/
|
||||
test-results/
|
||||
|
||||
|
|
@ -0,0 +1,59 @@
|
|||
# WANITIL Support Frontend
|
||||
|
||||
Веб-интерфейс системы технической поддержки сотрудников. Реализован единый
|
||||
метаданный CRUD-интерфейс для модулей Addresses, CRM, Service, Requests,
|
||||
Incidents, SLA, Configuration items, Device и System.
|
||||
|
||||
План реализации и принятые технические решения приведены в
|
||||
[`docs/PROJECT_PLAN.md`](docs/PROJECT_PLAN.md).
|
||||
|
||||
## Возможности
|
||||
|
||||
- аутентификация Knox Token;
|
||||
- загрузка текущего пользователя и эффективных разрешений через `/me/` и `/me/permissions/`;
|
||||
- мгновенное применение языка, светлой/тёмной темы и основного цвета;
|
||||
- форма управления профилем и ролевое ограничение меню/CRUD-действий;
|
||||
- навигация по модулям и сущностям;
|
||||
- серверная пагинация, поиск, выбор строк и состояния ошибок;
|
||||
- создание и редактирование через формы, построенные из OpenAPI-схем;
|
||||
- удаление с подтверждением;
|
||||
- пересчёт SLA и эскалация для основных процессов;
|
||||
- сохранение параметров списка в URL.
|
||||
|
||||
## Стек
|
||||
|
||||
Vue 3, TypeScript, Nuxt 3, Vuetify 3, Pinia, Vitest.
|
||||
|
||||
## Запуск
|
||||
|
||||
Требуется Node.js 18+ (для новых проектов рекомендуется Node.js 20 LTS).
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
По умолчанию API доступен по адресу `http://localhost:10000/api/v1`. Другой
|
||||
адрес задаётся переменной `NUXT_PUBLIC_API_BASE`.
|
||||
|
||||
## Проверки
|
||||
|
||||
```bash
|
||||
npm run typecheck
|
||||
npm test
|
||||
npm run build
|
||||
```
|
||||
|
||||
## Структура
|
||||
|
||||
- `config/modules.ts` — реестр модулей и ресурсов;
|
||||
- `components/ResourceCrud.vue` — общий список, фильтры и CRUD;
|
||||
- `components/ResourceForm.vue` — динамическая форма;
|
||||
- `server/api/resource-schema.get.ts` — преобразование OpenAPI request schema;
|
||||
- `stores/auth.ts` — состояние сессии;
|
||||
- `docs/PROJECT_PLAN.md` — исходный план и критерии готовности.
|
||||
|
||||
OpenAPI: `http://localhost:10000/api/v1/docs/`, основные методы:
|
||||
`/api/v1/main/*`.
|
||||
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
<template>
|
||||
<NuxtLayout>
|
||||
<NuxtPage />
|
||||
</NuxtLayout>
|
||||
</template>
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
:root { color-scheme: light; }
|
||||
html { overflow-y: auto; }
|
||||
body { background: #f4f7fb; }
|
||||
.page-shell { max-width: 1600px; margin: 0 auto; }
|
||||
.text-wrap { white-space: normal; min-width: 180px; }
|
||||
.mono { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
|
||||
|
|
@ -0,0 +1,124 @@
|
|||
<script setup lang="ts">
|
||||
import type { ApiRecord } from '~/types/api'
|
||||
|
||||
const props = defineProps<{ modelValue: unknown; readonly?: boolean }>()
|
||||
const emit = defineEmits<{ 'update:modelValue': [value: string | number | null] }>()
|
||||
const { request, normalizeList } = useApi()
|
||||
|
||||
type Option = { title: string; value: string | number }
|
||||
const towns = ref<Option[]>([])
|
||||
const streets = ref<Option[]>([])
|
||||
const houses = ref<Option[]>([])
|
||||
const townId = ref<string | number | null>(null)
|
||||
const streetId = ref<string | number | null>(null)
|
||||
|
||||
const options = (items: ApiRecord[], fallback: string): Option[] => items
|
||||
.filter(item => item.id !== undefined)
|
||||
.map(item => ({
|
||||
title: String(item.address || item.name || `${fallback} #${item.id}`),
|
||||
value: item.id!,
|
||||
}))
|
||||
|
||||
async function searchTowns(search = '') {
|
||||
const data = await request<any>('/main/adr/towns/', {
|
||||
query: { page_size: 50, ...(search.trim() ? { name__icontains: search.trim() } : {}) },
|
||||
})
|
||||
towns.value = options(normalizeList(data).items, 'Населённый пункт')
|
||||
}
|
||||
|
||||
async function searchStreets(search = '') {
|
||||
if (townId.value === null) {
|
||||
streets.value = []
|
||||
return
|
||||
}
|
||||
const data = await request<any>('/main/adr/streets/', {
|
||||
query: {
|
||||
page_size: 50,
|
||||
adr_town__id__exact: townId.value,
|
||||
...(search.trim() ? { name__icontains: search.trim() } : {}),
|
||||
},
|
||||
})
|
||||
streets.value = options(normalizeList(data).items, 'Улица')
|
||||
}
|
||||
|
||||
async function searchHouses(search = '') {
|
||||
if (streetId.value === null) {
|
||||
houses.value = []
|
||||
return
|
||||
}
|
||||
const data = await request<any>('/main/adr/houses/', {
|
||||
query: {
|
||||
page_size: 50,
|
||||
adr_street__id__exact: streetId.value,
|
||||
...(search.trim() ? { name__icontains: search.trim() } : {}),
|
||||
},
|
||||
})
|
||||
houses.value = options(normalizeList(data).items, 'Дом')
|
||||
}
|
||||
|
||||
async function selectTown(value: string | number | null) {
|
||||
if (String(townId.value ?? '') === String(value ?? '')) return
|
||||
townId.value = value
|
||||
streetId.value = null
|
||||
streets.value = []
|
||||
houses.value = []
|
||||
emit('update:modelValue', null)
|
||||
if (value !== null) await searchStreets()
|
||||
}
|
||||
|
||||
async function selectStreet(value: string | number | null) {
|
||||
if (String(streetId.value ?? '') === String(value ?? '')) return
|
||||
streetId.value = value
|
||||
houses.value = []
|
||||
emit('update:modelValue', null)
|
||||
if (value !== null) await searchHouses()
|
||||
}
|
||||
|
||||
async function initialize(value: unknown) {
|
||||
await searchTowns()
|
||||
if (value === null || value === undefined || Number(value) <= 0) return
|
||||
try {
|
||||
const house = await request<ApiRecord>(`/main/adr/houses/${value}/`)
|
||||
const street = house.adr_street as ApiRecord | undefined
|
||||
const town = street?.adr_town as ApiRecord | undefined
|
||||
townId.value = town?.id ?? null
|
||||
streetId.value = street?.id ?? null
|
||||
if (town?.id !== undefined) {
|
||||
if (!towns.value.some(option => String(option.value) === String(town.id))) {
|
||||
towns.value.unshift({ title: String(town.address || town.name || `Населённый пункт #${town.id}`), value: town.id })
|
||||
}
|
||||
await searchStreets()
|
||||
}
|
||||
if (street?.id !== undefined) {
|
||||
if (!streets.value.some(option => String(option.value) === String(street.id))) {
|
||||
streets.value.unshift({ title: String(street.address || street.name || `Улица #${street.id}`), value: street.id })
|
||||
}
|
||||
await searchHouses()
|
||||
}
|
||||
if (house.id !== undefined && !houses.value.some(option => String(option.value) === String(house.id))) {
|
||||
houses.value.unshift({ title: String(house.address || house.name || `Дом #${house.id}`), value: house.id })
|
||||
}
|
||||
} catch {
|
||||
// The stored ID remains in the form even if the address directory is temporarily unavailable.
|
||||
}
|
||||
}
|
||||
|
||||
watch(() => props.modelValue, (value, previous) => {
|
||||
if (String(value ?? '') !== String(previous ?? '')) initialize(value)
|
||||
}, { immediate: true })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<v-autocomplete :model-value="townId" :items="towns" label="Населённый пункт"
|
||||
clearable no-data-text="Ничего не найдено" :readonly="readonly"
|
||||
@update:search="searchTowns($event || '')" @update:model-value="selectTown" />
|
||||
<v-autocomplete :model-value="streetId" :items="streets" label="Улица"
|
||||
clearable no-data-text="Сначала выберите населённый пункт"
|
||||
:disabled="townId === null" :readonly="readonly"
|
||||
@update:search="searchStreets($event || '')" @update:model-value="selectStreet" />
|
||||
<v-autocomplete :model-value="modelValue" :items="houses" label="Дом"
|
||||
clearable no-data-text="Сначала выберите улицу"
|
||||
:disabled="streetId === null" :readonly="readonly"
|
||||
@update:search="searchHouses($event || '')"
|
||||
@update:model-value="emit('update:modelValue', $event)" />
|
||||
</template>
|
||||
|
|
@ -0,0 +1,102 @@
|
|||
<script setup lang="ts">
|
||||
import type { ApiRecord } from '~/types/api'
|
||||
|
||||
const props = defineProps<{
|
||||
resourcePath: string
|
||||
objectId: string | number
|
||||
readonly?: boolean
|
||||
}>()
|
||||
|
||||
const { request, normalizeList } = useApi()
|
||||
const assigned = ref<ApiRecord[]>([])
|
||||
const available = ref<ApiRecord[]>([])
|
||||
const selectedZoneId = ref<string | number | null>(null)
|
||||
const loading = ref(false)
|
||||
const saving = ref(false)
|
||||
const deletingId = ref<string | number | null>(null)
|
||||
const error = ref('')
|
||||
|
||||
const options = computed(() => available.value
|
||||
.filter(zone => zone.id !== undefined
|
||||
&& !assigned.value.some(item => String(item.id) === String(zone.id)))
|
||||
.map(zone => ({
|
||||
title: String(zone.name || `Зона #${zone.id}`),
|
||||
value: zone.id!,
|
||||
})))
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const [object, zones] = await Promise.all([
|
||||
request<ApiRecord>(`${props.resourcePath}${props.objectId}/`),
|
||||
request<any>('/main/adr/zones/', { query: { page_size: 1000 } }),
|
||||
])
|
||||
assigned.value = Array.isArray(object.adr_zone) ? object.adr_zone as ApiRecord[] : []
|
||||
available.value = normalizeList(zones).items
|
||||
} catch (e: any) {
|
||||
error.value = e.message
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function add() {
|
||||
if (selectedZoneId.value === null) return
|
||||
saving.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
await request(`${props.resourcePath}${props.objectId}/zones/${selectedZoneId.value}/`, {
|
||||
method: 'PUT',
|
||||
})
|
||||
selectedZoneId.value = null
|
||||
await load()
|
||||
} catch (e: any) {
|
||||
error.value = e.message
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(zone: ApiRecord) {
|
||||
if (zone.id === undefined || !window.confirm(`Убрать зону «${zone.name || zone.id}»?`)) return
|
||||
deletingId.value = zone.id
|
||||
error.value = ''
|
||||
try {
|
||||
await request(`${props.resourcePath}${props.objectId}/zones/${zone.id}/`, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
assigned.value = assigned.value.filter(item => String(item.id) !== String(zone.id))
|
||||
} catch (e: any) {
|
||||
error.value = e.message
|
||||
} finally {
|
||||
deletingId.value = null
|
||||
}
|
||||
}
|
||||
|
||||
watch(() => [props.resourcePath, props.objectId], load, { immediate: true })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<v-divider class="my-6" />
|
||||
<h3 class="text-subtitle-1 font-weight-bold mb-4">Зоны</h3>
|
||||
<v-alert v-if="error" type="error" variant="tonal" class="mb-4">{{ error }}</v-alert>
|
||||
<v-progress-linear v-if="loading" indeterminate color="primary" class="mb-4" />
|
||||
<v-list v-if="assigned.length" class="border rounded-lg mb-5">
|
||||
<v-list-item v-for="zone in assigned" :key="zone.id"
|
||||
:title="String(zone.name || `Зона #${zone.id}`)">
|
||||
<template #append>
|
||||
<v-btn v-if="!readonly" icon="mdi-link-off" variant="text" color="error"
|
||||
:loading="String(deletingId) === String(zone.id)"
|
||||
aria-label="Убрать зону" @click="remove(zone)" />
|
||||
</template>
|
||||
</v-list-item>
|
||||
</v-list>
|
||||
<p v-else-if="!loading" class="text-medium-emphasis mb-5">Зоны не назначены</p>
|
||||
<div v-if="!readonly" class="d-flex flex-column flex-sm-row ga-3 align-sm-start">
|
||||
<v-autocomplete v-model="selectedZoneId" :items="options"
|
||||
label="Добавить зону" clearable no-data-text="Нет доступных зон" hide-details />
|
||||
<v-btn color="primary" prepend-icon="mdi-link-plus" :loading="saving"
|
||||
:disabled="selectedZoneId === null" @click="add">Добавить</v-btn>
|
||||
</div>
|
||||
</template>
|
||||
|
|
@ -0,0 +1,112 @@
|
|||
<script setup lang="ts">
|
||||
import type { ApiRecord } from '~/types/api'
|
||||
|
||||
const props = defineProps<{
|
||||
groupId: string | number
|
||||
readonly?: boolean
|
||||
}>()
|
||||
|
||||
const { request, normalizeList } = useApi()
|
||||
const assigned = ref<ApiRecord[]>([])
|
||||
const available = ref<ApiRecord[]>([])
|
||||
const selectedHolidayId = ref<string | number | null>(null)
|
||||
const loading = ref(false)
|
||||
const saving = ref(false)
|
||||
const deletingId = ref<string | number | null>(null)
|
||||
const error = ref('')
|
||||
|
||||
function holidayTitle(holiday: ApiRecord) {
|
||||
const period = [holiday.date_begin, holiday.date_end].filter(Boolean).join(' — ')
|
||||
return [holiday.name || `Праздник #${holiday.id}`, period].filter(Boolean).join(' · ')
|
||||
}
|
||||
|
||||
const options = computed(() => available.value
|
||||
.filter(holiday => holiday.id !== undefined
|
||||
&& !assigned.value.some(item => String(item.id) === String(holiday.id)))
|
||||
.map(holiday => ({
|
||||
title: holidayTitle(holiday),
|
||||
value: holiday.id!,
|
||||
})))
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const [assignedResult, allResult] = await Promise.all([
|
||||
request<any>(`/main/sys/holiday-groups/${props.groupId}/holidays/`, {
|
||||
query: { page_size: 1000 },
|
||||
}),
|
||||
request<any>('/main/sys/holidayelements/', {
|
||||
query: { page_size: 1000 },
|
||||
}),
|
||||
])
|
||||
assigned.value = normalizeList(assignedResult).items
|
||||
available.value = normalizeList(allResult).items
|
||||
} catch (e: any) {
|
||||
error.value = e.message
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function add() {
|
||||
if (selectedHolidayId.value === null) return
|
||||
saving.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
await request(`/main/sys/holiday-groups/${props.groupId}/holidays/${selectedHolidayId.value}/`, {
|
||||
method: 'PUT',
|
||||
})
|
||||
selectedHolidayId.value = null
|
||||
await load()
|
||||
} catch (e: any) {
|
||||
error.value = e.message
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(holiday: ApiRecord) {
|
||||
if (holiday.id === undefined || !window.confirm(`Убрать «${holidayTitle(holiday)}» из группы?`)) return
|
||||
deletingId.value = holiday.id
|
||||
error.value = ''
|
||||
try {
|
||||
await request(`/main/sys/holiday-groups/${props.groupId}/holidays/${holiday.id}/`, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
assigned.value = assigned.value.filter(item => String(item.id) !== String(holiday.id))
|
||||
} catch (e: any) {
|
||||
error.value = e.message
|
||||
} finally {
|
||||
deletingId.value = null
|
||||
}
|
||||
}
|
||||
|
||||
watch(() => props.groupId, load, { immediate: true })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<v-divider class="my-6" />
|
||||
<h3 class="text-subtitle-1 font-weight-bold mb-4">Праздники группы</h3>
|
||||
<v-alert v-if="error" type="error" variant="tonal" class="mb-4">{{ error }}</v-alert>
|
||||
<v-progress-linear v-if="loading" indeterminate color="primary" class="mb-4" />
|
||||
<v-list v-if="assigned.length" class="border rounded-lg mb-5" lines="two">
|
||||
<v-list-item v-for="holiday in assigned" :key="holiday.id"
|
||||
:title="String(holiday.name || `Праздник #${holiday.id}`)"
|
||||
:subtitle="[holiday.date_begin, holiday.date_end].filter(Boolean).join(' — ')">
|
||||
<template #append>
|
||||
<v-btn v-if="!readonly" icon="mdi-link-off" variant="text" color="error"
|
||||
:loading="String(deletingId) === String(holiday.id)"
|
||||
aria-label="Убрать праздник из группы" @click="remove(holiday)" />
|
||||
</template>
|
||||
</v-list-item>
|
||||
</v-list>
|
||||
<p v-else-if="!loading" class="text-medium-emphasis mb-5">В группе пока нет праздников</p>
|
||||
<div v-if="!readonly" class="d-flex flex-column flex-sm-row ga-3 align-sm-start">
|
||||
<v-autocomplete v-model="selectedHolidayId" :items="options"
|
||||
label="Добавить существующий праздник" no-data-text="Нет доступных праздников"
|
||||
clearable hide-details />
|
||||
<v-btn color="primary" prepend-icon="mdi-link-plus" :loading="saving"
|
||||
:disabled="selectedHolidayId === null" @click="add">Добавить</v-btn>
|
||||
</div>
|
||||
</template>
|
||||
|
|
@ -0,0 +1,156 @@
|
|||
<script setup lang="ts">
|
||||
import type { ApiRecord } from '~/types/api'
|
||||
import type { JsonSchema } from '~/types/schema'
|
||||
|
||||
type SelectOption = { title: string; value: string | number | boolean }
|
||||
|
||||
const props = defineProps<{
|
||||
title: string
|
||||
endpoint: string
|
||||
collectionEndpoint?: string
|
||||
parentId: string | number
|
||||
relationField: string
|
||||
relationPayloadField?: string
|
||||
includeRelationPayload?: boolean
|
||||
fieldOptions?: Record<string, SelectOption[]>
|
||||
readonly?: boolean
|
||||
}>()
|
||||
|
||||
const { request, normalizeList } = useApi()
|
||||
const items = ref<ApiRecord[]>([])
|
||||
const schema = ref<JsonSchema>({ type: 'object', properties: {} })
|
||||
const draft = ref<ApiRecord>({})
|
||||
const loading = ref(false)
|
||||
const saving = ref(false)
|
||||
const deletingId = ref<string | number | null>(null)
|
||||
const error = ref('')
|
||||
|
||||
const fields = computed(() => Object.entries(schema.value.properties || {})
|
||||
.filter(([name, field]) => name !== props.relationField
|
||||
&& name !== props.relationPayloadField
|
||||
&& !['id', 'info', 'extra', 'extras'].includes(name)
|
||||
&& !field.readOnly))
|
||||
|
||||
function itemTitle(item: ApiRecord) {
|
||||
return String(item.name || item.title || item.val || item.date || item.datetime || `Объект #${item.id}`)
|
||||
}
|
||||
|
||||
function itemSubtitle(item: ApiRecord) {
|
||||
return Object.entries(item)
|
||||
.filter(([name, value]) => !['id', 'name', 'title', 'val', props.relationField].includes(name)
|
||||
&& value !== null && value !== undefined && typeof value !== 'object')
|
||||
.slice(0, 3)
|
||||
.map(([name, value]) => {
|
||||
const option = props.fieldOptions?.[name]?.find(item => item.value === value)
|
||||
return option ? option.title : String(value)
|
||||
})
|
||||
.join(' · ')
|
||||
}
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const [list, loadedSchema] = await Promise.all([
|
||||
request<any>(props.collectionEndpoint || props.endpoint, {
|
||||
query: props.collectionEndpoint
|
||||
? { page_size: 1000 }
|
||||
: {
|
||||
page_size: 1000,
|
||||
[`${props.relationField}__id__exact`]: props.parentId,
|
||||
},
|
||||
}),
|
||||
$fetch<JsonSchema>('/api/resource-schema', {
|
||||
query: { path: props.endpoint, method: 'post' },
|
||||
}),
|
||||
])
|
||||
items.value = normalizeList(list).items
|
||||
schema.value = loadedSchema
|
||||
} catch (e: any) {
|
||||
error.value = e.message
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function setField(name: string, value: unknown) {
|
||||
draft.value = { ...draft.value, [name]: value }
|
||||
}
|
||||
|
||||
async function add() {
|
||||
saving.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
await request(props.collectionEndpoint || props.endpoint, {
|
||||
method: 'POST',
|
||||
body: {
|
||||
...draft.value,
|
||||
...(props.includeRelationPayload === false
|
||||
? {}
|
||||
: {
|
||||
[props.relationPayloadField || props.relationField]: props.relationPayloadField
|
||||
? Number(props.parentId)
|
||||
: { id: Number(props.parentId) },
|
||||
}),
|
||||
},
|
||||
})
|
||||
draft.value = {}
|
||||
await load()
|
||||
} catch (e: any) {
|
||||
error.value = e.message
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(item: ApiRecord) {
|
||||
if (item.id === undefined || !window.confirm(`Удалить «${itemTitle(item)}»?`)) return
|
||||
deletingId.value = item.id
|
||||
error.value = ''
|
||||
try {
|
||||
await request(`${props.endpoint}${item.id}/`, { method: 'DELETE' })
|
||||
items.value = items.value.filter(current => String(current.id) !== String(item.id))
|
||||
} catch (e: any) {
|
||||
error.value = e.message
|
||||
} finally {
|
||||
deletingId.value = null
|
||||
}
|
||||
}
|
||||
|
||||
watch(() => props.parentId, load, { immediate: true })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<v-divider class="my-6" />
|
||||
<h3 class="text-subtitle-1 font-weight-bold mb-4">{{ title }}</h3>
|
||||
<v-alert v-if="error" type="error" variant="tonal" class="mb-4">{{ error }}</v-alert>
|
||||
<v-progress-linear v-if="loading" indeterminate color="primary" class="mb-4" />
|
||||
<v-list v-if="items.length" class="border rounded-lg mb-5" lines="two">
|
||||
<v-list-item v-for="item in items" :key="item.id" :title="itemTitle(item)"
|
||||
:subtitle="itemSubtitle(item) || undefined">
|
||||
<template #append>
|
||||
<v-btn v-if="!readonly" icon="mdi-delete-outline" variant="text" color="error"
|
||||
:loading="String(deletingId) === String(item.id)" aria-label="Удалить"
|
||||
@click="remove(item)" />
|
||||
</template>
|
||||
</v-list-item>
|
||||
</v-list>
|
||||
<p v-else-if="!loading" class="text-medium-emphasis mb-5">Записей пока нет</p>
|
||||
<v-form v-if="!readonly && fields.length" @submit.prevent="add">
|
||||
<template v-for="[name, field] in fields" :key="name">
|
||||
<v-select v-if="fieldOptions?.[name]" :model-value="draft[name]"
|
||||
:items="fieldOptions[name]" :label="field.title || name.replaceAll('_', ' ')"
|
||||
:rules="Array.isArray(schema.required) && schema.required.includes(name)
|
||||
? [(value: unknown) => value !== null && value !== undefined || 'Обязательное поле']
|
||||
: []"
|
||||
@update:model-value="setField(name, $event)" />
|
||||
<ResourceField v-else :name="name" :schema="field"
|
||||
:model-value="draft[name]"
|
||||
:required="Array.isArray(schema.required) && schema.required.includes(name)"
|
||||
@update:model-value="setField(name, $event)" />
|
||||
</template>
|
||||
<div class="d-flex justify-end">
|
||||
<v-btn type="submit" color="primary" prepend-icon="mdi-plus" :loading="saving">Добавить</v-btn>
|
||||
</div>
|
||||
</v-form>
|
||||
</template>
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
<script setup lang="ts">
|
||||
const props = defineProps<{ apiPath: string; resource: string; id: string | number }>()
|
||||
const emit = defineEmits<{ completed: [message: string] }>()
|
||||
const { request } = useApi()
|
||||
const loading = ref('')
|
||||
const actions = computed(() => {
|
||||
if (props.resource === 'requests') return [
|
||||
{ key: 'recalcagreement', label: 'Пересчитать SLA', icon: 'mdi-timer-refresh' },
|
||||
{ key: 'escalateincident', label: 'Эскалировать в инцидент', icon: 'mdi-alert-plus' },
|
||||
]
|
||||
if (props.resource === 'incidents') return [{ key: 'recalcagreement', label: 'Пересчитать SLA', icon: 'mdi-timer-refresh' }]
|
||||
return []
|
||||
})
|
||||
async function run(key: string, label: string) {
|
||||
loading.value = key
|
||||
try {
|
||||
await request(`${props.apiPath}${props.id}/${key}/`, {
|
||||
method: 'POST',
|
||||
...(key === 'escalateincident' ? { body: {} } : {}),
|
||||
})
|
||||
emit('completed', `${label}: выполнено`)
|
||||
}
|
||||
finally { loading.value = '' }
|
||||
}
|
||||
</script>
|
||||
<template><div v-if="actions.length" class="d-flex flex-wrap ga-2 mb-5"><v-btn v-for="action in actions" :key="action.key"
|
||||
:prepend-icon="action.icon" variant="tonal" :loading="loading === action.key" @click="run(action.key, action.label)">{{ action.label }}</v-btn></div></template>
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,50 @@
|
|||
<script setup lang="ts">
|
||||
import type { JsonSchema } from '~/types/schema'
|
||||
|
||||
const props = defineProps<{ name: string; schema: JsonSchema; modelValue: unknown; required?: boolean; readonly?: boolean }>()
|
||||
const emit = defineEmits<{ 'update:modelValue': [value: unknown] }>()
|
||||
const label = computed(() => props.schema.title || props.name.replaceAll('_', ' '))
|
||||
const jsonValue = computed({
|
||||
get: () => typeof props.modelValue === 'string' ? props.modelValue : JSON.stringify(props.modelValue ?? (props.schema.type === 'array' ? [] : {}), null, 2),
|
||||
set: value => { try { emit('update:modelValue', JSON.parse(value)) } catch { emit('update:modelValue', value) } },
|
||||
})
|
||||
const inputType = computed(() => {
|
||||
if (props.schema.format === 'password') return 'password'
|
||||
if (props.schema.format === 'email') return 'email'
|
||||
if (props.schema.format === 'date') return 'date'
|
||||
if (props.schema.format === 'date-time' || props.schema.format === 'datetime') return 'datetime-local'
|
||||
if (props.schema.format === 'time') return 'time'
|
||||
if (props.schema.type === 'integer' || props.schema.type === 'number') return 'number'
|
||||
return 'text'
|
||||
})
|
||||
const inputValue = computed(() => {
|
||||
if (typeof props.modelValue !== 'string') return props.modelValue
|
||||
if (inputType.value === 'date') return props.modelValue.slice(0, 10)
|
||||
if (inputType.value === 'datetime-local') {
|
||||
const match = props.modelValue.match(/^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2}(?::\d{2})?)/)
|
||||
return match ? `${match[1]}T${match[2]}` : props.modelValue
|
||||
}
|
||||
if (inputType.value === 'time') return props.modelValue.replace(/Z$/, '')
|
||||
return props.modelValue
|
||||
})
|
||||
const rules = computed(() => [
|
||||
...(props.required ? [(value: unknown) => value !== '' && value !== null && value !== undefined || 'Обязательное поле'] : []),
|
||||
...(props.schema.minLength !== undefined ? [(value: unknown) => !value || String(value).length >= props.schema.minLength! || `Минимум ${props.schema.minLength} символов`] : []),
|
||||
...(props.schema.maxLength !== undefined ? [(value: unknown) => !value || String(value).length <= props.schema.maxLength! || `Максимум ${props.schema.maxLength} символов`] : []),
|
||||
...(props.schema.pattern ? [(value: unknown) => !value || new RegExp(props.schema.pattern!).test(String(value)) || 'Недопустимый формат'] : []),
|
||||
])
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<v-select v-if="schema.enum" :model-value="modelValue" :items="schema.enum" :label="label" :rules="rules" :readonly="readonly" clearable
|
||||
@update:model-value="emit('update:modelValue', $event)" />
|
||||
<v-switch v-else-if="schema.type === 'boolean'" :model-value="Boolean(modelValue)" :label="label" color="primary" :readonly="readonly"
|
||||
@update:model-value="emit('update:modelValue', $event)" />
|
||||
<v-textarea v-else-if="schema.type === 'object' || schema.type === 'array'" v-model="jsonValue" :label="`${label} (JSON)`" :readonly="readonly"
|
||||
:hint="schema.description" persistent-hint rows="3" class="mono" />
|
||||
<v-textarea v-else-if="name.includes('description') || name.includes('info') || name.includes('comment')" :model-value="modelValue as string"
|
||||
:label="label" :rules="rules" :hint="schema.description" :readonly="readonly" rows="3" @update:model-value="emit('update:modelValue', $event)" />
|
||||
<v-text-field v-else :model-value="inputValue" :label="label" :rules="rules" :hint="schema.description"
|
||||
:type="inputType"
|
||||
:readonly="readonly" persistent-hint @update:model-value="emit('update:modelValue', schema.type === 'integer' ? Number($event) : $event)" />
|
||||
</template>
|
||||
|
|
@ -0,0 +1,64 @@
|
|||
<script setup lang="ts">
|
||||
import type { ApiRecord } from '~/types/api'
|
||||
import type { JsonSchema } from '~/types/schema'
|
||||
|
||||
type SelectOption = { title: string; value: string | number | boolean }
|
||||
const props = defineProps<{
|
||||
modelValue: ApiRecord
|
||||
schema: JsonSchema
|
||||
loading?: boolean
|
||||
readonly?: boolean
|
||||
hiddenFields?: string[]
|
||||
fieldOptions?: Record<string, SelectOption[]>
|
||||
fieldLabels?: Record<string, string>
|
||||
relationOptions?: Record<string, SelectOption[]>
|
||||
relationLabels?: Record<string, string>
|
||||
}>()
|
||||
const emit = defineEmits<{
|
||||
'update:modelValue': [value: ApiRecord]
|
||||
submit: []
|
||||
relationSearch: [name: string, search: string]
|
||||
}>()
|
||||
const form = ref()
|
||||
const ignoredFields = ['id', 'info', 'extra', 'extras']
|
||||
const fields = computed(() => Object.entries(props.schema.properties || {})
|
||||
.filter(([name, field]) => !ignoredFields.includes(name)
|
||||
&& !field.readOnly && !props.hiddenFields?.includes(name)))
|
||||
function setField(name: string, value: unknown) { emit('update:modelValue', { ...props.modelValue, [name]: value }) }
|
||||
function relationValue(name: string) {
|
||||
const value = props.modelValue[name]
|
||||
return value && typeof value === 'object' ? (value as ApiRecord).id : value
|
||||
}
|
||||
async function submit() { const result = await form.value?.validate(); if (result?.valid !== false) emit('submit') }
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<v-form ref="form" @submit.prevent="submit">
|
||||
<slot name="prepend" />
|
||||
<template v-for="[name, field] in fields" :key="name">
|
||||
<v-autocomplete v-if="relationOptions?.[name]" :model-value="relationValue(name)"
|
||||
:items="relationOptions[name]"
|
||||
:label="relationLabels?.[name] || field.title || name.replaceAll('_', ' ')"
|
||||
:readonly="readonly" clearable no-data-text="Ничего не найдено"
|
||||
@update:search="emit('relationSearch', name, $event || '')"
|
||||
:rules="Array.isArray(schema.required) && schema.required.includes(name)
|
||||
? [(value: unknown) => value !== null && value !== undefined || 'Обязательное поле']
|
||||
: []"
|
||||
@update:model-value="setField(name, $event === null ? null : { id: $event })" />
|
||||
<v-select v-else-if="fieldOptions?.[name]" :model-value="modelValue[name]"
|
||||
:items="fieldOptions[name]"
|
||||
:label="fieldLabels?.[name] || field.title || name.replaceAll('_', ' ')"
|
||||
:readonly="readonly"
|
||||
:rules="Array.isArray(schema.required) && schema.required.includes(name)
|
||||
? [(value: unknown) => value !== null && value !== undefined || 'Обязательное поле']
|
||||
: []"
|
||||
@update:model-value="setField(name, $event)" />
|
||||
<ResourceField v-else :name="name" :schema="field"
|
||||
:model-value="modelValue[name]"
|
||||
:required="Array.isArray(schema.required) && schema.required.includes(name)"
|
||||
:readonly="readonly"
|
||||
@update:model-value="setField(name, $event)" />
|
||||
</template>
|
||||
<div v-if="!readonly" class="d-flex justify-end mt-4"><v-btn type="submit" color="primary" :loading="loading">Сохранить</v-btn></div>
|
||||
</v-form>
|
||||
</template>
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
import type { ApiErrorPayload, ApiRecord, PaginatedResponse } from '~/types/api'
|
||||
|
||||
export class ApiError extends Error {
|
||||
constructor(public status: number, public payload: ApiErrorPayload | null) {
|
||||
super(payload?.detail || `Ошибка API (${status})`)
|
||||
}
|
||||
}
|
||||
|
||||
export function useApi() {
|
||||
const config = useRuntimeConfig()
|
||||
const token = useCookie<string | null>('wanitil-token', { sameSite: 'lax' })
|
||||
|
||||
async function request<T>(path: string, options: Parameters<typeof $fetch<T>>[1] = {}) {
|
||||
try {
|
||||
return await $fetch<T>(`${config.public.apiBase}${path}`, {
|
||||
...options,
|
||||
headers: {
|
||||
...(token.value ? { Authorization: `Token ${token.value}` } : {}),
|
||||
...(options.headers || {}),
|
||||
},
|
||||
})
|
||||
} catch (error: any) {
|
||||
const status = error?.response?.status || error?.statusCode || error?.status || 0
|
||||
if (status === 401) {
|
||||
token.value = null
|
||||
if (import.meta.client && window.location.pathname !== '/login') {
|
||||
const redirect = `${window.location.pathname}${window.location.search}${window.location.hash}`
|
||||
await navigateTo({ path: '/login', query: { redirect } }, { replace: true })
|
||||
}
|
||||
}
|
||||
throw new ApiError(status, error?.data || null)
|
||||
}
|
||||
}
|
||||
|
||||
const normalizeList = <T extends ApiRecord>(data: PaginatedResponse<T> | T[]) =>
|
||||
Array.isArray(data) ? { items: data, total: data.length } : { items: data.results, total: data.count }
|
||||
|
||||
return { request, normalizeList, token }
|
||||
}
|
||||
|
|
@ -0,0 +1,88 @@
|
|||
const ADMIN_MARKERS = ['admin', 'administrator', 'root', 'superuser', 'администратор']
|
||||
const WRITE_MARKERS = ['edit', 'write', 'manage', 'editor', 'operator', 'изменение', 'редактор', 'оператор']
|
||||
const CREATE_MARKERS = ['create', 'add', 'write', 'manage', 'создание', 'добавление']
|
||||
const DELETE_MARKERS = ['delete', 'remove', 'write', 'manage', 'удаление']
|
||||
const READ_ONLY_MARKERS = ['read', 'view', 'viewer', 'readonly', 'чтение', 'просмотр']
|
||||
|
||||
export function usePermissions() {
|
||||
const auth = useAuthStore()
|
||||
const roleNames = computed(() => auth.roles.map(role => `${role.name} ${role.sys_managment?.name || ''}`.toLowerCase()))
|
||||
const isAdmin = computed(() => roleNames.value.some(name => ADMIN_MARKERS.some(marker => name.includes(marker))))
|
||||
|
||||
function documentedActions(apiPrefix: string, resourceKey?: string) {
|
||||
if (!auth.permissions || !resourceKey) return null
|
||||
const resource = resourceKey.toLowerCase()
|
||||
const prefix = apiPrefix.toLowerCase()
|
||||
const candidates = [
|
||||
resource, `${prefix}.${resource}`, `${prefix}:${resource}`, `${prefix}/${resource}`,
|
||||
`/main/${prefix}/${resource}`, `main.${prefix}.${resource}`,
|
||||
]
|
||||
const entry = Object.entries(auth.permissions).find(([key]) => {
|
||||
const normalized = key.toLowerCase().replace(/\/$/, '')
|
||||
return candidates.includes(normalized)
|
||||
|| normalized.endsWith(`.${resource}`)
|
||||
|| normalized.endsWith(`/${resource}`)
|
||||
})
|
||||
return (entry?.[1] || []).map(action => action.toLowerCase())
|
||||
}
|
||||
|
||||
function allows(actions: string[], markers: string[]) {
|
||||
return actions.some(action => markers.some(marker =>
|
||||
action === marker || action.endsWith(`_${marker}`) || action.includes(`.${marker}`)))
|
||||
}
|
||||
|
||||
function matchesObject(moduleKey: string, apiPrefix: string, resourceKey?: string) {
|
||||
if (!auth.allowedObjects.length) return null
|
||||
const candidates = [moduleKey, apiPrefix, resourceKey || ''].filter(Boolean).map(value => value.toLowerCase())
|
||||
const endpoint = `/main/${apiPrefix}/${resourceKey || ''}`.toLowerCase()
|
||||
return auth.allowedObjects.some(object => {
|
||||
const values = [object.name, object.prefix, object.url, object.description, object.spec_field]
|
||||
.filter((value): value is string => Boolean(value)).map(value => value.toLowerCase())
|
||||
return values.some(value => value.includes(endpoint)
|
||||
|| candidates.some(candidate => value === candidate || value.includes(`/${candidate}/`) || value.includes(`_${candidate}`)))
|
||||
})
|
||||
}
|
||||
|
||||
function matchesModule(name: string, moduleKey: string, apiPrefix: string) {
|
||||
const aliases = [moduleKey, apiPrefix, moduleKey.replace('-items', ''), '*', 'all', 'support', 'поддержка']
|
||||
return aliases.some(alias => name.includes(alias))
|
||||
}
|
||||
function canView(moduleKey: string, apiPrefix: string, resourceKey?: string) {
|
||||
if (isAdmin.value) return true
|
||||
const actions = documentedActions(apiPrefix, resourceKey)
|
||||
if (actions) return allows(actions, ['view', 'list', 'retrieve', 'read'])
|
||||
if (!roleNames.value.length) return false
|
||||
const objectAccess = matchesObject(moduleKey, apiPrefix, resourceKey)
|
||||
if (objectAccess !== null) return objectAccess
|
||||
return roleNames.value.some(name => matchesModule(name, moduleKey, apiPrefix)) || roleNames.value.every(name => !name.includes(':'))
|
||||
}
|
||||
function canEdit(moduleKey: string, apiPrefix: string, resourceKey?: string) {
|
||||
if (isAdmin.value) return true
|
||||
const actions = documentedActions(apiPrefix, resourceKey)
|
||||
if (actions) return allows(actions, ['change', 'update', 'edit', 'write'])
|
||||
if (!canView(moduleKey, apiPrefix, resourceKey)) return false
|
||||
const matchingRoles = roleNames.value.filter(name => matchesModule(name, moduleKey, apiPrefix))
|
||||
if (matchingRoles.some(name => READ_ONLY_MARKERS.some(marker => name.includes(marker)))) return false
|
||||
if (matchesObject(moduleKey, apiPrefix, resourceKey) === true) return true
|
||||
return matchingRoles.some(name =>
|
||||
WRITE_MARKERS.some(marker => name.includes(marker))
|
||||
&& !READ_ONLY_MARKERS.some(marker => name.includes(marker)))
|
||||
}
|
||||
function canCreate(moduleKey: string, apiPrefix: string, resourceKey?: string) {
|
||||
if (isAdmin.value) return true
|
||||
const actions = documentedActions(apiPrefix, resourceKey)
|
||||
if (actions) return allows(actions, ['add', 'create'])
|
||||
if (!canEdit(moduleKey, apiPrefix, resourceKey)) return false
|
||||
const matchingRoles = roleNames.value.filter(name => matchesModule(name, moduleKey, apiPrefix))
|
||||
return matchingRoles.some(name => CREATE_MARKERS.some(marker => name.includes(marker)))
|
||||
}
|
||||
function canDelete(moduleKey: string, apiPrefix: string, resourceKey?: string) {
|
||||
if (isAdmin.value) return true
|
||||
const actions = documentedActions(apiPrefix, resourceKey)
|
||||
if (actions) return allows(actions, ['delete', 'remove'])
|
||||
if (!canEdit(moduleKey, apiPrefix, resourceKey)) return false
|
||||
const matchingRoles = roleNames.value.filter(name => matchesModule(name, moduleKey, apiPrefix))
|
||||
return matchingRoles.some(name => DELETE_MARKERS.some(marker => name.includes(marker)))
|
||||
}
|
||||
return { isAdmin, canView, canCreate, canEdit, canDelete }
|
||||
}
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
import { useLocale, useTheme } from 'vuetify'
|
||||
import { resolveThemeColor } from '~/config/theme-colors'
|
||||
|
||||
export function useUiPreferences() {
|
||||
const auth = useAuthStore()
|
||||
const theme = useTheme()
|
||||
const locale = useLocale()
|
||||
const language = computed(() => auth.profile?.lang?.toLowerCase().startsWith('en') ? 'en' : 'ru')
|
||||
|
||||
watchEffect(() => {
|
||||
const profile = auth.profile
|
||||
const themeName = profile?.theme_is_light === false ? 'wanitilDark' : 'wanitilLight'
|
||||
theme.global.name.value = themeName
|
||||
locale.current.value = language.value
|
||||
theme.themes.value[themeName].colors.primary = resolveThemeColor(
|
||||
profile?.theme_color,
|
||||
profile?.theme_is_light !== false,
|
||||
)
|
||||
})
|
||||
return { language }
|
||||
}
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
const messages = {
|
||||
ru: {
|
||||
dashboard: 'Обзор', workspace: 'Рабочее пространство', workspaceHint: 'Выберите модуль для работы с объектами системы.',
|
||||
profile: 'Профиль', logout: 'Выйти', notifications: 'Уведомления', sections: 'разделов',
|
||||
filters: 'Фильтры', create: 'Создать', search: 'Поиск', apply: 'Применить', reset: 'Сбросить',
|
||||
noData: 'Объекты не найдены', newObject: 'Новый объект', save: 'Сохранить', cancel: 'Отмена', delete: 'Удалить',
|
||||
},
|
||||
en: {
|
||||
dashboard: 'Dashboard', workspace: 'Workspace', workspaceHint: 'Choose a module to work with system objects.',
|
||||
profile: 'Profile', logout: 'Sign out', notifications: 'Notifications', sections: 'sections',
|
||||
filters: 'Filters', create: 'Create', search: 'Search', apply: 'Apply', reset: 'Reset',
|
||||
noData: 'No objects found', newObject: 'New object', save: 'Save', cancel: 'Cancel', delete: 'Delete',
|
||||
},
|
||||
} as const
|
||||
|
||||
export function useUiText() {
|
||||
const { language } = useUiPreferences()
|
||||
const t = (key: keyof typeof messages.ru) => messages[language.value][key]
|
||||
return { t, language }
|
||||
}
|
||||
|
|
@ -0,0 +1,106 @@
|
|||
export const EnumFilterType = {
|
||||
str: 'str',
|
||||
int: 'int',
|
||||
float: 'float',
|
||||
datetime: 'datetime',
|
||||
bool: 'bool',
|
||||
} as const
|
||||
|
||||
export const EnumInputType = {
|
||||
str: 'str',
|
||||
int: 'int',
|
||||
float: 'float',
|
||||
datetime: 'datetime',
|
||||
bool: 'bool',
|
||||
} as const
|
||||
|
||||
export type FilterType = typeof EnumFilterType[keyof typeof EnumFilterType]
|
||||
export type FilterInputType = typeof EnumInputType[keyof typeof EnumInputType]
|
||||
|
||||
export interface FilterComparison {
|
||||
name1: string
|
||||
name2: string
|
||||
value: string
|
||||
filterType: FilterType
|
||||
inputType: FilterInputType
|
||||
}
|
||||
|
||||
const comparison = (
|
||||
name1: string,
|
||||
name2: string,
|
||||
value: string,
|
||||
filterType: FilterType,
|
||||
inputType: FilterInputType,
|
||||
): FilterComparison => ({ name1, name2, value, filterType, inputType })
|
||||
|
||||
/**
|
||||
* Named comparison enumeration.
|
||||
*
|
||||
* An object is used instead of a TypeScript enum because every member carries
|
||||
* metadata in addition to its API value.
|
||||
*/
|
||||
export const EnumFilterComparison = {
|
||||
strExact: comparison('Exact', '=A', 'exact', EnumFilterType.str, EnumInputType.str),
|
||||
strIExact: comparison('IExact', '=Aa', 'iexact', EnumFilterType.str, EnumInputType.str),
|
||||
strContains: comparison('Contains', '..A..', 'contains', EnumFilterType.str, EnumInputType.str),
|
||||
strIContains: comparison('IContains', '..Aa..', 'icontains', EnumFilterType.str, EnumInputType.str),
|
||||
strStartsWith: comparison('StartsWith', 'A..', 'startswith', EnumFilterType.str, EnumInputType.str),
|
||||
strIStartsWith: comparison('IStartsWith', 'Aa..', 'istartswith', EnumFilterType.str, EnumInputType.str),
|
||||
strEndsWith: comparison('EndsWith', '..A', 'endswith', EnumFilterType.str, EnumInputType.str),
|
||||
strIEndsWith: comparison('IEndsWith', '..Aa', 'iendswith', EnumFilterType.str, EnumInputType.str),
|
||||
strRegex: comparison('Regex', '^A$', 'regex', EnumFilterType.str, EnumInputType.str),
|
||||
strIRegex: comparison('IRegex', '^Aa$', 'iregex', EnumFilterType.str, EnumInputType.str),
|
||||
strIn: comparison('In', 'A,B', 'in', EnumFilterType.str, EnumInputType.str),
|
||||
strIsNull: comparison('IsNull', 'null', 'isnull', EnumFilterType.str, EnumInputType.bool),
|
||||
|
||||
intExact: comparison('Exact', '=1', 'exact', EnumFilterType.int, EnumInputType.int),
|
||||
intGt: comparison('Greater than', '>1', 'gt', EnumFilterType.int, EnumInputType.int),
|
||||
intLt: comparison('Lower than', '<1', 'lt', EnumFilterType.int, EnumInputType.int),
|
||||
intGte: comparison('Greater Equal than', '>=1', 'gte', EnumFilterType.int, EnumInputType.int),
|
||||
intLte: comparison('Lower Equal than', '<=1', 'lte', EnumFilterType.int, EnumInputType.int),
|
||||
intIn: comparison('In', '1,2', 'in', EnumFilterType.int, EnumInputType.str),
|
||||
intIsNull: comparison('IsNull', 'null', 'isnull', EnumFilterType.int, EnumInputType.bool),
|
||||
|
||||
floatExact: comparison('Exact', '=1.1', 'exact', EnumFilterType.float, EnumInputType.float),
|
||||
floatGt: comparison('Greater than', '>1.1', 'gt', EnumFilterType.float, EnumInputType.float),
|
||||
floatLt: comparison('Lower than', '<1.1', 'lt', EnumFilterType.float, EnumInputType.float),
|
||||
floatGte: comparison('Greater Equal than', '>=1.1', 'gte', EnumFilterType.float, EnumInputType.float),
|
||||
floatLte: comparison('Lower Equal than', '<=1.1', 'lte', EnumFilterType.float, EnumInputType.float),
|
||||
floatIn: comparison('In', '1,2', 'in', EnumFilterType.float, EnumInputType.str),
|
||||
floatIsNull: comparison('IsNull', 'null', 'isnull', EnumFilterType.float, EnumInputType.bool),
|
||||
|
||||
datetimeExact: comparison('Exact', '=D', 'exact', EnumFilterType.datetime, EnumInputType.datetime),
|
||||
datetimeGt: comparison('Greater than', '>D', 'gt', EnumFilterType.datetime, EnumInputType.datetime),
|
||||
datetimeLt: comparison('Lower than', '<D', 'lt', EnumFilterType.datetime, EnumInputType.datetime),
|
||||
datetimeGte: comparison('Greater Equal than', '>=D', 'gte', EnumFilterType.datetime, EnumInputType.datetime),
|
||||
datetimeLte: comparison('Lower Equal than', '<=D', 'lte', EnumFilterType.datetime, EnumInputType.datetime),
|
||||
datetimeGtN: comparison('Greater than now+sec', 'now+1<D', 'gtn', EnumFilterType.datetime, EnumInputType.int),
|
||||
datetimeLtN: comparison('Lower than now+sec', 'now+1>D', 'ltn', EnumFilterType.datetime, EnumInputType.int),
|
||||
datetimeGteN: comparison('Greater Equal than now+sec', 'now+1<=D', 'gten', EnumFilterType.datetime, EnumInputType.int),
|
||||
datetimeLteN: comparison('Lower Equal than now+sec', 'now+1>=D', 'lten', EnumFilterType.datetime, EnumInputType.int),
|
||||
datetimeIsNull: comparison('IsNull', 'null', 'isnull', EnumFilterType.datetime, EnumInputType.bool),
|
||||
|
||||
boolExact: comparison('Exact', '=D', 'exact', EnumFilterType.bool, EnumInputType.bool),
|
||||
boolIsNull: comparison('IsNull', 'null', 'isnull', EnumFilterType.bool, EnumInputType.bool),
|
||||
} as const satisfies Record<string, FilterComparison>
|
||||
|
||||
export const filterComparisons: readonly FilterComparison[] = Object.values(EnumFilterComparison)
|
||||
|
||||
export function normalizeFilterType(value: unknown): FilterType {
|
||||
const type = String(value || '').toLowerCase()
|
||||
if (['int', 'integer', 'bigint', 'smallint'].includes(type)) return EnumFilterType.int
|
||||
if (['float', 'double', 'decimal', 'number', 'numeric'].includes(type)) return EnumFilterType.float
|
||||
if (['datetime', 'date', 'time', 'timestamp'].includes(type)) return EnumFilterType.datetime
|
||||
if (['bool', 'boolean'].includes(type)) return EnumFilterType.bool
|
||||
return EnumFilterType.str
|
||||
}
|
||||
|
||||
export function comparisonsFor(type: unknown) {
|
||||
const normalized = normalizeFilterType(type)
|
||||
return filterComparisons
|
||||
.filter(item => item.filterType === normalized)
|
||||
.map(item => ({
|
||||
...item,
|
||||
title: `${item.name1} (${item.name2})`,
|
||||
}))
|
||||
}
|
||||
|
|
@ -0,0 +1,69 @@
|
|||
import type { ModuleDefinition } from '~/types/api'
|
||||
|
||||
const resource = (key: string, title: string, readOnly = false, path = key, menuGroup?: string) =>
|
||||
({ key, title, path, readOnly, menuGroup })
|
||||
|
||||
export const modules: ModuleDefinition[] = [
|
||||
{ key: 'addresses', title: 'Адреса', icon: 'mdi-map-marker', apiPrefix: 'adr', resources: [
|
||||
resource('countries', 'Страны'), resource('regions', 'Регионы'), resource('areas', 'Районы'),
|
||||
resource('towns', 'Населённые пункты'), resource('streets', 'Улицы'),
|
||||
resource('houses', 'Дома'), resource('zones', 'Зоны'),
|
||||
resource('towntypes', 'Типы населённых пунктов', false, 'town-types', 'settings'),
|
||||
resource('streettypes', 'Типы улиц', false, 'street-types', 'settings'),
|
||||
resource('housetypes', 'Типы домов', false, 'house-types', 'settings'),
|
||||
resource('zonetypes', 'Типы зон', false, 'zone-types', 'settings'),
|
||||
] },
|
||||
{ key: 'crm', title: 'CRM', icon: 'mdi-account-group', apiPrefix: 'crm', resources: [
|
||||
resource('clients', 'Клиенты'), resource('contracts', 'Договоры'),
|
||||
resource('categories', 'Категории', false, 'client-categories', 'settings'),
|
||||
resource('types', 'Типы', false, 'client-types', 'settings'),
|
||||
] },
|
||||
{ key: 'service', title: 'Сервисы', icon: 'mdi-room-service', apiPrefix: 'srv', resources: [
|
||||
resource('services', 'Сервисы'), resource('requests', 'Запросы сервиса', false, 'request-types'),
|
||||
resource('solutions', 'Решения'),
|
||||
resource('statuses', 'Статусы', false, 'service-statuses', 'settings'),
|
||||
resource('types', 'Типы', false, 'service-types', 'settings'),
|
||||
] },
|
||||
{ key: 'requests', title: 'Обращения', icon: 'mdi-inbox-arrow-down', apiPrefix: 'req', resources: [
|
||||
resource('requests', 'Обращения'), resource('comments', 'Комментарии'), resource('employees', 'Сотрудники'),
|
||||
resource('depends', 'Зависимости'), resource('criticalities', 'Критичности'),
|
||||
resource('sourcetypes', 'Источники', false, 'source-types'),
|
||||
resource('statuses', 'Статусы'), resource('statustransits', 'Переходы статусов', false, 'status-transitions'),
|
||||
resource('requesthistoricals', 'История', true), resource('preferences', 'Настройки'),
|
||||
resource('requestnotifies', 'Уведомления'), resource('requestnotifyfields', 'Поля уведомлений'),
|
||||
] },
|
||||
{ key: 'incidents', title: 'Инциденты', icon: 'mdi-alert-circle', apiPrefix: 'inc', resources: [
|
||||
resource('incidents', 'Инциденты'), resource('comments', 'Комментарии'), resource('employees', 'Сотрудники'),
|
||||
resource('groups', 'Группы'), resource('cis', 'Конфигурационные единицы'), resource('categories', 'Категории'),
|
||||
resource('subcategories', 'Подкатегории'), resource('impacts', 'Влияния'), resource('priorities', 'Приоритеты'),
|
||||
resource('sourcetypes', 'Источники', false, 'source-types'), resource('statuses', 'Статусы'),
|
||||
resource('statustransits', 'Переходы статусов', false, 'status-transitions'),
|
||||
resource('solutions', 'Решения'), resource('incidenthistoricals', 'История', true), resource('preferences', 'Настройки'),
|
||||
] },
|
||||
{ key: 'sla', title: 'SLA', icon: 'mdi-timer-outline', apiPrefix: 'sla', resources: [
|
||||
resource('requestagreements', 'SLA обращений'), resource('incidentagreements', 'SLA инцидентов'),
|
||||
resource('requeststatuses', 'Статусы обращений', true), resource('incidentstatuses', 'Статусы инцидентов', true),
|
||||
resource('scheduleweeks', 'Рабочие недели'), resource('scheduleweekperiods', 'Рабочие периоды'),
|
||||
resource('requestgraphs', 'Графики обращений'), resource('incidentgraphs', 'Графики инцидентов'),
|
||||
resource('requesthistcalcs', 'Расчёты обращений', true), resource('incidenthistcalcs', 'Расчёты инцидентов', true),
|
||||
] },
|
||||
{ key: 'configuration-items', title: 'Configuration items', icon: 'mdi-vector-link', apiPrefix: 'cim', resources: [
|
||||
resource('cis', 'Конфигурационные единицы'),
|
||||
resource('types', 'Типы', false, 'ci-types'),
|
||||
resource('relations', 'Связи', false, 'ci-relations'),
|
||||
] },
|
||||
{ key: 'devices', title: 'Устройства', icon: 'mdi-devices', apiPrefix: 'dev', resources: [
|
||||
resource('manufacturers', 'Производители'), resource('models', 'Модели'),
|
||||
] },
|
||||
{ key: 'system', title: 'Система', icon: 'mdi-cog', apiPrefix: 'sys', resources: [
|
||||
resource('users', 'Пользователи'),
|
||||
resource('objects', 'Объекты'), resource('views', 'Представления'),
|
||||
resource('holidaygroups', 'Группы праздников', false, 'holiday-groups'), resource('holidayelements', 'Праздники'),
|
||||
resource('settings', 'Настройки'), resource('preferences', 'Предпочтения'),
|
||||
] },
|
||||
]
|
||||
|
||||
export function getModule(key: string) { return modules.find(item => item.key === key) }
|
||||
export function getResource(moduleKey: string, resourceKey: string) {
|
||||
return getModule(moduleKey)?.resources.find(item => item.key === resourceKey)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,82 @@
|
|||
export const themeColorValues = [
|
||||
'black',
|
||||
'white',
|
||||
'base',
|
||||
'indigo',
|
||||
'blue',
|
||||
'cyan',
|
||||
'teal',
|
||||
'green',
|
||||
'yellow',
|
||||
'amber',
|
||||
'orange',
|
||||
'deeporange',
|
||||
'red',
|
||||
'pink',
|
||||
'purple',
|
||||
'brown',
|
||||
'grey',
|
||||
] as const
|
||||
|
||||
export type ThemeColorName = typeof themeColorValues[number]
|
||||
|
||||
const colorHex: Record<Exclude<ThemeColorName, 'base'>, string> = {
|
||||
black: '#000000',
|
||||
white: '#FFFFFF',
|
||||
indigo: '#3F51B5',
|
||||
blue: '#2196F3',
|
||||
cyan: '#00BCD4',
|
||||
teal: '#009688',
|
||||
green: '#4CAF50',
|
||||
yellow: '#FFEB3B',
|
||||
amber: '#FFC107',
|
||||
orange: '#FF9800',
|
||||
deeporange: '#FF5722',
|
||||
red: '#F44336',
|
||||
pink: '#E91E63',
|
||||
purple: '#9C27B0',
|
||||
brown: '#795548',
|
||||
grey: '#9E9E9E',
|
||||
}
|
||||
|
||||
const titles: Record<ThemeColorName, { ru: string; en: string }> = {
|
||||
black: { ru: 'Чёрный', en: 'Black' },
|
||||
white: { ru: 'Белый', en: 'White' },
|
||||
base: { ru: 'Базовый', en: 'Base' },
|
||||
indigo: { ru: 'Индиго', en: 'Indigo' },
|
||||
blue: { ru: 'Синий', en: 'Blue' },
|
||||
cyan: { ru: 'Циан', en: 'Cyan' },
|
||||
teal: { ru: 'Бирюзовый', en: 'Teal' },
|
||||
green: { ru: 'Зелёный', en: 'Green' },
|
||||
yellow: { ru: 'Жёлтый', en: 'Yellow' },
|
||||
amber: { ru: 'Янтарный', en: 'Amber' },
|
||||
orange: { ru: 'Оранжевый', en: 'Orange' },
|
||||
deeporange: { ru: 'Тёмно-оранжевый', en: 'Deep orange' },
|
||||
red: { ru: 'Красный', en: 'Red' },
|
||||
pink: { ru: 'Розовый', en: 'Pink' },
|
||||
purple: { ru: 'Фиолетовый', en: 'Purple' },
|
||||
brown: { ru: 'Коричневый', en: 'Brown' },
|
||||
grey: { ru: 'Серый', en: 'Grey' },
|
||||
}
|
||||
|
||||
export function isThemeColorName(value: unknown): value is ThemeColorName {
|
||||
return typeof value === 'string' && themeColorValues.includes(value.toLowerCase() as ThemeColorName)
|
||||
}
|
||||
|
||||
export function normalizeThemeColor(value: unknown): ThemeColorName {
|
||||
return isThemeColorName(value) ? value.toLowerCase() as ThemeColorName : 'grey'
|
||||
}
|
||||
|
||||
export function resolveThemeColor(value: unknown, lightTheme = true) {
|
||||
const name = normalizeThemeColor(value)
|
||||
if (name === 'base') return lightTheme ? '#2356A8' : '#7AA7F8'
|
||||
return colorHex[name]
|
||||
}
|
||||
|
||||
export function getThemeColorOptions(language: 'ru' | 'en' = 'ru') {
|
||||
return themeColorValues.map(value => ({
|
||||
title: titles[value][language],
|
||||
value,
|
||||
color: resolveThemeColor(value),
|
||||
}))
|
||||
}
|
||||
|
|
@ -0,0 +1,180 @@
|
|||
# План разработки системы технической поддержки
|
||||
|
||||
## 1. Цель и границы проекта
|
||||
|
||||
Создать административный веб-интерфейс для сотрудников, в котором можно
|
||||
переходить между функциональными модулями, просматривать и фильтровать списки,
|
||||
выбирать объекты, создавать и редактировать их, а также выполнять специальные
|
||||
операции, предусмотренные API.
|
||||
|
||||
Первая версия охватывает модули:
|
||||
|
||||
| Раздел интерфейса | Префикс API | Основные сущности |
|
||||
| --- | --- | --- |
|
||||
| Addresses | `adr` | страны, регионы, районы, населённые пункты, улицы, дома, зоны и типы |
|
||||
| CRM | `crm` | клиенты, договоры, категории и типы |
|
||||
| Service | `srv` | сервисы, запросы, решения, статусы и типы |
|
||||
| Requests | `req` | обращения, комментарии, сотрудники, зависимости, статусы, критичности, уведомления и отчётные данные |
|
||||
| Incidents | `inc` | инциденты, комментарии, сотрудники, группы, CI, категории, приоритеты, статусы, решения и уведомления |
|
||||
| SLA | `sla` | соглашения, графики, статусы, расчёты, рабочие недели и периоды |
|
||||
| Configuration item | `cim` | конфигурационные единицы, типы, поля и связи |
|
||||
| Device | `dev` | производители, модели, аппаратные и программные версии |
|
||||
| System | `sys` | пользователи, профили, роли, наборы ролей, представления, поля, настройки и календари |
|
||||
|
||||
Дополнительные группы API `con` (каналы связи и уведомления) и `rep` (отчёты)
|
||||
следует подключать как общие подсистемы там, где они используются основными
|
||||
модулями. Их выделение в самостоятельные пункты меню согласуется отдельно.
|
||||
|
||||
## 2. Исходные данные и ограничения
|
||||
|
||||
- Контракт: OpenAPI 3.0.3, `http://localhost:10000/api/v1/schema/`.
|
||||
- Документация: `http://localhost:10000/api/v1/docs/`.
|
||||
- Основные ресурсы используют пагинированные списки и CRUD-операции
|
||||
`GET`, `POST`, `PUT`, `PATCH`, `DELETE`.
|
||||
- API защищён схемой `knoxApiToken`; точный сценарий входа, хранения и обновления
|
||||
токена нужно подтвердить до завершения каркаса авторизации.
|
||||
- Помимо CRUD имеются предметные действия: привязка зон, CI, вложений, ролей,
|
||||
статусов и календарей; эскалация и связывание обращений; пересчёт SLA;
|
||||
операции настройки системы.
|
||||
- Названия, обязательность полей, варианты фильтрации и права должны строиться
|
||||
по OpenAPI-схеме и проверяться на тестовом API, а не дублироваться вручную.
|
||||
|
||||
## 3. Архитектура фронтенда
|
||||
|
||||
### Базовый каркас
|
||||
|
||||
- Nuxt с TypeScript и Vuetify, SSR-режим выбирается после проверки требований
|
||||
развёртывания; для внутренней системы допустим SPA-режим.
|
||||
- Layout приложения: боковое меню модулей, верхняя панель, хлебные крошки,
|
||||
область уведомлений, меню пользователя.
|
||||
- Маршруты: `/addresses`, `/crm`, `/service`, `/requests`, `/incidents`, `/sla`,
|
||||
`/configuration-items`, `/devices`, `/system`, затем сущность и `id`.
|
||||
- Runtime-конфигурация для base URL API без встраивания адреса в исходный код.
|
||||
|
||||
### Слой данных
|
||||
|
||||
- Типизированный API-клиент, генерируемый из OpenAPI; кастомная обёртка только
|
||||
для авторизации, нормализации ошибок, отмены запросов и файловых операций.
|
||||
- Pinia используется только для общего состояния: сессии, пользователя,
|
||||
разрешений, справочников и настроек UI. Серверные списки не копируются без
|
||||
необходимости в глобальное хранилище.
|
||||
- Единые модели пагинации, сортировки и фильтров; состояние списка отражается
|
||||
в query-параметрах URL, чтобы ссылки можно было сохранять и пересылать.
|
||||
|
||||
### Переиспользуемый CRUD-каркас
|
||||
|
||||
- Таблица: серверная пагинация, сортировка, загрузка, пустое состояние, ошибки,
|
||||
настраиваемые колонки и массовый выбор.
|
||||
- Панель фильтров: текст, число, дата/диапазон, enum, boolean и связанный объект;
|
||||
применение, сброс и сохранение фильтров в URL.
|
||||
- Форма: конфигурация полей, синхронная и серверная валидация, защита от потери
|
||||
несохранённых изменений, создание и редактирование.
|
||||
- Выбор связанных объектов: асинхронный поиск, пагинация, единичный и
|
||||
множественный выбор.
|
||||
- Общие диалоги подтверждения удаления и предметных операций, уведомления об
|
||||
успехе/ошибке, обработка `401`, `403`, `404`, `409` и ошибок валидации.
|
||||
- Расширения сущности: вкладки связей, история, комментарии, вложения и SLA.
|
||||
|
||||
## 4. Этапы выполнения
|
||||
|
||||
### Этап 0. Уточнение требований и API
|
||||
|
||||
1. Зафиксировать роли пользователей и матрицу доступа к модулям и действиям.
|
||||
2. Уточнить сценарий аутентификации Knox, время жизни токена и выход из системы.
|
||||
3. Согласовать перечень колонок, обязательных фильтров и редактируемых полей для
|
||||
каждой сущности.
|
||||
4. Проверить CORS, загрузку/скачивание вложений, форматы дат, часовой пояс,
|
||||
локализацию и допустимые размеры страниц.
|
||||
5. Согласовать, какие системные и отчётные сущности доступны обычному сотруднику.
|
||||
|
||||
Результат: согласованный MVP, матрица ролей и проверенный контракт API.
|
||||
|
||||
### Этап 1. Инициализация приложения
|
||||
|
||||
1. Создать Nuxt-проект и подключить Vuetify, Pinia, линтер, форматтер и тесты.
|
||||
2. Настроить переменные окружения, aliases, тему, локализацию и базовые layouts.
|
||||
3. Добавить генерацию TypeScript-типов/клиента из OpenAPI в отдельную команду.
|
||||
4. Настроить CI: typecheck, lint, unit tests и production build.
|
||||
|
||||
Результат: запускаемый каркас с воспроизводимой сборкой.
|
||||
|
||||
### Этап 2. Платформенные функции
|
||||
|
||||
1. Реализовать вход, восстановление сессии, выход и route middleware.
|
||||
2. Реализовать навигацию с учётом разрешений.
|
||||
3. Создать API-обёртку и единый обработчик ошибок.
|
||||
4. Создать CRUD-компоненты таблицы, фильтров, форм и выбора связей.
|
||||
5. Добавить дизайн-токены, состояния загрузки/ошибки и адаптивность.
|
||||
|
||||
Результат: вертикальный срез на одной справочной сущности Addresses.
|
||||
|
||||
### Этап 3. Справочники и базовые зависимости
|
||||
|
||||
Порядок снижает число временных заглушек в связанных полях:
|
||||
|
||||
1. Addresses: географическая иерархия, типы, зоны, привязка зон.
|
||||
2. Device: производители, модели и версии.
|
||||
3. CRM: типы, категории, клиенты и договоры.
|
||||
4. Service: типы, статусы, сервисы, решения и запросы сервиса.
|
||||
5. Configuration item: типы и поля, затем CI и связи между ними.
|
||||
6. System: справочники, пользователи, роли и представления; опасные операции
|
||||
первоначальной настройки выводить только после отдельного согласования.
|
||||
|
||||
Результат: CRUD, фильтры и выбор объектов для базовых сущностей.
|
||||
|
||||
### Этап 4. Основные процессы поддержки
|
||||
|
||||
1. Requests: карточка обращения, история, комментарии, вложения, зависимости,
|
||||
связывание с инцидентом, эскалация и пересчёт SLA.
|
||||
2. Incidents: карточка инцидента, сотрудники и группы, CI, комментарии,
|
||||
вложения, переходы статусов, связанные обращения и пересчёт SLA.
|
||||
3. SLA: соглашения, статусы, календари, рабочие периоды, графики и результаты
|
||||
расчётов.
|
||||
4. Интегрировать уведомления `con` и отчётные данные `rep` в нужные карточки.
|
||||
|
||||
Результат: сквозной рабочий процесс от обращения до инцидента и контроля SLA.
|
||||
|
||||
### Этап 5. Качество и ввод в эксплуатацию
|
||||
|
||||
1. Unit-тесты composables, преобразования фильтров и валидации.
|
||||
2. Component-тесты таблиц, форм и выбора связанных объектов.
|
||||
3. E2E smoke-сценарии: вход, навигация, CRUD, фильтр, связь, вложение,
|
||||
эскалация, смена статуса и проверка прав.
|
||||
4. Проверка доступности с клавиатуры, контрастности и адаптивных разрешений.
|
||||
5. Проверка производительности больших списков и отмены устаревших запросов.
|
||||
6. Подготовить Docker/CI-конфигурацию, инструкцию развёртывания и руководство
|
||||
пользователя/администратора.
|
||||
|
||||
Результат: протестированный релиз-кандидат и эксплуатационная документация.
|
||||
|
||||
## 5. Критерии готовности сущности
|
||||
|
||||
Сущность считается реализованной, когда:
|
||||
|
||||
- список загружается с серверной пагинацией, сортировкой и согласованными фильтрами;
|
||||
- фильтры воспроизводятся из URL и корректно сбрасываются;
|
||||
- создание, просмотр, изменение и удаление соответствуют разрешениям API;
|
||||
- связанные объекты выбираются без загрузки всего справочника;
|
||||
- поля валидируются, серверные ошибки отображаются рядом с полями;
|
||||
- опасные операции требуют подтверждения, а несохранённые изменения защищены;
|
||||
- есть состояния загрузки, пустого результата, отсутствия доступа и ошибки;
|
||||
- ключевые сценарии покрыты unit/component-тестами и хотя бы одним E2E-сценарием;
|
||||
- typecheck, lint, тесты и production build проходят в CI.
|
||||
|
||||
## 6. Контрольные точки
|
||||
|
||||
1. **M1 — каркас:** авторизация, layout, API-клиент, общий CRUD и Addresses.
|
||||
2. **M2 — справочники:** CRM, Service, Device, Configuration item и System.
|
||||
3. **M3 — процессы:** Requests и Incidents со связями, файлами и историей.
|
||||
4. **M4 — SLA и отчётность:** соглашения, календари, расчёты и виджеты.
|
||||
5. **M5 — релиз:** права, E2E, документация, сборка и развёртывание.
|
||||
|
||||
Оценку сроков следует выполнять после этапа 0: OpenAPI содержит более сотни
|
||||
ресурсов и специальные действия, поэтому оценка только по числу верхнеуровневых
|
||||
модулей будет недостоверной.
|
||||
|
||||
## 7. Ближайший следующий шаг
|
||||
|
||||
Провести короткую сессию уточнения этапа 0 и выбрать одну справочную сущность
|
||||
Addresses как эталонный вертикальный срез. После подтверждения сценария входа и
|
||||
полей этой сущности можно создавать Nuxt-приложение и общий CRUD-каркас.
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
<script setup lang="ts">defineProps<{ error: { statusCode?: number; statusMessage?: string; message?: string } }>()</script>
|
||||
<template><v-app><v-main class="d-flex align-center"><v-container class="text-center"><div class="text-h1 font-weight-bold text-primary">{{ error.statusCode || 500 }}</div>
|
||||
<h1 class="text-h5 my-4">{{ error.statusMessage || error.message || 'Произошла ошибка' }}</h1><v-btn color="primary" to="/">На главную</v-btn></v-container></v-main></v-app></template>
|
||||
|
|
@ -0,0 +1 @@
|
|||
<template><v-app><v-main class="d-flex align-center bg-grey-lighten-4"><v-container><slot /></v-container></v-main></v-app></template>
|
||||
|
|
@ -0,0 +1,64 @@
|
|||
<script setup lang="ts">
|
||||
import { modules } from '~/config/modules'
|
||||
|
||||
const drawer = ref(true)
|
||||
const route = useRoute()
|
||||
const auth = useAuthStore()
|
||||
const permissions = usePermissions()
|
||||
const { t } = useUiText()
|
||||
const visibleModules = computed(() => modules.map(module => ({
|
||||
...module,
|
||||
resources: module.resources.filter(resource => permissions.canView(module.key, module.apiPrefix, resource.key)),
|
||||
})).filter(module => module.resources.length > 0))
|
||||
const menuGroupTitles: Record<string, string> = {
|
||||
settings: 'Настройки',
|
||||
}
|
||||
const ungroupedResources = (resources: typeof modules[number]['resources']) =>
|
||||
resources.filter(resource => !resource.menuGroup)
|
||||
const groupedResources = (resources: typeof modules[number]['resources']) =>
|
||||
Object.entries(Object.groupBy(
|
||||
resources.filter(resource => resource.menuGroup),
|
||||
resource => resource.menuGroup!,
|
||||
))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<v-app>
|
||||
<v-navigation-drawer v-model="drawer" width="290">
|
||||
<div class="pa-5 d-flex align-center ga-3">
|
||||
<v-avatar color="primary" rounded="lg"><v-icon>mdi-lifebuoy</v-icon></v-avatar>
|
||||
<div><div class="font-weight-bold">WANITIL</div><div class="text-caption text-medium-emphasis">Техническая поддержка</div></div>
|
||||
</div>
|
||||
<v-divider />
|
||||
<v-list nav density="comfortable" class="pa-3">
|
||||
<v-list-item to="/" prepend-icon="mdi-view-dashboard-outline" :title="t('dashboard')" exact />
|
||||
<v-list-group v-for="module in visibleModules" :key="module.key" :value="module.key">
|
||||
<template #activator="{ props }"><v-list-item v-bind="props" :prepend-icon="module.icon" :title="module.title" /></template>
|
||||
<v-list-item v-for="item in ungroupedResources(module.resources)" :key="item.key"
|
||||
:to="`/${module.key}/${item.key}`" :title="item.title" />
|
||||
<v-list-group v-for="[group, items] in groupedResources(module.resources)"
|
||||
:key="group" :value="`${module.key}-${group}`">
|
||||
<template #activator="{ props }">
|
||||
<v-list-item v-bind="props" prepend-icon="mdi-cog-outline"
|
||||
:title="menuGroupTitles[group] || group" />
|
||||
</template>
|
||||
<v-list-item v-for="item in items" :key="item.key"
|
||||
:to="`/${module.key}/${item.key}`" :title="item.title" />
|
||||
</v-list-group>
|
||||
</v-list-group>
|
||||
</v-list>
|
||||
</v-navigation-drawer>
|
||||
<v-app-bar elevation="0" border>
|
||||
<v-app-bar-nav-icon @click="drawer = !drawer" />
|
||||
<v-app-bar-title>{{ route.meta.title || 'WANITIL Support' }}</v-app-bar-title>
|
||||
<v-spacer />
|
||||
<v-btn icon="mdi-bell-outline" :aria-label="t('notifications')" />
|
||||
<v-menu>
|
||||
<template #activator="{ props }"><v-btn v-bind="props" prepend-icon="mdi-account-circle" :text="auth.user?.name || auth.user?.username || t('profile')" /></template>
|
||||
<v-list><v-list-item to="/profile" prepend-icon="mdi-account-edit" :title="t('profile')" />
|
||||
<v-list-item prepend-icon="mdi-logout" :title="t('logout')" @click="auth.logout" /></v-list>
|
||||
</v-menu>
|
||||
</v-app-bar>
|
||||
<v-main><v-container fluid class="pa-6"><slot /></v-container></v-main>
|
||||
</v-app>
|
||||
</template>
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
export default defineNuxtRouteMiddleware(async to => {
|
||||
const token = useCookie<string | null>('wanitil-token')
|
||||
if (!token.value && to.path !== '/login') return navigateTo('/login')
|
||||
if (token.value && to.path === '/login') return navigateTo('/')
|
||||
if (token.value) {
|
||||
try { await useAuthStore().restoreSession() }
|
||||
catch { if (to.path !== '/login') return navigateTo('/login') }
|
||||
}
|
||||
})
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
import vuetify, { transformAssetUrls } from 'vite-plugin-vuetify'
|
||||
|
||||
export default defineNuxtConfig({
|
||||
compatibilityDate: '2024-07-20',
|
||||
devtools: { enabled: true },
|
||||
ssr: false,
|
||||
modules: [
|
||||
'@pinia/nuxt',
|
||||
(_options, nuxt) => {
|
||||
nuxt.hooks.hook('vite:extendConfig', config => {
|
||||
config.plugins?.push(vuetify({ autoImport: true }))
|
||||
})
|
||||
},
|
||||
],
|
||||
build: { transpile: ['vuetify'] },
|
||||
vite: { vue: { template: { transformAssetUrls } } },
|
||||
css: ['vuetify/styles', '@mdi/font/css/materialdesignicons.css', '~/assets/main.css'],
|
||||
runtimeConfig: {
|
||||
public: {
|
||||
apiBase: process.env.NUXT_PUBLIC_API_BASE || 'http://localhost:10000/api/v1',
|
||||
},
|
||||
},
|
||||
app: {
|
||||
head: {
|
||||
title: 'WANITIL Support',
|
||||
meta: [{ name: 'description', content: 'Система технической поддержки сотрудников' }],
|
||||
},
|
||||
},
|
||||
typescript: { strict: true, typeCheck: true },
|
||||
})
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,38 @@
|
|||
{
|
||||
"name": "wanitil-support-frontend",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "nuxt dev",
|
||||
"build": "nuxt build",
|
||||
"generate": "nuxt generate",
|
||||
"preview": "nuxt preview",
|
||||
"generate:schemas": "node scripts/generate-resource-schemas.mjs",
|
||||
"typecheck": "nuxt typecheck",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@mdi/font": "7.4.47",
|
||||
"@pinia/nuxt": "0.5.1",
|
||||
"nuxt": "3.12.4",
|
||||
"pinia": "2.1.7",
|
||||
"vite-plugin-vuetify": "2.0.3",
|
||||
"vue": "3.4.31",
|
||||
"vuetify": "3.6.10",
|
||||
"yaml": "2.5.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "20.14.12",
|
||||
"nuxi": "3.12.0",
|
||||
"typescript": "5.5.4",
|
||||
"vue-tsc": "2.0.29",
|
||||
"vitest": "2.0.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
},
|
||||
"overrides": {
|
||||
"nuxi": "3.12.0",
|
||||
"nitropack": "2.9.7"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
<script setup lang="ts">
|
||||
import { getModule, getResource } from '~/config/modules'
|
||||
const route = useRoute()
|
||||
const moduleDefinition = computed(() => getModule(String(route.params.module)))
|
||||
const resourceDefinition = computed(() => getResource(String(route.params.module), String(route.params.resource)))
|
||||
if (!moduleDefinition.value || !resourceDefinition.value) throw createError({ statusCode: 404, statusMessage: 'Раздел не найден' })
|
||||
if (!usePermissions().canView(moduleDefinition.value.key, moduleDefinition.value.apiPrefix, resourceDefinition.value.key)) throw createError({ statusCode: 403, statusMessage: 'Недостаточно прав' })
|
||||
useHead({ title: `${resourceDefinition.value.title} · WANITIL` })
|
||||
</script>
|
||||
<template><ResourceCrud :module="moduleDefinition!" :resource="resourceDefinition!" /></template>
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
<script setup lang="ts">
|
||||
import { getModule } from '~/config/modules'
|
||||
const route = useRoute(); const moduleDefinition = computed(() => getModule(String(route.params.module)))
|
||||
if (!moduleDefinition.value) throw createError({ statusCode: 404, statusMessage: 'Модуль не найден' })
|
||||
const permissions = usePermissions()
|
||||
const firstResource = moduleDefinition.value.resources.find(resource => permissions.canView(moduleDefinition.value!.key, moduleDefinition.value!.apiPrefix, resource.key))
|
||||
if (!firstResource) throw createError({ statusCode: 403, statusMessage: 'Недостаточно прав' })
|
||||
await navigateTo(`/${moduleDefinition.value.key}/${firstResource.key}`, { replace: true })
|
||||
</script>
|
||||
<template><div /></template>
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
<script setup lang="ts">
|
||||
import { modules } from '~/config/modules'
|
||||
const permissions = usePermissions()
|
||||
const { t } = useUiText()
|
||||
const visibleModules = computed(() => modules.map(module => ({
|
||||
...module,
|
||||
resources: module.resources.filter(resource => permissions.canView(module.key, module.apiPrefix, resource.key)),
|
||||
})).filter(module => module.resources.length > 0))
|
||||
</script>
|
||||
<template><div class="page-shell"><h1 class="text-h4 font-weight-bold mb-2">{{ t('workspace') }}</h1>
|
||||
<p class="text-medium-emphasis mb-7">{{ t('workspaceHint') }}</p>
|
||||
<v-row><v-col v-for="module in visibleModules" :key="module.key" cols="12" sm="6" lg="4">
|
||||
<v-card :to="`/${module.key}/${module.resources[0]?.key}`" class="pa-5 h-100" hover>
|
||||
<v-avatar color="primary" variant="tonal" rounded="lg" class="mb-4"><v-icon>{{ module.icon }}</v-icon></v-avatar>
|
||||
<div class="text-h6">{{ module.title }}</div><div class="text-body-2 text-medium-emphasis">{{ module.resources.length }} {{ t('sections') }}</div>
|
||||
</v-card></v-col></v-row></div></template>
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
<script setup lang="ts">
|
||||
definePageMeta({ layout: 'auth' })
|
||||
const auth = useAuthStore()
|
||||
const route = useRoute()
|
||||
const username = ref('')
|
||||
const password = ref('')
|
||||
const error = ref('')
|
||||
async function submit() {
|
||||
error.value = ''
|
||||
try {
|
||||
await auth.login(username.value, password.value)
|
||||
const redirect = typeof route.query.redirect === 'string' && route.query.redirect.startsWith('/')
|
||||
? route.query.redirect
|
||||
: '/'
|
||||
await navigateTo(redirect)
|
||||
}
|
||||
catch (e: any) { error.value = e.message || 'Не удалось войти' }
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<v-card max-width="440" class="mx-auto pa-7" elevation="8">
|
||||
<div class="text-center mb-7"><v-avatar color="primary" size="56" rounded="lg"><v-icon size="32">mdi-lifebuoy</v-icon></v-avatar>
|
||||
<h1 class="text-h5 mt-4">WANITIL Support</h1><p class="text-medium-emphasis">Вход для сотрудников</p></div>
|
||||
<v-alert v-if="error" type="error" variant="tonal" class="mb-4">{{ error }}</v-alert>
|
||||
<v-form @submit.prevent="submit">
|
||||
<v-text-field v-model="username" label="Имя пользователя" autocomplete="username" required autofocus />
|
||||
<v-text-field v-model="password" label="Пароль" type="password" autocomplete="current-password" required />
|
||||
<v-btn type="submit" color="primary" block size="large" :loading="auth.loading">Войти</v-btn>
|
||||
</v-form>
|
||||
</v-card>
|
||||
</template>
|
||||
|
|
@ -0,0 +1,87 @@
|
|||
<script setup lang="ts">
|
||||
import type { UserProfile } from '~/types/api'
|
||||
import { getThemeColorOptions, normalizeThemeColor, resolveThemeColor } from '~/config/theme-colors'
|
||||
|
||||
const auth = useAuthStore()
|
||||
const { language } = useUiPreferences()
|
||||
const saving = ref(false)
|
||||
const saved = ref(false)
|
||||
const error = ref('')
|
||||
const form = reactive<Partial<UserProfile>>({})
|
||||
const original = ref<UserProfile | null>(null)
|
||||
const isEnglish = computed(() => language.value === 'en')
|
||||
const themeColorOptions = computed(() => getThemeColorOptions(isEnglish.value ? 'en' : 'ru'))
|
||||
const languages = [
|
||||
{ title: 'Русский', value: 'ru' },
|
||||
{ title: 'English', value: 'en' },
|
||||
]
|
||||
|
||||
function reset() {
|
||||
Object.assign(form, auth.profile || {})
|
||||
form.theme_color = normalizeThemeColor(auth.profile?.theme_color)
|
||||
original.value = auth.profile ? { ...auth.profile } : null
|
||||
}
|
||||
watch(() => auth.profile, reset, { immediate: true })
|
||||
watch(form, value => {
|
||||
if (auth.profile) auth.profile = { ...auth.profile, ...value } as UserProfile
|
||||
}, { deep: true })
|
||||
|
||||
async function save() {
|
||||
saving.value = true; error.value = ''
|
||||
try {
|
||||
await auth.updateProfile({
|
||||
lang: form.lang, status: form.status, timezone: form.timezone,
|
||||
theme_is_light: form.theme_is_light, theme_color: form.theme_color,
|
||||
})
|
||||
original.value = auth.profile ? { ...auth.profile } : null
|
||||
saved.value = true
|
||||
} catch (e: any) { error.value = e.message || 'Не удалось сохранить профиль' }
|
||||
finally { saving.value = false }
|
||||
}
|
||||
function cancel() {
|
||||
if (original.value) auth.profile = { ...original.value }
|
||||
reset()
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="page-shell" style="max-width: 1000px">
|
||||
<h1 class="text-h4 font-weight-bold mb-2">{{ isEnglish ? 'Profile' : 'Профиль' }}</h1>
|
||||
<p class="text-medium-emphasis mb-6">{{ isEnglish ? 'Personal settings are applied immediately.' : 'Персональные настройки применяются сразу.' }}</p>
|
||||
<v-alert v-if="error" type="error" closable class="mb-4" @click:close="error = ''">{{ error }}</v-alert>
|
||||
<v-snackbar v-model="saved" color="success">{{ isEnglish ? 'Profile saved' : 'Профиль сохранён' }}</v-snackbar>
|
||||
<v-row>
|
||||
<v-col cols="12" md="7"><v-card class="pa-6">
|
||||
<h2 class="text-h6 mb-5">{{ isEnglish ? 'Appearance' : 'Оформление' }}</h2>
|
||||
<v-select v-model="form.lang" :items="languages" :label="isEnglish ? 'Interface language' : 'Язык интерфейса'" />
|
||||
<v-switch v-model="form.theme_is_light" color="primary" inset
|
||||
:label="form.theme_is_light ? (isEnglish ? 'Light theme' : 'Светлая тема') : (isEnglish ? 'Dark theme' : 'Тёмная тема')" />
|
||||
<v-select v-model="form.theme_color" :items="themeColorOptions"
|
||||
:label="isEnglish ? 'Primary color' : 'Основной цвет'">
|
||||
<template #prepend-inner>
|
||||
<v-icon icon="mdi-circle" :color="resolveThemeColor(form.theme_color, form.theme_is_light !== false)" />
|
||||
</template>
|
||||
<template #item="{ props: itemProps, item }">
|
||||
<v-list-item v-bind="itemProps">
|
||||
<template #prepend><v-icon icon="mdi-circle" :color="item.raw.color" /></template>
|
||||
</v-list-item>
|
||||
</template>
|
||||
</v-select>
|
||||
<v-text-field v-model.number="form.timezone" :label="isEnglish ? 'Timezone code' : 'Код часового пояса'" type="number" />
|
||||
<div class="d-flex justify-end ga-2 mt-4"><v-btn variant="text" @click="cancel">{{ isEnglish ? 'Cancel' : 'Отмена' }}</v-btn>
|
||||
<v-btn color="primary" :loading="saving" @click="save">{{ isEnglish ? 'Save' : 'Сохранить' }}</v-btn></div>
|
||||
</v-card></v-col>
|
||||
<v-col cols="12" md="5"><v-card class="pa-6 mb-4">
|
||||
<h2 class="text-h6 mb-4">{{ isEnglish ? 'Account' : 'Учётная запись' }}</h2>
|
||||
<v-list density="compact"><v-list-item prepend-icon="mdi-account" :title="auth.user?.name || auth.user?.username" :subtitle="auth.user?.username" />
|
||||
<v-list-item prepend-icon="mdi-email-outline" :title="auth.user?.email || '—'" /></v-list>
|
||||
</v-card><v-card class="pa-6"><h2 class="text-h6 mb-3">{{ isEnglish ? 'Session roles' : 'Роли сессии' }}</h2>
|
||||
<v-chip v-for="role in auth.roles" :key="role.id" class="ma-1" color="primary" variant="tonal">{{ role.name }}</v-chip>
|
||||
<p v-if="!auth.roles.length" class="text-medium-emphasis">{{ isEnglish ? 'No roles assigned' : 'Роли не назначены' }}</p>
|
||||
<v-divider v-if="auth.allowedObjects.length" class="my-4" />
|
||||
<div v-if="auth.allowedObjects.length" class="text-subtitle-2 mb-2">{{ isEnglish ? 'Available objects' : 'Доступные объекты' }}</div>
|
||||
<v-chip v-for="object in auth.allowedObjects" :key="object.id" class="ma-1" size="small" variant="outlined">{{ object.name }}</v-chip>
|
||||
</v-card></v-col>
|
||||
</v-row>
|
||||
</div>
|
||||
</template>
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
import { createVuetify } from 'vuetify'
|
||||
import { ru } from 'vuetify/locale'
|
||||
|
||||
export default defineNuxtPlugin(nuxtApp => {
|
||||
const vuetify = createVuetify({
|
||||
locale: { locale: 'ru', fallback: 'ru', messages: { ru } },
|
||||
theme: {
|
||||
defaultTheme: 'wanitilLight',
|
||||
themes: {
|
||||
wanitilLight: {
|
||||
dark: false,
|
||||
colors: {
|
||||
primary: '#2356A8', secondary: '#60758F', accent: '#00A3A3',
|
||||
background: '#F4F7FB', surface: '#FFFFFF', error: '#B42318',
|
||||
success: '#16845B', warning: '#B54708',
|
||||
},
|
||||
},
|
||||
wanitilDark: {
|
||||
dark: true,
|
||||
colors: {
|
||||
primary: '#7AA7F8', secondary: '#A9B8CC', accent: '#49D6D6',
|
||||
background: '#10141C', surface: '#181E28', error: '#FFB4AB',
|
||||
success: '#65D6A6', warning: '#FFB86B',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
defaults: {
|
||||
VBtn: { rounded: 'lg' }, VCard: { rounded: 'xl' },
|
||||
VTextField: { variant: 'outlined', density: 'comfortable' },
|
||||
VSelect: { variant: 'outlined', density: 'comfortable' },
|
||||
},
|
||||
})
|
||||
nuxtApp.vueApp.use(vuetify)
|
||||
})
|
||||
|
|
@ -0,0 +1,56 @@
|
|||
import { readFile, writeFile } from 'node:fs/promises'
|
||||
import { resolve as resolvePath } from 'node:path'
|
||||
import { parse } from 'yaml'
|
||||
|
||||
const source = resolvePath(process.argv[2] || 'openapi.yaml')
|
||||
const target = resolvePath(process.argv[3] || 'config/resource-schemas.json')
|
||||
const document = parse(await readFile(source, 'utf8'))
|
||||
|
||||
function dereference(value, references = new Set()) {
|
||||
if (!value || typeof value !== 'object') return value
|
||||
if (Array.isArray(value)) return value.map(item => dereference(item, references))
|
||||
if (value.$ref) {
|
||||
if (references.has(value.$ref)) return { type: 'object' }
|
||||
const nextReferences = new Set(references).add(value.$ref)
|
||||
const targetSchema = value.$ref
|
||||
.split('/')
|
||||
.slice(1)
|
||||
.reduce((current, key) => current?.[key], document)
|
||||
return dereference(targetSchema, nextReferences)
|
||||
}
|
||||
if (value.allOf) {
|
||||
const ownProperties = Object.fromEntries(Object.entries(value).filter(([key]) => key !== 'allOf'))
|
||||
return Object.assign({}, ...value.allOf.map(item => dereference(item, references)), dereference(ownProperties, references))
|
||||
}
|
||||
return Object.fromEntries(
|
||||
Object.entries(value).map(([key, child]) => [key, dereference(child, references)]),
|
||||
)
|
||||
}
|
||||
|
||||
function requestSchema(operation) {
|
||||
const content = operation?.requestBody?.content
|
||||
const root = content?.['application/json']?.schema
|
||||
|| content?.['application/x-www-form-urlencoded']?.schema
|
||||
|| content?.['multipart/form-data']?.schema
|
||||
return root ? dereference(root) : null
|
||||
}
|
||||
|
||||
const registry = {}
|
||||
for (const [openApiPath, operations] of Object.entries(document.paths || {})) {
|
||||
if (!/^\/api\/v1\/main\/[a-z]+\/[a-z-]+\/$/.test(openApiPath)) continue
|
||||
const apiPath = openApiPath.replace(/^\/api\/v1/, '')
|
||||
const post = requestSchema(operations.post)
|
||||
const detail = document.paths?.[`${openApiPath}{id}/`]
|
||||
const patch = requestSchema(detail?.patch)
|
||||
const put = requestSchema(detail?.put)
|
||||
if (post || patch || put) {
|
||||
registry[apiPath] = {
|
||||
...(post ? { post } : {}),
|
||||
...(patch ? { patch } : {}),
|
||||
...(put ? { put } : {}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await writeFile(target, `${JSON.stringify(registry, null, 2)}\n`)
|
||||
process.stdout.write(`Generated ${Object.keys(registry).length} resource schema entries in ${target}\n`)
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
import resourceSchemas from '~/config/resource-schemas.json'
|
||||
|
||||
type Method = 'post' | 'patch' | 'put'
|
||||
type Schema = Record<string, any>
|
||||
type Registry = Record<string, Partial<Record<Method, Schema>>>
|
||||
|
||||
const registry = resourceSchemas as Registry
|
||||
|
||||
export default defineEventHandler(event => {
|
||||
const query = getQuery(event)
|
||||
const apiPath = String(query.path || '')
|
||||
const method = String(query.method || 'post').toLowerCase() as Method
|
||||
|
||||
if (!/^\/main\/[a-z]+\/[a-z-]+\/$/.test(apiPath)) {
|
||||
throw createError({ statusCode: 400, statusMessage: 'Некорректный путь ресурса' })
|
||||
}
|
||||
if (!['post', 'patch', 'put'].includes(method)) {
|
||||
throw createError({ statusCode: 400, statusMessage: 'Некорректный метод схемы' })
|
||||
}
|
||||
|
||||
const schemas = registry[apiPath]
|
||||
const schema = schemas?.[method]
|
||||
|| (method === 'patch' ? schemas?.put : undefined)
|
||||
|| (method !== 'post' ? schemas?.post : undefined)
|
||||
|
||||
if (!schema) {
|
||||
throw createError({
|
||||
statusCode: 404,
|
||||
statusMessage: `Статическая схема формы не найдена: ${method.toUpperCase()} ${apiPath}`,
|
||||
})
|
||||
}
|
||||
return schema
|
||||
})
|
||||
|
|
@ -0,0 +1,80 @@
|
|||
import type { ManagementObject, PermissionsResponse, SessionUser, UserManagement, UserProfile, UserRole } from '~/types/api'
|
||||
import { normalizeThemeColor } from '~/config/theme-colors'
|
||||
|
||||
interface LoginResponse { token?: string; expiry?: string }
|
||||
|
||||
export const useAuthStore = defineStore('auth', () => {
|
||||
const { request, token } = useApi()
|
||||
const user = ref<SessionUser | null>(null)
|
||||
const profile = ref<UserProfile | null>(null)
|
||||
const roles = ref<UserRole[]>([])
|
||||
const allowedObjects = ref<ManagementObject[]>([])
|
||||
const permissions = ref<Record<string, string[]> | null>(null)
|
||||
const loading = ref(false)
|
||||
const initialized = ref(false)
|
||||
const authenticated = computed(() => Boolean(token.value))
|
||||
|
||||
async function login(username: string, password: string) {
|
||||
loading.value = true
|
||||
try {
|
||||
const result = await request<LoginResponse>('/login/', { method: 'POST', body: { username, password } })
|
||||
if (!result.token) throw new Error('API не вернул токен авторизации')
|
||||
token.value = result.token
|
||||
try { await loadSession() }
|
||||
catch (error) { token.value = null; throw error }
|
||||
} finally { loading.value = false }
|
||||
}
|
||||
|
||||
async function loadSession() {
|
||||
const [current, permissionResult] = await Promise.all([
|
||||
request<SessionUser>('/me/'),
|
||||
request<PermissionsResponse>('/me/permissions/').catch(() => null),
|
||||
])
|
||||
user.value = current
|
||||
roles.value = current.sys_role || []
|
||||
permissions.value = permissionResult?.resources || null
|
||||
const managementIds = [...new Set(roles.value.map(role => role.sys_managment?.id).filter((id): id is number => typeof id === 'number'))]
|
||||
const managementResults = await Promise.allSettled(
|
||||
managementIds.map(id => request<UserManagement>(`/main/sys/managments/${id}/`)),
|
||||
)
|
||||
const objects = managementResults.flatMap(result => result.status === 'fulfilled' ? result.value.sys_object || [] : [])
|
||||
allowedObjects.value = [...new Map(objects.map(object => [object.id, object])).values()]
|
||||
profile.value = current.sys_user_profile || null
|
||||
initialized.value = true
|
||||
}
|
||||
|
||||
async function restoreSession() {
|
||||
if (!token.value || initialized.value) return
|
||||
loading.value = true
|
||||
try { await loadSession() }
|
||||
catch (error) { token.value = null; user.value = null; profile.value = null; roles.value = []; allowedObjects.value = []; permissions.value = null; throw error }
|
||||
finally { loading.value = false; initialized.value = true }
|
||||
}
|
||||
|
||||
async function updateProfile(changes: Partial<UserProfile>) {
|
||||
if (!user.value) throw new Error('Пользователь не загружен')
|
||||
const body = {
|
||||
...changes,
|
||||
...(changes.theme_color !== undefined
|
||||
? { theme_color: normalizeThemeColor(changes.theme_color) }
|
||||
: {}),
|
||||
}
|
||||
profile.value = await request<UserProfile>('/main/sys/users/me/updateprofile/', { method: 'POST', body })
|
||||
user.value = { ...user.value, sys_user_profile: profile.value }
|
||||
}
|
||||
|
||||
async function logout() {
|
||||
try { if (token.value) await request('/logout/', { method: 'POST' }) } finally {
|
||||
token.value = null
|
||||
user.value = null
|
||||
profile.value = null
|
||||
roles.value = []
|
||||
allowedObjects.value = []
|
||||
permissions.value = null
|
||||
initialized.value = false
|
||||
await navigateTo('/login')
|
||||
}
|
||||
}
|
||||
|
||||
return { user, profile, roles, allowedObjects, permissions, loading, initialized, authenticated, login, logout, restoreSession, updateProfile }
|
||||
})
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
EnumFilterComparison,
|
||||
comparisonsFor,
|
||||
filterComparisons,
|
||||
normalizeFilterType,
|
||||
} from '../config/filter-comparisons'
|
||||
|
||||
describe('filter comparisons', () => {
|
||||
it('contains every named comparison', () => {
|
||||
expect(Object.keys(EnumFilterComparison)).toHaveLength(38)
|
||||
expect(filterComparisons).toHaveLength(38)
|
||||
expect(EnumFilterComparison.strIContains).toEqual({
|
||||
name1: 'IContains',
|
||||
name2: '..Aa..',
|
||||
value: 'icontains',
|
||||
filterType: 'str',
|
||||
inputType: 'str',
|
||||
})
|
||||
})
|
||||
|
||||
it('returns comparisons only for the selected field type', () => {
|
||||
const comparisons = comparisonsFor('integer')
|
||||
|
||||
expect(comparisons).toHaveLength(7)
|
||||
expect(comparisons.every(item => item.filterType === 'int')).toBe(true)
|
||||
expect(comparisons.find(item => item.value === 'in')?.inputType).toBe('str')
|
||||
expect(comparisons.find(item => item.value === 'isnull')?.inputType).toBe('bool')
|
||||
})
|
||||
|
||||
it('normalizes API field type aliases and falls back to string', () => {
|
||||
expect(normalizeFilterType('decimal')).toBe('float')
|
||||
expect(normalizeFilterType('timestamp')).toBe('datetime')
|
||||
expect(normalizeFilterType('boolean')).toBe('bool')
|
||||
expect(normalizeFilterType(undefined)).toBe('str')
|
||||
})
|
||||
})
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
import { describe, expect, it } from 'vitest'
|
||||
import { getModule, getResource, modules } from '../config/modules'
|
||||
|
||||
describe('module registry', () => {
|
||||
it('contains every required support module', () => {
|
||||
expect(modules.map(module => module.key)).toEqual([
|
||||
'addresses', 'crm', 'service', 'requests', 'incidents', 'sla',
|
||||
'configuration-items', 'devices', 'system',
|
||||
])
|
||||
})
|
||||
|
||||
it('uses unique module and resource keys', () => {
|
||||
expect(new Set(modules.map(module => module.key)).size).toBe(modules.length)
|
||||
for (const module of modules) {
|
||||
expect(new Set(module.resources.map(resource => resource.key)).size).toBe(module.resources.length)
|
||||
expect(module.resources.length).toBeGreaterThan(0)
|
||||
}
|
||||
})
|
||||
|
||||
it('resolves configured resources', () => {
|
||||
expect(getModule('incidents')?.apiPrefix).toBe('inc')
|
||||
expect(getResource('requests', 'requests')?.title).toBe('Обращения')
|
||||
expect(getResource('system', 'holidaygroups')?.path).toBe('holiday-groups')
|
||||
expect(getResource('system', 'holidayelements')?.path).toBe('holidayelements')
|
||||
expect(getResource('configuration-items', 'types')?.path).toBe('ci-types')
|
||||
expect(getResource('configuration-items', 'relations')?.path).toBe('ci-relations')
|
||||
expect(getResource('addresses', 'towntypes')?.path).toBe('town-types')
|
||||
expect(getResource('addresses', 'streettypes')?.path).toBe('street-types')
|
||||
expect(getResource('addresses', 'housetypes')?.path).toBe('house-types')
|
||||
expect(getResource('addresses', 'zonetypes')?.path).toBe('zone-types')
|
||||
expect(getResource('crm', 'categories')?.path).toBe('client-categories')
|
||||
expect(getResource('crm', 'types')?.path).toBe('client-types')
|
||||
expect(getResource('service', 'requests')?.path).toBe('request-types')
|
||||
expect(getResource('requests', 'sourcetypes')?.path).toBe('source-types')
|
||||
expect(getResource('incidents', 'statustransits')?.path).toBe('status-transitions')
|
||||
expect(getResource('missing', 'requests')).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
import { describe, expect, it } from 'vitest'
|
||||
import resourceSchemas from '../config/resource-schemas.json'
|
||||
import { modules } from '../config/modules'
|
||||
|
||||
describe('static resource form schemas', () => {
|
||||
it('contains schemas for every editable configured resource', () => {
|
||||
const missing = modules.flatMap(module => module.resources
|
||||
.filter(resource => !resource.readOnly)
|
||||
.map(resource => `/main/${module.apiPrefix}/${resource.path}/`)
|
||||
.filter(path => !(path in resourceSchemas)))
|
||||
|
||||
expect(missing).toEqual([])
|
||||
})
|
||||
|
||||
it('preserves JSON Schema required fields as arrays', () => {
|
||||
for (const methods of Object.values(resourceSchemas)) {
|
||||
for (const schema of Object.values(methods)) {
|
||||
if (schema.required !== undefined) expect(Array.isArray(schema.required)).toBe(true)
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
import { describe, expect, it } from 'vitest'
|
||||
import { normalizeThemeColor, resolveThemeColor, themeColorValues } from '../config/theme-colors'
|
||||
|
||||
describe('theme colors', () => {
|
||||
it('contains every supported API value', () => {
|
||||
expect(themeColorValues).toEqual([
|
||||
'black', 'white', 'base', 'indigo', 'blue', 'cyan', 'teal', 'green',
|
||||
'yellow', 'amber', 'orange', 'deeporange', 'red', 'pink', 'purple',
|
||||
'brown', 'grey',
|
||||
])
|
||||
})
|
||||
|
||||
it('uses grey for an unknown value', () => {
|
||||
expect(normalizeThemeColor('#2356A8')).toBe('grey')
|
||||
expect(resolveThemeColor('unknown')).toBe('#9E9E9E')
|
||||
})
|
||||
|
||||
it('resolves base for light and dark themes', () => {
|
||||
expect(resolveThemeColor('base', true)).toBe('#2356A8')
|
||||
expect(resolveThemeColor('base', false)).toBe('#7AA7F8')
|
||||
})
|
||||
})
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
{
|
||||
"extends": "./.nuxt/tsconfig.json"
|
||||
}
|
||||
|
|
@ -0,0 +1,76 @@
|
|||
export type ApiRecord = Record<string, unknown> & { id?: string | number }
|
||||
|
||||
export interface PaginatedResponse<T> {
|
||||
count: number
|
||||
next: string | null
|
||||
previous: string | null
|
||||
results: T[]
|
||||
}
|
||||
|
||||
export interface ApiErrorPayload {
|
||||
detail?: string
|
||||
non_field_errors?: string[]
|
||||
[field: string]: unknown
|
||||
}
|
||||
|
||||
export interface ResourceDefinition {
|
||||
key: string
|
||||
title: string
|
||||
path: string
|
||||
readOnly?: boolean
|
||||
menuGroup?: string
|
||||
}
|
||||
|
||||
export interface ModuleDefinition {
|
||||
key: string
|
||||
title: string
|
||||
icon: string
|
||||
apiPrefix: string
|
||||
resources: ResourceDefinition[]
|
||||
}
|
||||
|
||||
export interface UserProfile {
|
||||
sys_user_id: number
|
||||
lang?: string
|
||||
status?: number
|
||||
timezone?: number
|
||||
theme_is_light?: boolean
|
||||
theme_color?: string
|
||||
info?: string
|
||||
name?: string
|
||||
}
|
||||
|
||||
export interface UserRole {
|
||||
id: number
|
||||
name: string
|
||||
sys_managment?: { id: number; name: string }
|
||||
info?: string
|
||||
}
|
||||
|
||||
export interface ManagementObject {
|
||||
id: number
|
||||
name: string
|
||||
description?: string
|
||||
prefix?: string
|
||||
url?: string
|
||||
spec_field?: string
|
||||
}
|
||||
|
||||
export interface UserManagement {
|
||||
id: number
|
||||
name: string
|
||||
sys_object?: ManagementObject[]
|
||||
}
|
||||
|
||||
export interface PermissionsResponse {
|
||||
resources: Record<string, string[]>
|
||||
}
|
||||
|
||||
export interface SessionUser extends ApiRecord {
|
||||
id: number
|
||||
username: string
|
||||
email?: string
|
||||
name?: string
|
||||
sys_user_profile?: UserProfile
|
||||
sys_role?: UserRole[]
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
export interface JsonSchema {
|
||||
type?: string
|
||||
title?: string
|
||||
description?: string
|
||||
format?: string
|
||||
readOnly?: boolean
|
||||
nullable?: boolean
|
||||
enum?: unknown[]
|
||||
default?: unknown
|
||||
minLength?: number
|
||||
maxLength?: number
|
||||
pattern?: string
|
||||
minimum?: number
|
||||
maximum?: number
|
||||
properties?: Record<string, JsonSchema>
|
||||
items?: JsonSchema
|
||||
required?: string[]
|
||||
}
|
||||
Loading…
Reference in New Issue