This commit is contained in:
timur 2026-09-29 01:07:04 +05:00
parent 6eed1f1a95
commit 40715ce28f
22 changed files with 1728 additions and 386 deletions

View File

@ -11,7 +11,7 @@ Incidents, SLA, Configuration items, Device и System.
- аутентификация Knox Token;
- загрузка текущего пользователя, эффективных разрешений и доступной навигации через `/me/`, `/me/permissions/` и `/me/capabilities/`;
- мгновенное применение языка, светлой/тёмной темы и основного цвета;
- мгновенное применение языка и светлой/тёмной темы;
- форма управления профилем и ролевое ограничение меню/CRUD-действий;
- навигация по модулям и сущностям;
- серверная пагинация, поиск, выбор строк и состояния ошибок;

View File

@ -1,12 +1,14 @@
:root {
color-scheme: light;
--soft-text: #17233c;
--soft-muted: #75819a;
--soft-bg: #f4f6fa;
--soft-border: #e3e8f1;
--soft-text: #172033;
--soft-muted: #66758f;
--soft-bg: #f4f7fb;
--soft-border: #dfe6f0;
--theme-primary-contrast: #ffffff;
--theme-primary-button: rgb(var(--v-theme-primary));
--soft-shadow: 0 1px 2px rgb(16 24 40 / 3%);
--soft-shadow-hover: 0 8px 24px rgb(36 87 230 / 9%);
--soft-gradient: linear-gradient(135deg, #1f55e5 0%, #356df4 100%);
--soft-shadow-hover: 0 8px 24px rgb(var(--v-theme-primary) / 12%);
--soft-gradient: linear-gradient(135deg, var(--theme-primary-button) 0%, rgb(var(--v-theme-primary) / 82%) 100%);
}
html { overflow-y: auto; }
@ -19,9 +21,11 @@ body {
}
.v-theme--wanitilDark {
--soft-text: #f8f9fa;
--soft-muted: #a8b8d8;
--soft-bg: #141727;
color-scheme: dark;
--soft-text: #e7eef8;
--soft-muted: #9cabc0;
--soft-bg: #0f172a;
--soft-border: rgb(148 163 184 / 20%);
--soft-shadow: 0 14px 22px 0 rgb(0 0 0 / 14%);
--soft-shadow-hover: 0 16px 24px 0 rgb(0 0 0 / 20%);
}
@ -48,12 +52,13 @@ h1, h2, h3, h4, h5, h6,
.soft-sidebar {
border: 0 !important;
border-right: 1px solid var(--soft-border) !important;
background: rgb(var(--v-theme-surface)) !important;
box-shadow: none;
}
.soft-sidebar .v-navigation-drawer__content { background: #fff; }
.soft-brand-title { color: #17233c; font-size: .93rem; letter-spacing: .045em; }
.engineer-brand-mark { background: #17233c; color: white; font-size: 1rem; font-weight: 800; }
.soft-sidebar .v-navigation-drawer__content { background: rgb(var(--v-theme-surface)); }
.soft-brand-title { color: var(--soft-text); font-size: .93rem; letter-spacing: .045em; }
.engineer-brand-mark { background: rgb(var(--v-theme-primary)); color: var(--theme-primary-contrast); font-size: 1rem; font-weight: 800; }
.soft-sidebar.v-navigation-drawer--rail .soft-brand {
padding-inline: 8px !important;
@ -133,11 +138,11 @@ h1, h2, h3, h4, h5, h6,
}
.workspace-card .v-avatar {
box-shadow: 0 6px 12px rgb(33 82 255 / 14%);
box-shadow: 0 6px 12px rgb(var(--v-theme-primary) / 14%);
}
.workspace-card:hover .v-avatar {
box-shadow: 0 8px 16px rgb(33 82 255 / 20%);
box-shadow: 0 8px 16px rgb(var(--v-theme-primary) / 22%);
}
.workspace-zone {
@ -178,6 +183,14 @@ h1, h2, h3, h4, h5, h6,
z-index: 2;
}
.resource-editor-content { overflow-y: auto; }
@media (min-width: 1000px) {
.resource-editor-content { overflow-x: hidden; }
}
@media (max-width: 999px) {
.resource-editor-content { overflow-x: auto; }
}
.resource-highlight {
display: inline-block;
border-left: 4px solid transparent;
@ -211,15 +224,44 @@ h1, h2, h3, h4, h5, h6,
}
.v-btn.bg-primary {
background: var(--soft-gradient) !important;
box-shadow: 0 3px 6px -1px rgb(0 0 0 / 7%), 0 2px 3px -1px rgb(0 0 0 / 4%) !important;
border: 1px solid #245fcf !important;
background-color: #2f6fed !important;
background-image: linear-gradient(135deg, #2f6fed 0%, #255fcf 100%) !important;
color: #fff !important;
box-shadow: 0 3px 9px rgb(47 111 237 / 24%) !important;
}
.v-btn.bg-primary:hover {
box-shadow: 0 6px 12px rgb(33 82 255 / 16%) !important;
.v-btn.bg-primary .v-btn__content,
.v-btn.bg-primary .v-icon {
color: #fff !important;
opacity: 1;
}
.v-btn.bg-primary:not(.v-btn--disabled):hover {
background-color: #255fcf !important;
background-image: linear-gradient(135deg, #2865de 0%, #1f55bd 100%) !important;
box-shadow: 0 6px 15px rgb(47 111 237 / 30%) !important;
transform: translateY(-1px);
}
.v-btn.bg-primary:focus-visible {
outline: 3px solid rgb(47 111 237 / 28%);
outline-offset: 2px;
}
.v-btn.v-btn--active:not(.v-btn--disabled) {
border-color: rgb(var(--v-theme-primary)) !important;
background: rgb(var(--v-theme-primary)) !important;
color: var(--theme-primary-contrast) !important;
box-shadow: inset 0 0 0 1px rgb(var(--v-theme-on-surface) / 18%),
0 3px 7px -1px rgb(var(--v-theme-on-surface) / 16%),
0 2px 8px rgb(var(--v-theme-primary) / 18%) !important;
}
.v-btn.v-btn--active:not(.v-btn--disabled) .v-icon {
color: currentColor !important;
}
.v-field {
border-radius: 10px !important;
background: rgb(var(--v-theme-surface));
@ -291,14 +333,14 @@ h1, h2, h3, h4, h5, h6,
padding: 0 11px;
border: 1px solid var(--soft-border);
border-radius: 8px;
background: #f8f9fc;
background: rgb(var(--v-theme-on-surface) / 4%);
color: var(--soft-muted);
transition: border-color .18s ease, box-shadow .18s ease, background .18s ease;
}
.app-command-search.is-focused { border-color: rgb(var(--v-theme-primary) / 55%); background: white; box-shadow: 0 0 0 3px rgb(var(--v-theme-primary) / 8%); }
.app-command-search.is-focused { border-color: rgb(var(--v-theme-primary) / 55%); background: rgb(var(--v-theme-surface)); box-shadow: 0 0 0 3px rgb(var(--v-theme-primary) / 8%); }
.app-command-search input { min-width: 0; flex: 1; border: 0; outline: 0; background: transparent; color: var(--soft-text); font: inherit; font-size: .8rem; }
.app-command-search input::placeholder { color: #96a0b5; }
.app-command-search kbd { padding: 2px 6px; border: 1px solid #dce2ec; border-radius: 5px; background: #fff; color: #8791a6; font: 600 .62rem/1.3 Inter, sans-serif; }
.app-command-search input::placeholder { color: var(--soft-muted); }
.app-command-search kbd { padding: 2px 6px; border: 1px solid var(--soft-border); border-radius: 5px; background: rgb(var(--v-theme-background)); color: var(--soft-muted); font: 600 .62rem/1.3 Inter, sans-serif; }
.app-create-action { min-width: 104px; }
.app-profile-action .v-btn__content { gap: 9px; }
@ -308,21 +350,21 @@ h1, h2, h3, h4, h5, h6,
.engineer-eyebrow { color: rgb(var(--v-theme-primary)); font-size: .67rem; font-weight: 800; letter-spacing: .1em; }
.engineer-filter-row { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 22px; padding-bottom: 20px; border-bottom: 1px solid var(--soft-border); }
.engineer-filter-row .v-btn { min-width: 82px; }
.engineer-section { overflow: hidden; margin-bottom: 22px; border: 1px solid var(--soft-border); border-radius: 10px; background: white; }
.engineer-section { overflow: hidden; margin-bottom: 22px; border: 1px solid var(--soft-border); border-radius: 10px; background: rgb(var(--v-theme-surface)); }
.engineer-section-heading { display: flex; align-items: center; justify-content: space-between; padding: 17px 18px; border-bottom: 1px solid var(--soft-border); }
.engineer-section-heading h2 { margin: 0 0 2px; font-size: .98rem; }
.engineer-section-heading > span { color: var(--soft-muted); font-size: .75rem; }
.engineer-queue-row { display: grid; grid-template-columns: 38px minmax(0, 1fr) auto 20px; align-items: center; gap: 12px; min-height: 67px; padding: 10px 17px; border-bottom: 1px solid #edf0f5; color: var(--soft-text); text-decoration: none; transition: background .16s ease; }
.engineer-queue-row { display: grid; grid-template-columns: 38px minmax(0, 1fr) auto 20px; align-items: center; gap: 12px; min-height: 67px; padding: 10px 17px; border-bottom: 1px solid var(--soft-border); color: var(--soft-text); text-decoration: none; transition: background .16s ease; }
.engineer-queue-row:last-child { border-bottom: 0; }
.engineer-queue-row:hover { background: #f7f9ff; }
.engineer-module-icon { display: inline-grid; width: 36px; height: 36px; place-items: center; border: 1px solid #dce4f9; border-radius: 8px; background: #f1f5ff; color: rgb(var(--v-theme-primary)); }
.engineer-queue-row:hover { background: rgb(var(--v-theme-primary) / 6%); }
.engineer-module-icon { display: inline-grid; width: 36px; height: 36px; place-items: center; border: 1px solid rgb(var(--v-theme-primary) / 18%); border-radius: 8px; background: rgb(var(--v-theme-primary) / 9%); color: rgb(var(--v-theme-primary)); }
.engineer-module-copy, .engineer-tool-card > span:nth-child(2) { display: flex; min-width: 0; flex-direction: column; }
.engineer-module-copy strong, .engineer-tool-card strong { font-size: .84rem; }
.engineer-module-copy small, .engineer-tool-card small { margin-top: 2px; color: var(--soft-muted); font-size: .71rem; }
.engineer-tools-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 1px; background: var(--soft-border); }
.engineer-tool-card { display: flex; align-items: center; gap: 10px; min-height: 76px; padding: 13px 15px; background: white; color: var(--soft-text); text-decoration: none; transition: background .16s ease; }
.engineer-tool-card:hover { background: #f7f9ff; }
.engineer-tool-card > .v-icon { color: #9aa4b7; }
.engineer-tool-card { display: flex; align-items: center; gap: 10px; min-height: 76px; padding: 13px 15px; background: rgb(var(--v-theme-surface)); color: var(--soft-text); text-decoration: none; transition: background .16s ease; }
.engineer-tool-card:hover { background: rgb(var(--v-theme-primary) / 6%); }
.engineer-tool-card > .v-icon { color: rgb(var(--v-theme-primary) / 68%); }
.resource-view-select { max-width: 230px; }
.page-shell > .v-breadcrumbs { padding-bottom: 8px !important; }

View File

@ -322,7 +322,11 @@ onMounted(load)
@update:model-value="loadEmployee" />
<v-progress-linear v-if="employeeLoading" indeterminate class="mb-4" />
<template v-if="employee">
<div class="text-h6 mb-4">{{ employee.name || employee.fullname || `Сотрудник #${employee.id}` }}</div>
<div class="d-flex align-center ga-3 mb-4">
<EmployeeAvatar :avatar="employee.avatar as string | number | null"
:name="String(employee.name || employee.fullname || employee.username || '')" />
<div class="text-h6">{{ employee.name || employee.fullname || `Сотрудник #${employee.id}` }}</div>
</div>
<AccessSelectionList :permissions="accessIds(employee.permissions)"
:navigations="accessIds(employee.navigations)"
:permission-options="employeePermissions" :navigation-options="employeeNavigations"

View File

@ -15,6 +15,7 @@ const loading = ref(false)
const saving = ref(false)
const deletingId = ref<string | number | null>(null)
const error = ref('')
const createDialog = ref(false)
let searchTimer: ReturnType<typeof setTimeout> | undefined
const options = computed(() => available.value
@ -70,6 +71,7 @@ async function add() {
})
selectedZoneId.value = null
await load()
createDialog.value = false
} catch (e: any) {
error.value = e.message
} finally {
@ -77,6 +79,12 @@ async function add() {
}
}
function openCreateDialog() {
selectedZoneId.value = null
error.value = ''
createDialog.value = true
}
async function remove(zone: ApiRecord) {
if (zone.id === undefined || !window.confirm(`Убрать зону «${zone.name || zone.id}»?`)) return
deletingId.value = zone.id
@ -113,14 +121,33 @@ onBeforeUnmount(() => { if (searchTimer) clearTimeout(searchTimer) })
</v-list-item>
</v-list>
<p v-else-if="!loading" class="text-medium-emphasis mb-5">Зоны не назначены</p>
<template v-if="!readonly">
<h4 class="text-subtitle-2 font-weight-bold mb-3">Добавить</h4>
<div 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
@update:search="searchAvailable($event || '')" />
<v-btn color="primary" prepend-icon="mdi-link-plus" :loading="saving"
:disabled="selectedZoneId === null" @click="add">Добавить</v-btn>
<div v-if="!readonly" class="d-flex justify-end">
<v-btn color="primary" prepend-icon="mdi-link-plus" @click="openCreateDialog">
Добавить
</v-btn>
</div>
</template>
<v-dialog v-model="createDialog" max-width="560">
<v-card>
<v-card-title class="d-flex align-center px-6 py-4">
<span>Добавить зону</span>
<v-spacer />
<v-btn icon="mdi-close" variant="text" :disabled="saving"
aria-label="Закрыть" @click="createDialog = false" />
</v-card-title>
<v-divider />
<v-card-text class="px-6 pt-5">
<v-alert v-if="error" type="error" variant="tonal" class="mb-4">{{ error }}</v-alert>
<v-autocomplete v-model="selectedZoneId" :items="options"
label="Зона" clearable no-data-text="Нет доступных зон" :loading="loading"
@update:search="searchAvailable($event || '')" />
</v-card-text>
<v-card-actions class="px-6 pb-5">
<v-spacer />
<v-btn variant="text" :disabled="saving" @click="createDialog = false">Отмена</v-btn>
<v-btn color="primary" prepend-icon="mdi-link-plus" :loading="saving"
:disabled="selectedZoneId === null" @click="add">Добавить</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
</template>

View File

@ -23,6 +23,7 @@ const props = defineProps<{
const { request, normalizeList } = useApi()
const files = ref<DskFile[]>([])
const selectedFiles = ref<File[]>([])
const filePicker = ref<HTMLInputElement | null>(null)
const loading = ref(false)
const uploading = ref(false)
const downloadingId = ref<string | number | null>(null)
@ -39,9 +40,6 @@ function formatSize(value?: number | null) {
if (value < 1024 ** 2) return `${(value / 1024).toFixed(1)} КБ`
return `${(value / 1024 ** 2).toFixed(1)} МБ`
}
function normalizeFiles(value: File[] | File | null) {
selectedFiles.value = value === null ? [] : Array.isArray(value) ? value : [value]
}
async function loadFiles(force = false) {
if (!targetKey.value || (!force && loadedKey.value === targetKey.value)) return
loading.value = true
@ -72,7 +70,20 @@ async function uploadFiles() {
await loadFiles(true)
} catch (caught: any) {
error.value = caught?.message || 'Не удалось загрузить вложения'
} finally { uploading.value = false }
} finally {
uploading.value = false
if (filePicker.value) filePicker.value.value = ''
}
}
function openFilePicker() {
if (!uploading.value) filePicker.value?.click()
}
async function selectFiles(event: Event) {
const input = event.target as HTMLInputElement
selectedFiles.value = Array.from(input.files || [])
if (selectedFiles.value.length) await uploadFiles()
}
async function downloadFile(file: DskFile) {
downloadingId.value = file.id
@ -93,7 +104,7 @@ async function downloadFile(file: DskFile) {
}
async function detachFile(file: DskFile) {
const name = String(file.original_name || file.name || `#${file.id}`)
if (!window.confirm(`Отвязать вложение «${name}»?`)) return
if (!window.confirm(`Удалить файл «${name}»?`)) return
const attachment = file.attachments?.find(item => item.target_type === resolvedTargetType.value
&& String(item.target_id) === String(props.recordId))
deletingId.value = file.id
@ -106,7 +117,7 @@ async function detachFile(file: DskFile) {
}
files.value = files.value.filter(item => String(item.id) !== String(file.id))
} catch (caught: any) {
error.value = caught?.message || 'Не удалось отвязать вложение'
error.value = caught?.message || 'Не удалось удалить файл'
} finally { deletingId.value = null }
}
@ -119,15 +130,6 @@ watch(() => [targetKey.value, props.active], () => {
<template>
<v-alert v-if="!targetKey" type="info" variant="tonal">Сначала сохраните объект, затем можно будет добавлять вложения.</v-alert>
<template v-else>
<v-card v-if="!readonly" variant="outlined" class="mb-4">
<v-card-title class="text-subtitle-1">Добавить вложения</v-card-title>
<v-card-text>
<v-file-input :model-value="selectedFiles" label="Выберите файлы" multiple chips show-size
prepend-icon="mdi-paperclip" :disabled="uploading" @update:model-value="normalizeFiles" />
<div class="d-flex justify-end"><v-btn type="button" color="primary" prepend-icon="mdi-upload"
:loading="uploading" :disabled="!selectedFiles.length" @click="uploadFiles">Загрузить</v-btn></div>
</v-card-text>
</v-card>
<v-alert v-if="error" type="error" variant="tonal" class="mb-4">{{ error }}</v-alert>
<div v-if="loading" class="d-flex justify-center py-8"><v-progress-circular indeterminate color="primary" /></div>
<v-alert v-else-if="!files.length" type="info" variant="tonal">Вложений пока нет.</v-alert>
@ -138,11 +140,20 @@ watch(() => [targetKey.value, props.active], () => {
· {{ formatDateValue(String(file.updated_at || file.created_at)) }}</template></template>
<template #append><div class="d-flex ga-1">
<v-btn type="button" icon="mdi-download" variant="text" color="primary"
:loading="downloadingId === file.id" title="Скачать" @click="downloadFile(file)" />
<v-btn v-if="!readonly" type="button" icon="mdi-link-off" variant="text" color="error"
:loading="deletingId === file.id" title="Отвязать" @click="detachFile(file)" />
:loading="downloadingId === file.id" title="Скачать" aria-label="Скачать файл"
@click="downloadFile(file)" />
<v-btn v-if="!readonly" type="button" icon="mdi-delete-outline" variant="text" color="error"
:loading="deletingId === file.id" title="Удалить" aria-label="Удалить файл"
@click="detachFile(file)" />
</div></template>
</v-list-item>
</v-list>
<div v-if="!readonly" class="d-flex justify-end mt-4">
<input ref="filePicker" class="d-none" type="file" multiple @change="selectFiles">
<v-btn type="button" color="primary" prepend-icon="mdi-plus" :loading="uploading"
:disabled="uploading" @click="openFilePicker">
Добавить
</v-btn>
</div>
</template>
</template>

View File

@ -0,0 +1,159 @@
<script setup lang="ts">
import type { ApiRecord } from '~/types/api'
type GraphNode = { id: string | number; title: string; depth: number; x: number; y: number }
type GraphEdge = { id: string; source: string | number; target: string | number; label: string }
const props = defineProps<{ ciId: string | number }>()
const { request, normalizeList } = useApi()
const depth = ref(1)
const loading = ref(false)
const error = ref('')
const nodes = ref<GraphNode[]>([])
const edges = ref<GraphEdge[]>([])
const graphWidth = computed(() => Math.max(720, (depth.value + 1) * 260 + 80))
const graphHeight = computed(() => {
const counts = Object.values(Object.groupBy(nodes.value, node => String(node.depth)))
.map(group => group?.length || 0)
return Math.max(360, Math.max(1, ...counts) * 112 + 80)
})
function recordId(value: unknown): string | number | null {
if (typeof value === 'string' || typeof value === 'number') return value
if (value && typeof value === 'object') {
const id = (value as ApiRecord).id
if (typeof id === 'string' || typeof id === 'number') return id
}
return null
}
function recordTitle(value: unknown, id: string | number) {
const record = value && typeof value === 'object' ? value as ApiRecord : undefined
return String(record?.name || record?.title || record?.number || `CI #${id}`)
}
async function loadGraph() {
loading.value = true
error.value = ''
try {
const root = await request<ApiRecord>(`/main/cim/cis/${props.ciId}/`)
const nodeMap = new Map<string, Omit<GraphNode, 'x' | 'y'>>()
const edgeMap = new Map<string, GraphEdge>()
nodeMap.set(String(props.ciId), {
id: props.ciId,
title: recordTitle(root, props.ciId),
depth: 0,
})
let frontier: (string | number)[] = [props.ciId]
const expanded = new Set<string>()
for (let level = 0; level < depth.value && frontier.length; level += 1) {
const current = frontier.filter(id => !expanded.has(String(id)))
current.forEach(id => expanded.add(String(id)))
const results = await Promise.all(current.flatMap(id => [
request<any>('/main/cim/ci-relations/', {
query: { page_size: 1000, ci__id__exact: id },
}),
request<any>('/main/cim/ci-relations/', {
query: { page_size: 1000, ci_rel__id__exact: id },
}),
]))
const next = new Set<string | number>()
results.flatMap(result => normalizeList(result).items).forEach(relation => {
const sourceValue = relation.ci ?? relation.source_ci ?? relation.source_ci_id
const targetValue = relation.ci_rel ?? relation.target_ci ?? relation.target_ci_id
const source = recordId(sourceValue)
const target = recordId(targetValue)
if (source === null || target === null) return
const sourceDepth = nodeMap.get(String(source))?.depth
const targetDepth = nodeMap.get(String(target))?.depth
if (sourceDepth === undefined) {
nodeMap.set(String(source), { id: source, title: recordTitle(sourceValue, source), depth: level + 1 })
next.add(source)
}
if (targetDepth === undefined) {
nodeMap.set(String(target), { id: target, title: recordTitle(targetValue, target), depth: level + 1 })
next.add(target)
}
const edgeId = String(relation.id ?? `${source}-${target}-${relation.type ?? ''}-${relation.mode ?? ''}`)
edgeMap.set(edgeId, {
id: edgeId,
source,
target,
label: String(relation.mode_name || relation.type_name || relation.name || ''),
})
})
frontier = [...next]
}
const grouped = Object.groupBy([...nodeMap.values()], node => String(node.depth))
nodes.value = Object.values(grouped).flatMap(group => (group || []).map((node, index) => ({
...node,
x: 40 + node.depth * 260,
y: 40 + index * 112,
})))
edges.value = [...edgeMap.values()]
} catch (caught: any) {
error.value = caught.message || 'Не удалось построить граф связей'
} finally {
loading.value = false
}
}
function nodeById(id: string | number) {
return nodes.value.find(node => String(node.id) === String(id))
}
watch(depth, loadGraph)
watch(() => props.ciId, loadGraph, { immediate: true })
</script>
<template>
<div>
<div class="graph-toolbar">
<v-select v-model="depth" :items="[1, 2, 3, 4, 5]" label="Глубина связей"
density="compact" hide-details class="graph-depth" />
<v-btn icon="mdi-refresh" variant="text" :loading="loading"
aria-label="Перестроить граф" @click="loadGraph" />
</div>
<v-alert v-if="error" type="error" variant="tonal" class="mb-4">{{ error }}</v-alert>
<div class="ci-graph" :style="{ minWidth: `${graphWidth}px`, height: `${graphHeight}px` }">
<svg class="ci-graph-lines" :width="graphWidth" :height="graphHeight">
<defs>
<marker id="ci-graph-arrow" markerWidth="8" markerHeight="8" refX="7" refY="4"
orient="auto" markerUnits="strokeWidth">
<path d="M0,0 L8,4 L0,8 Z" fill="currentColor" />
</marker>
</defs>
<template v-for="edge in edges" :key="edge.id">
<line v-if="nodeById(edge.source) && nodeById(edge.target)"
:x1="nodeById(edge.source)!.x + 200" :y1="nodeById(edge.source)!.y + 32"
:x2="nodeById(edge.target)!.x" :y2="nodeById(edge.target)!.y + 32"
marker-end="url(#ci-graph-arrow)" />
</template>
</svg>
<div v-for="node in nodes" :key="node.id" class="ci-graph-node"
:class="{ 'ci-graph-node--root': node.depth === 0 }"
:style="{ left: `${node.x}px`, top: `${node.y}px` }">
<v-icon :icon="node.depth === 0 ? 'mdi-server' : 'mdi-cube-outline'" size="18" />
<span>{{ node.title }}</span>
</div>
<div v-if="loading" class="ci-graph-loading">
<v-progress-circular indeterminate color="primary" />
</div>
</div>
</div>
</template>
<style scoped>
.graph-toolbar { display: flex; align-items: center; justify-content: flex-end; gap: 8px; margin-bottom: 16px; }
.graph-depth { max-width: 190px; }
.ci-graph { position: relative; overflow: hidden; border: 1px solid var(--soft-border); border-radius: 12px; background-color: rgb(var(--v-theme-background)); background-image: radial-gradient(rgb(var(--v-theme-primary) / 16%) 1px, transparent 1px); background-size: 20px 20px; }
.ci-graph-lines { position: absolute; inset: 0; overflow: visible; color: rgb(var(--v-theme-primary) / 58%); }
.ci-graph-lines line { stroke: currentColor; stroke-width: 2; }
.ci-graph-node { position: absolute; display: flex; width: 200px; min-height: 64px; align-items: center; gap: 10px; padding: 12px 14px; border: 1px solid var(--soft-border); border-radius: 10px; background: rgb(var(--v-theme-surface)); box-shadow: var(--soft-shadow); color: var(--soft-text); font-size: .82rem; font-weight: 700; overflow-wrap: anywhere; }
.ci-graph-node .v-icon { flex: 0 0 auto; color: rgb(var(--v-theme-primary)); }
.ci-graph-node--root { border-color: rgb(var(--v-theme-primary) / 65%); box-shadow: 0 0 0 3px rgb(var(--v-theme-primary) / 9%); }
.ci-graph-loading { position: absolute; inset: 0; display: grid; place-items: center; background: rgb(var(--v-theme-background) / 65%); }
</style>

View File

@ -22,6 +22,8 @@ const loading = ref(false)
const saving = ref(false)
const deletingId = ref<string | number | null>(null)
const error = ref('')
const createDialog = ref(false)
const graphDialog = ref(false)
function relatedCi(item: RelationItem) {
return (item.direction === 'outgoing' ? item.ci_rel : item.ci) as ApiRecord | undefined
@ -100,6 +102,7 @@ async function add() {
relationType.value = null
relationMode.value = null
await load()
createDialog.value = false
} catch (e: any) {
error.value = e.message
} finally {
@ -107,6 +110,14 @@ async function add() {
}
}
function openCreateDialog() {
targetCiId.value = null
relationType.value = null
relationMode.value = null
error.value = ''
createDialog.value = true
}
async function remove(item: RelationItem) {
if (item.id === undefined || !window.confirm(`Удалить связь с «${relatedTitle(item)}»?`)) return
deletingId.value = item.id
@ -126,6 +137,11 @@ watch(() => props.ciId, load, { immediate: true })
<template>
<div>
<div class="d-flex justify-end mb-3">
<v-btn icon="mdi-graph-outline" color="primary" variant="tonal"
title="Открыть граф связей" aria-label="Открыть граф связей"
@click="graphDialog = true" />
</div>
<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" />
@ -144,25 +160,66 @@ watch(() => props.ciId, load, { immediate: true })
</v-list>
<p v-else-if="!loading" class="text-medium-emphasis mb-5">Связей пока нет</p>
<template v-if="!readonly">
<h4 class="text-subtitle-2 font-weight-bold mb-3">Добавить связь</h4>
<v-form @submit.prevent="add">
<v-autocomplete v-model="targetCiId" :items="ciOptions" label="Связанная CI"
clearable no-data-text="CI не найдены"
@update:search="searchCis($event || '')" />
<v-row dense>
<v-col cols="12" md="6">
<v-select v-model="relationType" :items="typeOptions" label="Тип связи" clearable />
</v-col>
<v-col cols="12" md="6">
<v-select v-model="relationMode" :items="modeOptions" label="Режим связи" clearable />
</v-col>
</v-row>
<div class="d-flex justify-end">
<v-btn type="submit" color="primary" prepend-icon="mdi-plus" :loading="saving"
:disabled="targetCiId === null">Добавить</v-btn>
</div>
</v-form>
</template>
<div v-if="!readonly" class="d-flex justify-end">
<v-btn color="primary" prepend-icon="mdi-plus" @click="openCreateDialog">
Добавить связь
</v-btn>
</div>
<v-dialog v-model="createDialog" max-width="640">
<v-card>
<v-card-title class="d-flex align-center px-6 py-4">
<span>Добавить связь CI</span>
<v-spacer />
<v-btn icon="mdi-close" variant="text" :disabled="saving"
aria-label="Закрыть" @click="createDialog = false" />
</v-card-title>
<v-divider />
<v-form @submit.prevent="add">
<v-card-text class="px-6 pt-5">
<v-alert v-if="error" type="error" variant="tonal" class="mb-4">{{ error }}</v-alert>
<v-autocomplete v-model="targetCiId" :items="ciOptions" label="Связанная CI"
clearable no-data-text="CI не найдены"
@update:search="searchCis($event || '')" />
<v-row dense>
<v-col cols="12" md="6">
<v-select v-model="relationType" :items="typeOptions" label="Тип связи" clearable />
</v-col>
<v-col cols="12" md="6">
<v-select v-model="relationMode" :items="modeOptions" label="Режим связи" clearable />
</v-col>
</v-row>
</v-card-text>
<v-card-actions class="px-6 pb-5">
<v-spacer />
<v-btn variant="text" :disabled="saving" @click="createDialog = false">Отмена</v-btn>
<v-btn type="submit" color="primary" prepend-icon="mdi-plus" :loading="saving"
:disabled="targetCiId === null">Добавить</v-btn>
</v-card-actions>
</v-form>
</v-card>
</v-dialog>
<v-dialog v-model="graphDialog" max-width="1200" scrollable>
<v-card>
<v-card-title class="d-flex align-center px-6 py-4">
<v-icon icon="mdi-graph-outline" class="mr-2" />
<span>Граф связей CI</span>
<v-spacer />
<v-btn icon="mdi-close" variant="text" aria-label="Закрыть"
@click="graphDialog = false" />
</v-card-title>
<v-divider />
<v-card-text class="pa-6 ci-graph-dialog-content">
<CiRelationsGraph v-if="graphDialog" :ci-id="ciId" />
</v-card-text>
</v-card>
</v-dialog>
</div>
</template>
<style scoped>
.ci-graph-dialog-content {
overflow: auto;
}
</style>

View File

@ -12,12 +12,14 @@ const props = defineProps<{
formId?: string
hideActions?: boolean
relationOptions?: Record<string, Option[]>
fieldLinks?: Record<string, string>
beforeStatusChange?: () => Promise<boolean>
}>()
const emit = defineEmits<{
'update:modelValue': [value: ApiRecord]
submit: []
relationSearch: [name: string, search: string]
openLinked: [path: string, id: string | number]
}>()
const { request, normalizeList } = useApi()
const form = ref()
@ -33,6 +35,13 @@ const relationValue = (name: string) => {
const value = props.modelValue[name]
return value && typeof value === 'object' ? (value as ApiRecord).id : value
}
function openLinked(name: string) {
const path = props.fieldLinks?.[name]
const id = relationValue(name)
if (path && (typeof id === 'string' || typeof id === 'number')) emit('openLinked', path, id)
}
const linkedIcon = (name: string) => props.fieldLinks?.[name] && relationValue(name) !== null
&& relationValue(name) !== undefined ? 'mdi-open-in-new' : undefined
const relationColor = (name: string) => {
const value = props.modelValue[name]
return value && typeof value === 'object' ? String((value as ApiRecord).color || '') : ''
@ -140,15 +149,12 @@ watch(activeTab, value => { if (value === 'history') loadHistory() })
<v-tab value="main">Основное</v-tab>
<v-tab value="request">Запрос/решение</v-tab>
<v-tab value="comments">Комментарии</v-tab>
<v-tab value="attachments">Вложения</v-tab>
<v-tab value="sla">SLA</v-tab>
<v-tab value="related">Связанные объекты</v-tab>
<v-tab value="history">История</v-tab>
</v-tabs>
<v-window v-model="activeTab">
<v-window-item value="main">
<TagsTab target-type="inc.incident" :record-id="modelValue.id as string | number | undefined"
:readonly="readonly" :active="activeTab === 'main'" />
<v-card variant="outlined" class="mb-4">
<v-card-title class="text-subtitle-1">Данные инцидента</v-card-title>
<v-card-text>
@ -164,6 +170,7 @@ watch(activeTab, value => { if (value === 'history') loadHistory() })
<v-col v-for="[name, label] in relationFields.slice(0, 2)" :key="name" cols="12" md="3">
<v-autocomplete v-if="field(name)" :model-value="relationValue(name)"
:items="relationOptions?.[name] || []" :label="label" clearable :readonly="readonly"
:append-inner-icon="linkedIcon(name)" @click:append-inner.stop="openLinked(name)"
@update:search="emit('relationSearch', name, $event || '')"
@update:model-value="selectRelation(name, $event)" />
</v-col>
@ -181,12 +188,20 @@ watch(activeTab, value => { if (value === 'history') loadHistory() })
:style="['inc_impact', 'inc_priority'].includes(name) && relationColor(name)
? { '--field-accent': relationColor(name) }
: undefined"
:append-inner-icon="linkedIcon(name)" @click:append-inner.stop="openLinked(name)"
@update:search="emit('relationSearch', name, $event || '')"
@update:model-value="selectRelation(name, $event)" />
</v-col>
</v-row>
</v-card-text>
</v-card>
<div class="mb-6">
<h3 class="text-subtitle-1 font-weight-bold mb-4">Вложения</h3>
<AttachmentsTab target-type="inc.incident" :record-id="modelValue.id as string | number | undefined"
:readonly="readonly" :active="activeTab === 'main'" />
</div>
<TagsTab target-type="inc.incident" :record-id="modelValue.id as string | number | undefined"
:readonly="readonly" :active="activeTab === 'main'" />
</v-window-item>
<v-window-item value="request">
<v-card variant="outlined" class="mb-4">
@ -203,6 +218,7 @@ watch(activeTab, value => { if (value === 'history') loadHistory() })
<v-card-text>
<v-autocomplete v-if="field('inc_solution')" :model-value="relationValue('inc_solution')"
:items="relationOptions?.inc_solution || []" label="Решение" clearable :readonly="readonly"
:append-inner-icon="linkedIcon('inc_solution')" @click:append-inner.stop="openLinked('inc_solution')"
@update:search="emit('relationSearch', 'inc_solution', $event || '')"
@update:model-value="selectRelation('inc_solution', $event)" />
<v-textarea v-if="field('solution_text')" :model-value="modelValue.solution_text"
@ -216,10 +232,6 @@ watch(activeTab, value => { if (value === 'history') loadHistory() })
<CommentsTab kind="inc" :record-id="modelValue.id as string | number | undefined" :readonly="readonly"
:active="activeTab === 'comments'" />
</v-window-item>
<v-window-item value="attachments">
<AttachmentsTab target-type="inc.incident" :record-id="modelValue.id as string | number | undefined"
:readonly="readonly" :active="activeTab === 'attachments'" />
</v-window-item>
<v-window-item value="sla">
<SlaCalculationHistory kind="incident"
:record-id="modelValue.id as string | number | undefined" />

View File

@ -19,6 +19,9 @@ const props = withDefaults(defineProps<{
itemEditPath?: string
manageItems?: boolean
allowCreate?: boolean
createInDialog?: boolean
createLabel?: string
compact?: boolean
readonly?: boolean
}>(), {
manageItems: true,
@ -34,6 +37,7 @@ const loading = ref(false)
const saving = ref(false)
const deletingId = ref<string | number | null>(null)
const error = ref('')
const createDialog = ref(false)
const fields = computed(() => Object.entries(schema.value.properties || {})
.filter(([name, field]) => name !== props.relationField
@ -100,6 +104,19 @@ function setField(name: string, value: unknown) {
draft.value = { ...draft.value, [name]: value }
}
function fieldLabel(name: string, field: JsonSchema) {
if (field.title) return field.title
if (name === 'name') return 'Название'
if (name === 'description') return 'Описание'
return name.replaceAll('_', ' ')
}
function openCreateDialog() {
draft.value = {}
error.value = ''
createDialog.value = true
}
async function add() {
saving.value = true
error.value = ''
@ -119,6 +136,7 @@ async function add() {
})
draft.value = {}
await load()
createDialog.value = false
} catch (e: any) {
error.value = e.message
} finally {
@ -144,42 +162,157 @@ watch(() => props.parentId, load, { immediate: true })
</script>
<template>
<div class="inline-resource-manager" :class="{ 'inline-resource-manager--compact': compact }">
<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"
:to="itemEditPath && item.id !== undefined
? { path: itemEditPath, query: { edit: item.id } }
: undefined">
<template #append>
<v-btn v-if="!readonly && manageItems !== false" icon="mdi-delete-outline" variant="text" color="error"
:loading="String(deletingId) === String(item.id)" aria-label="Удалить"
@click.prevent.stop="remove(item)" />
<div class="inline-resource-list-area">
<v-list v-if="items.length" class="border rounded-lg mb-5"
:lines="itemSubtitleFields?.length === 0 ? 'one' : 'two'"
:density="compact ? 'compact' : 'default'">
<template v-for="item in items" :key="item.id">
<v-list-item :title="itemTitle(item)"
:subtitle="itemSubtitle(item) || undefined"
:to="itemEditPath && item.id !== undefined
? { path: itemEditPath, query: { edit: item.id } }
: undefined">
<template #append>
<v-btn v-if="!readonly && manageItems !== false" icon="mdi-delete-outline" variant="text" color="error"
:loading="String(deletingId) === String(item.id)" aria-label="Удалить"
@click.prevent.stop="remove(item)" />
</template>
</v-list-item>
<div v-if="$slots['item-details'] && item.id !== undefined" class="inline-resource-children">
<slot name="item-details" :item="item" />
</div>
</template>
</v-list-item>
</v-list>
<p v-else-if="!loading" class="text-medium-emphasis mb-5">Записей пока нет</p>
<template v-if="!readonly && manageItems !== false && allowCreate !== false && fields.length">
</v-list>
<p v-else-if="!loading" class="text-medium-emphasis mb-5">Записей пока нет</p>
</div>
<template v-if="!readonly && manageItems !== false && allowCreate !== false && fields.length && !createInDialog">
<h4 class="text-subtitle-2 font-weight-bold mb-3">Добавить</h4>
<v-form @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('_', ' ')"
:items="fieldOptions[name]" :label="fieldLabel(name, field)"
: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"
<ResourceField v-else :name="name" :schema="{ ...field, title: fieldLabel(name, 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 class="inline-resource-actions d-flex justify-end">
<v-btn type="submit" color="primary" prepend-icon="mdi-plus" :loading="saving"
:density="compact ? 'compact' : 'default'">
{{ createLabel || 'Добавить' }}
</v-btn>
</div>
</v-form>
</template>
<template v-else-if="!readonly && manageItems !== false && allowCreate !== false && fields.length">
<div class="d-flex justify-end">
<v-btn color="primary" prepend-icon="mdi-plus" :density="compact ? 'compact' : 'default'"
@click="openCreateDialog">
{{ createLabel || 'Добавить' }}
</v-btn>
</div>
<v-dialog v-model="createDialog" max-width="560">
<v-card>
<v-card-title class="d-flex align-center px-6 py-4">
<span>Добавить: {{ title.toLocaleLowerCase() }}</span>
<v-spacer />
<v-btn icon="mdi-close" variant="text" :disabled="saving"
aria-label="Закрыть" @click="createDialog = false" />
</v-card-title>
<v-divider />
<v-form @submit.prevent="add">
<v-card-text class="px-6 pt-5">
<v-alert v-if="error" type="error" variant="tonal" class="mb-4">{{ error }}</v-alert>
<template v-for="[name, field] in fields" :key="name">
<v-select v-if="fieldOptions?.[name]" :model-value="draft[name]"
:items="fieldOptions[name]" :label="fieldLabel(name, field)"
: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, title: fieldLabel(name, field) }"
:model-value="draft[name]"
:required="Array.isArray(schema.required) && schema.required.includes(name)"
@update:model-value="setField(name, $event)" />
</template>
</v-card-text>
<v-card-actions class="px-6 pb-5">
<v-spacer />
<v-btn variant="text" :disabled="saving" @click="createDialog = false">Отмена</v-btn>
<v-btn type="submit" color="primary" prepend-icon="mdi-plus" :loading="saving">
{{ createLabel || 'Добавить' }}
</v-btn>
</v-card-actions>
</v-form>
</v-card>
</v-dialog>
</template>
</div>
</template>
<style scoped>
.inline-resource-manager {
display: flex;
min-width: 0;
height: 100%;
flex-direction: column;
}
.inline-resource-list-area {
min-height: 0;
flex: 1 1 auto;
}
.inline-resource-actions {
margin-top: auto;
}
.inline-resource-children {
margin: 0 16px 12px 48px;
padding-left: 16px;
border-left: 2px solid rgb(var(--v-theme-on-surface) / 10%);
}
.inline-resource-children :deep(.inline-resource-manager > .v-divider) {
margin-top: 8px !important;
}
.inline-resource-manager--compact > .v-divider {
margin-top: 10px !important;
margin-bottom: 10px !important;
}
.inline-resource-manager--compact > h3 {
margin-bottom: 8px !important;
}
.inline-resource-manager--compact > .inline-resource-list-area > .v-list {
margin-bottom: 8px !important;
}
.inline-resource-manager--compact .inline-resource-children {
margin-bottom: 4px;
}
.inline-resource-manager--compact :deep(.v-list-item) {
min-height: 40px;
}
@media (max-width: 600px) {
.inline-resource-children {
margin-right: 8px;
margin-left: 24px;
padding-left: 8px;
}
}
</style>

View File

@ -29,11 +29,11 @@ const { request, normalizeList } = useApi()
const sections: SettingSection[] = [
{
key: 'srv',
title: 'Сервисы',
title: 'Услуги',
endpoint: '/main/srv/settings/1/',
fields: [
{ name: 'status_create', title: 'Начальный статус сервиса', type: 'integer', optionsEndpoint: '/main/srv/service-statuses/' },
{ name: 'status_closed', title: 'Статус закрытого сервиса', type: 'integer', optionsEndpoint: '/main/srv/service-statuses/' },
{ name: 'status_create', title: 'Начальный статус услуги', type: 'integer', optionsEndpoint: '/main/srv/service-statuses/' },
{ name: 'status_closed', title: 'Статус закрытой услуги', type: 'integer', optionsEndpoint: '/main/srv/service-statuses/' },
],
},
{
@ -180,7 +180,9 @@ async function save(section: SettingSection) {
field.name,
data[section.key]?.[field.name] ?? (field.type === 'integer' ? null : ''),
]))
const updated = await request<ApiRecord>(section.endpoint, { method: 'PATCH', body })
const updated = await request<ApiRecord>(section.endpoint, {
method: 'PATCH', body, preserveNulls: true,
})
data[section.key] = {
...data[section.key],
...updated,

View File

@ -14,12 +14,14 @@ const props = defineProps<{
fieldOptions?: Record<string, Option[]>
relationOptions?: Record<string, Option[]>
relationLabels?: Record<string, string>
fieldLinks?: Record<string, string>
beforeStatusChange?: () => Promise<boolean>
}>()
const emit = defineEmits<{
'update:modelValue': [value: ApiRecord]
submit: []
relationSearch: [name: string, search: string]
openLinked: [path: string, id: string | number]
}>()
const { request, normalizeList } = useApi()
const form = ref()
@ -46,6 +48,13 @@ const relationValue = (name: string) => {
const value = props.modelValue[name]
return value && typeof value === 'object' ? (value as ApiRecord).id : value
}
function openLinked(name: string) {
const path = props.fieldLinks?.[name]
const id = relationValue(name)
if (path && (typeof id === 'string' || typeof id === 'number')) emit('openLinked', path, id)
}
const linkedIcon = (name: string) => props.fieldLinks?.[name] && relationValue(name) !== null
&& relationValue(name) !== undefined ? 'mdi-open-in-new' : undefined
const relationColor = (name: string) => {
const value = props.modelValue[name]
return value && typeof value === 'object' ? String((value as ApiRecord).color || '') : ''
@ -92,7 +101,7 @@ async function loadClientServices(clientId: string | number, search = '') {
serviceOptions.value = normalizeList(data).items
.filter(item => item.id !== undefined)
.map(item => ({
title: String(item.name || `Сервис #${item.id}`),
title: String(item.name || `Услуга #${item.id}`),
value: item.id!,
}))
}
@ -290,7 +299,7 @@ const historyMetaFields = new Set([
const historyFieldLabels: Record<string, string> = {
req_status: 'Статус', req_criticality: 'Критичность', req_employee: 'Исполнитель',
client_name: 'Клиент', client_type_name: 'Тип клиента', client_category_name: 'Категория клиента',
service_name: 'Сервис', service_type_name: 'Тип сервиса', request_type_name: 'Тип запроса',
service_name: 'Услуга', service_type_name: 'Тип услуги', request_type_name: 'Тип запроса',
request_text: 'Текст запроса', solution_type_name: 'Решение', solution_text: 'Текст решения',
house_name: 'Адрес', flat: 'Квартира', lat: 'Широта', lon: 'Долгота',
contact_type_name: 'Тип контакта', contact_value: 'Контакт', req_source_type: 'Источник',
@ -451,7 +460,6 @@ onMounted(async () => {
<v-tab value="main">Основное</v-tab>
<v-tab value="request">Запрос/решение</v-tab>
<v-tab value="comments">Комментарии</v-tab>
<v-tab value="attachments">Вложения</v-tab>
<v-tab value="sla">SLA</v-tab>
<v-tab value="related">Связанные объекты</v-tab>
<v-tab value="history">История</v-tab>
@ -459,8 +467,6 @@ onMounted(async () => {
<v-window v-model="activeTab">
<v-window-item value="main">
<TagsTab target-type="req.request" :record-id="modelValue.id as string | number | undefined"
:readonly="readonly" :active="activeTab === 'main'" />
<v-card variant="outlined" class="mb-4">
<v-card-title class="text-subtitle-1">Данные по обращению</v-card-title>
<v-card-text>
@ -473,12 +479,14 @@ onMounted(async () => {
<v-autocomplete v-if="field('req_source_type')" :model-value="relationValue('req_source_type')"
:items="relationOptions?.req_source_type || []" :readonly="readonly" label="Источник"
clearable no-data-text="Ничего не найдено"
:append-inner-icon="linkedIcon('req_source_type')" @click:append-inner.stop="openLinked('req_source_type')"
@update:search="emit('relationSearch', 'req_source_type', $event || '')"
@update:model-value="set('req_source_type', $event === null ? null : { id: $event })" />
</v-col>
<v-col cols="12" md="3">
<v-autocomplete v-if="field('req_employee')" :model-value="relationValue('req_employee')"
:items="relationOptions?.req_employee || []" label="Исполнитель" clearable :readonly="readonly"
:append-inner-icon="linkedIcon('req_employee')" @click:append-inner.stop="openLinked('req_employee')"
@update:search="emit('relationSearch', 'req_employee', $event || '')"
@update:model-value="set('req_employee', $event === null ? null : { id: $event })" />
</v-col>
@ -498,6 +506,7 @@ onMounted(async () => {
:items="relationOptions?.req_criticality || []" label="Критичность" clearable :readonly="readonly"
:class="{ 'colored-object-field': relationColor('req_criticality') }"
:style="relationColor('req_criticality') ? { '--field-accent': relationColor('req_criticality') } : undefined"
:append-inner-icon="linkedIcon('req_criticality')" @click:append-inner.stop="openLinked('req_criticality')"
@update:search="emit('relationSearch', 'req_criticality', $event || '')"
@update:model-value="selectColoredRelation('req_criticality', $event)" />
</v-col>
@ -513,6 +522,7 @@ onMounted(async () => {
<v-combobox v-if="field('client_id')" :model-value="modelValue.client_id || modelValue.client_name || null"
:items="fieldOptions?.client_id || []" label="Клиент" clearable :readonly="readonly"
:loading="dependencyLoading" no-data-text="Введите имя нового клиента"
:append-inner-icon="linkedIcon('client_id')" @click:append-inner.stop="openLinked('client_id')"
@update:search="emit('relationSearch', 'client_id', $event || '')"
@update:model-value="selectClient" />
</div>
@ -534,8 +544,9 @@ onMounted(async () => {
<div class="request-service-row">
<div>
<v-autocomplete v-if="field('service_id')" :model-value="modelValue.service_id"
:items="serviceOptions" label="Сервис" clearable :readonly="readonly"
:loading="dependencyLoading" no-data-text="Сервисы не найдены"
:items="serviceOptions" label="Услуга" clearable :readonly="readonly"
:loading="dependencyLoading" no-data-text="Услуги не найдены"
:append-inner-icon="linkedIcon('service_id')" @click:append-inner.stop="openLinked('service_id')"
@update:search="modelValue.client_id !== null && modelValue.client_id !== undefined
? loadClientServices(modelValue.client_id as string | number, $event || '')
: emit('relationSearch', 'service_id', $event || '')"
@ -543,7 +554,7 @@ onMounted(async () => {
</div>
<div>
<v-autocomplete v-if="field('service_type_id')" :model-value="modelValue.service_type_id"
:items="fieldOptions?.service_type_id || []" label="Тип сервиса" clearable
:items="fieldOptions?.service_type_id || []" label="Тип услуги" clearable
:readonly="readonly || modelValue.service_id !== null && modelValue.service_id !== undefined"
@update:search="emit('relationSearch', 'service_type_id', $event || '')"
@update:model-value="selectServiceType" />
@ -572,6 +583,14 @@ onMounted(async () => {
</v-card-text>
</v-card>
<div class="mb-6">
<h3 class="text-subtitle-1 font-weight-bold mb-4">Вложения</h3>
<AttachmentsTab target-type="req.request" :record-id="modelValue.id as string | number | undefined"
:readonly="readonly" :active="activeTab === 'main'" />
</div>
<TagsTab target-type="req.request" :record-id="modelValue.id as string | number | undefined"
:readonly="readonly" :active="activeTab === 'main'" />
</v-window-item>
<v-window-item value="request">
@ -582,6 +601,7 @@ onMounted(async () => {
:items="requestTypeOptions" label="Тип запроса" clearable :readonly="readonly"
:disabled="modelValue.service_type_id === null || modelValue.service_type_id === undefined"
:loading="dependencyLoading"
:append-inner-icon="linkedIcon('request_type_id')" @click:append-inner.stop="openLinked('request_type_id')"
@update:search="loadRequestTypes(modelValue.service_type_id as string | number | null, $event || '')"
@update:model-value="selectRequestType" />
<v-textarea v-if="field('request_text')" :model-value="modelValue.request_text"
@ -598,6 +618,7 @@ onMounted(async () => {
:items="solutionOptions" label="Решение" clearable :readonly="readonly"
:disabled="modelValue.request_type_id === null || modelValue.request_type_id === undefined"
:loading="dependencyLoading"
:append-inner-icon="linkedIcon('solution_type_id')" @click:append-inner.stop="openLinked('solution_type_id')"
@update:search="loadSolutions(modelValue.request_type_id as string | number | null, $event || '')"
@update:model-value="selectSolution" />
<v-textarea v-if="field('solution_text')" :model-value="modelValue.solution_text"
@ -612,10 +633,6 @@ onMounted(async () => {
<CommentsTab kind="req" :record-id="modelValue.id as string | number | undefined" :readonly="readonly"
:active="activeTab === 'comments'" />
</v-window-item>
<v-window-item value="attachments">
<AttachmentsTab target-type="req.request" :record-id="modelValue.id as string | number | undefined"
:readonly="readonly" :active="activeTab === 'attachments'" />
</v-window-item>
<v-window-item value="sla">
<SlaCalculationHistory kind="request"
:record-id="modelValue.id as string | number | undefined" />

File diff suppressed because it is too large Load Diff

View File

@ -1,9 +1,19 @@
<script setup lang="ts">
import type { JsonSchema } from '~/types/schema'
const props = defineProps<{ name: string; schema: JsonSchema; modelValue: unknown; required?: boolean; readonly?: boolean }>()
const props = defineProps<{
name: string
schema: JsonSchema
modelValue: unknown
required?: boolean
readonly?: boolean
clearable?: boolean
}>()
const emit = defineEmits<{ 'update:modelValue': [value: unknown] }>()
const label = computed(() => props.schema.title || props.name.replaceAll('_', ' '))
const isActiveField = computed(() => ['is_active', 'isactive', 'active'].includes(props.name))
const label = computed(() => isActiveField.value
? 'active'
: 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) } },
@ -27,6 +37,30 @@ const inputValue = computed(() => {
if (inputType.value === 'time') return props.modelValue.replace(/Z$/, '')
return props.modelValue
})
const timezoneText = ref('')
function formatTimezone(value: unknown) {
if (typeof value === 'string' && /^\d{2}:\d{2}$/.test(value)) return value
const minutes = Math.min(1440, Math.max(0, Number(value) || 0))
return `${String(Math.floor(minutes / 60)).padStart(2, '0')}:${String(minutes % 60).padStart(2, '0')}`
}
function validTimezone(value: string) {
const match = value.match(/^(\d{2}):(\d{2})$/)
if (!match) return false
const hours = Number(match[1])
const minutes = Number(match[2])
return hours < 24 && minutes < 60 || hours === 24 && minutes === 0
}
function updateTimezone(value: string) {
const digits = String(value || '').replace(/\D/g, '').slice(0, 4)
timezoneText.value = digits.length > 2 ? `${digits.slice(0, 2)}:${digits.slice(2)}` : digits
if (!validTimezone(timezoneText.value)) return
const [hours, minutes] = timezoneText.value.split(':').map(Number)
emit('update:modelValue', hours * 60 + minutes)
}
watch(() => props.modelValue, value => {
if (props.name !== 'timezone') return
timezoneText.value = formatTimezone(value)
}, { immediate: true })
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} символов`] : []),
@ -45,13 +79,59 @@ const rules = computed(() => [
@update:model-value="emit('update:modelValue', $event)" />
<v-select v-else-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)" />
<div v-else-if="name === 'theme_is_light'" class="theme-mode-field">
<span class="text-body-2">Тема</span>
<v-btn :icon="modelValue !== false ? 'mdi-white-balance-sunny' : 'mdi-weather-night'"
color="primary" variant="tonal" :disabled="readonly"
:aria-label="modelValue !== false ? 'Включить тёмную тему' : 'Включить светлую тему'"
:title="modelValue !== false ? 'Светлая тема' : 'Тёмная тема'"
@click="emit('update:modelValue', modelValue === false)" />
</div>
<v-text-field v-else-if="name === 'timezone'" :model-value="timezoneText"
label="Timezone" placeholder="00:00" maxlength="5" inputmode="numeric"
:readonly="readonly"
:rules="[(value: string) => validTimezone(value) || 'Введите время от 00:00 до 24:00']"
@update:model-value="updateTimezone" />
<div v-else-if="schema.type === 'boolean' && isActiveField" class="active-switch-field">
<div class="text-caption text-medium-emphasis">{{ label }}</div>
<v-switch :model-value="Boolean(modelValue)" color="primary" :readonly="readonly" hide-details
@update:model-value="emit('update:modelValue', $event)" />
</div>
<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"
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" :readonly="readonly" rows="3" @update:model-value="emit('update:modelValue', $event)" />
<v-text-field v-else :model-value="inputValue" :label="label" :rules="rules"
:type="inputType"
:readonly="readonly" @update:model-value="emit('update:modelValue', schema.type === 'integer' ? Number($event) : $event)" />
:readonly="readonly" :clearable="clearable"
@update:model-value="emit('update:modelValue', schema.type === 'integer' ? Number($event) : $event)" />
</template>
<style scoped>
.active-switch-field {
display: flex;
min-height: 56px;
align-items: center;
justify-content: flex-start;
gap: 8px;
padding-top: 2px;
}
.active-switch-field > .text-caption {
flex: 0 0 auto;
text-align: left;
}
.active-switch-field :deep(.v-switch) {
flex: 0 0 auto;
}
.theme-mode-field {
display: flex;
min-height: 48px;
align-items: center;
gap: 10px;
}
</style>

View File

@ -10,12 +10,14 @@ const props = defineProps<{
loading?: boolean
readonly?: boolean
readonlyFields?: string[]
clearableFields?: string[]
textFields?: string[]
hiddenFields?: string[]
fieldOptions?: Record<string, SelectOption[]>
fieldLabels?: Record<string, string>
relationOptions?: Record<string, SelectOption[]>
relationLabels?: Record<string, string>
fieldLinks?: Record<string, string>
formClass?: string
fieldClasses?: Record<string, string>
tabs?: FormTab[]
@ -24,21 +26,74 @@ const props = defineProps<{
}>()
const emit = defineEmits<{
'update:modelValue': [value: ApiRecord]
'fieldChange': [name: string, value: unknown]
'activeTabChange': [value: string]
'openLinked': [path: string, id: string | number]
submit: []
relationSearch: [name: string, search: string]
}>()
const form = ref()
const activeTab = 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)))
const activeFieldName = computed(() => ['is_active', 'isactive', 'active']
.find(name => {
const field = props.schema.properties?.[name]
return field && !field.readOnly && !props.hiddenFields?.includes(name)
}) || '')
const primaryFieldName = computed(() => {
const properties = props.schema.properties || {}
const visible = (name: string) => properties[name] && name !== activeFieldName.value
&& !properties[name].readOnly && !props.hiddenFields?.includes(name)
return ['name', 'title', 'number', 'code', 'username', 'label', 'value']
.find(visible)
|| Object.keys(properties).find(name => visible(name) && properties[name].type === 'string')
|| ''
})
const fields = computed(() => {
const entries = Object.entries(props.schema.properties || {})
.filter(([name, field]) => !ignoredFields.includes(name)
&& !field.readOnly && !props.hiddenFields?.includes(name))
if (!activeFieldName.value || !primaryFieldName.value) return entries
const activeIndex = entries.findIndex(([name]) => name === activeFieldName.value)
const primaryIndex = entries.findIndex(([name]) => name === primaryFieldName.value)
if (activeIndex < 0 || primaryIndex < 0) return entries
const [activeEntry] = entries.splice(activeIndex, 1)
const nextPrimaryIndex = entries.findIndex(([name]) => name === primaryFieldName.value)
entries.splice(nextPrimaryIndex + 1, 0, activeEntry)
return entries
})
const fieldTabs = computed(() => Object.fromEntries((props.tabs || []).flatMap(tab =>
(tab.fields || []).map(field => [field, tab.value]))))
const defaultTab = computed(() => props.tabs?.[0]?.value || '')
function fieldReadonly(name: string) {
return Boolean(props.readonly || props.readonlyFields?.includes(name))
}
function fieldWidthClass(name: string) {
const field = props.schema.properties?.[name]
if (!field) return ''
if (field.type === 'object' || field.type === 'array'
|| name.includes('description') || name.includes('info') || name.includes('comment')) {
return 'resource-field-wide'
}
if (['date', 'date-time', 'datetime', 'time'].includes(field.format || '')) {
return 'resource-field-date'
}
if (field.type === 'boolean' || field.type === 'integer' || field.type === 'number') {
return 'resource-field-compact'
}
if (field.enum || props.fieldOptions?.[name] || props.relationOptions?.[name]) {
return 'resource-field-select'
}
return 'resource-field-text'
}
function fieldClass(name: string) {
return [
props.fieldClasses?.[name],
fieldWidthClass(name),
name === primaryFieldName.value && activeFieldName.value ? 'resource-primary-field' : '',
name === activeFieldName.value && primaryFieldName.value ? 'resource-active-field' : '',
].filter(Boolean)
}
function fieldLabel(name: string, field: JsonSchema) {
return props.relationLabels?.[name] || props.fieldLabels?.[name]
|| field.title || name.replaceAll('_', ' ')
@ -62,13 +117,17 @@ function tabForField(name: string) { return fieldTabs.value[name] || defaultTab.
watch(() => props.tabs, tabs => {
if (!tabs?.some(tab => tab.value === activeTab.value)) activeTab.value = tabs?.[0]?.value || ''
}, { immediate: true })
watch(activeTab, value => emit('activeTabChange', value), { immediate: true })
const hasCoordinates = computed(() => {
const properties = props.schema.properties
return Boolean(properties?.lat && properties?.lon
&& !props.hiddenFields?.includes('lat')
&& !props.hiddenFields?.includes('lon'))
})
function setField(name: string, value: unknown) { emit('update:modelValue', { ...props.modelValue, [name]: value }) }
function setField(name: string, value: unknown) {
emit('update:modelValue', { ...props.modelValue, [name]: value })
emit('fieldChange', name, value)
}
function setCoordinates(coordinates: Partial<{ lat: number | null; lon: number | null }>) {
emit('update:modelValue', { ...props.modelValue, ...coordinates })
}
@ -85,17 +144,60 @@ function relationRecord(name: string, value: string | number | null) {
const option = props.relationOptions?.[name]?.find(item => String(item.value) === String(value))
return { id: value, ...(option?.title ? { name: option.title } : {}), ...(option?.color ? { color: option.color } : {}) }
}
function linkedValue(name: string): string | number | null {
const value = props.modelValue[name]
if (Array.isArray(value)) return null
if (typeof value === 'string' || typeof value === 'number') return value
if (value && typeof value === 'object') {
const record = value as ApiRecord
const id = record.value ?? record.id
return typeof id === 'string' || typeof id === 'number' ? id : null
}
return null
}
function openLinked(name: string) {
const path = props.fieldLinks?.[name]
const id = linkedValue(name)
if (path && id !== null) emit('openLinked', path, id)
}
function fieldOption(name: string, value: unknown): SelectOption | null {
if (value === null || value === undefined || value === '') return null
if (typeof value === 'object') return value as SelectOption
if (typeof value === 'object') {
const record = value as ApiRecord
const optionValue = record.value ?? record.id
if (typeof optionValue !== 'string' && typeof optionValue !== 'number'
&& typeof optionValue !== 'boolean') return null
const knownOption = props.fieldOptions?.[name]
?.find(option => String(option.value) === String(optionValue))
return knownOption || {
title: String(record.title || record.name || optionValue),
value: optionValue,
...(record.color ? { color: String(record.color) } : {}),
}
}
return props.fieldOptions?.[name]?.find(option => String(option.value) === String(value))
|| { title: String(value), value: value as string | number | boolean }
}
function fieldOptionValue(name: string) {
const value = props.modelValue[name]
return Array.isArray(value)
? value.map(item => fieldOption(name, item)).filter(Boolean)
: fieldOption(name, value)
if (!Array.isArray(value)) return fieldOption(name, value)
if (props.schema.properties?.[name]?.type === 'array') {
return value.map(item => fieldOption(name, item)).filter(Boolean)
}
const [optionValue, optionTitle] = value
const knownOption = props.fieldOptions?.[name]
?.find(option => String(option.value) === String(optionValue))
if (knownOption) return knownOption
if (typeof optionValue !== 'string' && typeof optionValue !== 'number'
&& typeof optionValue !== 'boolean') return null
return {
title: String(optionTitle || optionValue),
value: optionValue,
}
}
function fieldOptionColor(name: string) {
const selected = fieldOptionValue(name)
return selected && !Array.isArray(selected) ? selected.color || '' : ''
}
function setOptionField(name: string, value: SelectOption | SelectOption[] | null) {
setField(name, Array.isArray(value) ? value.map(option => option.value) : value?.value ?? null)
@ -104,7 +206,7 @@ async function submit() { const result = await form.value?.validate(); if (resul
</script>
<template>
<v-form :id="formId" ref="form" :class="formClass" @submit.prevent="submit">
<v-form :id="formId" ref="form" :class="['resource-form-grid', formClass]" @submit.prevent="submit">
<slot name="prepend" />
<v-tabs v-if="tabs?.length" v-model="activeTab" class="mb-4">
<v-tab v-for="tab in tabs" :key="tab.value" :value="tab.value">{{ tab.title }}</v-tab>
@ -113,7 +215,7 @@ async function submit() { const result = await form.value?.validate(); if (resul
<slot name="tab-prepend" :active-tab="activeTab" />
</div>
<template v-for="[name, field] in fields" :key="name">
<div v-show="!tabs?.length || tabForField(name) === activeTab" :class="fieldClasses?.[name]">
<div v-show="!tabs?.length || tabForField(name) === activeTab" :class="fieldClass(name)">
<div v-if="textFields?.includes(name)" class="resource-text-field mb-4">
<div class="text-caption text-medium-emphasis">{{ fieldLabel(name, field) }}</div>
<div class="text-body-1">{{ textFieldValue(name) }}</div>
@ -142,21 +244,52 @@ async function submit() { const result = await form.value?.validate(); if (resul
: []"
:class="{ 'colored-object-field': relationColor(name) }"
:style="relationColor(name) ? { '--field-accent': relationColor(name) } : undefined"
@update:model-value="setField(name, relationRecord(name, $event))" />
:append-inner-icon="fieldLinks?.[name] && linkedValue(name) !== null ? 'mdi-open-in-new' : undefined"
@click:append-inner.stop="openLinked(name)"
@update:model-value="setField(name, relationRecord(name, $event))">
<template #item="{ props: optionProps, item }">
<v-list-item v-bind="optionProps">
<template v-if="item.raw.color" #prepend>
<span class="resource-option-color" :style="{ backgroundColor: item.raw.color }" />
</template>
</v-list-item>
</template>
<template #selection="{ item }">
<span v-if="item.raw.color" class="resource-option-color" :style="{ backgroundColor: item.raw.color }" />
<span>{{ item.title }}</span>
</template>
</v-autocomplete>
<v-autocomplete v-else-if="fieldOptions?.[name]" :model-value="fieldOptionValue(name)"
:items="fieldOptions[name]"
:label="fieldLabels?.[name] || field.title || name.replaceAll('_', ' ')"
:readonly="fieldReadonly(name)" :multiple="field.type === 'array'" :chips="field.type === 'array'"
:append-inner-icon="fieldLinks?.[name] && linkedValue(name) !== null ? 'mdi-open-in-new' : undefined"
:class="{ 'colored-object-field': fieldOptionColor(name) }"
:style="fieldOptionColor(name) ? { '--field-accent': fieldOptionColor(name) } : undefined"
return-object clearable
:rules="Array.isArray(schema.required) && schema.required.includes(name)
? [(value: unknown) => value !== null && value !== undefined || 'Обязательное поле']
: []"
@update:search="emit('relationSearch', name, $event || '')"
@update:model-value="setOptionField(name, $event)" />
@click:append-inner.stop="openLinked(name)"
@update:model-value="setOptionField(name, $event)">
<template #item="{ props: optionProps, item }">
<v-list-item v-bind="optionProps">
<template v-if="item.raw.color" #prepend>
<span class="resource-option-color" :style="{ backgroundColor: item.raw.color }" />
</template>
</v-list-item>
</template>
<template #selection="{ item }">
<span v-if="item.raw.color" class="resource-option-color" :style="{ backgroundColor: item.raw.color }" />
<span>{{ item.title }}</span>
</template>
</v-autocomplete>
<ResourceField v-else :name="name" :schema="field"
:model-value="modelValue[name]"
:required="Array.isArray(schema.required) && schema.required.includes(name)"
:readonly="fieldReadonly(name)"
:clearable="clearableFields?.includes(name)"
@update:model-value="setField(name, $event)" />
</div>
<div v-show="!tabs?.length || tabForField(name) === activeTab" class="field-slot">
@ -175,21 +308,70 @@ async function submit() { const result = await form.value?.validate(); if (resul
display: contents;
}
.resource-option-color {
display: inline-block;
flex: 0 0 auto;
width: 10px;
height: 10px;
margin-right: 8px;
border-radius: 50%;
}
.tab-content {
grid-column: 1 / -1;
min-width: 0;
}
.client-form-grid {
.resource-form-grid {
display: grid;
grid-template-columns: repeat(40, minmax(0, 1fr));
grid-template-columns: repeat(10, minmax(0, 1fr));
column-gap: 16px;
}
.resource-form-grid > :deep(*) {
grid-column: 1 / -1;
}
.resource-form-grid > .resource-primary-field {
grid-column: span 8;
}
.resource-form-grid > .resource-active-field {
grid-column: span 2;
min-width: 96px;
}
.resource-form-grid > .resource-field-compact {
width: 100%;
max-width: 320px;
}
.resource-form-grid > .resource-field-date {
width: 100%;
max-width: 400px;
}
.resource-form-grid > .resource-field-select {
width: 100%;
max-width: 600px;
}
.resource-form-grid > .resource-field-text {
width: 100%;
max-width: 700px;
}
.resource-form-grid > .resource-field-wide {
width: 100%;
max-width: 900px;
}
.client-form-grid {
grid-template-columns: repeat(10, minmax(0, 1fr));
}
.employee-form-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
column-gap: 16px;
grid-template-columns: repeat(10, minmax(0, 1fr));
}
.employee-form-grid > :deep(*) {
@ -197,23 +379,32 @@ async function submit() { const result = await form.value?.validate(); if (resul
}
.employee-form-grid > .employee-name-field {
grid-column: span 1;
grid-column: span 3;
}
.employee-form-grid > .employee-theme-mode {
grid-column: span 5;
}
.employee-form-grid > .employee-timezone {
grid-column: span 3;
}
.client-form-grid > :deep(*) {
grid-column: 1 / -1;
}
.client-form-grid > .client-half {
grid-column: span 20;
grid-column: span 5;
}
.client-form-grid > .client-given-name {
grid-column: span 11;
grid-column: span 3;
}
.client-form-grid > .client-surname {
grid-column: span 18;
grid-column: span 4;
}
.client-form-grid :deep(.address-flat-row) {
@ -222,10 +413,16 @@ async function submit() { const result = await form.value?.validate(); if (resul
min-width: 0;
}
.lead-form-grid > :deep(*) {
grid-column: 1 / -1;
}
.lead-form-grid > .lead-half {
grid-column: span 5;
}
.contract-form-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
column-gap: 16px;
grid-template-columns: repeat(10, minmax(0, 1fr));
}
.contract-form-grid > :deep(*) {
@ -233,13 +430,19 @@ async function submit() { const result = await form.value?.validate(); if (resul
}
.contract-form-grid > .contract-date {
grid-column: span 1;
grid-column: span 5;
width: 100%;
max-width: 400px;
}
.contract-form-grid > .contract-status {
grid-column: 1 / -1;
width: 100%;
max-width: 400px;
}
.holiday-form-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
column-gap: 16px;
grid-template-columns: repeat(10, minmax(0, 1fr));
}
.holiday-form-grid > :deep(*) {
@ -247,13 +450,11 @@ async function submit() { const result = await form.value?.validate(); if (resul
}
.holiday-form-grid > .holiday-date {
grid-column: span 1;
grid-column: span 5;
}
.service-form-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
column-gap: 16px;
grid-template-columns: repeat(10, minmax(0, 1fr));
}
.service-form-grid > :deep(*) {
@ -261,13 +462,25 @@ async function submit() { const result = await form.value?.validate(); if (resul
}
.service-form-grid > .service-half {
grid-column: span 1;
grid-column: span 5;
}
.service-form-grid > .service-client {
grid-column: 1 / 6;
}
.service-form-grid > .service-contract {
grid-column: 6 / -1;
}
.service-form-grid :deep(.address-flat-row) {
grid-column: 1 / -1;
width: 100%;
min-width: 0;
}
.ci-form-grid {
display: grid;
grid-template-columns: repeat(6, minmax(0, 1fr));
column-gap: 16px;
grid-template-columns: repeat(10, minmax(0, 1fr));
row-gap: 16px;
}
@ -276,17 +489,15 @@ async function submit() { const result = await form.value?.validate(); if (resul
}
.ci-form-grid > .ci-half {
grid-column: span 3;
grid-column: span 5;
}
.ci-form-grid > .ci-third {
grid-column: span 2;
grid-column: span 3;
}
.sla-request-form-grid {
display: grid;
grid-template-columns: repeat(6, minmax(0, 1fr));
column-gap: 16px;
grid-template-columns: repeat(10, minmax(0, 1fr));
}
.sla-request-form-grid > :deep(*) {
@ -294,17 +505,15 @@ async function submit() { const result = await form.value?.validate(); if (resul
}
.sla-request-form-grid > .sla-request-client {
grid-column: span 2;
}
.sla-request-form-grid > .sla-request-service {
grid-column: span 3;
}
.sla-request-form-grid > .sla-request-service {
grid-column: span 5;
}
.sla-incident-form-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
column-gap: 16px;
grid-template-columns: repeat(10, minmax(0, 1fr));
}
.sla-incident-form-grid > :deep(*) {
@ -312,10 +521,27 @@ async function submit() { const result = await form.value?.validate(); if (resul
}
.sla-incident-form-grid > .sla-incident-half {
grid-column: span 1;
grid-column: span 5;
}
@media (max-width: 600px) {
.resource-form-grid {
grid-template-columns: 1fr;
}
.resource-form-grid > .resource-primary-field,
.resource-form-grid > .resource-active-field {
grid-column: 1 / -1;
}
.resource-form-grid > .resource-field-compact,
.resource-form-grid > .resource-field-date,
.resource-form-grid > .resource-field-select,
.resource-form-grid > .resource-field-text,
.resource-form-grid > .resource-field-wide {
max-width: none;
}
.holiday-form-grid {
grid-template-columns: 1fr;
}
@ -335,17 +561,37 @@ async function submit() { const result = await form.value?.validate(); if (resul
grid-column: 1 / -1;
}
.employee-form-grid > .employee-theme-mode,
.employee-form-grid > .employee-timezone {
grid-column: 1 / -1;
}
.client-form-grid > .client-half,
.client-form-grid > .client-given-name,
.client-form-grid > .client-surname {
grid-column: 1 / -1;
}
.contract-form-grid > .contract-date {
.client-form-grid :deep(.address-flat-row) {
grid-column: 1 / -1;
}
.service-form-grid > .service-half {
.lead-form-grid > .lead-half {
grid-column: 1 / -1;
}
.contract-form-grid > .contract-date {
grid-column: 1 / -1;
max-width: none;
}
.contract-form-grid > .contract-status {
max-width: none;
}
.service-form-grid > .service-half,
.service-form-grid > .service-client,
.service-form-grid > .service-contract {
grid-column: 1 / -1;
}

View File

@ -40,7 +40,7 @@ const targetDefinitions: Record<string, { title: string; path: string }> = {
'dev.model': { title: 'Модель устройства', path: '/main/dev/models/' },
'dev.software-version': { title: 'Версия ПО', path: '/main/dev/software-versions/' },
'dev.hardware-version': { title: 'Версия оборудования', path: '/main/dev/hardware-versions/' },
'srv.service': { title: 'Сервис', path: '/main/srv/services/' },
'srv.service': { title: 'Услуга', path: '/main/srv/services/' },
'crm.client': { title: 'Клиент', path: '/main/crm/clients/' },
'crm.lead': { title: 'Лид', path: '/main/crm/leads/' },
'crm.contract': { title: 'Договор', path: '/main/crm/contracts/' },

View File

@ -1,10 +1,4 @@
import { useLocale, useTheme } from 'vuetify'
import { resolveThemeColor } from '~/config/theme-colors'
function primaryRgb(value: string) {
const hex = value.replace('#', '')
return [0, 2, 4].map(offset => Number.parseInt(hex.slice(offset, offset + 2), 16)).join(',')
}
export function useUiPreferences() {
const auth = useAuthStore()
@ -15,21 +9,8 @@ export function useUiPreferences() {
watchEffect(() => {
const profile = auth.profile
const themeName = profile?.theme_is_light === false ? 'wanitilDark' : 'wanitilLight'
const primary = resolveThemeColor(
profile?.theme_color ?? 'base',
profile?.theme_is_light !== false,
)
locale.current.value = language.value
theme.themes.value[themeName].colors.primary = primary
theme.global.name.value = themeName
if (import.meta.client) {
const cssValue = primaryRgb(primary)
nextTick(() => {
document.documentElement.style.setProperty('--v-theme-primary', cssValue)
document.querySelectorAll<HTMLElement>(`.v-theme--${themeName}`)
.forEach(element => element.style.setProperty('--v-theme-primary', cssValue))
})
}
})
return { language }
}

View File

@ -21,10 +21,10 @@ export const modules: ModuleDefinition[] = [
{ ...resource('settings', 'Настройки', false, 'settings', 'settings', 'settings', true),
accessKeys: ['settings', 'client-category', 'client-type'] },
] },
{ key: 'service', title: 'Сервисы', icon: 'mdi-room-service', apiPrefix: 'srv', resources: [
resource('services', 'Сервисы'),
resource('requests', 'Запросы сервиса', false, 'request-types', 'settings'),
resource('solutions', 'Решения', false, 'solutions', 'settings'),
{ key: 'service', title: 'Услуги', icon: 'mdi-room-service', apiPrefix: 'srv', resources: [
resource('services', 'Услуги'),
resource('requests', 'Запросы услуг', false, 'request-types', 'settings'),
resource('solutions', 'Решения', false, 'solutions', 'settings', undefined, true),
resource('statuses', 'Статусы', false, 'service-statuses', 'settings'),
resource('types', 'Типы', false, 'service-types', 'settings'),
resource('settings', 'Настройки', false, 'settings', 'settings'),

View File

@ -12612,6 +12612,11 @@
"type": "string",
"description": "Description of the service type",
"maxLength": 1024
},
"color": {
"type": "string",
"default": "",
"maxLength": 7
}
}
},
@ -12627,6 +12632,11 @@
"type": "string",
"description": "Description of the service type",
"maxLength": 1024
},
"color": {
"type": "string",
"default": "",
"maxLength": 7
}
}
},
@ -12642,6 +12652,11 @@
"type": "string",
"description": "Description of the service type",
"maxLength": 1024
},
"color": {
"type": "string",
"default": "",
"maxLength": 7
}
}
}
@ -13461,6 +13476,10 @@
"type": "string",
"maxLength": 64
},
"avatar": {
"type": "integer",
"nullable": true
},
"departments": {
"type": "array",
"items": {
@ -13553,6 +13572,10 @@
"type": "string",
"maxLength": 64
},
"avatar": {
"type": "integer",
"nullable": true
},
"departments": {
"type": "array",
"items": {
@ -13641,6 +13664,10 @@
"type": "string",
"maxLength": 64
},
"avatar": {
"type": "integer",
"nullable": true
},
"departments": {
"type": "array",
"items": {

View File

@ -49,7 +49,7 @@ const secondaryModules = computed(() => visibleModules.value.filter(module => !p
</section>
<section v-if="secondaryModules.length" class="engineer-section engineer-section-secondary">
<div class="engineer-section-heading"><div><h2>Все инструменты</h2><p>Сервисы, справочники и настройки</p></div></div>
<div class="engineer-section-heading"><div><h2>Все инструменты</h2><p>Услуги, справочники и настройки</p></div></div>
<div class="engineer-tools-grid">
<NuxtLink v-for="module in secondaryModules" :key="module.key" :to="`/${module.key}`" class="engineer-tool-card">
<span class="engineer-module-icon"><v-icon size="19">{{ module.icon }}</v-icon></span>

View File

@ -1,6 +1,7 @@
<script setup lang="ts">
import type { UserProfile } from '~/types/api'
import { getThemeColorOptions, normalizeThemeColor, resolveThemeColor } from '~/config/theme-colors'
import type { ApiRecord } from '~/types/api'
import type { JsonSchema } from '~/types/schema'
const auth = useAuthStore()
const { language } = useUiPreferences()
@ -16,15 +17,37 @@ const passwordDialog = ref(false)
const form = reactive<Partial<UserProfile>>({})
const { request } = useApi()
const isEnglish = computed(() => language.value === 'en')
const themeColorOptions = computed(() => getThemeColorOptions(isEnglish.value ? 'en' : 'ru'))
const languages = [
{ title: 'Русский', value: 'ru' },
{ title: 'English', value: 'en' },
{ title: 'en 🇬🇧', value: 'en' },
{ title: 'ru 🇷🇺', value: 'ru' },
{ title: 'fr 🇫🇷', value: 'fr' },
]
const preferencesSchema: JsonSchema = {
type: 'object',
properties: {
lang: { type: 'string', title: 'Язык' },
theme_is_light: { type: 'boolean', title: 'Тема' },
timezone: { type: 'integer', title: 'Timezone' },
},
}
const preferenceFieldOptions = computed(() => ({
lang: languages,
}))
const preferenceFieldClasses = {
theme_is_light: 'employee-theme-mode',
timezone: 'employee-timezone',
}
const profilePreferences = computed<ApiRecord>({
get: () => ({
lang: form.lang,
theme_is_light: form.theme_is_light,
timezone: form.timezone,
}),
set: value => Object.assign(form, value),
})
function reset() {
Object.assign(form, auth.profile || {})
form.theme_color = normalizeThemeColor(auth.profile?.theme_color)
}
watch(() => auth.profile, reset, { immediate: true })
watch(form, value => {
@ -36,7 +59,7 @@ async function save() {
try {
await auth.updateProfile({
lang: form.lang, timezone: form.timezone,
theme_is_light: form.theme_is_light, theme_color: form.theme_color,
theme_is_light: form.theme_is_light,
})
saved.value = true
} catch (e: any) { error.value = e.message || 'Не удалось сохранить профиль' }
@ -85,23 +108,14 @@ function avatarUpdated(avatar: string | number | null, employee: Record<string,
:name="auth.profile?.name || auth.user?.name || auth.user?.username"
@updated="avatarUpdated" />
<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" />
<ResourceForm v-model="profilePreferences" :schema="preferencesSchema"
form-class="employee-form-grid" :field-options="preferenceFieldOptions"
:field-classes="preferenceFieldClasses" hide-actions />
<div class="d-flex justify-end ga-2 mt-4"><v-btn variant="text" prepend-icon="mdi-exit-to-app" @click="exitProfile">{{ isEnglish ? 'Exit' : 'Выход' }}</v-btn>
<v-btn color="primary" :loading="saving" @click="save">{{ isEnglish ? 'Save' : 'Сохранить' }}</v-btn></div>
<v-btn class="profile-save-btn" color="primary" variant="flat"
prepend-icon="mdi-content-save-outline" :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>
@ -169,3 +183,9 @@ function avatarUpdated(avatar: string | number | null, employee: Record<string,
</v-dialog>
</div>
</template>
<style scoped>
.profile-save-btn {
min-width: 132px;
}
</style>

View File

@ -10,19 +10,19 @@ export default defineNuxtPlugin(nuxtApp => {
wanitilLight: {
dark: false,
colors: {
primary: '#2457E6', secondary: '#667085', accent: '#84CC16',
background: '#F4F6FA', surface: '#FFFFFF', error: '#E5484D',
success: '#2F9E64', warning: '#F59E0B', info: '#2F6FED',
'on-background': '#17233C', 'on-surface': '#17233C',
primary: '#2F6FED', secondary: '#64748B', accent: '#0F9F8F',
background: '#F4F7FB', surface: '#FFFFFF', error: '#D92D43',
success: '#16875D', warning: '#C97800', info: '#2563B8',
'on-primary': '#FFFFFF', 'on-background': '#172033', 'on-surface': '#172033',
},
},
wanitilDark: {
dark: true,
colors: {
primary: '#21D4FD', secondary: '#A8B8D8', accent: '#E293D3',
background: '#141727', surface: '#1F2235', error: '#FF667C',
success: '#82D616', warning: '#FBCF33', info: '#21D4FD',
'on-background': '#F8F9FA', 'on-surface': '#F8F9FA',
primary: '#2F6FED', secondary: '#94A3B8', accent: '#2DD4BF',
background: '#0F172A', surface: '#182235', error: '#FF647C',
success: '#42C991', warning: '#F5B942', info: '#70A5FF',
'on-primary': '#FFFFFF', 'on-background': '#E7EEF8', 'on-surface': '#E7EEF8',
},
},
},

View File

@ -1,5 +1,4 @@
import type { CapabilitiesResponse, ManagementObject, PermissionsResponse, SessionUser, UserManagement, UserProfile, UserRole } from '~/types/api'
import { normalizeThemeColor, serializeThemeColor } from '~/config/theme-colors'
interface LoginResponse { token?: string; expiry?: string }
interface SetupStatusResponse { status: 'waiting' | 'completed' }
@ -94,23 +93,14 @@ export const useAuthStore = defineStore('auth', () => {
async function updateProfile(changes: Partial<UserProfile>) {
if (!user.value) throw new Error('Пользователь не загружен')
const body = {
...changes,
...(changes.theme_color !== undefined
? { theme_color: serializeThemeColor(changes.theme_color, changes.theme_is_light !== false) }
: {}),
}
const result = await request<UserProfile | SessionUser>('/main/sys/employees/me/', {
method: 'PATCH',
body,
body: changes,
preserveNulls: changes.avatar === null,
})
const returnedUser = 'username' in result ? result as SessionUser : null
const returnedProfile = returnedUser?.sys_employee || returnedUser?.sys_user_profile || result as UserProfile
profile.value = {
...returnedProfile,
theme_color: normalizeThemeColor(returnedProfile.theme_color),
}
profile.value = returnedProfile
user.value = returnedUser
? { ...user.value, ...returnedUser, sys_employee: profile.value }
: { ...user.value, sys_employee: profile.value }