This commit is contained in:
timur 2026-10-07 01:37:14 +05:00
parent 40715ce28f
commit 57b79f90ef
18 changed files with 1871 additions and 341 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.4 KiB

View File

@ -338,6 +338,8 @@ onMounted(load)
Сохранить доступ
</v-btn>
</div>
<AuditHistory v-if="employee.id !== undefined"
object-type="wanitil.sysemployee" :object-id="employee.id" />
</template>
<v-alert v-else-if="!employeeLoading" type="info" variant="tonal">
Выберите сотрудника для просмотра и изменения его фактического доступа.
@ -375,6 +377,8 @@ onMounted(load)
</v-alert>
<v-switch v-model="form.is_active" label="Профиль активен" color="primary"
:readonly="profileReadonly" />
<AuditHistory v-if="editingProfile?.id !== undefined"
object-type="wanitil.sysprofile" :object-id="editingProfile.id" />
</v-card-text>
<v-card-actions>
<v-spacer />

View File

@ -30,6 +30,7 @@ const downloadingId = ref<string | number | null>(null)
const deletingId = ref<string | number | null>(null)
const loadedKey = ref('')
const error = ref('')
const historyFile = ref<DskFile | null>(null)
const resolvedTargetType = computed(() => props.targetType || (props.kind === 'req' ? 'req.request' : 'inc.incident'))
const targetKey = computed(() => props.recordId === undefined || props.recordId === null
? '' : `${resolvedTargetType.value}:${props.recordId}`)
@ -139,6 +140,8 @@ watch(() => [targetKey.value, props.active], () => {
<template #subtitle>{{ formatSize(file.size) }}<template v-if="file.updated_at || file.created_at">
· {{ formatDateValue(String(file.updated_at || file.created_at)) }}</template></template>
<template #append><div class="d-flex ga-1">
<v-btn type="button" icon="mdi-history" variant="text"
title="История файла" aria-label="История файла" @click="historyFile = file" />
<v-btn type="button" icon="mdi-download" variant="text" color="primary"
:loading="downloadingId === file.id" title="Скачать" aria-label="Скачать файл"
@click="downloadFile(file)" />
@ -155,5 +158,22 @@ watch(() => [targetKey.value, props.active], () => {
Добавить
</v-btn>
</div>
<v-dialog :model-value="Boolean(historyFile)" max-width="1000" scrollable
@update:model-value="!$event && (historyFile = null)">
<v-card v-if="historyFile">
<v-card-title class="d-flex align-center px-6 py-4">
<span>История файла «{{ historyFile.original_name || historyFile.name || `#${historyFile.id}` }}»</span>
<v-spacer />
<v-btn icon="mdi-close" variant="text" aria-label="Закрыть" @click="historyFile = null" />
</v-card-title>
<v-divider />
<v-card-text class="pa-6">
<AuditHistory object-type="wanitil.dskfile" :object-id="historyFile.id" />
<AuditHistory v-for="attachment in historyFile.attachments || []" :key="attachment.id"
object-type="wanitil.dskattachment" :object-id="attachment.id"
:title="`История вложения #${attachment.id}`" />
</v-card-text>
</v-card>
</v-dialog>
</template>
</template>

208
components/AuditHistory.vue Normal file
View File

@ -0,0 +1,208 @@
<script setup lang="ts">
import type { ApiRecord, PaginatedResponse } from '~/types/api'
import { formatDateValue } from '~/utils/date'
interface AuditEvent extends ApiRecord {
id: number
occurred_at: string
actor?: number | null
actor_name?: string
source?: string
request_id?: string
object_type: string
object_id: string
action: string
field?: string
changes?: Record<string, unknown>
reason?: string
}
const props = defineProps<{
objectType: string
objectId: string | number
title?: string
embedded?: boolean
}>()
const { request, normalizeList } = useApi()
const events = ref<AuditEvent[]>([])
const loading = ref(false)
const error = ref('')
const loaded = ref(false)
const expanded = ref<string[]>([])
const page = ref(1)
const pageSize = 20
const total = ref(0)
const action = ref('')
const actionOptions = [
{ title: 'Все операции', value: '' },
{ title: 'Создание', value: 'created' },
{ title: 'Изменение', value: 'updated' },
{ title: 'Добавление связи', value: 'added' },
{ title: 'Удаление связи', value: 'removed' },
{ title: 'Очистка связей', value: 'cleared' },
{ title: 'Удаление', value: 'deleted' },
]
const actionLabels: Record<string, string> = Object.fromEntries(
actionOptions.filter(item => item.value).map(item => [item.value, item.title]),
)
const actionColors: Record<string, string> = {
created: 'success', updated: 'primary', deleted: 'error',
added: 'success', removed: 'warning', cleared: 'warning',
}
function display(value: unknown): string {
if (value === null || value === undefined || value === '') return '—'
if (typeof value === 'boolean') return value ? 'Да' : 'Нет'
if (typeof value === 'string' || typeof value === 'number') return String(value)
try { return JSON.stringify(value, null, 2) }
catch { return String(value) }
}
function changeRows(event: AuditEvent) {
const changes = event.changes
if (!changes || typeof changes !== 'object') return []
return Object.entries(changes).map(([field, value]) => {
if (value && typeof value === 'object' && !Array.isArray(value)
&& ('old' in value || 'new' in value)) {
const pair = value as { old?: unknown; new?: unknown }
return { field, oldValue: display(pair.old), newValue: display(pair.new) }
}
return { field, oldValue: '', newValue: display(value) }
})
}
async function load(force = false) {
if (loading.value || (loaded.value && !force)) return
loading.value = true
error.value = ''
try {
const data = await request<PaginatedResponse<AuditEvent> | AuditEvent[]>('/main/sys/audit-events/', {
query: {
object_type: props.objectType,
object_id: props.objectId,
page: page.value,
page_size: pageSize,
...(action.value ? { action: action.value } : {}),
},
})
const normalized = normalizeList<AuditEvent>(data)
events.value = normalized.items
total.value = normalized.total
loaded.value = true
} catch (caught: any) {
error.value = caught?.status === 403
? 'История доступна только администраторам.'
: caught?.message || 'Не удалось загрузить историю изменений.'
} finally { loading.value = false }
}
function reload() {
loaded.value = false
load()
}
watch(expanded, value => {
if (value.includes('history')) load()
})
watch([page, action], ([newPage], [oldPage]) => {
if (newPage !== oldPage && loaded.value) reload()
else if (loaded.value) {
page.value = 1
reload()
}
})
watch(() => [props.objectType, props.objectId], () => {
events.value = []
total.value = 0
page.value = 1
loaded.value = false
error.value = ''
if (expanded.value.includes('history')) load()
})
</script>
<template>
<v-expansion-panels v-model="expanded" class="audit-history" multiple>
<v-expansion-panel value="history">
<v-expansion-panel-title>
<div class="d-flex align-center ga-2">
<v-icon icon="mdi-history" />
<span>{{ title || 'История изменений' }}</span>
<v-chip v-if="loaded" size="x-small" variant="tonal">{{ total }}</v-chip>
</div>
</v-expansion-panel-title>
<v-expansion-panel-text>
<div class="d-flex flex-wrap align-center ga-3 mb-4">
<v-select v-model="action" :items="actionOptions" label="Операция"
density="compact" variant="outlined" hide-details class="audit-history-filter" />
<v-spacer />
<v-btn type="button" prepend-icon="mdi-refresh" variant="text"
:loading="loading" @click="reload">Обновить</v-btn>
</div>
<div v-if="loading" class="d-flex justify-center py-8">
<v-progress-circular indeterminate color="primary" />
</div>
<v-alert v-else-if="error" type="error" variant="tonal">{{ error }}</v-alert>
<v-alert v-else-if="!events.length" type="info" variant="tonal">
История изменений пока отсутствует.
</v-alert>
<v-timeline v-else side="end" density="compact" truncate-line="both">
<v-timeline-item v-for="event in events" :key="event.id"
:dot-color="actionColors[event.action] || 'grey'" size="small">
<v-card variant="outlined">
<v-card-title class="d-flex flex-wrap align-center ga-2 text-subtitle-1">
<v-chip :color="actionColors[event.action] || 'grey'" size="small" variant="tonal">
{{ actionLabels[event.action] || event.action }}
</v-chip>
<span v-if="event.field" class="text-body-2">{{ event.field }}</span>
<v-spacer />
<span class="text-caption text-medium-emphasis">{{ formatDateValue(event.occurred_at) }}</span>
</v-card-title>
<v-card-text>
<div class="audit-history-meta mb-3">
<span><strong>Пользователь:</strong> {{ event.actor_name || (event.actor ? `#${event.actor}` : 'Система') }}</span>
<span v-if="event.source"><strong>Источник:</strong> {{ event.source }}</span>
<span v-if="event.request_id"><strong>ID операции:</strong> {{ event.request_id }}</span>
</div>
<v-alert v-if="event.reason" type="info" variant="tonal" density="compact" class="mb-3">
{{ event.reason }}
</v-alert>
<div v-for="row in changeRows(event)" :key="row.field" class="audit-history-change">
<strong>{{ row.field.replaceAll('_', ' ') }}</strong>
<template v-if="row.oldValue">
<span class="audit-history-value">{{ row.oldValue }}</span>
<v-icon icon="mdi-arrow-right" size="small" />
</template>
<span class="audit-history-value">{{ row.newValue }}</span>
</div>
</v-card-text>
</v-card>
</v-timeline-item>
</v-timeline>
<v-pagination v-if="total > pageSize" v-model="page"
:length="Math.ceil(total / pageSize)" density="comfortable" class="mt-4" />
</v-expansion-panel-text>
</v-expansion-panel>
</v-expansion-panels>
</template>
<style scoped>
.audit-history { margin-top: 24px; }
.audit-history-filter { max-width: 260px; }
.audit-history-meta { display: flex; flex-wrap: wrap; gap: 8px 20px; }
.audit-history-change {
display: grid;
grid-template-columns: minmax(120px, 0.7fr) minmax(120px, 1fr) auto minmax(120px, 1fr);
gap: 12px;
align-items: start;
padding: 10px 0;
border-top: 1px solid rgb(var(--v-theme-on-surface) / 10%);
}
.audit-history-value { white-space: pre-wrap; overflow-wrap: anywhere; }
@media (max-width: 700px) {
.audit-history-change { grid-template-columns: 1fr; gap: 4px; }
.audit-history-change .v-icon { transform: rotate(90deg); }
}
</style>

View File

@ -3,12 +3,27 @@ import type { ApiRecord } from '~/types/api'
const props = defineProps<{ parentKind: 'change' | 'task'; parentId?: string | number; readonly?: boolean; active?: boolean }>()
const { request, normalizeList } = useApi()
const items = ref<ApiRecord[]>([])
const title = ref('')
const description = ref('')
const loading = ref(false)
const creating = ref(false)
const optionsLoading = ref(false)
const dialog = ref(false)
const createForm = ref()
const error = ref('')
const loadedKey = ref('')
type Option = { title: string; value: string | number; color?: string; department?: string | number | null }
const options = ref<Record<string, Option[]>>({})
const emptyTask = () => ({
title: '', description: '', task_type: null as string | number | null,
priority: null as string | number | null, category: null as string | number | null,
department: null as string | number | null, assignees: [] as (string | number)[],
planned_start_at: '', planned_finish_at: '', progress: 0, external_id: '',
})
const task = reactive(emptyTask())
const dateRangeError = computed(() => {
if (!task.planned_start_at || !task.planned_finish_at) return ''
return new Date(task.planned_start_at).getTime() < new Date(task.planned_finish_at).getTime()
? '' : 'Плановое начало должно быть раньше планового завершения'
})
const key = computed(() => props.parentId === undefined || props.parentId === null ? '' : `${props.parentKind}:${props.parentId}`)
function relationTitle(value: unknown, fallback: string) {
if (value && typeof value === 'object') return String((value as ApiRecord).name || (value as ApiRecord).title || `${fallback} #${(value as ApiRecord).id}`)
@ -28,16 +43,62 @@ async function load(force = false) {
} catch (caught: any) { error.value = caught?.message || 'Не удалось загрузить дочерние задачи' }
finally { loading.value = false }
}
async function loadOptions() {
if (Object.keys(options.value).length) return
optionsLoading.value = true
const definitions: Record<string, string> = {
task_type: '/main/chn/task-types/', priority: '/main/chn/task-priorities/',
category: '/main/chn/task-categories/', department: '/main/sys/departments/',
assignees: '/main/sys/employees/',
}
try {
const entries = await Promise.all(Object.entries(definitions).map(async ([field, path]) => {
const data = await request<any>(path, { query: { page_size: 1000 } })
return [field, normalizeList(data).items.filter(item => item.id !== undefined).map(item => ({
title: String(item.employee_name || item.name || item.fullname || item.username || `Объект #${item.id}`),
value: item.id as string | number,
...(item.color ? { color: String(item.color) } : {}),
...(field === 'task_type' ? { department: relationId(item.department) } : {}),
}))] as const
}))
options.value = Object.fromEntries(entries)
} catch (caught: any) {
error.value = caught?.message || 'Не удалось загрузить параметры задачи'
} finally { optionsLoading.value = false }
}
function relationId(value: unknown): string | number | null {
if (typeof value === 'string' || typeof value === 'number') return value
if (value && typeof value === 'object') return relationId((value as ApiRecord).id)
return null
}
async function openCreate() {
Object.assign(task, emptyTask())
dialog.value = true
await loadOptions()
}
function selectTaskType(value: string | number | null) {
task.task_type = value
const department = options.value.task_type?.find(option => String(option.value) === String(value))?.department
if (department !== undefined && department !== null) task.department = department
}
async function create() {
if (!key.value || !title.value.trim()) return
const validation = await createForm.value?.validate()
if (!key.value || validation?.valid === false || !task.title.trim() || dateRangeError.value) return
creating.value = true
error.value = ''
try {
await request(`/main/chn/${props.parentKind === 'task' ? 'tasks' : 'changes'}/${props.parentId}/child-tasks/`, {
method: 'POST', body: { title: title.value.trim(), description: description.value },
method: 'POST', body: {
title: task.title.trim(), description: task.description,
task_type: task.task_type, priority: task.priority, category: task.category,
department: task.department, assignees: task.assignees,
planned_start_at: task.planned_start_at || null,
planned_finish_at: task.planned_finish_at || null,
progress: Number(task.progress) || 0,
external_id: task.external_id,
},
})
title.value = ''
description.value = ''
dialog.value = false
await load(true)
} catch (caught: any) { error.value = caught?.message || 'Не удалось создать дочернюю задачу' }
finally { creating.value = false }
@ -48,22 +109,66 @@ watch(() => [key.value, props.active], () => { if (props.active !== false) load(
<template>
<v-alert v-if="!key" 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-text-field v-model="title" label="Название" required @keyup.enter="create" />
<v-textarea v-model="description" label="Описание" rows="3" />
<div class="d-flex justify-end"><v-btn type="button" color="primary" prepend-icon="mdi-plus"
:disabled="!title.trim()" :loading="creating" @click="create">Добавить</v-btn></div>
</v-card-text>
</v-card>
<h3 class="text-subtitle-1 font-weight-bold mb-4">Дочерние задачи</h3>
<v-dialog v-model="dialog" max-width="960" scrollable>
<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" @click="dialog = false" />
</v-card-title>
<v-divider />
<v-card-text class="pa-6">
<v-form ref="createForm" @submit.prevent="create">
<v-text-field v-model="task.title" label="Название"
:rules="[(value: string) => Boolean(value?.trim()) || 'Укажите название']" required />
<v-textarea v-model="task.description" label="Описание" rows="3" />
<v-alert v-if="dateRangeError" type="error" variant="tonal" density="compact" class="mb-4">
{{ dateRangeError }}
</v-alert>
<v-row>
<v-col cols="12" md="6"><v-autocomplete :model-value="task.task_type"
:items="options.task_type || []" label="Тип задачи" clearable :loading="optionsLoading"
@update:model-value="selectTaskType" /></v-col>
<v-col cols="12" md="6"><v-autocomplete v-model="task.category"
:items="options.category || []" label="Категория" clearable :loading="optionsLoading" /></v-col>
<v-col cols="12" md="6"><v-autocomplete v-model="task.priority"
:items="options.priority || []" label="Приоритет" clearable :loading="optionsLoading" /></v-col>
<v-col cols="12" md="6"><v-autocomplete v-model="task.department"
:items="options.department || []" label="Подразделение" clearable :loading="optionsLoading" /></v-col>
<v-col cols="12"><v-autocomplete v-model="task.assignees"
:items="options.assignees || []" label="Исполнители" multiple chips closable-chips clearable
:loading="optionsLoading" /></v-col>
<v-col cols="12" md="6"><v-text-field v-model="task.planned_start_at"
label="Плановое начало" type="datetime-local" /></v-col>
<v-col cols="12" md="6"><v-text-field v-model="task.planned_finish_at"
label="Плановое завершение" type="datetime-local"
:rules="[() => !dateRangeError || dateRangeError]" /></v-col>
<v-col cols="12" md="6"><v-text-field v-model.number="task.progress"
label="Прогресс" type="number" min="0" max="100" suffix="%" /></v-col>
<v-col cols="12" md="6"><v-text-field v-model="task.external_id"
label="Внешний ID" /></v-col>
</v-row>
</v-form>
</v-card-text>
<v-divider />
<v-card-actions class="px-6 py-4">
<v-spacer /><v-btn variant="text" @click="dialog = false">Отмена</v-btn>
<v-btn color="primary" :loading="creating" :disabled="optionsLoading" @click="create">Создать</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
<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-alert v-else-if="!items.length" type="info" variant="tonal">Дочерних задач пока нет.</v-alert>
<v-list v-else border rounded lines="two">
<v-alert v-else-if="!items.length" type="info" variant="tonal" class="mb-4">Дочерних задач пока нет.</v-alert>
<v-list v-else border rounded lines="two" class="mb-4">
<v-list-item v-for="task in items" :key="String(task.id)" prepend-icon="mdi-subdirectory-arrow-right"
:title="String(task.title || `Задача #${task.id}`)"
:subtitle="[relationTitle(task.status, 'Статус'), task.progress !== undefined ? `Прогресс: ${task.progress}%` : ''].filter(Boolean).join(' · ')" />
</v-list>
<div v-if="!readonly" class="d-flex justify-end">
<v-btn type="button" color="primary" prepend-icon="mdi-plus" @click="openCreate">
Добавить дочернюю задачу
</v-btn>
</div>
</template>
</template>

View File

@ -24,6 +24,7 @@ const deletingId = ref<string | number | null>(null)
const error = ref('')
const createDialog = ref(false)
const graphDialog = ref(false)
const historyRelation = ref<RelationItem | null>(null)
function relatedCi(item: RelationItem) {
return (item.direction === 'outgoing' ? item.ci_rel : item.ci) as ApiRecord | undefined
@ -145,13 +146,16 @@ watch(() => props.ciId, load, { immediate: true })
<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="relations.length" class="border rounded-lg mb-5" lines="two">
<v-list v-if="relations.length" class="ci-relations-list border rounded-lg mb-5" lines="two">
<v-list-item v-for="item in relations" :key="item.id"
:title="relatedTitle(item)" :subtitle="relationSubtitle(item) || undefined">
<template #prepend>
<v-icon :icon="item.direction === 'outgoing' ? 'mdi-arrow-right' : 'mdi-arrow-left'" />
</template>
<template #append>
<v-btn v-if="item.id !== undefined" icon="mdi-history" variant="text"
title="История связи" aria-label="История связи"
@click="historyRelation = item" />
<v-btn v-if="!readonly" icon="mdi-delete-outline" variant="text" color="error"
:loading="String(deletingId) === String(item.id)" aria-label="Удалить связь"
@click="remove(item)" />
@ -200,6 +204,22 @@ watch(() => props.ciId, load, { immediate: true })
</v-card>
</v-dialog>
<v-dialog :model-value="Boolean(historyRelation)" max-width="1000" scrollable
@update:model-value="!$event && (historyRelation = null)">
<v-card v-if="historyRelation">
<v-card-title class="d-flex align-center px-6 py-4">
<span>История связи CI #{{ historyRelation.id }}</span>
<v-spacer />
<v-btn icon="mdi-close" variant="text" aria-label="Закрыть"
@click="historyRelation = null" />
</v-card-title>
<v-divider />
<v-card-text class="pa-6">
<AuditHistory object-type="wanitil.cimrelation" :object-id="historyRelation.id!" />
</v-card-text>
</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">
@ -219,6 +239,11 @@ watch(() => props.ciId, load, { immediate: true })
</template>
<style scoped>
.ci-relations-list {
max-height: 400px;
overflow-y: auto;
}
.ci-graph-dialog-content {
overflow: auto;
}

View File

@ -11,6 +11,8 @@ const props = defineProps<{
const { request, normalizeList } = useApi()
const activities = ref<ApiRecord[]>([])
const callDetails = ref<Record<string, ApiRecord>>({})
const callDetailErrors = ref<Record<string, string>>({})
const loading = ref(false)
const loaded = ref(false)
const error = ref('')
@ -18,11 +20,12 @@ const createDialog = ref(false)
const createLoading = ref(false)
const createError = ref('')
const createMode = ref<'comment' | 'task' | 'reminder'>('comment')
const editingActivity = ref<ApiRecord | null>(null)
const newActivity = reactive({ title: '', text: '', occurredAt: '' })
const newTask = reactive({ taskType: null as number | null, status: null as number | null,
priority: null as number | null, category: null as number | null, department: null as number | null,
assignees: [] as number[], plannedStartAt: '', plannedFinishAt: '' })
const newReminder = reactive({ remindAt: '' })
const newReminder = reactive({ remindAt: '', recipientIds: [] as number[] })
const taskTypes = ref<{ title: string; value: number }[]>([])
const taskStatuses = ref<{ title: string; value: number }[]>([])
const taskPriorities = ref<{ title: string; value: number }[]>([])
@ -40,6 +43,108 @@ const typePresentation: Record<string, { title: string; icon: string; color: str
reminder: { title: 'Напоминание', icon: 'mdi-bell-outline', color: 'warning' },
}
const callDirections: Record<string, string> = {
incoming: 'Входящий',
outgoing: 'Исходящий',
}
const callStatuses: Record<string, { title: string; color: string }> = {
ringing: { title: 'Звонок', color: 'info' },
answered: { title: 'Отвечен', color: 'success' },
completed: { title: 'Завершён', color: 'success' },
missed: { title: 'Пропущен', color: 'error' },
failed: { title: 'Ошибка', color: 'error' },
canceled: { title: 'Отменён', color: 'grey' },
}
const transcriptionStatuses: Record<string, { title: string; color: string }> = {
not_requested: { title: 'Не запрашивалась', color: 'grey' },
pending: { title: 'Обрабатывается', color: 'warning' },
completed: { title: 'Готова', color: 'success' },
failed: { title: 'Ошибка', color: 'error' },
}
const transcriptSpeakers: Record<string, string> = {
manager: 'Менеджер',
client: 'Клиент',
agent: 'Оператор',
customer: 'Клиент',
}
function callKey(activity: ApiRecord) {
return String(activity.reference_id ?? activity.id ?? '')
}
function callDetail(activity: ApiRecord) {
return callDetails.value[callKey(activity)]
}
function callStatus(call: ApiRecord) {
const status = String(call.status || '')
return callStatuses[status] || { title: status || 'Статус не указан', color: 'grey' }
}
function transcriptionStatus(call: ApiRecord) {
const status = String(call.transcription_status || 'not_requested')
return transcriptionStatuses[status] || { title: status, color: 'grey' }
}
function formatDuration(value: unknown) {
const total = Number(value)
if (!Number.isFinite(total) || total < 0) return ''
const seconds = Math.floor(total)
const hours = Math.floor(seconds / 3600)
const minutes = Math.floor((seconds % 3600) / 60)
const rest = seconds % 60
return hours
? `${hours} ч ${String(minutes).padStart(2, '0')} мин ${String(rest).padStart(2, '0')} с`
: minutes ? `${minutes} мин ${String(rest).padStart(2, '0')} с` : `${rest} с`
}
function callTranscript(call: ApiRecord) {
return Array.isArray(call.transcript) ? call.transcript.filter(item => item && typeof item === 'object') as ApiRecord[] : []
}
function transcriptOffset(value: unknown) {
const seconds = Number(value)
if (!Number.isFinite(seconds) || seconds < 0) return ''
const minutes = Math.floor(seconds / 60)
return `${minutes}:${String(Math.floor(seconds % 60)).padStart(2, '0')}`
}
function recordingSource(call: ApiRecord) {
return String(call.recording_file || call.recording_url || '')
}
async function loadCallDetails(items: ApiRecord[]) {
const calls = items.filter(item => String(item.type) === 'call')
await Promise.all(calls.map(async activity => {
const key = callKey(activity)
if (callDetails.value[key]) return
const embedded = activity.call_details || activity.call || activity.reference
if (embedded && typeof embedded === 'object') {
callDetails.value = { ...callDetails.value, [key]: embedded as ApiRecord }
return
}
if (activity.reference_id === undefined || activity.reference_id === null) {
callDetailErrors.value = {
...callDetailErrors.value,
[key]: 'У активности не указан связанный звонок',
}
return
}
try {
const call = await request<ApiRecord>(`/main/con/calls/${activity.reference_id}/`)
callDetails.value = { ...callDetails.value, [key]: call }
} catch (caught: any) {
callDetailErrors.value = {
...callDetailErrors.value,
[key]: caught?.message || 'Не удалось загрузить данные звонка',
}
}
}))
}
function presentation(activity: ApiRecord) {
const type = String(activity.type || '')
return typePresentation[type] || { title: type || 'Активность', icon: 'mdi-circle-outline', color: 'grey' }
@ -50,6 +155,13 @@ function localDateTimeValue() {
return new Date(now.getTime() - now.getTimezoneOffset() * 60_000).toISOString().slice(0, 16)
}
function dateTimeInputValue(value: unknown) {
if (!value) return ''
const date = new Date(String(value))
if (Number.isNaN(date.getTime())) return ''
return new Date(date.getTime() - date.getTimezoneOffset() * 60_000).toISOString().slice(0, 16)
}
async function loadOptions(path: string, fallback: string) {
const data = await request<any>(path, { query: { page_size: 1000 } })
return normalizeList(data).items.filter(item => typeof item.id === 'number').map(item => ({
@ -105,6 +217,7 @@ watch(() => newTask.department, async departmentId => {
})
async function openCreate(mode: 'comment' | 'task' | 'reminder') {
editingActivity.value = null
createMode.value = mode
newActivity.title = ''
newActivity.text = ''
@ -119,8 +232,19 @@ async function openCreate(mode: 'comment' | 'task' | 'reminder') {
newTask.plannedFinishAt = ''
newReminder.remindAt = new Date(Date.now() + 24 * 60 * 60_000
- new Date().getTimezoneOffset() * 60_000).toISOString().slice(0, 16)
newReminder.recipientIds = []
createError.value = ''
createDialog.value = true
if (mode === 'reminder' && !employees.value.length) {
createLoading.value = true
try {
employees.value = await loadEmployeeOptions(null)
} catch (caught: any) {
createError.value = caught?.message || 'Не удалось загрузить список получателей'
} finally {
createLoading.value = false
}
}
if (mode === 'task' && (!taskTypes.value.length || !taskPriorities.value.length)) {
createLoading.value = true
try {
@ -146,6 +270,48 @@ async function openCreate(mode: 'comment' | 'task' | 'reminder') {
}
}
function reminderRecipientIds(reminder: ApiRecord) {
const values = reminder.recipient_ids || reminder.recipients || reminder.recipient
const items = Array.isArray(values) ? values : values === null || values === undefined ? [] : [values]
return items.map(value => {
if (typeof value === 'number') return value
if (typeof value === 'string' && value) return Number(value)
if (value && typeof value === 'object') return Number((value as ApiRecord).id)
return NaN
}).filter(Number.isFinite)
}
async function openEdit(activity: ApiRecord) {
if (activity.id === undefined || !['comment', 'reminder'].includes(String(activity.type))) return
editingActivity.value = activity
createMode.value = String(activity.type) as 'comment' | 'reminder'
newActivity.title = String(activity.title || '')
newActivity.text = String(activity.text || '')
newActivity.occurredAt = dateTimeInputValue(activity.occurred_at)
newReminder.remindAt = ''
newReminder.recipientIds = []
createError.value = ''
createDialog.value = true
if (createMode.value !== 'reminder') return
createLoading.value = true
try {
const [employeeOptions, reminder] = await Promise.all([
employees.value.length ? Promise.resolve(employees.value) : loadEmployeeOptions(null),
activity.reference_id !== undefined && activity.reference_id !== null
? request<ApiRecord>(`/main/sys/reminders/${activity.reference_id}/`)
: Promise.reject(new Error('У активности не указано связанное напоминание')),
])
employees.value = employeeOptions
newReminder.remindAt = dateTimeInputValue(reminder.remind_at)
newReminder.recipientIds = reminderRecipientIds(reminder)
} catch (caught: any) {
createError.value = caught?.message || 'Не удалось загрузить напоминание'
} finally {
createLoading.value = false
}
}
async function createActivity() {
if (props.subjectId === undefined || props.subjectId === null) return
if (!newActivity.title.trim() && !newActivity.text.trim()) {
@ -179,6 +345,39 @@ async function createActivity() {
createLoading.value = true
createError.value = ''
try {
if (editingActivity.value) {
const activity = editingActivity.value
const updatedActivity = await request<ApiRecord>(`/main/crm/activities/${activity.id}/`, {
method: 'PATCH',
body: {
title: newActivity.title.trim(),
text: newActivity.text.trim(),
...(createMode.value === 'comment'
? { occurred_at: new Date(newActivity.occurredAt).toISOString() }
: {}),
},
})
if (createMode.value === 'reminder') {
if (activity.reference_id === undefined || activity.reference_id === null) {
throw new Error('У активности не указано связанное напоминание')
}
await request(`/main/sys/reminders/${activity.reference_id}/`, {
method: 'PATCH',
body: {
title: newActivity.title.trim(),
text: newActivity.text.trim(),
remind_at: new Date(newReminder.remindAt).toISOString(),
recipient_ids: newReminder.recipientIds,
},
})
}
activities.value = activities.value.map(item => String(item.id) === String(activity.id)
? { ...item, ...updatedActivity, title: newActivity.title.trim(), text: newActivity.text.trim() }
: item)
editingActivity.value = null
createDialog.value = false
return
}
let created = await request<ApiRecord>('/main/crm/activities/', {
method: 'POST',
body: {
@ -215,7 +414,8 @@ async function createActivity() {
const reminder = await request<ApiRecord>(`/main/crm/activities/${created.id}/create-reminder/`, {
method: 'POST',
body: { title: newActivity.title.trim(), text: newActivity.text.trim(),
remind_at: new Date(newReminder.remindAt).toISOString() },
remind_at: new Date(newReminder.remindAt).toISOString(),
recipient_ids: newReminder.recipientIds },
})
created = { ...created, type: 'reminder', reference_type: 'reminder', reference_id: reminder.id }
}
@ -243,6 +443,7 @@ async function load() {
},
})
activities.value = normalizeList(data).items
await loadCallDetails(activities.value)
loaded.value = true
} catch (caught: any) {
error.value = caught?.message || 'Не удалось загрузить активности'
@ -253,6 +454,8 @@ async function load() {
watch([() => props.subjectType, () => props.subjectId], () => {
activities.value = []
callDetails.value = {}
callDetailErrors.value = {}
loaded.value = false
error.value = ''
load()
@ -264,7 +467,8 @@ watch(() => props.active, load, { immediate: true })
<div v-if="subjectId !== undefined && subjectId !== null && canCreate" class="d-flex flex-wrap justify-end ga-2 mb-4">
<v-btn variant="outlined" prepend-icon="mdi-comment-plus-outline" @click="openCreate('comment')">Комментарий</v-btn>
<v-btn variant="outlined" prepend-icon="mdi-bell-plus-outline" @click="openCreate('reminder')">Напоминание</v-btn>
<v-btn color="primary" prepend-icon="mdi-checkbox-marked-circle-plus-outline" @click="openCreate('task')">Задача</v-btn>
<v-btn variant="outlined" prepend-icon="mdi-checkbox-marked-circle-plus-outline"
@click="openCreate('task')">Задача</v-btn>
</div>
<v-alert v-if="subjectId === undefined || subjectId === null" type="info" variant="tonal">
Сохраните объект, чтобы управлять его активностями.
@ -285,16 +489,127 @@ watch(() => props.active, load, { immediate: true })
<v-chip size="x-small" variant="tonal" :color="presentation(activity).color">
{{ presentation(activity).title }}
</v-chip>
<v-spacer />
<v-btn v-if="canCreate && ['comment', 'reminder'].includes(String(activity.type))"
icon="mdi-pencil-outline" size="small" variant="text"
:aria-label="`Редактировать ${presentation(activity).title.toLowerCase()}`"
@click="openEdit(activity)" />
</v-card-title>
<v-card-subtitle>{{ formatDateValue(activity.occurred_at) }}</v-card-subtitle>
<v-card-text v-if="activity.text" class="activity-text">{{ activity.text }}</v-card-text>
<v-card-text v-if="String(activity.type) === 'call'" class="pt-2">
<v-alert v-if="callDetailErrors[callKey(activity)]" type="warning" variant="tonal" density="compact">
{{ callDetailErrors[callKey(activity)] }}
</v-alert>
<div v-else-if="!callDetail(activity)" class="d-flex align-center ga-2 text-medium-emphasis">
<v-progress-circular indeterminate size="18" width="2" />
<span>Загрузка данных звонка...</span>
</div>
<template v-else>
<div class="d-flex flex-wrap align-center ga-2 mb-3">
<v-chip size="small" variant="tonal" prepend-icon="mdi-swap-horizontal">
{{ callDirections[String(callDetail(activity).direction)] || callDetail(activity).direction || 'Направление не указано' }}
</v-chip>
<v-chip size="small" variant="tonal" :color="callStatus(callDetail(activity)).color">
{{ callStatus(callDetail(activity)).title }}
</v-chip>
<v-chip v-if="formatDuration(callDetail(activity).duration_seconds)" size="small"
variant="tonal" prepend-icon="mdi-timer-outline">
{{ formatDuration(callDetail(activity).duration_seconds) }}
</v-chip>
</div>
<dl class="call-info-grid">
<template v-if="callDetail(activity).caller_number">
<dt>От кого</dt>
<dd>{{ callDetail(activity).caller_number }}</dd>
</template>
<template v-if="callDetail(activity).callee_number">
<dt>Кому</dt>
<dd>{{ callDetail(activity).callee_number }}</dd>
</template>
<template v-if="callDetail(activity).started_at">
<dt>Начало</dt>
<dd>{{ formatDateValue(callDetail(activity).started_at) }}</dd>
</template>
<template v-if="callDetail(activity).answered_at">
<dt>Ответ</dt>
<dd>{{ formatDateValue(callDetail(activity).answered_at) }}</dd>
</template>
<template v-if="callDetail(activity).ended_at">
<dt>Завершение</dt>
<dd>{{ formatDateValue(callDetail(activity).ended_at) }}</dd>
</template>
<template v-if="callDetail(activity).disposition">
<dt>Результат</dt>
<dd>{{ callDetail(activity).disposition }}</dd>
</template>
<template v-if="callDetail(activity).provider">
<dt>Телефония</dt>
<dd>{{ callDetail(activity).provider }}</dd>
</template>
</dl>
<audio v-if="recordingSource(callDetail(activity))" class="call-recording mt-3" controls preload="none"
:src="recordingSource(callDetail(activity))">
Ваш браузер не поддерживает воспроизведение аудио.
</audio>
<div v-if="callDetail(activity).note" class="call-note mt-3">
<div class="text-caption text-medium-emphasis mb-1">Заметка</div>
<div class="activity-text">{{ callDetail(activity).note }}</div>
</div>
<v-expansion-panels v-if="callTranscript(callDetail(activity)).length
|| !['', 'not_requested'].includes(String(callDetail(activity).transcription_status || ''))"
class="mt-3" variant="accordion">
<v-expansion-panel>
<v-expansion-panel-title>
<v-icon icon="mdi-text-box-outline" class="mr-2" />
Транскрипция звонка
<v-chip class="ml-2" size="x-small" variant="tonal"
:color="transcriptionStatus(callDetail(activity)).color">
{{ transcriptionStatus(callDetail(activity)).title }}
</v-chip>
</v-expansion-panel-title>
<v-expansion-panel-text>
<div v-if="callDetail(activity).transcript_language"
class="text-caption text-medium-emphasis mb-3">
Язык: {{ callDetail(activity).transcript_language }}
</div>
<div v-if="callTranscript(callDetail(activity)).length" class="transcript-list">
<div v-for="(segment, segmentIndex) in callTranscript(callDetail(activity))"
:key="segmentIndex" class="transcript-segment">
<div class="d-flex align-center ga-2 mb-1">
<strong>{{ transcriptSpeakers[String(segment.speaker)] || segment.speaker }}</strong>
<span v-if="transcriptOffset(segment.start_seconds)" class="text-caption text-medium-emphasis">
{{ transcriptOffset(segment.start_seconds) }}
</span>
</div>
<div class="activity-text">{{ segment.text }}</div>
</div>
</div>
<div v-else class="text-medium-emphasis">
{{ String(callDetail(activity).transcription_status) === 'failed'
? 'Не удалось сформировать транскрипцию.'
: 'Транскрипция ещё не готова.' }}
</div>
</v-expansion-panel-text>
</v-expansion-panel>
</v-expansion-panels>
</template>
</v-card-text>
</v-card>
</v-timeline-item>
</v-timeline>
<v-dialog v-model="createDialog" max-width="560">
<v-card>
<v-card-title class="pt-6 px-6">{{ createMode === 'task' ? 'Новая задача' : createMode === 'reminder' ? 'Новое напоминание' : 'Новая активность' }}</v-card-title>
<v-card-title class="pt-6 px-6">
{{ editingActivity
? createMode === 'reminder' ? 'Редактирование напоминания' : 'Редактирование комментария'
: createMode === 'task' ? 'Новая задача' : createMode === 'reminder' ? 'Новое напоминание' : 'Новая активность' }}
</v-card-title>
<v-card-text>
<v-alert v-if="createError" type="error" variant="tonal" class="mb-4">{{ createError }}</v-alert>
<v-text-field v-model="newActivity.title" label="Заголовок" maxlength="256" />
@ -312,15 +627,21 @@ watch(() => props.active, load, { immediate: true })
<v-text-field v-model="newTask.plannedStartAt" label="Плановое начало" type="datetime-local" clearable />
<v-text-field v-model="newTask.plannedFinishAt" label="Плановое завершение" type="datetime-local" clearable />
</template>
<v-text-field v-else-if="createMode === 'reminder'" v-model="newReminder.remindAt"
label="Напомнить *" type="datetime-local" required />
<template v-else-if="createMode === 'reminder'">
<v-text-field v-model="newReminder.remindAt"
label="Напомнить *" type="datetime-local" required />
<v-autocomplete v-model="newReminder.recipientIds" :items="employees"
label="Получатели" multiple chips closable-chips clearable
no-data-text="Сотрудники не найдены" />
</template>
<v-text-field v-else v-model="newActivity.occurredAt" label="Дата и время" type="datetime-local" required />
</v-card-text>
<v-card-actions class="px-6 pb-6">
<v-spacer />
<v-btn :disabled="createLoading" @click="createDialog = false">Отмена</v-btn>
<v-btn color="primary" variant="flat" :loading="createLoading" @click="createActivity">
{{ createMode === 'task' ? 'Создать задачу' : createMode === 'reminder' ? 'Создать напоминание' : 'Добавить' }}
{{ editingActivity ? 'Сохранить'
: createMode === 'task' ? 'Создать задачу' : createMode === 'reminder' ? 'Создать напоминание' : 'Добавить' }}
</v-btn>
</v-card-actions>
</v-card>
@ -331,4 +652,42 @@ watch(() => props.active, load, { immediate: true })
.activity-text {
white-space: pre-wrap;
}
.call-info-grid {
display: grid;
grid-template-columns: max-content minmax(0, 1fr);
gap: 4px 16px;
margin: 0;
}
.call-info-grid dt {
color: rgb(var(--v-theme-on-surface-variant));
}
.call-info-grid dd {
margin: 0;
overflow-wrap: anywhere;
}
.call-recording {
display: block;
width: 100%;
max-width: 520px;
}
.call-note {
padding: 12px;
border-radius: 8px;
background: rgb(var(--v-theme-surface-variant));
}
.transcript-list {
display: grid;
gap: 12px;
}
.transcript-segment {
padding-left: 12px;
border-left: 2px solid rgb(var(--v-theme-primary));
}
</style>

View File

@ -31,10 +31,6 @@ const serviceOptions = ref<Option[]>([])
const requestTypeOptions = ref<Option[]>([])
const solutionOptions = ref<Option[]>([])
const selectedClientRecord = ref<ApiRecord | null>(null)
const historyRecords = ref<ApiRecord[]>([])
const historyLoading = ref(false)
const historyError = ref('')
const historyLoaded = ref(false)
const slaCalculations = ref<ApiRecord[]>([])
const slaTotals = ref<ApiRecord[]>([])
const slaLoading = ref(false)
@ -69,8 +65,6 @@ function set(name: string, value: unknown) {
}
function applyStatusRecord(record: ApiRecord) {
emit('update:modelValue', { ...props.modelValue, ...record })
historyLoaded.value = false
historyRecords.value = []
}
function relationId(record: ApiRecord, nestedName: string, scalarName: string) {
const nested = record[nestedName] as ApiRecord | undefined
@ -292,31 +286,6 @@ async function saveBeforeStatusChange() {
const createdValue = computed(() => props.modelValue.created_at || props.modelValue.created
|| props.modelValue.datecreate || props.modelValue.date_create || props.modelValue.create_date)
const historyMetaFields = new Set([
'history_id', 'history_date', 'history_type', 'history_user', 'history_change_reason',
'id', 'info', 'extra', 'extras',
])
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: 'Тип запроса',
request_text: 'Текст запроса', solution_type_name: 'Решение', solution_text: 'Текст решения',
house_name: 'Адрес', flat: 'Квартира', lat: 'Широта', lon: 'Долгота',
contact_type_name: 'Тип контакта', contact_value: 'Контакт', req_source_type: 'Источник',
}
function historyValue(value: unknown) {
if (value === null || value === undefined || value === '') return '—'
if (typeof value === 'boolean') return value ? 'Да' : 'Нет'
if (typeof value === 'object') {
const record = value as ApiRecord
return String(record.name || record.fullname || record.username || record.id || JSON.stringify(value))
}
return typeof value === 'string' ? formatDateValue(value) : String(value)
}
function historyType(value: unknown) {
return ({ '+': 'Создание', '~': 'Изменение', '-': 'Удаление' } as Record<string, string>)[String(value)]
|| String(value || 'Изменение')
}
const slaTypeNames: Record<string, string> = {
'0': 'Не определён', '1': 'Начало SLA', '2': 'Работа',
'5': 'Приостановка SLA', '10': 'Завершение SLA',
@ -348,43 +317,6 @@ const filteredSlaCalculations = computed(() => {
return slaCalculations.value.filter(calculation =>
String(slaAgreementId(calculation)) === String(agreementId))
})
const historyEntries = computed(() => historyRecords.value.map((record, index, records) => {
const previous = records[index - 1]
const fields = new Set([
...Object.keys(previous || {}),
...Object.keys(record),
].filter(name => !historyMetaFields.has(name)))
const changes = [...fields].flatMap(name => {
const oldValue = previous?.[name]
const newValue = record[name]
if (JSON.stringify(oldValue ?? null) === JSON.stringify(newValue ?? null)) return []
return [{
name,
label: historyFieldLabels[name] || name.replaceAll('_', ' '),
oldValue: previous ? historyValue(oldValue) : '—',
newValue: historyValue(newValue),
}]
})
return { record, changes }
}))
async function loadHistory() {
if (historyLoaded.value || props.modelValue.id === undefined || props.modelValue.id === null) return
historyLoading.value = true
historyError.value = ''
try {
const data = await request<any>('/main/req/request-history/', {
query: { page_size: 1000, id__exact: props.modelValue.id },
})
historyRecords.value = normalizeList(data).items
.filter(item => item.id === undefined || String(item.id) === String(props.modelValue.id))
.sort((a, b) => String(a.history_date || '').localeCompare(String(b.history_date || '')))
historyLoaded.value = true
} catch (error: any) {
historyError.value = error?.message || 'Не удалось загрузить историю обращения'
} finally { historyLoading.value = false }
}
async function loadSla() {
if (slaLoaded.value || props.modelValue.id === undefined || props.modelValue.id === null) return
slaLoading.value = true
@ -406,10 +338,6 @@ async function loadSla() {
} finally { slaLoading.value = false }
}
watch(activeTab, value => {
if (value === 'history') loadHistory()
})
watch(() => props.modelValue.id, () => {
slaLoaded.value = false
slaCalculations.value = []
@ -458,50 +386,60 @@ onMounted(async () => {
@changed="applyStatusRecord" />
<v-tabs v-model="activeTab" color="primary" class="mb-4">
<v-tab value="main">Основное</v-tab>
<v-tab value="request">Запрос/решение</v-tab>
<v-tab value="comments">Комментарии</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">
<div class="request-main-layout">
<div class="request-main-layout__request">
<v-card variant="outlined" class="mb-4">
<v-card-title class="text-subtitle-1">Запрос</v-card-title>
<v-card-text>
<v-autocomplete v-if="field('request_type_id')" :model-value="modelValue.request_type_id"
: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"
label="Текст запроса" rows="3" :readonly="readonly"
:rules="required('request_text') ? [(value: unknown) => Boolean(value) || 'Обязательное поле'] : []"
@update:model-value="set('request_text', $event)" />
</v-card-text>
</v-card>
<v-card variant="outlined" class="mb-4">
<v-card-title class="text-subtitle-1">Решение</v-card-title>
<v-card-text>
<v-autocomplete v-if="field('solution_type_id')" :model-value="modelValue.solution_type_id"
: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"
label="Текст решения" rows="3" :readonly="readonly"
:rules="required('solution_text') ? [(value: unknown) => Boolean(value) || 'Обязательное поле'] : []"
@update:model-value="set('solution_text', $event)" />
</v-card-text>
</v-card>
</div>
<div class="request-main-layout__details">
<v-card variant="outlined" class="mb-4">
<v-card-title class="text-subtitle-1">Данные по обращению</v-card-title>
<v-card-text>
<v-row>
<v-col cols="12" md="3">
<v-row class="request-data-row">
<v-col cols="12" md="4">
<v-text-field :model-value="createdValue ? formatDateValue(String(createdValue)) : 'Будет указана после создания'"
label="Дата создания" readonly />
</v-col>
<v-col cols="12" md="3">
<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>
<v-col v-if="field('contact_type_id')" cols="12" md="3">
<v-autocomplete :model-value="modelValue.contact_type_id"
:items="fieldOptions?.contact_type_id || []" label="Тип контакта" clearable :readonly="readonly"
@update:search="emit('relationSearch', 'contact_type_id', $event || '')"
@update:model-value="selectContactType" />
</v-col>
<v-col cols="12" md="6">
<ResourceField v-if="field('contact_value')" name="contact_value" :schema="field('contact_value')!"
:model-value="modelValue.contact_value" :required="required('contact_value')" :readonly="readonly"
@update:model-value="set('contact_value', $event)" />
</v-col>
<v-col v-if="field('req_criticality')" cols="12" md="3">
<v-col v-if="field('req_criticality')" cols="12" md="4">
<v-autocomplete :model-value="relationValue('req_criticality')"
:items="relationOptions?.req_criticality || []" label="Критичность" clearable :readonly="readonly"
:class="{ 'colored-object-field': relationColor('req_criticality') }"
@ -510,6 +448,32 @@ onMounted(async () => {
@update:search="emit('relationSearch', 'req_criticality', $event || '')"
@update:model-value="selectColoredRelation('req_criticality', $event)" />
</v-col>
<v-col cols="12" md="4">
<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>
<v-col cols="12" md="4">
<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 v-if="field('contact_type_id')" cols="12" md="4">
<v-autocomplete :model-value="modelValue.contact_type_id"
:items="fieldOptions?.contact_type_id || []" label="Тип контакта" clearable :readonly="readonly"
@update:search="emit('relationSearch', 'contact_type_id', $event || '')"
@update:model-value="selectContactType" />
</v-col>
<v-col v-if="field('contact_value')" cols="12" md="4">
<ResourceField name="contact_value" :schema="field('contact_value')!"
:model-value="modelValue.contact_value" :required="required('contact_value')" :readonly="readonly"
@update:model-value="set('contact_value', $event)" />
</v-col>
</v-row>
</v-card-text>
</v-card>
@ -590,48 +554,14 @@ onMounted(async () => {
</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">
<v-card variant="outlined" class="mb-4">
<v-card-title class="text-subtitle-1">Запрос</v-card-title>
<v-card-text>
<v-autocomplete v-if="field('request_type_id')" :model-value="modelValue.request_type_id"
: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"
label="Текст запроса" rows="3" :readonly="readonly"
:rules="required('request_text') ? [(value: unknown) => Boolean(value) || 'Обязательное поле'] : []"
@update:model-value="set('request_text', $event)" />
</v-card-text>
</v-card>
<v-card variant="outlined" class="mb-4">
<v-card-title class="text-subtitle-1">Решение</v-card-title>
<v-card-text>
<v-autocomplete v-if="field('solution_type_id')" :model-value="modelValue.solution_type_id"
: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"
label="Текст решения" rows="3" :readonly="readonly"
:rules="required('solution_text') ? [(value: unknown) => Boolean(value) || 'Обязательное поле'] : []"
@update:model-value="set('solution_text', $event)" />
</v-card-text>
</v-card>
</div>
</div>
</v-window-item>
<v-window-item value="comments">
<CommentsTab kind="req" :record-id="modelValue.id as string | number | undefined" :readonly="readonly"
:active="activeTab === 'comments'" />
<div class="request-comments-container">
<CommentsTab kind="req" :record-id="modelValue.id as string | number | undefined" :readonly="readonly"
:active="activeTab === 'comments'" />
</div>
</v-window-item>
<v-window-item value="sla">
<SlaCalculationHistory kind="request"
@ -642,38 +572,6 @@ onMounted(async () => {
<v-card-text class="text-medium-emphasis">Связанные объекты пока отсутствуют.</v-card-text>
</v-card>
</v-window-item>
<v-window-item value="history">
<div class="d-flex justify-center py-8" v-if="historyLoading">
<v-progress-circular indeterminate color="primary" />
</div>
<v-alert v-else-if="historyError" type="error" variant="tonal" class="mb-4">
{{ historyError }}
</v-alert>
<v-alert v-else-if="!historyEntries.length" type="info" variant="tonal" class="mb-4">
История обращения пока отсутствует.
</v-alert>
<v-card v-for="(entry, index) in historyEntries" v-else
:key="String(entry.record.history_id || index)" variant="outlined" class="mb-4">
<v-card-title class="text-subtitle-1">
Запись {{ index + 1 }}
</v-card-title>
<v-card-text>
<div class="history-meta-grid mb-4">
<div><span>Тип записи</span><strong>{{ historyType(entry.record.history_type) }}</strong></div>
<div><span>Дата</span><strong>{{ historyValue(entry.record.history_date) }}</strong></div>
<div><span>Пользователь</span><strong>{{ historyValue(entry.record.history_user) }}</strong></div>
</div>
<div v-if="!entry.changes.length" class="text-medium-emphasis">
Изменённых полей нет.
</div>
<div v-for="change in entry.changes" :key="change.name" class="history-change-row">
<div class="history-field-name"><span>Поле</span><strong>{{ change.label }}</strong></div>
<div><span>Старое значение</span><strong>{{ change.oldValue }}</strong></div>
<div><span>Новое значение</span><strong>{{ change.newValue }}</strong></div>
</div>
</v-card-text>
</v-card>
</v-window-item>
</v-window>
<div v-if="!readonly && !hideActions" class="d-flex justify-end mt-4">
@ -683,6 +581,33 @@ onMounted(async () => {
</template>
<style scoped>
.request-main-layout {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
grid-template-areas: "details request";
gap: 16px;
align-items: start;
}
.request-main-layout__request {
grid-area: request;
}
.request-main-layout__details {
grid-area: details;
}
.request-data-row > [class*="v-col"] {
padding-top: 4px;
padding-bottom: 4px;
}
.request-comments-container {
padding: 16px;
border: 1px solid rgba(var(--v-border-color), var(--v-border-opacity));
border-radius: 4px;
}
.request-address-row {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
@ -705,4 +630,13 @@ onMounted(async () => {
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px;
}
@media (max-width: 959px) {
.request-main-layout {
grid-template-columns: minmax(0, 1fr);
grid-template-areas:
"details"
"request";
}
}
</style>

View File

@ -5,6 +5,7 @@ import { comparisonsFor, normalizeFilterType } from '~/config/filter-comparisons
import { modules } from '~/config/modules'
import { formatDateValue } from '~/utils/date'
import { accessOption } from '~/utils/access'
import { auditObjectType } from '~/utils/audit'
const props = defineProps<{ module: ModuleDefinition; resource: ResourceDefinition; embedded?: boolean }>()
const { request, normalizeList } = useApi()
@ -78,6 +79,9 @@ type CisReferenceOption = {
}
const cisReferenceOptions = ref<Record<string, CisReferenceOption[]>>({})
const scalarReferenceOptions = ref<Record<string, { title: string; value: string | number }[]>>({})
const taskListParameterOptions = ref<Record<string, { title: string; value: string | number; color?: string }[]>>({})
const taskTypeDepartments = ref<Record<string, string | number | null>>({})
const taskAssigneeDepartments = ref<Record<string, (string | number)[]>>({})
const contractStatusOptions = ref<{ title: string; value: string; color?: string }[]>([])
const addressRelationOptions = ref<Record<string, { title: string; value: string | number }[]>>({})
const houseTownOptions = ref<{ title: string; value: string | number }[]>([])
@ -107,6 +111,7 @@ const schemaLoading = ref(false)
const saving = ref(false)
const editorFormId = 'resource-editor-form'
const resourceFormActiveTab = ref('')
const auth = useAuthStore()
const viewOptions = computed(() => listViews.value
.filter(view => view.id !== undefined)
@ -157,6 +162,22 @@ const holidayDateRangeError = computed(() => {
if (!Number.isFinite(from) || !Number.isFinite(to)) return ''
return from < to ? '' : 'Дата начала должна быть раньше даты окончания'
})
function invalidDateRange(start: unknown, finish: unknown) {
if (!start || !finish) return false
const startTime = new Date(String(start)).getTime()
const finishTime = new Date(String(finish)).getTime()
return Number.isFinite(startTime) && Number.isFinite(finishTime) && startTime >= finishTime
}
const taskDateRangeError = computed(() => {
if (businessResourceKey.value !== 'chn:tasks') return ''
if (invalidDateRange(formData.value.planned_start_at, formData.value.planned_finish_at)) {
return 'Плановое начало должно быть раньше планового завершения'
}
if (invalidDateRange(formData.value.actual_start_at, formData.value.actual_finish_at)) {
return 'Фактическое начало должно быть раньше фактического завершения'
}
return ''
})
const isScheduleWeeksResource = computed(() => props.module.apiPrefix === 'sla' && props.resource.key === 'scheduleweeks')
const isSlaRequestAgreementsResource = computed(() => businessResourceKey.value === 'sla:requestagreements')
const isSlaIncidentAgreementsResource = computed(() => businessResourceKey.value === 'sla:incidentagreements')
@ -465,6 +486,9 @@ const businessRelationIdFields: Record<string, string[]> = {
],
}
const businessResourceKey = computed(() => `${props.module.apiPrefix}:${props.resource.key}`)
const auditType = computed(() => auditObjectType(props.module.apiPrefix, props.resource.key))
const canViewAuditHistory = computed(() => Boolean(auditType.value && editingId.value !== null
&& auth.user?.is_staff !== false))
const dskTargetTypes: Record<string, string> = {
'adr:countries': 'adr.country', 'adr:regions': 'adr.region', 'adr:areas': 'adr.area',
'adr:towns': 'adr.town', 'adr:streets': 'adr.street', 'adr:houses': 'adr.house', 'adr:zones': 'adr.zone',
@ -738,8 +762,12 @@ const formFieldClasses = computed<Record<string, string> | undefined>(() => {
srv_type: 'service-half',
} as Record<string, string>
if (isCisResource.value) return {
ci_type_id: 'ci-type-field',
owner_id: 'ci-owner-field',
manufacturer_id: 'ci-half',
model_id: 'ci-half',
softwareversion_id: 'ci-half',
hardwareversion_id: 'ci-half',
date_work_begin: 'ci-half',
date_work_end: 'ci-half',
inventory_number: 'ci-third',
@ -761,19 +789,35 @@ const formFieldClasses = computed<Record<string, string> | undefined>(() => {
impact_id: 'sla-incident-half',
priority_id: 'sla-incident-half',
} as Record<string, string>
if (businessResourceKey.value === 'chn:tasks') {
const sideFields: Record<string, string> = {
assignees: 'task-side-field task-assignees-field',
initiator: 'task-side-field task-initiator-field',
task_type: 'task-side-field task-type-field',
category: 'task-side-field task-category-field',
priority: 'task-side-field task-priority-field',
department: 'task-side-field task-department-field',
}
const dateFields: Record<string, string> = {
planned_start_at: 'task-main-field task-date-start task-planned-date',
planned_finish_at: 'task-main-field task-date-finish task-planned-date',
actual_start_at: 'task-main-field task-date-start task-actual-date',
actual_finish_at: 'task-main-field task-date-finish task-actual-date',
}
const mainFields: Record<string, string> = {
title: 'task-main-field task-title-field',
description: 'task-main-field task-description-field',
result: 'task-main-field task-result-field',
change: 'task-main-field task-change-field',
progress: 'task-main-field task-progress-field',
external_id: 'task-main-field task-external-id-field',
}
return Object.fromEntries(Object.keys(resourceFormSchema.value.properties || {})
.map(name => [name, sideFields[name] || dateFields[name] || mainFields[name] || 'task-main-field']))
}
return undefined
})
const formTabs = computed(() => {
if (businessResourceKey.value === 'chn:changes') return [
{ title: 'Основное', value: 'main' },
{ title: 'Дочерние задачи', value: 'tasks', fields: [] },
{ title: 'Согласования', value: 'approvals', fields: [] },
{ title: 'Workflow', value: 'workflow', fields: [] },
]
if (businessResourceKey.value === 'chn:tasks') return [
{ title: 'Основное', value: 'main' },
{ title: 'Дочерние задачи', value: 'child-tasks', fields: [] },
]
if (businessResourceKey.value === 'chn:changetypes') return [
{ title: 'Основные', value: 'main' },
{
@ -799,23 +843,7 @@ const formTabs = computed(() => {
{ title: 'Связанные объекты', value: 'objects', fields: [] },
]
if (isClientsResource.value || isLeadsResource.value) return []
if (isCisResource.value) return [
{ title: 'Основные', value: 'main' },
{
title: 'Модель',
value: 'model',
fields: ['manufacturer_id', 'model_id', 'softwareversion_id', 'hardwareversion_id'],
},
{
title: 'Остальное',
value: 'other',
fields: [
'inventory_number', 'serial_number', 'factory_number',
'ipv4', 'ipv4mask', 'ipv6', 'ipv6mask',
],
},
{ title: 'Связи', value: 'relations', fields: [] },
]
if (isCisResource.value) return []
if (isSlaRequestAgreementsResource.value) return [
{ title: 'Основные', value: 'main' },
{ title: 'Статусы SLA', value: 'statuses', fields: [] },
@ -870,15 +898,32 @@ const resourceFormSchema = computed<JsonSchema>(() => {
]),
}
}
if (businessResourceKey.value === 'chn:changes') {
const rightFields = ['initiator', 'change_type', 'responsible']
const leftFields = ['title', 'description']
return {
...schema.value,
properties: Object.fromEntries([
...leftFields.filter(name => properties[name]).map(name => [name, properties[name]]),
...Object.entries(properties).filter(([name]) =>
!leftFields.includes(name) && !rightFields.includes(name)),
...rightFields.filter(name => properties[name]).map(name => [name, properties[name]]),
]),
}
}
if (isCisResource.value) {
const preferredFields = [
'name', 'description', 'cim_type', 'ci_type_id',
'manufacturer_id', 'model_id',
'house_id', 'house_extid', 'house_name', 'flat',
'date_work_begin', 'date_work_end',
const modelFields = ['manufacturer_id', 'model_id', 'softwareversion_id', 'hardwareversion_id']
const otherFields = [
'inventory_number', 'serial_number', 'factory_number',
'ipv4', 'ipv4mask', 'ipv6', 'ipv6mask',
]
const preferredFields = [
'name', 'description', 'cim_type', 'ci_type_id', 'owner_id',
...modelFields,
'house_id', 'house_extid', 'house_name', 'flat',
'date_work_begin', 'date_work_end',
...otherFields,
]
return {
...schema.value,
properties: Object.fromEntries([
@ -887,6 +932,35 @@ const resourceFormSchema = computed<JsonSchema>(() => {
]),
}
}
if (businessResourceKey.value === 'chn:tasks') {
const rightFields = [
'initiator', 'task_type', 'category', 'priority', 'department', 'assignees',
'change', 'external_id', 'progress',
]
const leftFields = [
'title', 'description', 'result',
'planned_start_at', 'planned_finish_at',
'actual_start_at', 'actual_finish_at',
]
return {
...schema.value,
properties: Object.fromEntries([
...leftFields.filter(name => properties[name]).map(name => [name, properties[name]]),
...Object.entries(properties).filter(([name]) =>
!leftFields.includes(name) && !rightFields.includes(name)),
...rightFields.filter(name => properties[name]).map(name => [name, properties[name]]),
]),
}
}
if (businessResourceKey.value === 'chn:tasktypes' && properties.color) {
return {
...schema.value,
properties: Object.fromEntries([
...Object.entries(properties).filter(([name]) => name !== 'color'),
['color', properties.color],
]),
}
}
if (isLeadsResource.value) return { ...schema.value, properties }
if (!isClientsResource.value && !isServicesResource && !isContractsResource) return schema.value
const preferredFields = isClientsResource.value
@ -918,7 +992,11 @@ const serviceAddressAnchor = computed(() => {
const houseAddressAnchor = computed(() => resourceFormSchema.value.properties?.adr_house_type
? 'adr_house_type'
: 'name')
const ciAddressAnchor = computed(() => 'ci_type_id')
const ciAddressAnchor = computed(() => {
const properties = resourceFormSchema.value.properties || {}
return ['hardwareversion_id', 'softwareversion_id', 'model_id', 'manufacturer_id', 'owner_id']
.find(name => properties[name] && !formHiddenFields.value.includes(name)) || 'ci_type_id'
})
const addressRelationLabels = computed(() => Object.fromEntries(
Object.entries(currentAddressRelations.value || {}).map(([field, definition]) => [field, definition.label]),
))
@ -1046,6 +1124,27 @@ function relationId(value: unknown): string | number | null {
return null
}
function clearMismatchedTaskType(department: unknown, assignees: unknown) {
if (businessResourceKey.value !== 'chn:tasks' || editingId.value !== null) return
const taskTypeId = relationId(formData.value.task_type)
if (taskTypeId === null) return
const expectedDepartmentId = taskTypeDepartments.value[String(taskTypeId)]
if (expectedDepartmentId === undefined || expectedDepartmentId === null) return
const departmentId = relationId(department)
const departmentMismatch = departmentId !== null
&& String(departmentId) !== String(expectedDepartmentId)
const assigneeMismatch = departmentId === null && Array.isArray(assignees)
&& assignees.some(assignee => {
const assigneeId = relationId(assignee)
return assigneeId !== null
&& !(taskAssigneeDepartments.value[String(assigneeId)] || [])
.some(id => String(id) === String(expectedDepartmentId))
})
if (departmentMismatch || assigneeMismatch) {
formData.value = { ...formData.value, task_type: null }
}
}
function employeeReferenceOption(employee: ApiRecord) {
if (employee.id === undefined) return null
return {
@ -1339,6 +1438,36 @@ async function searchCisReferenceOption(field: string, search: string) {
}
async function handleFormFieldChange(name: string, value: unknown) {
if (businessResourceKey.value === 'chn:tasks' && editingId.value === null) {
if (name === 'task_type') {
const taskTypeId = relationId(value)
if (taskTypeId === null) return
let departmentId = taskTypeDepartments.value[String(taskTypeId)]
if (departmentId === undefined) {
const taskType = await request<ApiRecord>(`/main/chn/task-types/${taskTypeId}/`)
departmentId = relationId(taskType.department)
taskTypeDepartments.value[String(taskTypeId)] = departmentId
}
const selectedAssignees = Array.isArray(formData.value.assignees) ? formData.value.assignees : []
formData.value = {
...formData.value,
task_type: taskTypeId,
department: departmentId,
assignees: departmentId === null ? selectedAssignees : selectedAssignees.filter(assignee => {
const assigneeId = relationId(assignee)
return assigneeId !== null
&& (taskAssigneeDepartments.value[String(assigneeId)] || []).some(id => String(id) === String(departmentId))
}),
}
if (departmentId !== null) await loadScalarReferenceOptions(['assignees'])
return
}
if (name === 'department' || name === 'assignees') {
clearMismatchedTaskType(name === 'department' ? value : formData.value.department,
name === 'assignees' ? value : formData.value.assignees)
return
}
}
if (!isCisResource.value) return
try {
if (name === 'manufacturer_id') {
@ -1460,13 +1589,25 @@ async function loadScalarReferenceOptions(fields = Object.keys(currentScalarFiel
query.departments__id__exact = relationId(formData.value.department)!
}
const data = await request<any>(definition.path, { query })
const items = normalizeList(data).items
const records = normalizeList(data).items
if (businessResourceKey.value === 'chn:tasks' && field === 'task_type') {
taskTypeDepartments.value = Object.fromEntries(records
.filter(item => item.id !== undefined)
.map(item => [String(item.id), relationId(item.department)]))
}
if (businessResourceKey.value === 'chn:tasks' && field === 'assignees') {
taskAssigneeDepartments.value = Object.fromEntries(records
.filter(item => item.id !== undefined)
.map(item => [String(item.id), relationIds(item.departments)]))
}
const items = records
.filter(item => item.id !== undefined)
.map(item => ({
title: String(item.employee_name || item.name || item.fullname || item.username
|| item.label || item.value || item.number
|| item.address || `Объект #${item.id}`),
value: item.id!,
...(item.color ? { color: String(item.color) } : {}),
}))
if (businessResourceKey.value === 'chn:tasks' && field === 'assignees') {
const departmentId = relationId(formData.value.department)
@ -1799,6 +1940,7 @@ watch(() => formData.value.department, async (department, previousDepartment) =>
if (businessResourceKey.value !== 'chn:tasks'
|| String(relationId(department)) === String(relationId(previousDepartment))) return
try {
if (editingId.value === null) clearMismatchedTaskType(department, formData.value.assignees)
await loadScalarReferenceOptions(['assignees'])
const allowedIds = new Set((scalarReferenceOptions.value.assignees || [])
.map(option => String(option.value)))
@ -1859,8 +2001,11 @@ const columns = computed(() => {
&& !(isLeadsResource.value && key === 'source_label')
&& !(isLeadsResource.value && ['updated_at', 'modified', 'dateupdate', 'date_update'].includes(key))
&& !(businessResourceKey.value === 'srv:services' && key === 'description')
&& !(businessResourceKey.value === 'chn:tasks' && key.endsWith('_name')
&& keys.has(key.slice(0, -5)))
&& !key.endsWith('_id')
&& !items.value.some(item => Array.isArray(item[key])))
&& (businessResourceKey.value === 'chn:tasks' && key === 'assignees'
|| !items.value.some(item => Array.isArray(item[key]))))
.sort((a, b) => score(a) - score(b))
.slice(0, 7)
if (props.module.apiPrefix === 'adr' && ['houses', 'streets'].includes(props.resource.key)) {
@ -1871,6 +2016,32 @@ const columns = computed(() => {
selectedColumns.push('zone')
}
}
if (isClientsResource.value) {
for (const key of ['firstname', 'secondname', 'surname']) {
const index = selectedColumns.indexOf(key)
if (index >= 0) selectedColumns.splice(index, 1)
}
const requestedColumns = [keys.has('tax_id') ? 'tax_id' : 'taxid', 'phone', 'email']
.filter(key => keys.has(key))
const clientDetailColumns = ['crm_type', 'crm_category', ...requestedColumns]
.filter(key => keys.has(key))
const pinnedColumns = new Set(['id', 'name', 'title', ...clientDetailColumns])
for (const key of clientDetailColumns) {
if (selectedColumns.includes(key)) continue
if (selectedColumns.length >= 7) {
const removable = [...selectedColumns].reverse().find(column => !pinnedColumns.has(column))
if (removable) selectedColumns.splice(selectedColumns.indexOf(removable), 1)
}
selectedColumns.push(key)
}
for (const key of clientDetailColumns) {
const index = selectedColumns.indexOf(key)
if (index >= 0) selectedColumns.splice(index, 1)
}
const identityIndex = Math.max(selectedColumns.indexOf('name'), selectedColumns.indexOf('title'),
selectedColumns.indexOf('id'))
selectedColumns.splice(identityIndex + 1, 0, ...clientDetailColumns)
}
if (isLeadsResource.value) {
const pinnedColumns = new Set(['id', 'name', 'title', 'status', 'source', 'email', 'phone'])
for (const key of ['phone', 'source']) {
@ -1894,6 +2065,18 @@ const columns = computed(() => {
selectedColumns.splice(selectedColumns.indexOf('email') + 1, 0, 'phone')
}
}
if (businessResourceKey.value === 'chn:tasks') {
const descriptionIndex = selectedColumns.indexOf('description')
if (descriptionIndex >= 0) selectedColumns.splice(descriptionIndex, 1)
const assigneeColumn = keys.has('assignees') ? 'assignees' : keys.has('assignee') ? 'assignee' : ''
if (assigneeColumn && !selectedColumns.includes(assigneeColumn)) {
if (selectedColumns.length >= 7) selectedColumns.pop()
selectedColumns.push(assigneeColumn)
}
if (keys.has('department') && !selectedColumns.includes('department')) {
selectedColumns.push('department')
}
}
return selectedColumns
})
function itemSlot(column: string): `item.${string}` {
@ -1908,7 +2091,14 @@ const columnLabels: Record<string, string> = {
req_status: 'Статус', req_criticality: 'Критичность',
inc_status: 'Статус', inc_impact: 'Влияние', inc_priority: 'Приоритет',
srv_status: 'Статус', srv_type: 'Тип',
color: 'Цвет', email: 'Email', phone: 'Телефон', isactive: 'Активен', is_active: 'Активен',
task_type: 'Тип задачи', category: 'Категория', priority: 'Приоритет',
change: 'Изменение', change_type: 'Тип изменения', department: 'Подразделение',
assignees: 'Исполнители', assignee: 'Исполнитель', initiator: 'Инициатор',
progress: 'Прогресс', result: 'Результат', external_id: 'Внешний ID',
planned_start_at: 'Плановое начало', planned_finish_at: 'Плановое завершение',
actual_start_at: 'Фактическое начало', actual_finish_at: 'Фактическое завершение',
color: 'Цвет', email: 'Email', phone: 'Телефон', tax_id: 'ИНН', taxid: 'ИНН',
isactive: 'Активен', is_active: 'Активен',
created_at: 'Создан', updated_at: 'Изменён', datecreate: 'Создан',
}
const headers = computed(() => [
@ -1946,6 +2136,11 @@ function columnColor(item: ApiRecord, column: string) {
if (value && typeof value === 'object' && !Array.isArray(value)) {
return usableColor((value as ApiRecord).color)
}
if (businessResourceKey.value === 'chn:tasks') {
const id = listParameterId(value)
return usableColor(taskListParameterOptions.value[column]
?.find(option => String(option.value) === String(id))?.color)
}
return column === 'color' ? usableColor(value) : ''
}
function isColoredClassifier(column: string) {
@ -1956,6 +2151,8 @@ function isColoredClassifier(column: string) {
'srv:services': ['srv_status', 'srv_type'],
'req:requests': ['req_status', 'req_criticality'],
'inc:incidents': ['inc_status', 'inc_impact', 'inc_priority'],
'chn:tasks': ['task_type', 'status', 'priority', 'category'],
'chn:changes': ['change_type'],
}
return coloredColumns[businessResourceKey.value]?.includes(column) || false
}
@ -1973,6 +2170,15 @@ function display(value: unknown): string {
if (typeof value === 'object') return (value as any).name || (value as any).title || (value as any).id || JSON.stringify(value)
return typeof value === 'string' ? formatDateValue(value) : String(value)
}
function listParameterId(value: unknown): string | number | null {
if (Array.isArray(value)) return listParameterId(value[0])
if (typeof value === 'string' || typeof value === 'number') return value
if (value && typeof value === 'object') {
const record = value as ApiRecord
return listParameterId(record.id ?? record.value)
}
return null
}
function displayColumn(item: ApiRecord, column: string) {
if (props.module.apiPrefix === 'adr'
&& ['houses', 'streets'].includes(props.resource.key) && column === 'zone') {
@ -1993,9 +2199,64 @@ function displayColumn(item: ApiRecord, column: string) {
const options = column === 'status' ? leadStatuses : leadSources
return options.find(option => option.value === String(item[column] || ''))?.title || display(item[column])
}
if (businessResourceKey.value === 'chn:tasks') {
const namedValue = item[`${column}_name`]
if (namedValue !== null && namedValue !== undefined && namedValue !== '') return display(namedValue)
const value = item[column]
if (Array.isArray(value) && column === 'assignees') {
const names = value.map(assignee => {
if (assignee && typeof assignee === 'object') return display(assignee)
return taskListParameterOptions.value.assignees
?.find(candidate => String(candidate.value) === String(assignee))?.title || String(assignee)
})
return names.length ? names.join(', ') : '—'
}
if (Array.isArray(value) && value.length === 2
&& (typeof value[0] === 'number' || typeof value[0] === 'string')
&& typeof value[1] === 'string') return value[1]
const id = listParameterId(value)
const option = taskListParameterOptions.value[column]
?.find(candidate => String(candidate.value) === String(id))
if (option) return option.title
}
return display(item[column])
}
async function loadTaskListParameterOptions() {
if (businessResourceKey.value !== 'chn:tasks') {
taskListParameterOptions.value = {}
return
}
const definitions: Record<string, string> = {
task_type: '/main/chn/task-types/',
status: '/main/chn/task-statuses/',
priority: '/main/chn/task-priorities/',
category: '/main/chn/task-categories/',
change: '/main/chn/changes/',
department: '/main/sys/departments/',
initiator: '/main/sys/employees/',
assignees: '/main/sys/employees/',
assignee: '/main/sys/employees/',
}
const entries = await Promise.all(Object.entries(definitions).map(async ([field, path]) => {
try {
const data = await request<any>(path, { query: { page_size: 1000 } })
const options = normalizeList(data).items
.filter(item => item.id !== undefined)
.map(item => ({
title: String(item.employee_name || item.name || item.title || item.number
|| item.fullname || item.username || `Объект #${item.id}`),
value: item.id as string | number,
...(item.color ? { color: String(item.color) } : {}),
}))
return [field, options] as const
} catch {
return [field, []] as const
}
}))
taskListParameterOptions.value = Object.fromEntries(entries)
}
function normalizedResourceTokens(value: unknown) {
if (typeof value !== 'string') return []
return value.toLowerCase().split(/[^a-zа-яё0-9]+/i).filter(Boolean)
@ -2104,6 +2365,7 @@ async function load() {
Object.assign(query, activeViewFilters())
const data = await request<any>(apiPath.value, { query })
const normalized = normalizeList(data); items.value = normalized.items; total.value = normalized.total
await loadTaskListParameterOptions()
await router.replace({ query: {
page: page.value,
page_size: pageSize.value,
@ -2373,8 +2635,8 @@ async function openView(item: ApiRecord) {
if (editor.value) editorReadonly.value = true
}
async function save() {
if (holidayDateRangeError.value) {
error.value = holidayDateRangeError.value
if (holidayDateRangeError.value || taskDateRangeError.value) {
error.value = holidayDateRangeError.value || taskDateRangeError.value
return
}
saving.value = true; error.value = ''
@ -2619,8 +2881,10 @@ onBeforeUnmount(() => window.removeEventListener('resize', updateContractProcess
<span class="resource-color-dot" :style="{ backgroundColor: itemColor(item) }" />
{{ displayColumn(item, column) }}
</v-chip>
<span v-else :class="{ 'text-wrap': column === 'description', 'resource-highlight': itemColor(item) && ['name', 'title', 'number'].includes(column) }"
:style="itemColor(item) && ['name', 'title', 'number'].includes(column) ? { borderLeftColor: itemColor(item) } : undefined">
<span v-else :class="{ 'text-wrap': column === 'description',
'resource-highlight': !isClientsResource && itemColor(item) && ['name', 'title', 'number'].includes(column) }"
:style="!isClientsResource && itemColor(item) && ['name', 'title', 'number'].includes(column)
? { borderLeftColor: itemColor(item) } : undefined">
{{ displayColumn(item, column) }}
</span>
</template>
@ -2746,17 +3010,46 @@ onBeforeUnmount(() => window.removeEventListener('resize', updateContractProcess
:readonly="editorReadonly" no-data-text="Подразделения не найдены"
@update:search="loadViewDepartments($event || '')" />
</v-form>
<v-form v-else-if="isModelsResource" :id="editorFormId" @submit.prevent="save">
<v-text-field v-model="formData.name" label="Название модели"
:readonly="editorReadonly" required />
<v-textarea v-model="formData.description" label="Описание"
:readonly="editorReadonly" rows="3" />
<v-autocomplete v-model="selectedManufacturerId" :items="manufacturerOptions"
label="Производитель" :readonly="editorReadonly"
@update:search="loadManufacturers($event || '')"
:rules="[(value: unknown) => value !== null && value !== undefined || 'Выберите производителя']"
required />
</v-form>
<div v-else-if="isModelsResource" class="model-editor-layout">
<div class="model-editor-column">
<v-form :id="editorFormId" @submit.prevent="save">
<v-text-field v-model="formData.name" label="Название модели"
:readonly="editorReadonly" required />
<v-textarea v-model="formData.description" label="Описание"
:readonly="editorReadonly" rows="3" />
<v-autocomplete v-model="selectedManufacturerId" :items="manufacturerOptions"
label="Производитель" :readonly="editorReadonly"
@update:search="loadManufacturers($event || '')"
:rules="[(value: unknown) => value !== null && value !== undefined || 'Выберите производителя']"
required />
</v-form>
<template v-if="dskTargetType">
<div class="mt-6">
<h3 class="text-subtitle-1 font-weight-bold mb-4">Вложения</h3>
<AttachmentsTab :target-type="dskTargetType" :record-id="editingId ?? undefined"
:readonly="editorReadonly" :active="true" />
</div>
<TagsTab class="resource-tags-last"
:target-type="dskTargetType" :record-id="editingId ?? undefined"
:readonly="editorReadonly" :active="true" />
</template>
</div>
<aside class="model-editor-column">
<template v-if="editingId !== null">
<InlineResourceManager title="Аппаратные версии" endpoint="/main/dev/hardware-versions/"
:collection-endpoint="`/main/dev/models/${editingId}/hardware-versions/`"
:parent-id="editingId" relation-field="dev_model" relation-payload-field="model_id"
create-in-dialog :readonly="editorReadonly" />
<InlineResourceManager title="Программные версии" endpoint="/main/dev/software-versions/"
:collection-endpoint="`/main/dev/models/${editingId}/software-versions/`"
:parent-id="editingId" relation-field="dev_model" relation-payload-field="model_id"
create-in-dialog :readonly="editorReadonly" />
</template>
<v-alert v-else type="info" variant="tonal">
Сохраните модель, чтобы добавить версии.
</v-alert>
</aside>
</div>
<v-form v-else-if="isVersionsResource" :id="editorFormId" @submit.prevent="save">
<v-text-field v-model="formData.name" label="Название версии"
:readonly="editorReadonly" required />
@ -2840,6 +3133,8 @@ onBeforeUnmount(() => window.removeEventListener('resize', updateContractProcess
? 'client-form-grid'
: isLeadsResource
? 'lead-form-grid'
: businessResourceKey === 'chn:tasks'
? 'task-form-grid'
: businessResourceKey === 'crm:contracts'
? 'contract-form-grid'
: businessResourceKey === 'srv:services'
@ -2852,6 +3147,21 @@ onBeforeUnmount(() => window.removeEventListener('resize', updateContractProcess
? 'sla-request-form-grid'
: isSlaIncidentAgreementsResource ? 'sla-incident-form-grid' : undefined"
:field-classes="formFieldClasses"
:split-right-fields="businessResourceKey === 'chn:tasks'
? [
'initiator', 'task_type', 'category', 'priority', 'department', 'assignees',
'change', 'external_id', 'progress',
]
: businessResourceKey === 'chn:changes'
? ['initiator', 'change_type', 'responsible']
: isCisResource
? [
'inventory_number', 'serial_number', 'factory_number',
'ipv4', 'ipv4mask', 'ipv6', 'ipv6mask',
]
: undefined"
:inline-fields="businessResourceKey === 'chn:tasks' ? ['initiator'] : undefined"
:stacked-label-fields="businessResourceKey === 'chn:tasks' ? ['assignees'] : undefined"
:tabs="formTabs"
:field-options="formFieldOptions"
:field-labels="formFieldLabels"
@ -2872,6 +3182,9 @@ onBeforeUnmount(() => window.removeEventListener('resize', updateContractProcess
<v-alert v-if="holidayDateRangeError" type="error" variant="tonal" class="mb-4">
{{ holidayDateRangeError }}
</v-alert>
<v-alert v-if="taskDateRangeError" type="error" variant="tonal" class="mb-4">
{{ taskDateRangeError }}
</v-alert>
<v-autocomplete v-if="businessResourceKey === 'sys:departments'"
v-model="departmentManagerId" :items="departmentManagerOptions"
label="Руководитель" no-data-text="Сотрудники не найдены"
@ -2985,20 +3298,19 @@ onBeforeUnmount(() => window.removeEventListener('resize', updateContractProcess
type="info" variant="tonal" class="mt-4">
Сохраните адресный объект, чтобы управлять зонами.
</v-alert>
<ChildTasks v-if="businessResourceKey === 'chn:changes' && activeTab === 'tasks'"
parent-kind="change" :parent-id="editingId ?? undefined" :readonly="editorReadonly" :active="true" />
<ChangeRelatedData v-if="businessResourceKey === 'chn:changes'
&& editingId !== null && ['approvals', 'workflow'].includes(activeTab)"
:change="formData"
:section="activeTab as 'tasks' | 'approvals' | 'workflow'"
:active="true" />
<v-alert v-else-if="businessResourceKey === 'chn:changes'
&& editingId === null && ['approvals', 'workflow'].includes(activeTab)"
type="info" variant="tonal">
Сохраните изменение, чтобы просматривать связанные данные.
</v-alert>
<ChildTasks v-if="businessResourceKey === 'chn:tasks' && activeTab === 'child-tasks'"
parent-kind="task" :parent-id="editingId ?? undefined" :readonly="editorReadonly" :active="true" />
<template v-if="businessResourceKey === 'chn:changes'">
<template v-if="editingId !== null">
<v-divider class="my-6" />
<h3 class="text-subtitle-1 font-weight-bold mb-4">Согласования</h3>
<ChangeRelatedData :change="formData" section="approvals" :active="true" />
<v-divider class="my-6" />
<h3 class="text-subtitle-1 font-weight-bold mb-4">Workflow</h3>
<ChangeRelatedData :change="formData" section="workflow" :active="true" />
</template>
<v-alert v-else type="info" variant="tonal">
Сохраните изменение, чтобы просматривать согласования и workflow.
</v-alert>
</template>
<ChangeWorkflowEditor v-if="businessResourceKey === 'chn:changetypes'
&& activeTab === 'workflow' && editingId !== null"
:change-type-id="editingId" :readonly="editorReadonly" />
@ -3052,6 +3364,40 @@ onBeforeUnmount(() => window.removeEventListener('resize', updateContractProcess
Сохраните SLA инцидентов, чтобы управлять связанными данными.
</v-alert>
</template>
<template #split-left-footer>
<template v-if="['chn:tasks', 'chn:changes'].includes(businessResourceKey)">
<ChildTasks :parent-kind="businessResourceKey === 'chn:tasks' ? 'task' : 'change'"
:parent-id="editingId ?? undefined"
:readonly="editorReadonly" :active="true" />
<div v-if="dskTargetType" class="mt-6">
<h3 class="text-subtitle-1 font-weight-bold mb-4">Вложения</h3>
<AttachmentsTab :target-type="dskTargetType" :record-id="editingId ?? undefined"
:readonly="editorReadonly" :active="true" />
</div>
<TagsTab v-if="dskTargetType" class="resource-tags-last"
:target-type="dskTargetType" :record-id="editingId ?? undefined"
:readonly="editorReadonly" :active="true" />
</template>
<template v-if="isCisResource && dskTargetType">
<div class="mt-6">
<h3 class="text-subtitle-1 font-weight-bold mb-4">Вложения</h3>
<AttachmentsTab :target-type="dskTargetType" :record-id="editingId ?? undefined"
:readonly="editorReadonly" :active="true" />
</div>
<TagsTab class="resource-tags-last"
:target-type="dskTargetType" :record-id="editingId ?? undefined"
:readonly="editorReadonly" :active="true" />
</template>
</template>
<template #split-right-footer>
<template v-if="isCisResource">
<CiRelationsManager v-if="editingId !== null"
:ci-id="editingId" :readonly="editorReadonly" />
<v-alert v-else type="info" variant="tonal">
Сохраните конфигурационную единицу, чтобы управлять связями.
</v-alert>
</template>
</template>
</ResourceForm>
<template v-if="isClientsResource || isLeadsResource">
<ContactRelationsManager v-if="hasContactRelations" :key="String(editingId ?? 'new')"
@ -3116,16 +3462,6 @@ onBeforeUnmount(() => window.removeEventListener('resize', updateContractProcess
:status-id="editingId" :readonly="editorReadonly" />
<RequestStatusTransitions v-if="businessResourceKey === 'req:statuses' && editingId !== null"
:status-id="editingId" :readonly="editorReadonly" />
<div v-if="isModelsResource && editingId !== null" class="model-versions-grid">
<InlineResourceManager title="Аппаратные версии" endpoint="/main/dev/hardware-versions/"
:collection-endpoint="`/main/dev/models/${editingId}/hardware-versions/`"
:parent-id="editingId" relation-field="dev_model" relation-payload-field="model_id"
create-in-dialog :readonly="editorReadonly" />
<InlineResourceManager title="Программные версии" endpoint="/main/dev/software-versions/"
:collection-endpoint="`/main/dev/models/${editingId}/software-versions/`"
:parent-id="editingId" relation-field="dev_model" relation-payload-field="model_id"
create-in-dialog :readonly="editorReadonly" />
</div>
<template v-if="isCimTypesResource && editingId !== null">
<InlineResourceManager title="Поля типа CI" endpoint="/main/cim/ci-fields/"
:collection-endpoint="`/main/cim/ci-types/${editingId}/fields/`"
@ -3198,7 +3534,8 @@ onBeforeUnmount(() => window.removeEventListener('resize', updateContractProcess
</div>
</template>
<template v-if="dskTargetType && (!formTabs?.length || resourceFormActiveTab === 'main')
&& !isClientsResource && !isLeadsResource
&& !isClientsResource && !isLeadsResource && !isModelsResource && !isCisResource
&& !['chn:tasks', 'chn:changes'].includes(businessResourceKey)
&& businessResourceKey !== 'req:requests' && businessResourceKey !== 'inc:incidents'">
<div class="mt-6">
<h3 class="text-subtitle-1 font-weight-bold mb-4">Вложения</h3>
@ -3209,6 +3546,8 @@ onBeforeUnmount(() => window.removeEventListener('resize', updateContractProcess
:target-type="dskTargetType" :record-id="editingId ?? undefined"
:readonly="editorReadonly" :active="true" />
</template>
<AuditHistory v-if="canViewAuditHistory" :key="`${auditType}:${editingId}`"
:object-type="auditType" :object-id="editingId!" />
</template>
</v-card-text>
</v-card>
@ -3331,14 +3670,14 @@ onBeforeUnmount(() => window.removeEventListener('resize', updateContractProcess
line-height: 1.1;
}
.model-versions-grid {
.model-editor-layout {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 24px;
align-items: stretch;
align-items: start;
}
.model-versions-grid > * {
.model-editor-column {
min-width: 0;
}
@ -3425,9 +3764,9 @@ onBeforeUnmount(() => window.removeEventListener('resize', updateContractProcess
border-left: 0;
}
.model-versions-grid {
.model-editor-layout {
grid-template-columns: 1fr;
gap: 0;
gap: 24px;
}
.address-flat-row,

View File

@ -13,7 +13,7 @@ const emit = defineEmits<{ 'update:modelValue': [value: unknown] }>()
const isActiveField = computed(() => ['is_active', 'isactive', 'active'].includes(props.name))
const label = computed(() => isActiveField.value
? 'active'
: props.schema.title || props.name.replaceAll('_', ' '))
: props.name === 'color' ? 'Цвет' : 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) } },
@ -101,7 +101,7 @@ const rules = computed(() => [
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"
<v-textarea v-else-if="name === 'result' || 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"

View File

@ -12,6 +12,9 @@ const props = defineProps<{
readonlyFields?: string[]
clearableFields?: string[]
textFields?: string[]
inlineFields?: string[]
stackedLabelFields?: string[]
splitRightFields?: string[]
hiddenFields?: string[]
fieldOptions?: Record<string, SelectOption[]>
fieldLabels?: Record<string, string>
@ -62,6 +65,9 @@ const fields = computed(() => {
entries.splice(nextPrimaryIndex + 1, 0, activeEntry)
return entries
})
const splitRightFieldSet = computed(() => new Set(props.splitRightFields || []))
const splitLeftFields = computed(() => fields.value.filter(([name]) => !splitRightFieldSet.value.has(name)))
const splitRightFields = computed(() => fields.value.filter(([name]) => splitRightFieldSet.value.has(name)))
const fieldTabs = computed(() => Object.fromEntries((props.tabs || []).flatMap(tab =>
(tab.fields || []).map(field => [field, tab.value]))))
const defaultTab = computed(() => props.tabs?.[0]?.value || '')
@ -72,7 +78,7 @@ 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')) {
|| name === 'result' || name.includes('description') || name.includes('info') || name.includes('comment')) {
return 'resource-field-wide'
}
if (['date', 'date-time', 'datetime', 'time'].includes(field.format || '')) {
@ -92,6 +98,8 @@ function fieldClass(name: string) {
fieldWidthClass(name),
name === primaryFieldName.value && activeFieldName.value ? 'resource-primary-field' : '',
name === activeFieldName.value && primaryFieldName.value ? 'resource-active-field' : '',
props.inlineFields?.includes(name) ? 'resource-inline-field' : '',
props.stackedLabelFields?.includes(name) ? 'resource-stacked-label-field' : '',
].filter(Boolean)
}
function fieldLabel(name: string, field: JsonSchema) {
@ -206,7 +214,90 @@ async function submit() { const result = await form.value?.validate(); if (resul
</script>
<template>
<v-form :id="formId" ref="form" :class="['resource-form-grid', formClass]" @submit.prevent="submit">
<v-form v-if="splitRightFields?.length" :id="formId" ref="form"
:class="['resource-split-form', formClass]" @submit.prevent="submit">
<slot name="prepend" />
<div class="resource-split-layout">
<div class="resource-split-column resource-split-column--left">
<template v-for="[name, field] in splitLeftFields" :key="name">
<div :class="['resource-split-field', fieldClass(name), {
'resource-split-field--date-start': ['planned_start_at', 'actual_start_at'].includes(name),
'resource-split-field--date-finish': ['planned_finish_at', 'actual_finish_at'].includes(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>
</div>
<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'"
:closable-chips="field.type === 'array' && !fieldReadonly(name)" return-object clearable
@update:search="emit('relationSearch', name, $event || '')"
@update:model-value="setOptionField(name, $event)" />
<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 class="resource-split-after-field">
<slot name="after-field" :field-name="name" />
</div>
</template>
<div v-if="$slots['split-left-footer']" class="resource-split-left-footer">
<slot name="split-left-footer" />
</div>
</div>
<div class="resource-split-column resource-split-column--right">
<div v-for="[name, field] in splitRightFields" :key="name"
:class="['resource-split-field', fieldClass(name)]">
<div v-if="textFields?.includes(name)" class="resource-split-inline-value">
<span class="resource-split-inline-label">{{ fieldLabel(name, field) }}</span>
<span>{{ textFieldValue(name) }}</span>
</div>
<div v-else-if="name === 'assignees'" class="resource-split-stacked-field">
<div class="text-caption text-medium-emphasis">{{ fieldLabel(name, field) }}</div>
<v-autocomplete :model-value="fieldOptionValue(name)" :items="fieldOptions?.[name] || []"
:readonly="fieldReadonly(name)" multiple chips closable-chips clearable return-object
@update:search="emit('relationSearch', name, $event || '')"
@update:model-value="setOptionField(name, $event)" />
</div>
<v-autocomplete v-else-if="fieldOptions?.[name]" :model-value="fieldOptionValue(name)"
:items="fieldOptions[name]" :label="fieldLabels?.[name] || field.title || name.replaceAll('_', ' ')"
:readonly="fieldReadonly(name)" return-object clearable
@update:search="emit('relationSearch', name, $event || '')"
@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)" />
<slot name="after-field" :field-name="name" />
</div>
<div v-if="$slots['split-right-footer']" class="resource-split-right-footer">
<slot name="split-right-footer" />
</div>
</div>
</div>
<div v-if="$slots['tab-content']" class="resource-split-content">
<slot name="tab-content" :active-tab="activeTab" />
</div>
<div v-if="!readonly && !hideActions" class="d-flex justify-end mt-4">
<v-btn type="submit" color="primary" :loading="loading">Сохранить</v-btn>
</div>
</v-form>
<v-form v-else :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>
@ -215,9 +306,11 @@ 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="fieldClass(name)">
<div v-show="!tabs?.length || tabForField(name) === activeTab" :class="fieldClass(name)"
:data-field-label="inlineFields?.includes(name) || stackedLabelFields?.includes(name)
? fieldLabel(name, field) : undefined">
<div v-if="textFields?.includes(name)" class="resource-text-field mb-4">
<div class="text-caption text-medium-emphasis">{{ fieldLabel(name, field) }}</div>
<div v-if="!inlineFields?.includes(name)" class="text-caption text-medium-emphasis">{{ fieldLabel(name, field) }}</div>
<div class="text-body-1">{{ textFieldValue(name) }}</div>
</div>
<CoordinatePicker v-else-if="name === 'lat' && hasCoordinates"
@ -232,7 +325,8 @@ async function submit() { const result = await form.value?.validate(); if (resul
<template v-else-if="name === 'lon' && hasCoordinates" />
<v-autocomplete v-else-if="relationOptions?.[name]" :model-value="relationValue(name)"
:items="relationOptions[name]"
:label="relationLabels?.[name] || field.title || name.replaceAll('_', ' ')"
:label="inlineFields?.includes(name) || stackedLabelFields?.includes(name)
? undefined : relationLabels?.[name] || field.title || name.replaceAll('_', ' ')"
:placeholder="name === 'adr_town'
? 'Начните вводить населённый пункт'
: name === 'adr_street' ? 'Начните вводить улицу' : undefined"
@ -261,8 +355,10 @@ async function submit() { const result = await form.value?.validate(); if (resul
</v-autocomplete>
<v-autocomplete v-else-if="fieldOptions?.[name]" :model-value="fieldOptionValue(name)"
:items="fieldOptions[name]"
:label="fieldLabels?.[name] || field.title || name.replaceAll('_', ' ')"
:label="inlineFields?.includes(name) || stackedLabelFields?.includes(name)
? undefined : fieldLabels?.[name] || field.title || name.replaceAll('_', ' ')"
:readonly="fieldReadonly(name)" :multiple="field.type === 'array'" :chips="field.type === 'array'"
:closable-chips="field.type === 'array' && !fieldReadonly(name)"
: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"
@ -308,6 +404,125 @@ async function submit() { const result = await form.value?.validate(); if (resul
display: contents;
}
.resource-split-layout {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 32px;
align-items: start;
}
.resource-split-column {
min-width: 0;
}
.resource-split-column--left {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
column-gap: 16px;
}
.resource-split-field {
min-width: 0;
}
.resource-split-after-field {
display: contents;
}
.resource-split-column--left > .resource-split-field {
grid-column: 1 / -1;
}
.resource-split-column--left > .resource-split-field--date-start {
grid-column: 1;
}
.resource-split-column--left > .resource-split-field--date-finish {
grid-column: 2;
}
.resource-split-column--left > .ci-type-field {
grid-column: 1;
}
.resource-split-column--left > .ci-owner-field {
grid-column: 2;
}
.ci-form-grid .resource-split-column--left > .ci-half {
grid-column: span 1;
}
.ci-form-grid .resource-split-column--right {
display: grid;
grid-template-columns: repeat(6, minmax(0, 1fr));
column-gap: 16px;
}
.ci-form-grid .resource-split-column--right > .ci-third {
grid-column: span 2;
}
.ci-form-grid .resource-split-column--right > .ci-half {
grid-column: span 3;
}
.ci-form-grid .resource-split-right-footer {
grid-column: 1 / -1;
}
.resource-split-left-footer {
grid-column: 1 / -1;
min-width: 0;
margin-top: 16px;
}
.resource-split-right-footer {
min-width: 0;
margin-top: 16px;
}
.resource-split-inline-value {
display: flex;
min-height: 48px;
align-items: center;
gap: 12px;
margin-bottom: 8px;
}
.resource-split-inline-label {
color: rgb(var(--v-theme-on-surface) / 42%);
font-size: .8125rem;
}
.resource-split-stacked-field {
display: flex;
flex-direction: column;
gap: 6px;
}
.resource-split-content {
margin-top: 24px;
}
@media (max-width: 959px) {
.resource-split-layout {
grid-template-columns: minmax(0, 1fr);
}
}
@media (max-width: 600px) {
.ci-form-grid .resource-split-column--left,
.ci-form-grid .resource-split-column--right {
grid-template-columns: minmax(0, 1fr);
}
.ci-form-grid .resource-split-column--left > .resource-split-field,
.ci-form-grid .resource-split-column--right > .resource-split-field {
grid-column: 1;
}
}
.resource-option-color {
display: inline-block;
flex: 0 0 auto;
@ -366,6 +581,94 @@ async function submit() { const result = await form.value?.validate(); if (resul
max-width: 900px;
}
.resource-form-grid > .resource-inline-field {
display: grid;
grid-template-columns: 120px minmax(0, 1fr);
align-items: center;
gap: 12px;
}
.resource-inline-field::before {
grid-column: 1;
grid-row: 1;
color: rgb(var(--v-theme-on-surface) / 60%);
content: attr(data-field-label);
font-size: .875rem;
}
.resource-inline-field > :deep(*) {
grid-column: 2;
grid-row: 1;
}
.resource-inline-field > .resource-text-field {
display: flex;
min-height: 40px;
align-items: center;
margin-bottom: 0 !important;
}
.resource-form-grid > .resource-stacked-label-field {
display: flex;
flex-direction: column;
align-items: stretch;
gap: 6px;
}
.resource-stacked-label-field::before {
color: rgb(var(--v-theme-on-surface) / 60%);
content: attr(data-field-label);
font-size: .875rem;
}
.task-form-grid {
display: block;
column-count: 2;
column-gap: 32px;
}
.task-form-grid > :deep(*) {
width: 100%;
max-width: none;
}
.task-form-grid > .task-main-field,
.task-form-grid > .task-side-field {
display: inline-block;
break-inside: avoid;
vertical-align: top;
}
.task-form-grid > .task-date-start {
width: calc(50% - 8px);
margin-right: 12px;
}
.task-form-grid > .task-date-finish {
width: calc(50% - 8px);
}
.task-form-grid > .task-initiator-field { break-before: column; }
.task-form-grid > .task-initiator-field::before {
color: rgb(var(--v-theme-on-surface) / 42%);
font-size: .8125rem;
}
.task-form-grid > .tab-content,
.task-form-grid > .field-slot {
column-span: all;
}
@media (max-width: 959px) {
.task-form-grid {
column-count: 1;
}
.task-form-grid > .task-initiator-field {
break-before: auto;
}
}
.client-form-grid {
grid-template-columns: repeat(10, minmax(0, 1fr));
}

View File

@ -141,46 +141,59 @@ watch([() => props.recordId, () => props.kind], load, { immediate: true })
</v-list-item>
</v-list>
<div class="text-subtitle-1 mb-3">Расчёты SLA</div>
<v-alert v-if="selectedTotalId === null && totals.length" type="info" variant="tonal" class="mb-4">
Выберите итоговый расчёт, чтобы посмотреть связанные расчёты SLA.
</v-alert>
<v-alert v-else-if="selectedTotalId !== null && !filteredCalculations.length"
type="info" variant="tonal" class="mb-4">
Для выбранной записи расчёты SLA отсутствуют.
</v-alert>
<v-card v-for="(calculation, index) in filteredCalculations"
:key="String(calculation.id || index)" variant="outlined" class="mb-3">
<v-card-title class="text-body-1 py-3">
Расчёт {{ index + 1 }} — {{ display(calculation.date_calc) }}
</v-card-title>
<v-card-text class="pt-0">
<div class="sla-fields sla-fields--single-row">
<div><span>Статус</span><strong>{{ namedValue(calculation.status, statusNames, 'Неизвестный статус') }}</strong></div>
<div>
<span>Тип расчёта</span>
<v-chip v-if="typeColor(calculation.type)"
:color="typeColor(calculation.type)" size="small" variant="tonal">
{{ namedValue(calculation.type, typeNames, 'Неизвестный тип') }}
</v-chip>
<strong v-else>{{ namedValue(calculation.type, typeNames, 'Неизвестный тип') }}</strong>
<div class="sla-details">
<div class="text-subtitle-1 mb-3">Расчёты SLA</div>
<v-alert v-if="selectedTotalId === null && totals.length" type="info" variant="tonal" class="mb-4">
Выберите итоговый расчёт, чтобы посмотреть связанные расчёты SLA.
</v-alert>
<v-alert v-else-if="selectedTotalId !== null && !filteredCalculations.length"
type="info" variant="tonal" class="mb-4">
Для выбранной записи расчёты SLA отсутствуют.
</v-alert>
<v-card v-for="(calculation, index) in filteredCalculations"
:key="String(calculation.id || index)" variant="outlined" class="mb-3">
<v-card-title class="text-body-1 py-3">
Расчёт {{ index + 1 }} — {{ display(calculation.date_calc) }}
</v-card-title>
<v-card-text class="pt-0">
<div class="sla-fields sla-fields--single-row">
<div>
<span>Статус</span>
<v-chip :color="statusColor(calculation.status)" size="small" variant="tonal">
{{ namedValue(calculation.status, statusNames, 'Неизвестный статус') }}
</v-chip>
</div>
<div>
<span>Тип расчёта</span>
<v-chip v-if="typeColor(calculation.type)"
:color="typeColor(calculation.type)" size="small" variant="tonal">
{{ namedValue(calculation.type, typeNames, 'Неизвестный тип') }}
</v-chip>
<strong v-else>{{ namedValue(calculation.type, typeNames, 'Неизвестный тип') }}</strong>
</div>
<div>
<span>Осталось</span>
<strong>{{ displayPassed(calculation.last) }}</strong>
</div>
<div><span>Прошло</span><strong>{{ displayPassed(calculation.passed) }}</strong></div>
<div><span>Дата окончания</span><strong>{{ display(calculation.date_end) }}</strong></div>
<div v-if="calculation.error" class="sla-error">
<span>Ошибка</span><strong>{{ calculation.error }}</strong>
</div>
</div>
<div>
<span>Осталось</span>
<strong>{{ displayPassed(calculation.last) }}</strong>
</div>
<div><span>Прошло</span><strong>{{ displayPassed(calculation.passed) }}</strong></div>
<div><span>Дата окончания</span><strong>{{ display(calculation.date_end) }}</strong></div>
<div v-if="calculation.error" class="sla-error">
<span>Ошибка</span><strong>{{ calculation.error }}</strong>
</div>
</div>
</v-card-text>
</v-card>
</v-card-text>
</v-card>
</div>
</template>
</template>
<style scoped>
.sla-details {
padding: 16px;
border: 1px solid rgba(var(--v-border-color), var(--v-border-opacity));
border-radius: 4px;
}
.sla-fields {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(170px, 1fr));

View File

@ -28,6 +28,9 @@ const transitions: Record<string, string[]> = {
const code = computed(() => String(status.value?.code || ''))
const title = computed(() => String(status.value?.name || status.value?.title
|| statusTitles[code.value] || `Статус #${status.value?.id || props.task.status}`))
const currentStatusId = computed(() => status.value?.id
?? (typeof props.task.status === 'string' || typeof props.task.status === 'number'
? props.task.status : null))
const options = computed(() => {
const allowed = new Set(transitions[code.value] || [])
return statuses.value.filter(item => allowed.has(String(item.code))).map(item => ({
@ -36,6 +39,17 @@ const options = computed(() => {
code: String(item.code || ''),
})).filter(item => item.value !== undefined)
})
const availableIds = computed(() => new Set(options.value.map(option => String(option.value))))
const statusSteps = computed(() => statuses.value
.filter(item => item.id !== undefined && item.is_active !== false)
.map(item => ({
title: String(item.name || item.title || statusTitles[String(item.code)] || `Статус #${item.id}`),
value: item.id as string | number,
code: String(item.code || ''),
color: String(item.color || ''),
current: String(item.id) === String(currentStatusId.value),
available: availableIds.value.has(String(item.id)),
})))
async function load() {
const raw = props.task.status
@ -78,27 +92,136 @@ watch(() => [props.task.id, props.task.status], load, { immediate: true, deep: t
</script>
<template>
<section class="mb-5 rounded-lg border pa-4">
<div class="d-flex flex-wrap align-center ga-3">
<div class="mr-auto">
<div class="text-caption text-medium-emphasis">Текущий статус</div>
<v-chip :color="String(status?.color || '') || undefined" variant="tonal">{{ title }}</v-chip>
<section class="task-status-progress mb-5 rounded-lg border px-4 py-2">
<v-progress-linear v-if="loading" indeterminate color="primary" />
<div v-else-if="statusSteps.length" class="task-status-track">
<div v-for="step in statusSteps" :key="step.value" class="task-status-step"
:class="{
'task-status-step--current': step.current,
'task-status-step--available': step.available && !readonly,
}"
:style="step.color ? { '--task-status-color': step.color } : undefined">
<span class="task-status-marker">
<v-progress-circular v-if="String(changingId) === String(step.value)" indeterminate size="16" width="2" />
<v-icon v-else-if="step.current" icon="mdi-check" size="12" color="white" />
</span>
<v-icon v-if="step.available && !readonly" class="task-status-transition-arrow"
icon="mdi-arrow-right-bold" size="20" color="success" />
<button v-if="step.available && !readonly" type="button" class="task-status-title"
:disabled="changingId !== null" @click="changeStatus(step)">
{{ step.title }}
</button>
<span v-else class="task-status-title">{{ step.title }}</span>
</div>
<v-menu v-if="!readonly && options.length">
<template #activator="{ props: menuProps }">
<v-btn v-bind="menuProps" color="primary" variant="tonal"
append-icon="mdi-chevron-down" :loading="loading || changingId !== null">
Изменить статус
</v-btn>
</template>
<v-list>
<v-list-item v-for="option in options" :key="option.value" :title="option.title"
@click="changeStatus(option)" />
</v-list>
</v-menu>
</div>
<div v-else class="text-body-2 text-medium-emphasis">{{ title }}</div>
<v-alert v-if="error" type="error" variant="tonal" density="compact" class="mt-4">
{{ error }}
</v-alert>
</section>
</template>
<style scoped>
.task-status-track {
display: flex;
width: 100%;
overflow-x: auto;
padding: 0;
}
.task-status-step {
position: relative;
display: flex;
flex: 1 0 155px;
flex-direction: row;
align-items: center;
justify-content: center;
gap: 5px;
color: rgb(var(--v-theme-on-surface) / 32%);
text-align: center;
}
.task-status-step::before {
position: absolute;
top: 8px;
right: 50%;
left: -50%;
height: 2px;
background: rgb(var(--v-theme-on-surface) / 12%);
content: '';
}
.task-status-step:first-child::before {
display: none;
}
.task-status-marker {
z-index: 1;
display: grid;
width: 18px;
height: 18px;
place-items: center;
border: 2px solid rgb(var(--v-theme-on-surface) / 18%);
border-radius: 50%;
background: rgb(var(--v-theme-surface));
}
.task-status-title {
border: 0;
background: transparent;
color: inherit;
font: inherit;
min-height: 44px;
padding: 10px 12px;
border-radius: 8px;
font-size: .875rem;
line-height: 1.2;
}
.task-status-step--current {
color: var(--task-status-color, rgb(var(--v-theme-primary)));
font-weight: 700;
}
.task-status-step--current .task-status-marker {
border-color: var(--task-status-color, rgb(var(--v-theme-primary)));
background: var(--task-status-color, rgb(var(--v-theme-primary)));
color: white;
box-shadow: 0 0 0 2px color-mix(in srgb, var(--task-status-color, rgb(var(--v-theme-primary))) 18%, transparent);
}
.task-status-step--available {
color: var(--task-status-color, rgb(var(--v-theme-primary)));
}
.task-status-step--available .task-status-marker {
border-color: currentColor;
}
.task-status-step--available .task-status-title {
cursor: pointer;
}
.task-status-step--available .task-status-title:hover {
background: rgb(var(--v-theme-success) / 8%);
color: rgb(var(--v-theme-success));
}
.task-status-step:not(.task-status-step--current):not(.task-status-step--available) .task-status-title {
color: rgb(var(--v-theme-on-surface)) !important;
}
.task-status-step:not(.task-status-step--current):not(.task-status-step--available) {
opacity: .28;
}
.task-status-transition-arrow {
flex: 0 0 auto;
margin-right: -2px;
}
.task-status-title:disabled {
cursor: wait;
opacity: .6;
}
</style>

View File

@ -1326,6 +1326,10 @@
"is_active": {
"type": "boolean"
},
"color": {
"type": "string",
"maxLength": 7
},
"requires_assessment": {
"type": "boolean",
"description": "Перед согласованием требуется оценка."
@ -1409,6 +1413,10 @@
"is_active": {
"type": "boolean"
},
"color": {
"type": "string",
"maxLength": 7
},
"requires_assessment": {
"type": "boolean",
"description": "Перед согласованием требуется оценка."
@ -1489,6 +1497,10 @@
"is_active": {
"type": "boolean"
},
"color": {
"type": "string",
"maxLength": 7
},
"requires_assessment": {
"type": "boolean",
"description": "Перед согласованием требуется оценка."
@ -1721,6 +1733,10 @@
"is_active": {
"type": "boolean"
},
"color": {
"type": "string",
"maxLength": 7
},
"parent": {
"type": "integer",
"nullable": true
@ -1745,6 +1761,10 @@
"is_active": {
"type": "boolean"
},
"color": {
"type": "string",
"maxLength": 7
},
"parent": {
"type": "integer",
"nullable": true
@ -1766,6 +1786,10 @@
"is_active": {
"type": "boolean"
},
"color": {
"type": "string",
"maxLength": 7
},
"parent": {
"type": "integer",
"nullable": true
@ -2063,6 +2087,10 @@
"is_active": {
"type": "boolean"
},
"color": {
"type": "string",
"maxLength": 7
},
"department": {
"type": "integer",
"nullable": true
@ -2087,6 +2115,10 @@
"is_active": {
"type": "boolean"
},
"color": {
"type": "string",
"maxLength": 7
},
"department": {
"type": "integer",
"nullable": true
@ -2108,6 +2140,10 @@
"is_active": {
"type": "boolean"
},
"color": {
"type": "string",
"maxLength": 7
},
"department": {
"type": "integer",
"nullable": true

20
tests/audit.test.ts Normal file
View File

@ -0,0 +1,20 @@
import { describe, expect, it } from 'vitest'
import { auditObjectType, auditObjectTypes } from '../utils/audit'
describe('audit object types', () => {
it('maps every object type documented by the audit API', () => {
expect(new Set(Object.values(auditObjectTypes))).toEqual(new Set([
'wanitil.change', 'wanitil.task', 'wanitil.changeapproval',
'wanitil.crmclient', 'wanitil.crmcontract', 'wanitil.crmlead',
'wanitil.cimci', 'wanitil.cimrelation', 'wanitil.srvservice',
'wanitil.slaagreement', 'wanitil.sysemployee', 'wanitil.sysdepartment',
'wanitil.sysprofile', 'wanitil.sysprofileemployee', 'wanitil.syspermission',
'wanitil.dskfile', 'wanitil.dskattachment',
]))
})
it('resolves a resource and leaves unsupported resources empty', () => {
expect(auditObjectType('crm', 'clients')).toBe('wanitil.crmclient')
expect(auditObjectType('adr', 'houses')).toBe('')
})
})

View File

@ -65,6 +65,21 @@ describe('static resource form schemas', () => {
])
})
it('supports colors for task and change classifiers', () => {
for (const path of [
'/main/chn/task-types/',
'/main/chn/task-categories/',
'/main/chn/change-types/',
] as const) {
for (const schema of Object.values(resourceSchemas[path])) {
expect(schema.properties.color).toMatchObject({
type: 'string',
maxLength: 7,
})
}
}
})
it('describes per-type change workflows and approvals', () => {
const changeType = resourceSchemas['/main/chn/change-types/'].post.properties
expect(changeType.approvers).toMatchObject({ type: 'array', items: { type: 'integer' } })

View File

@ -155,6 +155,7 @@ export interface SessionUser extends ApiRecord {
username: string
email?: string
name?: string
is_staff?: boolean
sys_employee?: UserProfile
/** @deprecated Старое имя профиля, оставлено для совместимости с предыдущим API. */
sys_user_profile?: UserProfile

25
utils/audit.ts Normal file
View File

@ -0,0 +1,25 @@
export const auditObjectTypes: Record<string, string> = {
'chn:changes': 'wanitil.change',
'chn:tasks': 'wanitil.task',
'chn:approvals': 'wanitil.changeapproval',
'crm:clients': 'wanitil.crmclient',
'crm:contracts': 'wanitil.crmcontract',
'crm:leads': 'wanitil.crmlead',
'cim:cis': 'wanitil.cimci',
'cim:relations': 'wanitil.cimrelation',
'srv:services': 'wanitil.srvservice',
'sla:requestagreements': 'wanitil.slaagreement',
'sla:incidentagreements': 'wanitil.slaagreement',
'sys:employees': 'wanitil.sysemployee',
'sys:departments': 'wanitil.sysdepartment',
'sys:accessprofiles': 'wanitil.sysprofile',
'sys:profileemployees': 'wanitil.sysprofileemployee',
'sys:permissions': 'wanitil.syspermission',
'dsk:files': 'wanitil.dskfile',
'dsk:attachments': 'wanitil.dskattachment',
}
export function auditObjectType(apiPrefix: string, resourceKey: string) {
return auditObjectTypes[`${apiPrefix}:${resourceKey}`] || ''
}